@boltic/sdk 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -105,10 +105,44 @@ export declare class BolticClient {
105
105
  private recordResource;
106
106
  private sqlResource;
107
107
  private indexResource;
108
+ private databaseResource;
108
109
  private currentDatabase;
109
110
  private clientOptions;
110
111
  constructor(apiKey: string, options?: ClientOptions);
112
+ /**
113
+ * Get current database context
114
+ */
111
115
  getCurrentDatabase(): DatabaseContext | null;
116
+ /**
117
+ * Switch to a different database using its internal name (slug).
118
+ * All subsequent operations will use this database.
119
+ *
120
+ * If no internal name is provided, the SDK will switch back to the default database.
121
+ *
122
+ * @param dbInternalName - Database internal name/slug to switch to. If omitted or empty, default DB is used.
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * // Switch to a specific database by slug
127
+ * await client.useDatabase('my_database_slug');
128
+ *
129
+ * // Switch back to default database
130
+ * await client.useDatabase();
131
+ * ```
132
+ */
133
+ useDatabase(dbInternalName?: string): Promise<void>;
134
+ get databases(): {
135
+ create: (data: DatabaseCreateRequest) => Promise<BolticErrorResponse | BolticSuccessResponse<DatabaseRecord>>;
136
+ findAll: (options?: DatabaseQueryOptions) => Promise<BolticErrorResponse | BolticListResponse<DatabaseRecord>>;
137
+ findOne: (dbInternalName: string, options?: {
138
+ fields?: string[];
139
+ }) => Promise<BolticErrorResponse | BolticSuccessResponse<DatabaseRecord>>;
140
+ getDefault: () => Promise<BolticErrorResponse | BolticSuccessResponse<DatabaseRecord>>;
141
+ update: (dbInternalName: string, data: DatabaseUpdateRequest) => Promise<BolticErrorResponse | BolticSuccessResponse<DatabaseRecord>>;
142
+ delete: (dbInternalName: string) => Promise<BolticErrorResponse | BolticSuccessResponse<DatabaseDeletionJobResponse>>;
143
+ listJobs: (options?: DatabaseJobQueryOptions) => Promise<BolticErrorResponse | BolticListResponse<DatabaseJobRecord>>;
144
+ pollDeleteStatus: (jobId: string) => Promise<BolticErrorResponse | BolticSuccessResponse<DatabaseDeletionStatusResponse>>;
145
+ };
112
146
  get tables(): {
113
147
  create: (data: TableCreateRequest) => Promise<BolticSuccessResponse<TableCreateResponse>>;
114
148
  findAll: (options?: TableQueryOptions) => Promise<ApiResponse<TableRecord>>;
@@ -116,8 +150,8 @@ export declare class BolticClient {
116
150
  findByName: (name: string) => Promise<BolticErrorResponse | BolticSuccessResponse<TableRecord | null>>;
117
151
  findOne: (options: TableQueryOptions) => Promise<BolticErrorResponse | BolticSuccessResponse<TableRecord | null>>;
118
152
  update: (name: string, data: TableUpdateRequest) => Promise<BolticErrorResponse | BolticSuccessResponse<TableRecord>>;
119
- delete: (name: string) => Promise<BolticErrorResponse | BolticSuccessResponse< {
120
- message: string;
153
+ delete: (name: string) => Promise<BolticErrorResponse | BolticSuccessResponse<{
154
+ message: string;
121
155
  }>>;
122
156
  rename: (oldName: string, newName: string) => Promise<BolticSuccessResponse<TableRecord>>;
123
157
  setAccess: (request: {
@@ -132,9 +166,9 @@ export declare class BolticClient {
132
166
  findOne: (tableName: string, columnName: string) => Promise<BolticErrorResponse | BolticSuccessResponse<ColumnDetails>>;
133
167
  findById: (tableName: string, columnId: string) => Promise<BolticErrorResponse | BolticSuccessResponse<ColumnDetails>>;
134
168
  update: (tableName: string, columnName: string, updates: ColumnUpdateRequest) => Promise<BolticErrorResponse | BolticSuccessResponse<ColumnDetails>>;
135
- delete: (tableName: string, columnName: string) => Promise<BolticErrorResponse | BolticSuccessResponse< {
136
- success: boolean;
137
- message?: string | undefined;
169
+ delete: (tableName: string, columnName: string) => Promise<BolticErrorResponse | BolticSuccessResponse<{
170
+ success: boolean;
171
+ message?: string | undefined;
138
172
  }>>;
139
173
  };
140
174
  get indexes(): {
@@ -144,15 +178,10 @@ export declare class BolticClient {
144
178
  };
145
179
  table(name: string): TableBuilder;
146
180
  from(tableName: string): {
147
- columns: () => {
148
- create: (column: FieldDefinition) => Promise<BolticErrorResponse | BolticSuccessResponse<ColumnRecord>>;
149
- findAll: (options?: ColumnQueryOptions) => Promise<BolticErrorResponse | BolticListResponse<ColumnDetails>>;
150
- get: (columnName: string) => Promise<BolticErrorResponse | BolticSuccessResponse<ColumnDetails>>;
151
- update: (columnName: string, updates: ColumnUpdateRequest) => Promise<BolticErrorResponse | BolticSuccessResponse<ColumnDetails>>;
152
- delete: (columnName: string) => Promise<BolticErrorResponse | BolticSuccessResponse< {
153
- success: boolean;
154
- message?: string | undefined;
155
- }>>;
181
+ indexes: () => {
182
+ addIndex: (payload: AddIndexRequest) => Promise<BolticErrorResponse | BolticSuccessResponse<AddIndexResponse>>;
183
+ listIndexes: (query: ListIndexesQuery) => Promise<BolticErrorResponse | BolticSuccessResponse<ListIndexesResponse>>;
184
+ deleteIndex: (indexName: string) => Promise<BolticErrorResponse | BolticSuccessResponse<DeleteIndexResponse>>;
156
185
  };
157
186
  records: () => {
158
187
  insert: (data: RecordData) => Promise<BolticErrorResponse | BolticSuccessResponse<RecordWithId>>;
@@ -162,19 +191,13 @@ export declare class BolticClient {
162
191
  findOne: (recordId: string) => Promise<BolticErrorResponse | BolticSuccessResponse<RecordWithId>>;
163
192
  update: (options: RecordUpdateOptions) => Promise<BolticErrorResponse | BolticListResponse<RecordWithId>>;
164
193
  updateById: (recordId: string, data: RecordData) => Promise<BolticErrorResponse | BolticSuccessResponse<RecordWithId>>;
165
- delete: (options: RecordDeleteOptions) => Promise<BolticErrorResponse | BolticSuccessResponse< {
166
- message: string;
194
+ delete: (options: RecordDeleteOptions) => Promise<BolticErrorResponse | BolticSuccessResponse<{
195
+ message: string;
167
196
  }>>;
168
- deleteById: (recordId: string) => Promise<BolticErrorResponse | BolticSuccessResponse< {
169
- message: string;
197
+ deleteById: (recordId: string) => Promise<BolticErrorResponse | BolticSuccessResponse<{
198
+ message: string;
170
199
  }>>;
171
200
  };
172
- record: () => RecordBuilder;
173
- indexes: () => {
174
- addIndex: (payload: AddIndexRequest) => Promise<BolticErrorResponse | BolticSuccessResponse<AddIndexResponse>>;
175
- listIndexes: (query: ListIndexesQuery) => Promise<BolticErrorResponse | BolticSuccessResponse<ListIndexesResponse>>;
176
- deleteIndex: (indexName: string) => Promise<BolticErrorResponse | BolticSuccessResponse<DeleteIndexResponse>>;
177
- };
178
201
  };
179
202
  get records(): {
180
203
  insert: (tableName: string, data: RecordData) => Promise<BolticErrorResponse | BolticSuccessResponse<RecordWithId>>;
@@ -185,11 +208,11 @@ export declare class BolticClient {
185
208
  findOne: (tableName: string, recordId: string) => Promise<BolticErrorResponse | BolticSuccessResponse<RecordWithId>>;
186
209
  update: (tableName: string, options: RecordUpdateOptions) => Promise<BolticErrorResponse | BolticListResponse<RecordWithId>>;
187
210
  updateById: (tableName: string, recordId: string, data: RecordData) => Promise<BolticErrorResponse | BolticSuccessResponse<RecordWithId>>;
188
- delete: (tableName: string, options: RecordDeleteOptions) => Promise<BolticErrorResponse | BolticSuccessResponse< {
189
- message: string;
211
+ delete: (tableName: string, options: RecordDeleteOptions) => Promise<BolticErrorResponse | BolticSuccessResponse<{
212
+ message: string;
190
213
  }>>;
191
- deleteById: (tableName: string, recordId: string) => Promise<BolticErrorResponse | BolticSuccessResponse< {
192
- message: string;
214
+ deleteById: (tableName: string, recordId: string) => Promise<BolticErrorResponse | BolticSuccessResponse<{
215
+ message: string;
193
216
  }>>;
194
217
  };
195
218
  record(tableName: string): RecordBuilder;
@@ -391,7 +414,126 @@ export declare function createClient(apiKey: string, options?: ClientOptions): B
391
414
  export declare function createErrorWithContext(message: string, context?: Record<string, unknown>): Error;
392
415
 
393
416
  declare interface DatabaseContext {
394
- databaseName: string;
417
+ databaseId?: string;
418
+ dbInternalName?: string;
419
+ }
420
+
421
+ /**
422
+ * Request to create a new database
423
+ */
424
+ declare interface DatabaseCreateRequest {
425
+ db_name: string;
426
+ db_internal_name?: string;
427
+ resource_id?: string;
428
+ }
429
+
430
+ /**
431
+ * Database deletion job initial response
432
+ */
433
+ declare interface DatabaseDeletionJobResponse {
434
+ job_id: string;
435
+ db_id: string;
436
+ status: 'pending';
437
+ }
438
+
439
+ /**
440
+ * Database deletion status response
441
+ */
442
+ declare interface DatabaseDeletionStatusResponse {
443
+ jobId: string;
444
+ status: DatabaseJobStatus;
445
+ message: string;
446
+ }
447
+
448
+ /**
449
+ * Database Job action enum
450
+ */
451
+ declare type DatabaseJobAction = 'DELETE';
452
+
453
+ /**
454
+ * Database job query options for SDK methods
455
+ */
456
+ declare interface DatabaseJobQueryOptions {
457
+ deleted_by_me?: boolean;
458
+ page?: PaginationParams;
459
+ sort?: SortParams[];
460
+ filters?: FilterParams[];
461
+ fields?: string[];
462
+ }
463
+
464
+ /**
465
+ * Database job record from API
466
+ */
467
+ declare interface DatabaseJobRecord {
468
+ id: string;
469
+ account_id: string;
470
+ resource_id: string;
471
+ type: string;
472
+ action: DatabaseJobAction;
473
+ db_id: string;
474
+ db_internal_name: string;
475
+ db_username: string;
476
+ job_status: DatabaseJobStatus;
477
+ total_dbs: number;
478
+ successful_dbs: number;
479
+ failed_dbs: number;
480
+ error: string | null;
481
+ is_read: boolean;
482
+ created_by: string;
483
+ created_at: string;
484
+ updated_at: string;
485
+ }
486
+
487
+ /**
488
+ * Database Job status enum
489
+ */
490
+ declare type DatabaseJobStatus = 'pending' | 'in_progress' | 'success' | 'failed';
491
+
492
+ /**
493
+ * Database query options for SDK methods
494
+ */
495
+ declare interface DatabaseQueryOptions {
496
+ connector_id?: string;
497
+ add_default_if_missing?: boolean;
498
+ page?: PaginationParams;
499
+ sort?: SortParams[];
500
+ filters?: FilterParams[];
501
+ fields?: string[];
502
+ }
503
+
504
+ /**
505
+ * Database record from API
506
+ */
507
+ declare interface DatabaseRecord {
508
+ id: string;
509
+ account_id: string;
510
+ db_name: string;
511
+ db_internal_name: string;
512
+ db_username: string;
513
+ resource_id: string;
514
+ status: DatabaseStatus;
515
+ is_default: boolean;
516
+ rank: number;
517
+ created_by: string;
518
+ updated_by: string;
519
+ created_at: string;
520
+ updated_at: string;
521
+ }
522
+
523
+ /**
524
+ * Database Management API Types
525
+ * Based on DATABASE_MANAGEMENT_API_CONTRACT.md
526
+ */
527
+ /**
528
+ * Database status enum
529
+ */
530
+ declare type DatabaseStatus = 'ACTIVE' | 'INACTIVE';
531
+
532
+ /**
533
+ * Request to update a database
534
+ */
535
+ declare interface DatabaseUpdateRequest {
536
+ db_name: string;
395
537
  }
396
538
 
397
539
  declare const DateFormatEnum: Readonly<{
@@ -471,6 +613,15 @@ export declare interface FieldDefinition {
471
613
 
472
614
  export declare type FieldType = 'text' | 'long-text' | 'number' | 'currency' | 'checkbox' | 'dropdown' | 'email' | 'phone-number' | 'link' | 'json' | 'date-time' | 'vector' | 'halfvec' | 'sparsevec';
473
615
 
616
+ /**
617
+ * Filter parameters
618
+ */
619
+ declare interface FilterParams {
620
+ field: string;
621
+ operator: string;
622
+ values: any[];
623
+ }
624
+
474
625
  /**
475
626
  * Formats error for logging/debugging
476
627
  */
@@ -574,6 +725,14 @@ declare interface ListIndexesResponse {
574
725
  };
575
726
  }
576
727
 
728
+ /**
729
+ * Pagination parameters
730
+ */
731
+ declare interface PaginationParams {
732
+ page_no?: number;
733
+ page_size?: number;
734
+ }
735
+
577
736
  declare type PhoneFormatType = '+91 123 456 7890' | '(123) 456-7890' | '+1 (123) 456-7890' | '+91 12 3456 7890';
578
737
 
579
738
  export declare interface QueryOperator<T = unknown> {
@@ -735,37 +894,37 @@ declare class RecordResource {
735
894
  /**
736
895
  * Insert a single record
737
896
  */
738
- insert(tableName: string, data: RecordData): Promise<BolticSuccessResponse<RecordWithId> | BolticErrorResponse>;
897
+ insert(tableName: string, data: RecordData, dbId?: string): Promise<BolticSuccessResponse<RecordWithId> | BolticErrorResponse>;
739
898
  /**
740
899
  * Insert multiple records in bulk
741
900
  */
742
- insertMany(tableName: string, records: RecordData[], options?: RecordBulkInsertOptions): Promise<RecordBulkInsertResponse | BolticErrorResponse>;
901
+ insertMany(tableName: string, records: RecordData[], options?: RecordBulkInsertOptions, dbId?: string): Promise<RecordBulkInsertResponse | BolticErrorResponse>;
743
902
  /**
744
903
  * Get a single record by ID
745
904
  */
746
- get(tableName: string, recordId: string): Promise<BolticSuccessResponse<RecordWithId> | BolticErrorResponse>;
905
+ get(tableName: string, recordId: string, dbId?: string): Promise<BolticSuccessResponse<RecordWithId> | BolticErrorResponse>;
747
906
  /**
748
907
  * List records with filtering and pagination
749
908
  */
750
- list(tableName: string, options?: RecordQueryOptions): Promise<BolticListResponse<RecordWithId> | BolticErrorResponse>;
909
+ list(tableName: string, options?: RecordQueryOptions, dbId?: string): Promise<BolticListResponse<RecordWithId> | BolticErrorResponse>;
751
910
  /**
752
911
  * Update records by filters
753
912
  */
754
- update(tableName: string, options: RecordUpdateOptions): Promise<BolticListResponse<RecordWithId> | BolticErrorResponse>;
913
+ update(tableName: string, options: RecordUpdateOptions, dbId?: string): Promise<BolticListResponse<RecordWithId> | BolticErrorResponse>;
755
914
  /**
756
915
  * Update a single record by ID
757
916
  */
758
- updateById(tableName: string, recordId: string, data: RecordData): Promise<BolticSuccessResponse<RecordWithId> | BolticErrorResponse>;
917
+ updateById(tableName: string, recordId: string, data: RecordData, dbId?: string): Promise<BolticSuccessResponse<RecordWithId> | BolticErrorResponse>;
759
918
  /**
760
919
  * Unified delete method that supports both record IDs and filters
761
920
  */
762
- delete(tableName: string, options: RecordDeleteOptions): Promise<BolticSuccessResponse<{
921
+ delete(tableName: string, options: RecordDeleteOptions, dbId?: string): Promise<BolticSuccessResponse<{
763
922
  message: string;
764
923
  }> | BolticErrorResponse>;
765
924
  /**
766
925
  * Delete a single record by ID
767
926
  */
768
- deleteById(tableName: string, recordId: string): Promise<BolticSuccessResponse<{
927
+ deleteById(tableName: string, recordId: string, dbId?: string): Promise<BolticSuccessResponse<{
769
928
  message: string;
770
929
  }> | BolticErrorResponse>;
771
930
  /**
@@ -802,6 +961,14 @@ export declare interface ServiceAuthConfig extends AuthConfig {
802
961
  serviceEndpoint?: string;
803
962
  }
804
963
 
964
+ /**
965
+ * Sort parameters
966
+ */
967
+ declare interface SortParams {
968
+ field: string;
969
+ direction: 'asc' | 'desc';
970
+ }
971
+
805
972
  declare class SqlResource {
806
973
  private sqlApiClient;
807
974
  constructor(client: BaseClient);
@@ -814,7 +981,7 @@ declare class SqlResource {
814
981
  * @returns AsyncIterable<string> for streaming SQL generation
815
982
  *
816
983
  */
817
- textToSQL(prompt: string, options?: TextToSQLOptions): Promise<AsyncIterable<string>>;
984
+ textToSQL(prompt: string, options?: TextToSQLOptions, dbId?: string): Promise<AsyncIterable<string>>;
818
985
  /**
819
986
  * Execute SQL query with built-in safety measures and performance optimization
820
987
  *
@@ -822,7 +989,7 @@ declare class SqlResource {
822
989
  * @returns Promise<ExecuteSQLApiResponse> with raw API response following Boltic API Response Structure
823
990
  *
824
991
  */
825
- executeSQL(query: string): Promise<ExecuteSQLApiResponse | BolticErrorResponse>;
992
+ executeSQL(query: string, dbId?: string): Promise<ExecuteSQLApiResponse | BolticErrorResponse>;
826
993
  }
827
994
 
828
995
  /**
@@ -995,6 +1162,7 @@ declare interface TableBuilderOptions {
995
1162
  declare interface TableCreateOptions {
996
1163
  is_ai_generated_schema?: boolean;
997
1164
  is_template?: boolean;
1165
+ db_id?: string;
998
1166
  }
999
1167
 
1000
1168
  export declare interface TableCreateRequest {
@@ -1015,6 +1183,7 @@ declare interface TableListOptions extends TableQueryOptions {
1015
1183
  page?: number;
1016
1184
  pageSize?: number;
1017
1185
  isShared?: boolean;
1186
+ db_id?: string;
1018
1187
  }
1019
1188
 
1020
1189
  declare interface TableQueryOptions {
@@ -1083,6 +1252,7 @@ declare class TablesApiClient {
1083
1252
  */
1084
1253
  getTable(tableId: string, options?: {
1085
1254
  fields?: Array<keyof TableRecord>;
1255
+ db_id?: string;
1086
1256
  }): Promise<BolticSuccessResponse_2<TableRecord> | BolticErrorResponse_2>;
1087
1257
  /**
1088
1258
  * Update an existing table
@@ -1092,11 +1262,14 @@ declare class TablesApiClient {
1092
1262
  description?: string;
1093
1263
  is_shared?: boolean;
1094
1264
  fields?: Array<keyof TableRecord>;
1265
+ db_id?: string;
1095
1266
  }): Promise<BolticSuccessResponse_2<TableRecord> | BolticErrorResponse_2>;
1096
1267
  /**
1097
1268
  * Delete a table
1098
1269
  */
1099
- deleteTable(tableId: string): Promise<BolticSuccessResponse_2<{
1270
+ deleteTable(tableId: string, options?: {
1271
+ db_id?: string;
1272
+ }): Promise<BolticSuccessResponse_2<{
1100
1273
  message: string;
1101
1274
  }> | BolticErrorResponse_2>;
1102
1275
  private buildHeaders;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@boltic/sdk",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "TypeScript SDK for Boltic databases infrastructure",
5
5
  "main": "dist/sdk.js",
6
6
  "module": "dist/sdk.mjs",
@@ -12,9 +12,9 @@
12
12
  },
13
13
  "exports": {
14
14
  ".": {
15
+ "types": "./dist/types/index.d.ts",
15
16
  "import": "./dist/sdk.mjs",
16
- "require": "./dist/sdk.js",
17
- "types": "./dist/types/index.d.ts"
17
+ "require": "./dist/sdk.js"
18
18
  }
19
19
  },
20
20
  "files": [
@@ -57,7 +57,7 @@
57
57
  "@types/node": "^20.0.0",
58
58
  "@typescript-eslint/eslint-plugin": "^6.21.0",
59
59
  "@typescript-eslint/parser": "^6.0.0",
60
- "@vitest/ui": "^1.0.0",
60
+ "@vitest/ui": "^4.0.16",
61
61
  "eslint": "^8.0.0",
62
62
  "eslint-config-prettier": "^9.0.0",
63
63
  "eslint-plugin-prettier": "^5.0.0",
@@ -67,9 +67,9 @@
67
67
  "terser": "^5.0.0",
68
68
  "typedoc": "^0.25.0",
69
69
  "typescript": "^5.0.0",
70
- "vite": "^5.0.0",
71
- "vite-plugin-dts": "^3.0.0",
72
- "vitest": "^1.0.0"
70
+ "vite": "^7.3.0",
71
+ "vite-plugin-dts": "^4.5.4",
72
+ "vitest": "^4.0.16"
73
73
  },
74
74
  "peerDependencies": {
75
75
  "axios": "^1.0.0"
@@ -78,5 +78,8 @@
78
78
  "axios": {
79
79
  "optional": true
80
80
  }
81
+ },
82
+ "dependencies": {
83
+ "dotenv": "^17.2.3"
81
84
  }
82
- }
85
+ }
@@ -1,2 +0,0 @@
1
- "use strict";class e extends Error{constructor(e,t=[]){super(e),this.name="ValidationError",this.failures=t}}class t extends Error{constructor(e,t,r){super(e),this.name="ApiError",this.statusCode=t,this.response=r}}function r(e,t){const r=new Error(e);return t&&(r.context=t),r}function s(e){if(e&&"object"==typeof e){if("response"in e&&e.response&&"object"==typeof e.response){const t=e.response;if("status"in t&&"number"==typeof t.status)return t.status}if("status"in e&&"number"==typeof e.status)return e.status}return null}function i(e){if(e instanceof Error){const t=e.context,r=s(e);let i=`${e.name}: ${e.message}`;return r&&(i+=` (HTTP ${r})`),t&&(i+=`\nContext: ${JSON.stringify(t,null,2)}`),i}return String(e)}class n{constructor(e){this.tokenInfo=null,this.config={maxRetries:3,...e},this.validateApiKey(e.apiKey)}validateApiKey(e){if(!e||"string"!=typeof e||0===e.trim().length)throw r("API key is required and must be a non-empty string",{name:"AuthenticationError",code:"INVALID_API_KEY"});if(e.length<10)throw r("API key appears to be invalid (too short)",{name:"AuthenticationError",code:"INVALID_API_KEY_FORMAT"})}getAuthHeaders(){return{"x-boltic-token":this.config.apiKey}}updateApiKey(e){this.validateApiKey(e),this.config.apiKey=e,this.tokenInfo=null}isAuthenticated(){return!!this.config.apiKey}async validateApiKeyAsync(){try{return this.validateApiKey(this.config.apiKey),!0}catch{return!1}}getTokenInfo(){return this.tokenInfo?{...this.tokenInfo}:null}getMaxRetries(){return this.config.maxRetries||3}toString(){return`AuthManager { authenticated: ${this.isAuthenticated()}, maxRetries: ${this.getMaxRetries()} }`}toJSON(){return{authenticated:this.isAuthenticated(),maxRetries:this.getMaxRetries()}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class o{constructor(){try{this.axios=require("axios")}catch(e){throw r("Axios is required for Node.js < 18. Please install axios: npm install axios",{error:e})}}async request(e){var t,s,i,n,o;try{const t={url:e.url,method:e.method.toLowerCase(),headers:e.headers,params:e.params,data:e.data,timeout:e.timeout,signal:e.signal,validateStatus:()=>!0},r=await this.axios(t);return{data:r.data,status:r.status,statusText:r.statusText,headers:r.headers||{}}}catch(a){const d=a;if("ECONNABORTED"===d.code||(null==(t=d.message)?void 0:t.includes("timeout")))throw r("Request timeout",{url:e.url,method:e.method,timeout:e.timeout});if("ERR_NETWORK"===d.code||"ENOTFOUND"===d.code||"ECONNREFUSED"===d.code||"EHOSTUNREACH"===d.code||"ETIMEDOUT"===d.code||"ERR_INTERNET_DISCONNECTED"===d.code||(null==(s=d.message)?void 0:s.includes("network"))||(null==(i=d.message)?void 0:i.includes("internet"))||(null==(n=d.message)?void 0:n.includes("connection"))||(null==(o=d.message)?void 0:o.includes("resolve")))throw r("Network connection failed. Please check your internet connection or VPN settings.",{url:e.url,method:e.method,networkError:!0,errorCode:d.code,originalMessage:d.message});if("AbortError"===d.name||"ERR_CANCELED"===d.code)throw r("Request was aborted",{url:e.url,method:e.method});throw r(`HTTP request failed: ${d.message||"Unknown error"}`,{url:e.url,method:e.method,originalError:a})}}}class a{async request(e){const t=new URL(e.url);e.params&&Object.entries(e.params).forEach(([e,r])=>{null!=r&&t.searchParams.append(e,String(r))});const s={method:e.method,headers:{"Content-Type":"application/json",...e.headers},signal:e.signal};e.data&&["POST","PUT","PATCH","DELETE"].includes(e.method)&&(s.body=JSON.stringify(e.data));try{const r=new AbortController;let i;e.timeout&&(i=setTimeout(()=>r.abort(),e.timeout),s.signal=e.signal?(()=>{const t=new AbortController;return e.signal.addEventListener("abort",()=>t.abort()),r.signal.addEventListener("abort",()=>t.abort()),t.signal})():r.signal);const n=await fetch(t.toString(),s);i&&clearTimeout(i);const o=n.headers.get("content-type");let a;a=(null==o?void 0:o.includes("application/json"))?await n.json():await n.text();const d={};n.headers.forEach((e,t)=>{d[t]=e});return{data:a,status:n.status,statusText:n.statusText,headers:d}}catch(i){if(i instanceof Error&&"AbortError"===i.name)throw r("Request was aborted",{type:"AbortError",url:e.url,method:e.method});if(i instanceof Error){const t=i.message.toLowerCase();if("TypeError"===i.name&&(t.includes("network")||t.includes("fetch")||t.includes("failed to fetch")||t.includes("internet")||t.includes("connection")||t.includes("resolve")||t.includes("unreachable")))throw r("Network connection failed. Please check your internet connection or VPN settings.",{url:e.url,method:e.method,networkError:!0,originalMessage:i.message})}throw r(`HTTP request failed: ${i instanceof Error?i.message:"Unknown error"}`,{url:e.url,method:e.method,originalError:i})}}}function d(){if("undefined"!=typeof fetch)return new a;try{return new o}catch(e){throw r("No suitable HTTP adapter found. Please use Node.js >= 18 or install axios: npm install axios",{error:e})}}class l{constructor(){this.requestInterceptors=new Map,this.responseInterceptors=new Map,this.nextId=0,this.request={use:e=>{const t=this.nextId++;return this.requestInterceptors.set(t,e),t},eject:e=>{this.requestInterceptors.delete(e)}},this.response={use:(e,t)=>{const r=this.nextId++;return this.responseInterceptors.set(r,{fulfilled:e,rejected:t}),r},eject:e=>{this.responseInterceptors.delete(e)}}}async executeRequestInterceptors(e){let t=e;for(const r of this.requestInterceptors.values())t=await r(t);return t}async executeResponseInterceptors(e){let t=e;for(const{fulfilled:r}of this.responseInterceptors.values())r&&(t=await r(t));return t}async executeErrorInterceptors(e){let t=e;for(const{rejected:r}of this.responseInterceptors.values())r&&(t=await r(t));return t}}class u{constructor(e,t){this.config=e,this.authManager=t,this.httpAdapter=d(),this.interceptors=new l,this.setupDefaultInterceptors()}setupDefaultInterceptors(){this.interceptors.request.use(e=>{const t=this.authManager.getAuthHeaders();return e.headers={...e.headers,...t,...this.config.headers},e}),this.interceptors.response.use(e=>(this.config.debug&&console.log("HTTP Response:",e),e),e=>this.handleError(e))}handleError(e){var t;if(this.config.debug&&console.error("HTTP Error:",e),e instanceof Error&&e.context)throw e;const i=s(e);if(!i)throw r("Network request failed",{name:"NetworkError",originalError:e});const n=(null==(t=e.response)?void 0:t.data)||e.data;throw r((null==n?void 0:n.message)||(null==n?void 0:n.error)||`HTTP ${i} error`,{name:"ApiError",statusCode:i,response:n,isClientError:i>=400&&i<500,isServerError:i>=500,isAuthError:401===i||403===i,isNotFoundError:404===i,isRateLimitError:429===i})}async request(e){let t;const i=this.config.maxRetries;for(let o=0;o<=i;o++)try{e.url.startsWith("http")||(e.url=`${this.config.baseURL}${e.url}`),e.timeout||(e.timeout=this.config.timeout);const t=await this.interceptors.executeRequestInterceptors(e),s=await this.httpAdapter.request(t);if(s.status>=400){const e=r(`HTTP ${s.status} error`,{name:"ApiError",statusCode:s.status,response:s.data,statusText:s.statusText});throw await this.interceptors.executeErrorInterceptors(e)}return await this.interceptors.executeResponseInterceptors(s)}catch(n){if(t=n,o===i)break;const e=s(n);if(e&&e>=400&&e<500)break;if(o<i){const e=this.config.retryDelay*Math.pow(2,o);await new Promise(t=>setTimeout(t,e))}}throw await this.interceptors.executeErrorInterceptors(t)}get(e,t){return this.request({...t,method:"GET",url:e})}post(e,t,r){return this.request({...r,method:"POST",url:e,data:t})}put(e,t,r){return this.request({...r,method:"PUT",url:e,data:t})}patch(e,t,r){return this.request({...r,method:"PATCH",url:e,data:t})}delete(e,t){return this.request({...t,method:"DELETE",url:e})}getInterceptors(){return this.interceptors}updateConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}}const c={"asia-south1":{local:{baseURL:"http://localhost:8000",timeout:3e4,debug:!0},sit:{baseURL:"https://asia-south1.api.fcz0.de/service/sdk/boltic-tables",timeout:15e3},uat:{baseURL:"https://asia-south1.api.uat.fcz0.de/service/sdk/boltic-tables",timeout:15e3},prod:{baseURL:"https://asia-south1.api.boltic.io/service/sdk/boltic-tables",timeout:1e4}},"us-central1":{local:{baseURL:"http://localhost:8000",timeout:3e4,debug:!0},sit:{baseURL:"https://us-central1.api.fcz0.de/service/sdk/boltic-tables",timeout:15e3},uat:{baseURL:"https://us-central1.api.uat.fcz0.de/service/sdk/boltic-tables",timeout:15e3},prod:{baseURL:"https://us-central1.api.boltic.io/service/sdk/boltic-tables",timeout:1e4}}},h=c["asia-south1"];class m{constructor(e,t="prod",r="asia-south1",s){const i=c[r][t];this.config={apiKey:e,environment:t,region:r,retryAttempts:3,retryDelay:1e3,maxRetries:3,debug:!1,headers:{},...i,...s}}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e}}toString(){return`ConfigManager { environment: "${this.config.environment}", region: "${this.config.region}", debug: ${this.config.debug} }`}toJSON(){const e={...this.config};return delete e.apiKey,e}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}function p(e,t){if(!t||0===t.length)return e;const r={};for(const s of t)s in e&&(r[s]=e[s]);return r}function f(e,t){return t&&0!==t.length?e.map(e=>p(e,t)):e}const g={path:"/tables/{table_id}/fields/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},_={path:"/tables/{table_id}/fields",method:"POST",authenticated:!0},b={path:"/tables/{table_id}/fields/{field_id}",method:"GET",authenticated:!0,rateLimit:{requests:300,window:6e4}},y={path:"/tables/{table_id}/fields/{field_id}",method:"PATCH",authenticated:!0},R={path:"/tables/{table_id}/fields/{field_id}",method:"DELETE",authenticated:!0},E=(e,t={})=>{let r=e.path;Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))});const s=r.match(/\{([^}]+)\}/g);if(s)throw new Error(`Missing path parameters: ${s.join(", ")}`);return r},w=Object.freeze({MMDDYY:"%m/%d/%y",MMDDYYYY:"%m/%d/%Y",MM_DD_YYYY:"%m-%d-%Y",DD_MM_YYYY:"%d-%m-%Y",DDMMYYYY:"%d/%m/%Y",DDMMYY:"%d/%m/%y",YYYY_MM_DD:"%Y-%m-%d",MMMM__DD__YYYY:"%B %d %Y",MMM__DD__YYYY:"%b %d %Y",ddd__MMM__DD__YYYY:"%a %b %d %Y"}),T=Object.freeze({HH_mm_ss:"%H:%M:%S",HH_mm_ssZ:"%H:%M:%SZ",HH_mm_ss_SSS:"%H:%M:%S.%f",HH_mm_ss__Z:"%H:%M:%S %Z",HH_mm__AMPM:"%I:%M %p",HH_mm_ss__AMPM:"%I:%M:%S %p"});function A(e){if(!e||"object"!=typeof e)throw new Error("Invalid request: single column data is required");if(!e.name||!e.type)throw new Error("Column name and type are required");return{name:(t=e).name,type:t.type,is_nullable:t.is_nullable??!0,is_primary_key:t.is_primary_key??!1,is_unique:t.is_unique??!1,is_visible:t.is_visible??!0,is_readonly:t.is_readonly??!1,is_indexed:t.is_indexed??!1,field_order:t.field_order??1,alignment:t.alignment??"left",timezone:t.timezone??void 0,date_format:t.date_format?v(t.date_format):void 0,time_format:t.time_format?I(t.time_format):void 0,decimals:t.decimals??void 0,currency_format:t.currency_format??void 0,selection_source:"dropdown"!==t.type||t.selection_source?t.selection_source??void 0:"provide-static-list",selectable_items:t.selectable_items??void 0,multiple_selections:t.multiple_selections??void 0,phone_format:t.phone_format??void 0,vector_dimension:t.vector_dimension??void 0,description:t.description??void 0,default_value:t.default_value??void 0};var t}function v(e){return w[e]||e}function I(e){return T[e]||e}class N{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}async createColumn(e,t){try{const r=_,s=`${this.baseURL}${E(r,{table_id:e})}`,i=A(t),n=await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:i,timeout:this.config.timeout});return this.config.debug&&console.log("Column API Response:",JSON.stringify(n.data,null,2)),n.data}catch(r){return this.formatErrorResponse(r)}}async createColumns(e,t){try{const r=t.columns,s=[];for(const t of r){const r=await this.createColumn(e,t);if("error"in r)return r;s.push(r.data)}if(t.fields&&s.length>0){const e=f(s,t.fields);s.splice(0,s.length,...e)}return{data:s,message:"Columns created successfully"}}catch(r){return this.formatErrorResponse(r)}}async listColumns(e,t={}){try{const r=g,s=`${this.baseURL}${E(r,{table_id:e})}?no_cache=true`,i=(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data;return t.fields&&i.data&&(i.data=f(i.data,t.fields)),i}catch(r){return this.formatErrorResponse(r)}}async getColumn(e,t,r={}){try{const s=b,i=`${this.baseURL}${E(s,{table_id:e,field_id:t})}`,n=await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),timeout:this.config.timeout});this.config.debug&&console.log("Column API Response:",JSON.stringify(n.data,null,2));const o=n.data;return r.fields&&o.data&&(o.data=p(o.data,r.fields)),o}catch(s){return this.formatErrorResponse(s)}}async updateColumn(e,t,r){try{const s=y,i=`${this.baseURL}${E(s,{table_id:e,field_id:t})}`,n=function(e){const t={};return void 0!==e.name&&(t.name=e.name),void 0!==e.type&&(t.type=e.type),void 0!==e.description&&(t.description=e.description),void 0!==e.is_nullable&&(t.is_nullable=e.is_nullable),void 0!==e.is_unique&&(t.is_unique=e.is_unique),void 0!==e.is_primary_key&&(t.is_primary_key=e.is_primary_key),void 0!==e.is_indexed&&(t.is_indexed=e.is_indexed),void 0!==e.is_visible&&(t.is_visible=e.is_visible),void 0!==e.is_readonly&&(t.is_readonly=e.is_readonly),void 0!==e.default_value&&(t.default_value=e.default_value),void 0!==e.field_order&&(t.field_order=e.field_order),void 0!==e.alignment&&(t.alignment=e.alignment),void 0!==e.decimals&&(t.decimals=e.decimals),void 0!==e.currency_format&&(t.currency_format=e.currency_format),"dropdown"===e.type||void 0!==e.selectable_items?t.selection_source="provide-static-list":void 0!==e.selection_source&&(t.selection_source=e.selection_source),void 0!==e.selectable_items&&(t.selectable_items=e.selectable_items),void 0!==e.multiple_selections&&(t.multiple_selections=e.multiple_selections),void 0!==e.phone_format&&(t.phone_format=e.phone_format),void 0!==e.timezone&&(t.timezone=e.timezone),void 0!==e.vector_dimension&&(t.vector_dimension=e.vector_dimension),void 0!==e.date_format&&(t.date_format=v(e.date_format)),void 0!==e.time_format&&(t.time_format=I(e.time_format)),t}(r),o=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:n,timeout:this.config.timeout})).data;return r.fields&&o.data&&(o.data=p(o.data,r.fields)),o}catch(s){return this.formatErrorResponse(s)}}async deleteColumn(e,t){try{const r=R,s=`${this.baseURL}${E(r,{table_id:e,field_id:t})}`;return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async findColumnByName(e,t){try{const r={page:{page_no:1,page_size:1},filters:[{field:"name",operator:"=",values:[t]}],sort:[]},s=await this.listColumns(e,r);if("error"in s)return s;const i=s.data[0]||null;return{data:i,message:i?"Column found":"Column not found"}}catch(r){return this.formatErrorResponse(r)}}convertColumnDetailsToUpdateRequest(e){return{name:e.name,type:e.type,description:e.description,is_nullable:e.is_nullable,is_unique:e.is_unique,is_indexed:e.is_indexed,is_visible:e.is_visible,is_primary_key:e.is_primary_key,is_readonly:e.is_readonly,default_value:e.default_value,field_order:e.field_order,alignment:e.alignment,decimals:e.decimals,currency_format:e.currency_format,selection_source:e.selection_source,selectable_items:e.selectable_items,multiple_selections:e.multiple_selections,phone_format:e.phone_format,date_format:e.date_format,time_format:e.time_format,timezone:e.timezone,vector_dimension:e.vector_dimension}}async updateColumnByName(e,t,r){try{const s=await this.findColumnByName(e,t);if("error"in s)return s;if(!s.data)return{error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table`,meta:["404"]}};const i={...this.convertColumnDetailsToUpdateRequest(s.data),...r};return await this.updateColumn(e,s.data.id,i)}catch(s){return this.formatErrorResponse(s)}}async deleteColumnByName(e,t){try{const r=await this.findColumnByName(e,t);return"error"in r?r:r.data?await this.deleteColumn(e,r.data.id):{error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table`,meta:["Column not found"]}}}catch(r){return this.formatErrorResponse(r)}}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey}}formatErrorResponse(e){var t,r,s;if(this.config.debug&&console.error("Columns API Error:",e),e&&"object"==typeof e&&"response"in e){const i=e;return(null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.error)?i.response.data:{error:{code:"API_ERROR",message:e.message||"Unknown API error",meta:[`Status: ${(null==(s=i.response)?void 0:s.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{error:{code:"CLIENT_ERROR",message:e.message,meta:["Client-side error occurred"]}}:{error:{code:"UNKNOWN_ERROR",message:"An unexpected error occurred",meta:["Unknown error type"]}}}}const C={path:"/tables/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},O={path:"/tables",method:"POST",authenticated:!0},L={path:"/tables/{table_id}",method:"GET",authenticated:!0,rateLimit:{requests:300,window:6e4}},x={path:"/tables/{table_id}",method:"PATCH",authenticated:!0},$={path:"/tables/{table_id}",method:"DELETE",authenticated:!0},U=(e,t={})=>{let r=e.path;Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))});const s=r.match(/\{([^}]+)\}/g);if(s)throw new Error(`Missing path parameters: ${s.join(", ")}`);return r},q={EQUALS:"=",NOT_EQUALS:"!=",GREATER_THAN:">",GREATER_THAN_EQUAL:">=",LESS_THAN:"<",LESS_THAN_EQUAL:"<=",LIKE:"LIKE",ILIKE:"ILIKE",STARTS_WITH:"STARTS WITH",IN:"IN",NOT_IN:"NOT IN",IS_EMPTY:"IS EMPTY",IS_NULL:"IS NULL",IS_NOT_NULL:"IS NOT NULL",BETWEEN:"BETWEEN",ARRAY_CONTAINS:"@>",ARRAY_NOT_CONTAINS:"NOT @>",ANY:"ANY",IS_ONE_OF_ARRAY:"IS ONE OF",DROPDOWN_ITEM_STARTS_WITH:"DROPDOWN ITEM STARTS WITH",WITHIN:"WITHIN"},S={$eq:q.EQUALS,$ne:q.NOT_EQUALS,$gt:q.GREATER_THAN,$gte:q.GREATER_THAN_EQUAL,$lt:q.LESS_THAN,$lte:q.LESS_THAN_EQUAL,$like:q.LIKE,$ilike:q.ILIKE,$startsWith:q.STARTS_WITH,$in:q.IN,$notIn:q.NOT_IN,$between:q.BETWEEN,$isEmpty:q.IS_EMPTY,$isNull:q.IS_NULL,$isNotNull:q.IS_NOT_NULL,$arrayContains:q.ARRAY_CONTAINS,$arrayNotContains:q.ARRAY_NOT_CONTAINS,$any:q.ANY,$isOneOfArray:q.IS_ONE_OF_ARRAY,$dropdownItemStartsWith:q.DROPDOWN_ITEM_STARTS_WITH,$within:q.WITHIN};function D(e){return Array.isArray(e)?e.length>0&&"object"==typeof e[0]&&"field"in e[0]&&"operator"in e[0]&&"values"in e[0]?e:(console.warn("Legacy Record<string, unknown>[] filter format detected. Please migrate to the new filter format."),[]):k(e)}function k(e){const t=[];return Object.entries(e).forEach(([e,r])=>{"object"!=typeof r||Array.isArray(r)||null===r?t.push({field:e,operator:q.EQUALS,values:[r]}):Object.entries(r).forEach(([r,s])=>{const i=S[r];if(!i)throw new Error(`Unsupported operator: ${r}`);let n;n=i===q.BETWEEN&&Array.isArray(s)&&2===s.length?s:i!==q.IN&&i!==q.NOT_IN&&i!==q.IS_ONE_OF_ARRAY||!Array.isArray(s)?i===q.IS_NULL||i===q.IS_NOT_NULL||i===q.IS_EMPTY?[]:[s]:s,t.push({field:e,operator:i,values:n})})}),t}class M{constructor(){this.filters=[]}equals(e,t){return this.filters.push({field:e,operator:q.EQUALS,values:[t]}),this}notEquals(e,t){return this.filters.push({field:e,operator:q.NOT_EQUALS,values:[t]}),this}greaterThan(e,t){return this.filters.push({field:e,operator:q.GREATER_THAN,values:[t]}),this}lessThan(e,t){return this.filters.push({field:e,operator:q.LESS_THAN,values:[t]}),this}between(e,t,r){return this.filters.push({field:e,operator:q.BETWEEN,values:[t,r]}),this}in(e,t){return this.filters.push({field:e,operator:q.IN,values:t}),this}like(e,t){return this.filters.push({field:e,operator:q.LIKE,values:[t]}),this}startsWith(e,t){return this.filters.push({field:e,operator:q.STARTS_WITH,values:[t]}),this}isEmpty(e){return this.filters.push({field:e,operator:q.IS_EMPTY,values:[]}),this}isNull(e){return this.filters.push({field:e,operator:q.IS_NULL,values:[]}),this}arrayContains(e,t){return this.filters.push({field:e,operator:q.ARRAY_CONTAINS,values:[t]}),this}build(){return[...this.filters]}clear(){return this.filters=[],this}}function P(e){return{name:e.name,type:e.type,is_nullable:e.is_nullable??!0,is_primary_key:e.is_primary_key??!1,is_unique:e.is_unique??!1,is_indexed:e.is_indexed??!1,is_visible:e.is_visible??!0,is_readonly:e.is_readonly??!1,field_order:e.field_order??1,alignment:e.alignment??"left",timezone:e.timezone??void 0,date_format:e.date_format??void 0,time_format:e.time_format??void 0,decimals:e.decimals??void 0,currency_format:e.currency_format??void 0,selection_source:"dropdown"!==e.type||e.selection_source?e.selection_source??void 0:"provide-static-list",selectable_items:e.selectable_items??void 0,multiple_selections:e.multiple_selections??!1,phone_format:e.phone_format??void 0,vector_dimension:e.vector_dimension??void 0,description:e.description,default_value:e.default_value}}class B{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}async createTable(e,t={}){try{const r=O,s=`${this.baseURL}${r.path}`,i=function(e,t={}){return{name:e.name,description:e.description,fields:e.fields.map(P),is_ai_generated_schema:t.is_ai_generated_schema||!1,is_template:t.is_template||!1}}(e,t);return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:i,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async listTables(e={}){try{const t=C,r=`${this.baseURL}${t.path}`,s=(await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data;return e.fields&&s.data&&(s.data=f(s.data,e.fields)),s}catch(t){return this.formatErrorResponse(t)}}async getTable(e,t={}){try{const r=L,s=`${this.baseURL}${U(r,{table_id:e})}`,i=(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data;return t.fields&&i.data&&(i.data=p(i.data,t.fields)),i}catch(r){return this.formatErrorResponse(r)}}async updateTable(e,t){try{const{fields:r,...s}=t,i=x,n=`${this.baseURL}${U(i,{table_id:e})}`,o=(await this.httpAdapter.request({url:n,method:i.method,headers:this.buildHeaders(),data:s,timeout:this.config.timeout})).data;return r&&o.data&&(o.data=p(o.data,r)),o}catch(r){return this.formatErrorResponse(r)}}async deleteTable(e){try{const t=$,r=`${this.baseURL}${U(t,{table_id:e})}`;return(await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey}}formatErrorResponse(e){var t,r,s;if(this.config.debug&&console.error("Tables API Error:",e),e&&"object"==typeof e&&"response"in e){const i=e;return(null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.error)?i.response.data:{error:{code:"API_ERROR",message:e.message||"Unknown API error",meta:[`Status: ${(null==(s=i.response)?void 0:s.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{error:{code:"CLIENT_ERROR",message:e.message,meta:["Client-side error occurred"]}}:{error:{code:"UNKNOWN_ERROR",message:"An unexpected error occurred",meta:["Unknown error type"]}}}}function H(e){return"error"in e&&void 0!==e.error}function j(e){return"pagination"in e}class Y{constructor(e,t){this.client=e,this.basePath=t}getBasePath(){return this.basePath}async makeRequest(e,t,r,s){const n=`${this.basePath}${t}`;try{let t;switch(e){case"GET":t=await this.client.get(n,{params:null==s?void 0:s.params});break;case"POST":t=await this.client.post(n,r,{params:null==s?void 0:s.params});break;case"PUT":t=await this.client.put(n,r,{params:null==s?void 0:s.params});break;case"PATCH":t=await this.client.patch(n,r,{params:null==s?void 0:s.params});break;case"DELETE":t=await this.client.delete(n,{params:null==s?void 0:s.params})}return t.data}catch(o){return{error:{code:"CLIENT_ERROR",message:i(o),meta:["Request failed"]}}}}buildQueryParams(e={}){var t,r;const s={};return(null==(t=e.fields)?void 0:t.length)&&(s.fields=e.fields.join(",")),(null==(r=e.sort)?void 0:r.length)&&(s.sort=e.sort.map(e=>`${e.field}:${e.order}`).join(",")),void 0!==e.limit&&(s.limit=e.limit),void 0!==e.offset&&(s.offset=e.offset),e.where&&Object.entries(e.where).forEach(([e,t])=>{null!=t&&(s[`where[${e}]`]="object"==typeof t?JSON.stringify(t):t)}),s}handleResponse(e){return"error"in e&&this.client.getConfig().debug&&console.error("API Error:",e.error),e}}class F extends Y{constructor(e){super(e,"/v1/tables");const t=e.getConfig();this.tablesApiClient=new B(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers})}async create(e){try{const r={...e};e.fields&&e.fields.length>0&&(r.fields=await this.processFieldsDefaults(e.fields));const s=await this.tablesApiClient.createTable(r);if(H(s))throw new t(s.error.message||"Create table failed",400,s.error);return s}catch(r){throw r instanceof t?r:new t(this.formatError(r),500)}}async processFieldsDefaults(e){const t=[];for(let r=0;r<e.length;r++){const s={...e[r]};if(void 0===s.is_primary_key&&(s.is_primary_key=!1),void 0===s.is_unique&&(s.is_unique=!1),void 0===s.is_nullable&&(s.is_nullable=!0),void 0===s.is_indexed&&(s.is_indexed=!1),void 0===s.field_order&&(s.field_order=r+1),s.field_order<=0||s.field_order>=2147483647)throw new Error("Field order must be a number greater than 0 and less than 2147483647");t.push(s)}return t}transformTableQueryToApiRequest(e){const t={page:{page_no:1,page_size:e.limit||100},filters:[],sort:[]};if(e.offset&&e.limit){const r=Math.floor(e.offset/e.limit)+1;t.page.page_no=r}return e.where&&Object.entries(e.where).forEach(([e,r])=>{null!=r&&t.filters.push({field:e,operator:"=",values:[r]})}),e.sort&&(t.sort=e.sort.map(e=>({field:e.field,direction:e.order}))),t}async findAll(e={}){try{const r=this.transformTableQueryToApiRequest(e),s=await this.tablesApiClient.listTables(r);if(H(s))throw new t(s.error.message||"List tables failed",400,s.error);return s}catch(r){throw r instanceof t?r:new t(this.formatError(r),500)}}async findOne(r){var s,i,n;try{if(!(null==(s=r.where)?void 0:s.id)&&!(null==(i=r.where)?void 0:i.name))throw new e("Either id or name must be provided in where clause");if(null==(n=r.where)?void 0:n.id){const e=await this.tablesApiClient.getTable(r.where.id);if(H(e)){if("TABLE_NOT_FOUND"===e.error.code)return{data:null,message:"Table not found"};throw new t(e.error.message||"Get table failed",400,e.error)}return e}{const e={page:{page_no:1,page_size:1},filters:[{field:"name",operator:"=",values:[r.where.name]}],sort:[]},s=await this.tablesApiClient.listTables(e);if(H(s))throw new t(s.error.message||"Find table by name failed",400,s.error);const i=j(s)?s.data[0]:null;return{data:i||null,message:i?"Table found":"Table not found"}}}catch(o){throw o instanceof t||o instanceof e?o:new t(this.formatError(o),500)}}async findByName(e){return this.findOne({where:{name:e}})}async findById(e){return this.findOne({where:{id:e}})}async update(e,r){try{const s=await this.findByName(e);if(!s.data)throw new t(`Table '${e}' not found`,404);if(s.data.snapshot_url)throw new t(`Cannot update snapshot table '${e}'. Snapshots are read-only and cannot be modified.`,400);const i=await this.tablesApiClient.updateTable(s.data.id,r);if(H(i))throw new t(i.error.message||"Update table failed",400,i.error);return i}catch(s){throw s instanceof t?s:new t(this.formatError(s),500)}}async delete(e){try{const r=await this.findByName(e);if(!r.data)throw new t(`Table '${e}' not found`,404);if(r.data.snapshot_url)throw new t(`Cannot delete snapshot table '${e}'. Snapshots are read-only and cannot be deleted.`,400);const s=await this.tablesApiClient.deleteTable(r.data.id);if(H(s))throw new t(s.error.message||"Delete table failed",400,s.error);return s}catch(r){throw r instanceof t?r:new t(this.formatError(r),500)}}async rename(e,r){try{return await this.update(e,{name:r})}catch(s){throw s instanceof t?s:new t(this.formatError(s),500)}}async setAccess(e){try{return await this.update(e.table_name,{is_shared:e.is_shared})}catch(r){throw r instanceof t?r:new t(this.formatError(r),500)}}formatError(e){return e instanceof Error?e.message:"string"==typeof e?e:"An unexpected error occurred"}}class K extends Y{constructor(e){super(e,"/v1/tables");const t=e.getConfig();this.columnsApiClient=new N(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers}),this.tablesApiClient=new B(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers})}async create(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.processColumnDefaults(r.id,t),i=await this.columnsApiClient.createColumn(r.id,s);return H(i),i}catch(r){return{error:{code:"CREATE_COLUMN_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async processColumnDefaults(e,t){const r={...t};if(void 0===r.is_primary_key&&(r.is_primary_key=!1),void 0===r.is_unique&&(r.is_unique=!1),void 0===r.is_nullable&&(r.is_nullable=!0),void 0===r.is_indexed&&(r.is_indexed=!1),void 0===r.field_order&&(r.field_order=await this.generateFieldOrder(e)),r.field_order<=0||r.field_order>=2147483647)throw new Error("Field order must be a number greater than 0 and less than 2147483647");return r}async generateFieldOrder(e){try{const t=await this.columnsApiClient.listColumns(e);let r=0;if(!H(t)&&t.data&&Array.isArray(t.data))for(const e of t.data)e.field_order&&e.field_order>r&&(r=e.field_order);return r+1}catch(t){return Math.floor(Date.now()/1e3)%2147483647}}transformColumnQueryToApiRequest(e){const t={page:{page_no:1,page_size:e.limit||100},filters:[],sort:[]};if(e.offset&&e.limit){const r=Math.floor(e.offset/e.limit)+1;t.page.page_no=r}return e.where&&Object.entries(e.where).forEach(([e,r])=>{null!=r&&t.filters.push({field:e,operator:"=",values:[r]})}),e.sort&&(t.sort=e.sort.map(e=>({field:e.field,direction:e.order}))),t}async createMany(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=[];for(const e of t){const t=await this.processColumnDefaults(r.id,e);s.push(t)}const i=await this.columnsApiClient.createColumns(r.id,{columns:s});return H(i),i}catch(r){return{error:{code:"CREATE_COLUMNS_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async findAll(e,t={}){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=this.transformColumnQueryToApiRequest(t),i=await this.columnsApiClient.listColumns(r.id,s);return H(i),i}catch(r){return{error:{code:"LIST_COLUMNS_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async get(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.columnsApiClient.findColumnByName(r.id,t);return H(s)?s:s.data?{data:s.data,message:"Column found successfully"}:{error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table '${e}'`}}}catch(r){return{error:{code:"GET_COLUMN_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async findById(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.columnsApiClient.getColumn(r.id,t);return H(s),s}catch(r){return{error:{code:"FIND_COLUMN_BY_ID_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async update(e,t,r){try{const s=await this.getTableInfo(e);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i=await this.columnsApiClient.updateColumnByName(s.id,t,r);return H(i),i}catch(s){return{error:{code:"UPDATE_COLUMN_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async delete(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.columnsApiClient.deleteColumnByName(r.id,t);return H(s)?s:{data:{success:!0,message:"Column deleted successfully"}}}catch(r){return{error:{code:"DELETE_COLUMN_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async getTableInfo(e){try{const t=new F(this.client),r=await t.findByName(e);return r.data?{id:r.data.id,snapshot_url:r.data.snapshot_url}:null}catch(t){return console.error("Error getting table info:",t),null}}async getTableId(e){const t=await this.getTableInfo(e);return(null==t?void 0:t.id)||null}}const W={path:"/tables/indexes/{table_id}",method:"POST",authenticated:!0},Q={path:"/tables/indexes/{table_id}/list",method:"POST",authenticated:!0},z={path:"/tables/indexes/{table_id}",method:"DELETE",authenticated:!0},G=(e,t={})=>{let r=e.path;Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))});const s=r.match(/\{([^}]+)\}/g);if(s)throw new Error(`Missing path parameters: ${s.join(", ")}`);return r};class V{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}async addIndex(e,t){try{const r=W,s=`${this.baseURL}${G(r,{table_id:e})}`;return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async listIndexes(e,t){try{const r=Q,s=`${this.baseURL}${G(r,{table_id:e})}`;return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async deleteIndex(e,t){try{const r=z,s=`${this.baseURL}${G(r,{table_id:e})}`;return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey}}formatErrorResponse(e){var t,r,s;if(this.config.debug&&console.error("Indexes API Error:",e),e&&"object"==typeof e&&"response"in e){const i=e;return(null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.error)?i.response.data:{error:{code:"API_ERROR",message:e.message||"Unknown API error",meta:[`Status: ${(null==(s=i.response)?void 0:s.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{error:{code:"CLIENT_ERROR",message:e.message,meta:["Client-side error occurred"]}}:{error:{code:"UNKNOWN_ERROR",message:"An unexpected error occurred",meta:["Unknown error type"]}}}}class J{constructor(e){this.client=e;const t=e.getConfig();this.apiClient=new V(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers}),this.tableResource=new F(e)}async resolveTableId(e){const t=await this.tableResource.findByName(e);if(!t.data)throw new Error(`Table not found: ${e}`);return t.data.id}async addIndex(e,t){try{const r=await this.resolveTableId(e);return await this.apiClient.addIndex(r,t)}catch(r){return{error:{code:"CLIENT_ERROR",message:(null==r?void 0:r.message)||"Failed to add index",meta:["IndexResource.addIndex"]}}}}async listIndexes(e,t){try{const r=await this.resolveTableId(e);return await this.apiClient.listIndexes(r,t)}catch(r){return{error:{code:"CLIENT_ERROR",message:(null==r?void 0:r.message)||"Failed to list indexes",meta:["IndexResource.listIndexes"]}}}}async deleteIndex(e,t){try{const r=await this.resolveTableId(e),s={index_name:t};return await this.apiClient.deleteIndex(r,s)}catch(r){return{error:{code:"CLIENT_ERROR",message:(null==r?void 0:r.message)||"Failed to delete index",meta:["IndexResource.deleteIndex"]}}}}}const Z={path:"/tables/{table_id}/records",method:"POST",authenticated:!0},X={path:"/tables/{table_id}/records/bulk-insert",method:"POST",authenticated:!0},ee={path:"/tables/{table_id}/records/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},te={path:"/tables/{table_id}/records/{record_id}",method:"GET",authenticated:!0,rateLimit:{requests:200,window:6e4}},re={path:"/tables/{table_id}/records",method:"PATCH",authenticated:!0},se={path:"/tables/{table_id}/records/{record_id}",method:"PATCH",authenticated:!0},ie={path:"/tables/{table_id}/records/list",method:"DELETE",authenticated:!0},ne=(e,t={})=>{let r=e.path;Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))});const s=r.match(/\{([^}]+)\}/g);if(s)throw new Error(`Missing path parameters: ${s.join(", ")}`);return r};class oe{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}async insertRecord(e){try{const{table_id:t,fields:r,...s}=e;if(!t)return this.formatErrorResponse(new Error("table_id is required for insert operation"));const i=Z,n=`${this.baseURL}${ne(i,{table_id:t})}`,o=(await this.httpAdapter.request({url:n,method:i.method,headers:this.buildHeaders(),data:s,timeout:this.config.timeout})).data;return r&&o.data&&(o.data=p(o.data,r)),o}catch(t){return this.formatErrorResponse(t)}}async insertManyRecords(e,t,r={validation:!0}){try{if(!t)return this.formatErrorResponse(new Error("table_id is required for bulk insert operation"));if(!e||!Array.isArray(e)||0===e.length)return this.formatErrorResponse(new Error("records array is required and cannot be empty"));const s=X;let i=`${this.baseURL}${ne(s,{table_id:t})}`;const n=new URLSearchParams;void 0!==r.validation&&n.append("validation",r.validation.toString()),n.toString()&&(i+=`?${n.toString()}`);return(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data}catch(s){return this.formatErrorResponse(s)}}async getRecord(e,t,r={}){try{if(!t)return this.formatErrorResponse(new Error("table_id is required for get operation"));const s=te,i=`${this.baseURL}${ne(s,{table_id:t,record_id:e})}`,n=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data;return r.fields&&n.data&&(n.data=p(n.data,r.fields)),n}catch(s){return this.formatErrorResponse(s)}}async listRecords(e={}){try{const{table_id:t,...r}=e;if(!t)return this.formatErrorResponse(new Error("table_id is required for list operation"));const s=ee,i=`${this.baseURL}${ne(s,{table_id:t})}`,n=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:r,timeout:this.config.timeout})).data;return r.fields&&n.data&&(n.data=f(n.data,r.fields)),n}catch(t){return this.formatErrorResponse(t)}}async updateRecords(e){try{const{table_id:t,...r}=e;if(!t)return this.formatErrorResponse(new Error("table_id is required for update operation"));const s=re,i=`${this.baseURL}${ne(s,{table_id:t})}`,n=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:r,timeout:this.config.timeout})).data;return r.fields&&n.data&&(n.data=f(n.data,r.fields)),n}catch(t){return this.formatErrorResponse(t)}}async updateRecordById(e,t){try{const{table_id:r,...s}=t;if(!r)return this.formatErrorResponse(new Error("table_id is required for updateById operation"));const i=se,n=`${this.baseURL}${ne(i,{record_id:e,table_id:r})}`,o=(await this.httpAdapter.request({url:n,method:i.method,headers:this.buildHeaders(),data:s.set,timeout:this.config.timeout})).data;return s.fields&&o.data&&(o.data=p(o.data,s.fields)),o}catch(r){return this.formatErrorResponse(r)}}async deleteRecords(e){try{const{table_id:t}=e;if(!t)return this.formatErrorResponse(new Error("table_id is required for delete operation"));const r=function(e){const t={};return e.record_ids&&e.record_ids.length>0&&(t.record_ids=e.record_ids),e.filters&&(Array.isArray(e.filters)?(e.filters.length>0&&"object"==typeof e.filters[0]&&"field"in e.filters[0]&&"operator"in e.filters[0]&&"values"in e.filters[0]||console.warn("Legacy Record<string, unknown>[] filter format detected. Please migrate to the new filter format."),t.filters=e.filters):t.filters=k(e.filters)),t}(e),s=ie,i=`${this.baseURL}${ne(s,{table_id:t})}`;return(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:r,timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}async deleteRecordById(e,t){return this.deleteRecords({record_ids:[e],table_id:t.table_id})}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey}}formatErrorResponse(e){var t,r,s;if(this.config.debug&&console.error("Records API Error:",e),e&&"object"==typeof e&&"response"in e){const i=e;return(null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.error)?i.response.data:{error:{code:"API_ERROR",message:e.message||"Unknown API error",meta:[`Status: ${(null==(s=i.response)?void 0:s.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{error:{code:"CLIENT_ERROR",message:e.message,meta:["Client-side error occurred"]}}:{error:{code:"UNKNOWN_ERROR",message:"An unexpected error occurred",meta:["Unknown error type"]}}}}class ae{constructor(e){this.client=e,this.apiClient=new oe(e.getConfig().apiKey,{environment:e.getConfig().environment,region:e.getConfig().region,timeout:e.getConfig().timeout,debug:e.getConfig().debug}),this.tablesApiClient=new B(e.getConfig().apiKey,{environment:e.getConfig().environment,region:e.getConfig().region,timeout:e.getConfig().timeout,debug:e.getConfig().debug})}async insert(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.ensureCompleteRecordData(e,t);if("error"in s&&s.error)return s;const i={...s,table_id:r.id},n=await this.apiClient.insertRecord(i);return H(n),n}catch(r){return{error:{code:"INSERT_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async insertMany(e,t,r={validation:!0}){try{if(!t||!Array.isArray(t)||0===t.length)return{error:{code:"INVALID_INPUT",message:"Records array is required and cannot be empty"}};const s=await this.getTableInfo(e);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i=await this.apiClient.insertManyRecords(t,s.id,r);return H(i),i}catch(s){return{error:{code:"INSERT_MANY_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async get(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.apiClient.getRecord(t,r.id);return H(s),s}catch(r){return{error:{code:"GET_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async list(e,t={}){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s={...t,table_id:r.id},i=await this.apiClient.listRecords(s);return H(i),i}catch(r){return{error:{code:"LIST_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async update(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s={...t,table_id:r.id},i=await this.apiClient.updateRecords(s);return H(i),i}catch(r){return{error:{code:"UPDATE_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async updateById(e,t,r){try{const s=await this.getTableInfo(e);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const i={id:t,set:r,table_id:s.id},n=await this.apiClient.updateRecordById(t,i);return H(n),n}catch(s){return{error:{code:"UPDATE_BY_ID_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async delete(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s={...t,table_id:r.id},i=await this.apiClient.deleteRecords(s);return H(i),i}catch(r){return{error:{code:"DELETE_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async deleteById(e,t){try{const r=await this.getTableInfo(e);if(!r)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const s=await this.apiClient.deleteRecordById(t,{table_id:r.id});return H(s),s}catch(r){return{error:{code:"DELETE_BY_ID_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}async getTableInfo(e){try{const t=new F(this.client),r=await t.findByName(e);return r.data?{id:r.data.id,snapshot_url:r.data.snapshot_url}:null}catch(t){return console.error("Error getting table info:",t),null}}async ensureCompleteRecordData(e,t){try{const r=new K(this.client),s=await r.findAll(e);if(H(s))return s;const i=Array.isArray(s.data)?s.data:[],n={...t};for(const e of i)"id"!==e.name&&"created_at"!==e.name&&"updated_at"!==e.name&&(e.name in t||(n[e.name]=null));return n}catch(r){return{error:{code:"COMPLETE_DATA_ERROR",message:r instanceof Error?r.message:"Unknown error occurred"}}}}}class de{constructor(e){this.queryOptions={},this.updateData={},this.tableName=e.tableName,this.recordResource=e.recordResource}where(e){return this.queryOptions.filters||(this.queryOptions.filters=[]),Object.entries(e).forEach(([e,t])=>{this.queryOptions.filters.push({field:e,operator:"equals",values:[t]})}),this}orderBy(e,t="asc"){return this.queryOptions.sort||(this.queryOptions.sort=[]),this.queryOptions.sort.push({field:e,order:t}),this}limit(e){return this.queryOptions.page?this.queryOptions.page.page_size=e:this.queryOptions.page={page_no:1,page_size:e},this}offset(e){if(this.queryOptions.page){const t=this.queryOptions.page.page_size||50;this.queryOptions.page.page_no=Math.floor(e/t)+1}else this.queryOptions.page={page_no:Math.floor(e/50)+1,page_size:50};return this}select(e){return this.queryOptions.fields=e,this}set(e){return this.updateData={...this.updateData,...e},this}page(e,t=50){return this.queryOptions.page={page_no:e,page_size:t},this}async list(){return this.recordResource.list(this.tableName,this.queryOptions)}async findAll(){return this.recordResource.list(this.tableName,this.queryOptions)}async findOne(){const e={...this.queryOptions,limit:1},t=await this.recordResource.list(this.tableName,e);if("error"in t)return t;const r=t.data.length>0?t.data[0]:null;return{data:r,message:r?"Record found":"No record found"}}buildWhereConditions(){const e={};return this.queryOptions.filters&&this.queryOptions.filters.forEach(t=>{if("field"in t&&"values"in t){const r=t,s=String(r.field);"equals"===r.operator?e[s]=r.values[0]:"contains"===r.operator?e[s]={$like:`%${String(r.values[0])}%`}:e[s]=r.values[0]}else Object.assign(e,t)}),e}async update(){if(!this.updateData)return{error:{code:"MISSING_UPDATE_DATA",message:"Update data is required for update operation"}};const e={set:this.updateData,filters:this.queryOptions.filters||[]};return this.recordResource.update(this.tableName,e)}async updateById(e){return this.recordResource.updateById(this.tableName,e,this.updateData)}async deleteById(e){return this.recordResource.deleteById(this.tableName,e)}async deleteByIds(e){return this.recordResource.delete(this.tableName,{record_ids:e})}async delete(){if(!this.queryOptions.filters||0===this.queryOptions.filters.length)return{error:{code:"MISSING_DELETE_CONDITIONS",message:"Filter conditions are required for delete operation. Use where() to specify conditions."}};const e={filters:this.buildWhereConditions()};return this.recordResource.delete(this.tableName,e)}getQueryOptions(){return{...this.queryOptions}}getUpdateData(){return{...this.updateData}}async insert(e){return this.recordResource.insert(this.tableName,e)}}function le(e){return new de(e)}const ue={path:"/tables/query/text-to-sql",method:"POST",authenticated:!0,rateLimit:{requests:100,window:6e4}},ce={path:"/tables/query/execute",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},he=(e,t={})=>{let r=e.path;return Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))}),r};class me{constructor(e,t={}){this.config={apiKey:e,...t},this.httpAdapter=d();const r=t.environment||"prod",s=t.region||"asia-south1";this.baseURL=this.getBaseURL(r,s)}getBaseURL(e,t){const r=c[t];if(!r)throw new Error(`Unsupported region: ${t}`);const s=r[e];if(!s)throw new Error(`Unsupported environment: ${e} for region: ${t}`);return`${s.baseURL}/v1`}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey,...this.config.headers}}formatErrorResponse(e,t="API"){var r,s,i;if(this.config.debug&&console.error(`${t} Error:`,e),e&&"object"==typeof e&&"response"in e){const n=e;return(null==(s=null==(r=n.response)?void 0:r.data)?void 0:s.error)?n.response.data:{error:{code:`${t}_ERROR`,message:e.message||`Unknown ${t} error`,meta:[`Status: ${(null==(i=n.response)?void 0:i.status)||"unknown"}`]}}}return e&&"object"==typeof e&&"message"in e?{error:{code:`${t}_CLIENT_ERROR`,message:e.message,meta:[`${t} client-side error occurred`]}}:{error:{code:`${t}_UNKNOWN_ERROR`,message:`An unexpected ${t} error occurred`,meta:[`Unknown ${t} error type`]}}}toString(){return`${this.constructor.name} { environment: "${this.config.environment||"prod"}", debug: ${this.config.debug||!1} }`}toJSON(){const e={...this.config};return delete e.apiKey,{client:this.constructor.name,config:e}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}class pe extends me{constructor(e,t={}){super(e,t)}async textToSQL(e){try{const t=ue,r=`${this.baseURL}${he(t)}`,s=await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout});if(s.status>=400)return this.formatErrorResponse({response:{data:s.data,status:s.status}},"SQL");const i=s.data;return this.createAsyncIterable(i.data)}catch(t){return this.formatErrorResponse(t,"SQL")}}async executeSQL(e){try{const t=ce,r=`${this.baseURL}${he(t)}`,s=await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout});return s.status>=400?this.formatErrorResponse({response:{data:s.data,status:s.status}},"SQL"):s.data}catch(t){return this.formatErrorResponse(t,"SQL")}}async*createAsyncIterable(e){yield e}}class fe{constructor(e){const t=e.getConfig();this.sqlApiClient=new pe(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug,retryAttempts:t.retryAttempts,retryDelay:t.retryDelay,headers:t.headers})}async textToSQL(e,t={}){const r=function(e,t={}){return{prompt:e,current_query:t.currentQuery}}(e,t),s=await this.sqlApiClient.textToSQL(r);if("error"in s&&void 0!==s.error)throw s;return s}async executeSQL(e){const t=await this.sqlApiClient.executeSQL({query:e});return H(t),t}}class ge{constructor(e,t){this.isPublic=!1,this.fields=[],this.tableName=e.name,this.description=e.description,this.tablesApiClient=t}name(e){return this.tableName=e,this}describe(e){return this.description=e,this}public(e=!0){return this.isPublic=e,this}text(e,t={}){return this.fields.push({name:e,type:"text",is_nullable:t.nullable??!0,is_unique:t.unique??!1,is_indexed:t.indexed??!1,is_primary_key:!1,default_value:t.defaultValue,description:t.description,alignment:t.alignment||"left",field_order:this.fields.length+1}),this}longText(e,t={}){return this.fields.push({name:e,type:"long-text",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,alignment:t.alignment||"left",field_order:this.fields.length+1}),this}number(e,t={}){return this.fields.push({name:e,type:"number",is_nullable:t.nullable??!0,is_unique:t.unique??!1,is_indexed:t.indexed??!1,is_primary_key:!1,default_value:t.defaultValue,description:t.description,decimals:t.decimals,alignment:t.alignment||"right",field_order:this.fields.length+1}),this}currency(e,t={}){return this.fields.push({name:e,type:"currency",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,default_value:t.defaultValue,description:t.description,currency_format:t.currencyFormat,decimals:t.decimals,alignment:"right",field_order:this.fields.length+1}),this}checkbox(e,t={}){return this.fields.push({name:e,type:"checkbox",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,default_value:t.defaultValue,description:t.description,alignment:"center",field_order:this.fields.length+1}),this}dropdown(e,t,r={}){return this.fields.push({name:e,type:"dropdown",is_nullable:r.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,default_value:r.defaultValue,description:r.description,selection_source:"provide-static-list",selectable_items:t,multiple_selections:r.multiple??!1,alignment:"left",field_order:this.fields.length+1}),this}email(e,t={}){return this.fields.push({name:e,type:"email",is_nullable:t.nullable??!0,is_unique:t.unique??!1,is_indexed:t.indexed??!1,is_primary_key:!1,description:t.description,alignment:"left",field_order:this.fields.length+1}),this}phone(e,t={}){return this.fields.push({name:e,type:"phone-number",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,phone_format:t.format,alignment:"left",field_order:this.fields.length+1}),this}link(e,t={}){return this.fields.push({name:e,type:"link",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,alignment:"left",field_order:this.fields.length+1}),this}json(e,t={}){return this.fields.push({name:e,type:"json",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,alignment:"left",field_order:this.fields.length+1}),this}dateTime(e,t={}){return this.fields.push({name:e,type:"date-time",is_nullable:t.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:t.description,date_format:t.dateFormat,time_format:t.timeFormat,timezone:t.timezone,alignment:"left",field_order:this.fields.length+1}),this}vector(e,t,r={}){return this.fields.push({name:e,type:"vector",is_nullable:r.nullable??!0,is_unique:!1,is_indexed:!1,is_primary_key:!1,description:r.description,vector_dimension:t,alignment:"left",field_order:this.fields.length+1}),this}addField(e){return this.fields.push({...e,field_order:e.field_order||this.fields.length+1}),this}removeField(e){return this.fields=this.fields.filter(t=>t.name!==e),this.fields.forEach((e,t)=>{e.field_order=t+1}),this}getFields(){return[...this.fields]}getName(){return this.tableName}getDescription(){return this.description}build(){if(!this.tableName)throw new e("Table name is required",[{field:"name",message:"Table name cannot be empty"}]);if(0===this.fields.length)throw new e("At least one field is required",[{field:"fields",message:"Table must have at least one field"}]);return{name:this.tableName,description:this.description,fields:this.fields}}async create(e={}){if(!this.tablesApiClient)throw new Error("TablesApiClient is required for table creation");const t=this.build();return this.tablesApiClient.createTable(t,e)}}function _e(e,t){return new ge(e,t)}class be{constructor(e,t={}){this.currentDatabase=null,this.clientOptions=t,this.configManager=new m(e,t.environment||"prod",t.region||"asia-south1",t);const r=this.configManager.getConfig();this.authManager=new n({apiKey:r.apiKey,maxRetries:r.maxRetries}),this.baseClient=new u(r,this.authManager),this.tableResource=new F(this.baseClient),this.columnResource=new K(this.baseClient),this.recordResource=new ae(this.baseClient),this.sqlResource=new fe(this.baseClient),this.indexResource=new J(this.baseClient),this.currentDatabase={databaseName:"Default"}}getCurrentDatabase(){return this.currentDatabase}get tables(){return{create:e=>this.tableResource.create(e),findAll:e=>this.tableResource.findAll(e),findById:e=>this.tableResource.findById(e),findByName:e=>this.tableResource.findByName(e),findOne:e=>this.tableResource.findOne(e),update:(e,t)=>this.tableResource.update(e,t),delete:e=>this.tableResource.delete(e),rename:(e,t)=>this.tableResource.rename(e,t),setAccess:e=>this.tableResource.setAccess(e)}}get columns(){return{create:(e,t)=>this.columnResource.create(e,t),createMany:(e,t)=>this.columnResource.createMany(e,t),findAll:(e,t)=>this.columnResource.findAll(e,t),findOne:(e,t)=>this.columnResource.get(e,t),findById:(e,t)=>this.columnResource.findById(e,t),update:(e,t,r)=>this.columnResource.update(e,t,r),delete:(e,t)=>this.columnResource.delete(e,t)}}get indexes(){return{addIndex:(e,t)=>this.indexResource.addIndex(e,t),listIndexes:(e,t)=>this.indexResource.listIndexes(e,t),deleteIndex:(e,t)=>this.indexResource.deleteIndex(e,t)}}table(e){return _e({name:e})}from(e){return{columns:()=>({create:t=>this.columnResource.create(e,t),findAll:t=>this.columnResource.findAll(e,t),get:t=>this.columnResource.get(e,t),update:(t,r)=>this.columnResource.update(e,t,r),delete:t=>this.columnResource.delete(e,t)}),records:()=>({insert:t=>this.recordResource.insert(e,t),insertMany:(t,r)=>this.recordResource.insertMany(e,t,r),findOne:t=>this.recordResource.get(e,t),update:t=>this.recordResource.update(e,t),updateById:(t,r)=>this.recordResource.updateById(e,t,r),delete:t=>this.recordResource.delete(e,t),deleteById:t=>this.recordResource.deleteById(e,t)}),record:()=>le({tableName:e,recordResource:this.recordResource}),indexes:()=>({addIndex:t=>this.indexResource.addIndex(e,t),listIndexes:t=>this.indexResource.listIndexes(e,t),deleteIndex:t=>this.indexResource.deleteIndex(e,t)})}}get records(){return{insert:(e,t)=>this.recordResource.insert(e,t),insertMany:(e,t,r)=>this.recordResource.insertMany(e,t,r),findAll:(e,t)=>this.recordResource.list(e,t),findOne:(e,t)=>this.recordResource.get(e,t),update:(e,t)=>this.recordResource.update(e,t),updateById:(e,t,r)=>this.recordResource.updateById(e,t,r),delete:(e,t)=>this.recordResource.delete(e,t),deleteById:(e,t)=>this.recordResource.deleteById(e,t)}}record(e){return le({tableName:e,recordResource:this.recordResource})}get sql(){return{textToSQL:(e,t)=>this.sqlResource.textToSQL(e,t),executeSQL:e=>this.sqlResource.executeSQL(e)}}getSqlResource(){return this.sqlResource}updateApiKey(e){this.configManager.updateConfig({apiKey:e}),this.authManager.updateApiKey(e)}updateConfig(e){this.configManager.updateConfig(e),this.baseClient.updateConfig(this.configManager.getConfig()),this.updateAllResourcesConfig()}getConfig(){return this.configManager.getConfig()}async validateApiKey(){return this.authManager.validateApiKeyAsync()}isAuthenticated(){return this.authManager.isAuthenticated()}getHttpClient(){return this.baseClient}addRequestInterceptor(e){return this.baseClient.getInterceptors().request.use(e)}addResponseInterceptor(e,t){return this.baseClient.getInterceptors().response.use(e,t)}ejectRequestInterceptor(e){this.baseClient.getInterceptors().request.eject(e)}ejectResponseInterceptor(e){this.baseClient.getInterceptors().response.eject(e)}async testConnection(){try{return await this.authManager.validateApiKeyAsync()}catch(e){return!1}}getVersion(){return"1.0.0"}getEnvironment(){return this.configManager.getConfig().environment}getRegion(){return this.configManager.getConfig().region}enableDebug(){this.configManager.updateConfig({debug:!0}),this.baseClient.updateConfig(this.configManager.getConfig()),this.updateAllResourcesConfig()}disableDebug(){this.configManager.updateConfig({debug:!1}),this.baseClient.updateConfig(this.configManager.getConfig()),this.updateAllResourcesConfig()}isDebugEnabled(){return this.configManager.getConfig().debug||!1}updateAllResourcesConfig(){this.tableResource=new F(this.baseClient),this.columnResource=new K(this.baseClient),this.recordResource=new ae(this.baseClient),this.sqlResource=new fe(this.baseClient),this.indexResource=new J(this.baseClient)}toString(){const e=this.getConfig();return`BolticClient { environment: "${e.environment}", region: "${e.region}", debug: ${e.debug} }`}toJSON(){const e=this.getConfig();return{environment:e.environment,region:e.region,debug:e.debug,timeout:e.timeout,version:this.getVersion()}}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}exports.ApiError=t,exports.BolticClient=be,exports.ENV_CONFIGS=h,exports.FILTER_OPERATORS=q,exports.FilterBuilder=M,exports.REGION_CONFIGS=c,exports.SqlResource=fe,exports.ValidationError=e,exports.buildApiFilters=function(e,t="AND"){const r=D(e);return r.forEach((e,t)=>{if(!e.field)throw new Error(`Filter at index ${t} missing required field`);if(!e.operator)throw new Error(`Filter at index ${t} missing required operator`);if(!Array.isArray(e.values))throw new Error(`Filter at index ${t} values must be an array`)}),{filters:r,whereOperator:t}},exports.createErrorResponse=function(e,t){return{error:e,details:t}},exports.createErrorWithContext=r,exports.createFilter=function(){return new M},exports.createMockResponse=function(e,t){return{data:e,pagination:t}},exports.createRecordBuilder=le,exports.createTableBuilder=_e,exports.createTestClient=function(e={}){return new be(e.apiKey||"test-api-key-12345",{environment:"local",region:"asia-south1",debug:e.debug??!0,timeout:3e4,...e})},exports.formatError=i,exports.getHttpStatusCode=s,exports.isErrorResponse=H,exports.isListResponse=j,exports.isNetworkError=function(e){return e instanceof Error&&(e.message.includes("network")||e.message.includes("fetch")||e.message.includes("timeout")||"AbortError"===e.name)},exports.mapFiltersToWhere=function(e){const t={};return e.forEach(e=>{const r={};Object.entries(S).forEach(([e,t])=>{r[t]=e});const s=r[e.operator];if(!s)throw new Error(`Unsupported API operator: ${e.operator}`);t[e.field]||(t[e.field]={});const i=t[e.field];"$between"===s&&2===e.values.length?i[s]=e.values:i[s]="$in"===s||"$notIn"===s||"$isOneOfArray"===s?e.values:"$isNull"===s||"$isNotNull"===s||"$isEmpty"===s||e.values[0]}),t},exports.mapWhereToFilters=k,exports.normalizeFilters=D;
2
- //# sourceMappingURL=test-client-DfOmma3t.js.map