@boltic/sdk 0.1.4 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/databases/index.d.ts +82 -0
- package/dist/databases/index.js +1 -1
- package/dist/databases/index.mjs +1 -1
- package/dist/databases/test-client-DzMli6cH.js +2 -0
- package/dist/databases/test-client-DzMli6cH.js.map +1 -0
- package/dist/databases/test-client-rR_4EBUe.mjs +2 -0
- package/dist/databases/test-client-rR_4EBUe.mjs.map +1 -0
- package/dist/databases/testing.d.ts +82 -0
- package/dist/databases/testing.js +1 -1
- package/dist/databases/testing.mjs +1 -1
- package/dist/sdk.js +559 -22
- package/dist/sdk.js.map +1 -1
- package/dist/sdk.mjs +559 -22
- package/dist/sdk.mjs.map +1 -1
- package/dist/types/index.d.ts +271 -0
- package/package.json +1 -1
- package/dist/databases/test-client-BEAX5vfC.mjs +0 -2
- package/dist/databases/test-client-BEAX5vfC.mjs.map +0 -1
- package/dist/databases/test-client-BgkvBtst.js +0 -2
- package/dist/databases/test-client-BgkvBtst.js.map +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const e={"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}}},t=e["asia-south1"],r={"asia-south1":{local:{host:"http://localhost:8000",timeout:3e4,debug:!0},sit:{host:"https://asia-south1.api.fcz0.de",timeout:15e3},uat:{host:"https://asia-south1.api.uat.fcz0.de",timeout:15e3},prod:{host:"https://asia-south1.api.boltic.io",timeout:1e4}},"us-central1":{local:{host:"http://localhost:8000",timeout:3e4,debug:!0},sit:{host:"https://us-central1.api.fcz0.de",timeout:15e3},uat:{host:"https://us-central1.api.uat.fcz0.de",timeout:15e3},prod:{host:"https://us-central1.api.boltic.io",timeout:1e4}}};function s(e,t,s){const i=r[e];if(!i)throw new Error(`Unsupported region: ${e}`);const a=i[t];if(!a)throw new Error(`Unsupported environment: ${t} for region: ${e}`);return`${a.host}${s}`}function i(e){return"error"in e&&void 0!==e.error}function a(e){return"pagination"in e}class n extends Error{constructor(e,t=[]){super(e),this.name="ValidationError",this.failures=t}}class o extends Error{constructor(e,t,r){super(e),this.name="ApiError",this.statusCode=t,this.response=r}}function d(e,t){const r=new Error(e);return t&&(r.context=t),r}function l(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 u(e){if(e instanceof Error){const t=e.context,r=l(e);let s=`${e.name}: ${e.message}`;return r&&(s+=` (HTTP ${r})`),t&&(s+=`\nContext: ${JSON.stringify(t,null,2)}`),s}return String(e)}class c{constructor(){try{this.axios=require("axios")}catch(e){throw d("Axios is required for Node.js < 18. Please install axios: npm install axios",{error:e})}}async request(e){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);if(r.status<200||r.status>=300){if("string"==typeof r.data&&r.data.trim().startsWith("<!DOCTYPE")||"string"==typeof r.data&&r.data.includes("<html")){const t=r.data.match(/<pre>(.*?)<\/pre>/s);throw d(t?t[1].trim():`HTTP ${r.status}: ${r.statusText}`,{url:e.url,method:e.method,status:r.status,statusText:r.statusText,isHtmlError:!0})}if(r.data&&"object"==typeof r.data&&"error"in r.data)return{data:r.data,status:r.status,statusText:r.statusText,headers:r.headers||{}};throw d(`HTTP ${r.status}: ${r.statusText}`,{url:e.url,method:e.method,status:r.status,statusText:r.statusText,responseData:r.data})}return{data:r.data,status:r.status,statusText:r.statusText,headers:r.headers||{}}}catch(t){const r=t;if("ECONNABORTED"===r.code||r.message?.includes("timeout"))throw d("Request timeout",{url:e.url,method:e.method,timeout:e.timeout});if("ERR_NETWORK"===r.code||"ENOTFOUND"===r.code||"ECONNREFUSED"===r.code||"EHOSTUNREACH"===r.code||"ETIMEDOUT"===r.code||"ERR_INTERNET_DISCONNECTED"===r.code||r.message?.includes("network")||r.message?.includes("internet")||r.message?.includes("connection")||r.message?.includes("resolve"))throw d("Network connection failed. Please check your internet connection or VPN settings.",{url:e.url,method:e.method,networkError:!0,errorCode:r.code,originalMessage:r.message});if("AbortError"===r.name||"ERR_CANCELED"===r.code)throw d("Request was aborted",{url:e.url,method:e.method});throw d(`HTTP request failed: ${r.message||"Unknown error"}`,{url:e.url,method:e.method,originalError:t})}}}class h{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 r={method:e.method,headers:{"Content-Type":"application/json",...e.headers},signal:e.signal};e.data&&["POST","PUT","PATCH","DELETE"].includes(e.method)&&(r.body=JSON.stringify(e.data));try{const s=new AbortController;let i;e.timeout&&(i=setTimeout(()=>s.abort(),e.timeout),r.signal=e.signal?(()=>{const t=new AbortController;return e.signal.addEventListener("abort",()=>t.abort()),s.signal.addEventListener("abort",()=>t.abort()),t.signal})():s.signal);const a=await fetch(t.toString(),r);i&&clearTimeout(i);const n=a.headers.get("content-type");let o;o=n?.includes("application/json")?await a.json():await a.text();const l={};if(a.headers.forEach((e,t)=>{l[t]=e}),a.status<200||a.status>=300){if("string"==typeof o&&(o.trim().startsWith("<!DOCTYPE")||o.includes("<html"))){const t=o.match(/<pre>(.*?)<\/pre>/s);throw d(t?t[1].trim():`HTTP ${a.status}: ${a.statusText}`,{url:e.url,method:e.method,status:a.status,statusText:a.statusText,isHtmlError:!0})}if(o&&"object"==typeof o&&"error"in o)return{data:o,status:a.status,statusText:a.statusText,headers:l};throw d(`HTTP ${a.status}: ${a.statusText}`,{url:e.url,method:e.method,status:a.status,statusText:a.statusText,responseData:o})}return{data:o,status:a.status,statusText:a.statusText,headers:l}}catch(s){if(s instanceof Error&&"AbortError"===s.name)throw d("Request was aborted",{type:"AbortError",url:e.url,method:e.method});if(s instanceof Error){const t=s.message.toLowerCase();if("TypeError"===s.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 d("Network connection failed. Please check your internet connection or VPN settings.",{url:e.url,method:e.method,networkError:!0,originalMessage:s.message})}throw d(`HTTP request failed: ${s instanceof Error?s.message:"Unknown error"}`,{url:e.url,method:e.method,originalError:s})}}}function p(){if("undefined"!=typeof fetch)return new h;try{return new c}catch(e){throw d("No suitable HTTP adapter found. Please use Node.js >= 18 or install axios: npm install axios",{error:e})}}class m{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 d("API key is required and must be a non-empty string",{name:"AuthenticationError",code:"INVALID_API_KEY"});if(e.length<10)throw d("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()}}const f="/service/sdk/boltic-tables/v1",g="/service/panel/temporal/v1.0",_="/service/panel/integration/v1";class b{constructor(e,t={},r=f){this.config={apiKey:e,...t},this.httpAdapter=p(),this.environment=t.environment||"prod",this.region=t.region||"asia-south1",this.baseURL=s(this.region,this.environment,r)}resolveAdditionalServiceURL(e){return s(this.region,this.environment,e)}buildHeaders(){return{"Content-Type":"application/json",Accept:"application/json","x-boltic-token":this.config.apiKey,...this.config.headers}}formatErrorResponse(e,t="API"){if(this.config.debug&&console.error(`[${this.constructor.name}] ${t} Error:`,e),e&&"object"==typeof e&&"response"in e){const r=e;return r.response?.data?.error?r.response.data:{error:{code:`${t}_ERROR`,message:e instanceof Error?e.message:`Unknown ${t} error`,meta:[`Status: ${r.response?.status||"unknown"}`]}}}return e instanceof Error?{error:{code:`${t}_CLIENT_ERROR`,message:e.message,meta:[]}}:{error:{code:`${t}_UNKNOWN_ERROR`,message:`An unexpected ${t} error occurred`,meta:[]}}}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 y{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 Array.from(this.requestInterceptors.values()))t=await r(t);return t}async executeResponseInterceptors(e){let t=e;for(const{fulfilled:r}of Array.from(this.responseInterceptors.values()))r&&(t=await r(t));return t}async executeErrorInterceptors(e){let t=e;for(const{rejected:r}of Array.from(this.responseInterceptors.values()))r&&(t=await r(t));return t}}class w{constructor(e,t){this.config=e,this.authManager=t,this.httpAdapter=p(),this.interceptors=new y,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){if(this.config.debug&&console.error("HTTP Error:",e),e instanceof Error&&e.context)throw e;const t=l(e);if(!t)throw d("Network request failed",{name:"NetworkError",originalError:e});const r=e.response?.data||e.data;throw d(r?.message||r?.error||`HTTP ${t} error`,{name:"ApiError",statusCode:t,response:r,isClientError:t>=400&&t<500,isServerError:t>=500,isAuthError:401===t||403===t,isNotFoundError:404===t,isRateLimitError:429===t})}async request(e){let t;const r=this.config.maxRetries;for(let i=0;i<=r;i++)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),r=await this.httpAdapter.request(t);if(r.status>=400){const e=d(`HTTP ${r.status} error`,{name:"ApiError",statusCode:r.status,response:r.data,statusText:r.statusText});throw await this.interceptors.executeErrorInterceptors(e)}return await this.interceptors.executeResponseInterceptors(r)}catch(s){if(t=s,i===r)break;const e=l(s);if(e&&e>=400&&e<500)break;if(i<r){const e=this.config.retryDelay*Math.pow(2,i);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}}}class E{constructor(e,t){this.client=e,this.basePath=t}getBasePath(){return this.basePath}async makeRequest(e,t,r,s){const i=`${this.basePath}${t}`;try{let t;switch(e){case"GET":t=await this.client.get(i,{params:s?.params});break;case"POST":t=await this.client.post(i,r,{params:s?.params});break;case"PUT":t=await this.client.put(i,r,{params:s?.params});break;case"PATCH":t=await this.client.patch(i,r,{params:s?.params});break;case"DELETE":t=await this.client.delete(i,{params:s?.params})}return t.data}catch(a){return{error:{code:"CLIENT_ERROR",message:u(a),meta:["Request failed"]}}}}buildQueryParams(e={}){const t={};return e.fields?.length&&(t.fields=e.fields.join(",")),e.sort?.length&&(t.sort=e.sort.map(e=>`${e.field}:${e.order}`).join(",")),void 0!==e.limit&&(t.limit=e.limit),void 0!==e.offset&&(t.offset=e.offset),e.where&&Object.entries(e.where).forEach(([e,r])=>{null!=r&&(t[`where[${e}]`]="object"==typeof r?JSON.stringify(r):r)}),t}handleResponse(e){return"error"in e&&this.client.getConfig().debug&&console.error("API Error:",e.error),e}}class R{constructor(t,r="prod",s="asia-south1",i){const a=e[s][r];this.config={apiKey:t,environment:r,region:s,retryAttempts:3,retryDelay:1e3,maxRetries:3,debug:!1,headers:{},...a,...i}}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 T(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 v(e,t){return t&&0!==t.length?e.map(e=>T(e,t)):e}function A(e,t){if(!t||""===t)return e;const r=e.includes("?")?"&":"?";return`${e}${r}db_id=${encodeURIComponent(t)}`}const I={path:"/tables/{table_id}/fields/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},C={path:"/tables/{table_id}/fields",method:"POST",authenticated:!0},x={path:"/tables/{table_id}/fields/{field_id}",method:"GET",authenticated:!0,rateLimit:{requests:300,window:6e4}},O={path:"/tables/{table_id}/fields/{field_id}",method:"PATCH",authenticated:!0},N={path:"/tables/{table_id}/fields/{field_id}",method:"DELETE",authenticated:!0},$=(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},S=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"}),L=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"});var q=(e=>(e.TEXT="text",e.EMAIL="email",e.LONG_TEXT="long-text",e.DATE_TIME="date-time",e.NUMBER="number",e.CURRENCY="currency",e.CHECKBOX="checkbox",e.DROPDOWN="dropdown",e.PHONE_NUMBER="phone-number",e.LINK="link",e.JSON="json",e.VECTOR="vector",e.SPARSEVECTOR="sparsevec",e.HALFVECTOR="halfvec",e.ENCRYPTED="encrypted",e))(q||{});const k={text:["email","long-text","date-time","number","currency","checkbox","phone-number","link","json","vector","sparsevec","halfvec","encrypted"],email:["text","long-text","date-time","number","currency","checkbox","phone-number","link","json","vector","sparsevec","halfvec"],"long-text":["text","email","date-time","number","currency","checkbox","phone-number","link","json","vector","sparsevec","halfvec"],"date-time":["text","email","long-text","phone-number","link"],number:["text","email","long-text","currency","phone-number","link"],currency:["text","email","long-text","number","phone-number","link"],checkbox:["text","email","long-text","phone-number","link"],dropdown:[],"phone-number":["text","email","long-text","date-time","number","currency","checkbox","link","json","vector","sparsevec","halfvec"],link:["text","email","long-text","number","currency","checkbox","phone-number","json","vector","sparsevec","halfvec"],json:["text","email","long-text","phone-number","link"],vector:["text","email","long-text","phone-number","link","halfvec","sparsevec","vector"],sparsevec:["text","email","long-text","phone-number","link","vector","halfvec","sparsevec"],halfvec:["text","email","long-text","phone-number","link","vector","sparsevec","halfvec"],encrypted:[]},D={text:[],email:[],"long-text":[],number:["decimals"],currency:["decimals","currency_format"],checkbox:[],dropdown:["selection_source","selectable_items","multiple_selections"],"date-time":["timezone","date_format","time_format"],"phone-number":["phone_format"],link:[],json:[],vector:["vector_dimension"],sparsevec:["vector_dimension"],halfvec:["vector_dimension"],encrypted:["show_decrypted","is_deterministic"]};function U(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?M(t.date_format):void 0,time_format:t.time_format?H(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,show_decrypted:t.show_decrypted??void 0,is_deterministic:t.is_deterministic??void 0};var t}function M(e){return S[e]||e}function H(e){return L[e]||e}class P extends b{constructor(e,t={}){super(e,t)}async createColumn(e,t){try{const r=C,s=`${this.baseURL}${$(r,{table_id:e})}`,i=U(t),a=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(a.data,null,2)),a.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(i(r))return r;s.push(r.data)}if(t.fields&&s.length>0){const e=v(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=I;let s=`${this.baseURL}${$(r,{table_id:e})}?no_cache=true`;s=A(s,t.db_id);const 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=v(i.data,t.fields)),i}catch(r){return this.formatErrorResponse(r)}}async getColumn(e,t,r={}){try{const s=x,i=`${this.baseURL}${$(s,{table_id:e,field_id:t})}`,a=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(a.data,null,2));const n=a.data;return r.fields&&n.data&&(n.data=T(n.data,r.fields)),n}catch(s){return this.formatErrorResponse(s)}}async updateColumn(e,t,r){try{const s=O,i=`${this.baseURL}${$(s,{table_id:e,field_id:t})}`,a=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.show_decrypted&&(t.show_decrypted=e.show_decrypted),void 0!==e.is_deterministic&&(t.is_deterministic=e.is_deterministic),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=M(e.date_format)),void 0!==e.time_format&&(t.time_format=H(e.time_format)),t}(r),n=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:a,timeout:this.config.timeout})).data;return r.fields&&n.data&&(n.data=T(n.data,r.fields)),n}catch(s){return this.formatErrorResponse(s)}}async deleteColumn(e,t){try{const r=N,s=`${this.baseURL}${$(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(i(s))return s;const a=s.data[0]||null;return{data:a,message:a?"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(i(s))return s;if(!s.data)return{error:{code:"COLUMN_NOT_FOUND",message:`Column '${t}' not found in table`,meta:["404"]}};const a={...this.convertColumnDetailsToUpdateRequest(s.data),...r};return await this.updateColumn(e,s.data.id,a)}catch(s){return this.formatErrorResponse(s)}}async deleteColumnByName(e,t){try{const r=await this.findColumnByName(e,t);return i(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)}}}const B={path:"/tables/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},F={path:"/tables",method:"POST",authenticated:!0},j={path:"/tables/{table_id}",method:"GET",authenticated:!0,rateLimit:{requests:300,window:6e4}},Y={path:"/tables/{table_id}",method:"PATCH",authenticated:!0},K={path:"/tables/{table_id}",method:"DELETE",authenticated:!0},W=(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},z={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"},Q={$eq:z.EQUALS,$ne:z.NOT_EQUALS,$gt:z.GREATER_THAN,$gte:z.GREATER_THAN_EQUAL,$lt:z.LESS_THAN,$lte:z.LESS_THAN_EQUAL,$like:z.LIKE,$ilike:z.ILIKE,$startsWith:z.STARTS_WITH,$in:z.IN,$notIn:z.NOT_IN,$between:z.BETWEEN,$isEmpty:z.IS_EMPTY,$isNull:z.IS_NULL,$isNotNull:z.IS_NOT_NULL,$arrayContains:z.ARRAY_CONTAINS,$arrayNotContains:z.ARRAY_NOT_CONTAINS,$any:z.ANY,$isOneOfArray:z.IS_ONE_OF_ARRAY,$dropdownItemStartsWith:z.DROPDOWN_ITEM_STARTS_WITH,$within:z.WITHIN};function G(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."),[]):V(e)}function V(e){const t=[];return Object.entries(e).forEach(([e,r])=>{"object"!=typeof r||Array.isArray(r)||null===r?t.push({field:e,operator:z.EQUALS,values:[r]}):Object.entries(r).forEach(([r,s])=>{const i=Q[r];if(!i)throw new Error(`Unsupported operator: ${r}`);let a;a=i===z.BETWEEN&&Array.isArray(s)&&2===s.length?s:i!==z.IN&&i!==z.NOT_IN&&i!==z.IS_ONE_OF_ARRAY||!Array.isArray(s)?i===z.IS_NULL||i===z.IS_NOT_NULL||i===z.IS_EMPTY?[]:[s]:s,t.push({field:e,operator:i,values:a})})}),t}class J{constructor(){this.filters=[]}equals(e,t){return this.filters.push({field:e,operator:z.EQUALS,values:[t]}),this}notEquals(e,t){return this.filters.push({field:e,operator:z.NOT_EQUALS,values:[t]}),this}greaterThan(e,t){return this.filters.push({field:e,operator:z.GREATER_THAN,values:[t]}),this}lessThan(e,t){return this.filters.push({field:e,operator:z.LESS_THAN,values:[t]}),this}between(e,t,r){return this.filters.push({field:e,operator:z.BETWEEN,values:[t,r]}),this}in(e,t){return this.filters.push({field:e,operator:z.IN,values:t}),this}like(e,t){return this.filters.push({field:e,operator:z.LIKE,values:[t]}),this}startsWith(e,t){return this.filters.push({field:e,operator:z.STARTS_WITH,values:[t]}),this}isEmpty(e){return this.filters.push({field:e,operator:z.IS_EMPTY,values:[]}),this}isNull(e){return this.filters.push({field:e,operator:z.IS_NULL,values:[]}),this}arrayContains(e,t){return this.filters.push({field:e,operator:z.ARRAY_CONTAINS,values:[t]}),this}build(){return[...this.filters]}clear(){return this.filters=[],this}}function X(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 Z extends b{constructor(e,t={}){super(e,t)}async createTable(e,t={}){try{const r=F;let s=`${this.baseURL}${r.path}`;s=A(s,t.db_id);const i=function(e,t={}){return{name:e.name,description:e.description,fields:e.fields.map(X),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=B;let r=`${this.baseURL}${t.path}`;r=A(r,e.db_id);const 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=v(s.data,e.fields)),s}catch(t){return this.formatErrorResponse(t)}}async getTable(e,t={}){try{const r=j;let s=`${this.baseURL}${W(r,{table_id:e})}`;s=A(s,t.db_id);const 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=T(i.data,t.fields)),i}catch(r){return this.formatErrorResponse(r)}}async updateTable(e,t){try{const{fields:r,db_id:s,...i}=t,a=Y;let n=`${this.baseURL}${W(a,{table_id:e})}`;n=A(n,s);const o=(await this.httpAdapter.request({url:n,method:a.method,headers:this.buildHeaders(),data:i,timeout:this.config.timeout})).data;return r&&o.data&&(o.data=T(o.data,r)),o}catch(r){return this.formatErrorResponse(r)}}async deleteTable(e,t={}){try{const r=K;let s=`${this.baseURL}${W(r,{table_id:e})}`;s=A(s,t.db_id);return(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}}class ee extends E{constructor(e){super(e,"/v1/tables");const t=e.getConfig();this.tablesApiClient=new Z(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={...e};e.fields&&e.fields.length>0&&(r.fields=await this.processFieldsDefaults(e.fields));const s=await this.tablesApiClient.createTable(r,t?{db_id:t}:{});if(i(s))throw new o(s.error.message||"Create table failed",400,s.error);return s}catch(r){throw r instanceof o?r:new o(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),"encrypted"===s.type&&(void 0===s.show_decrypted&&(s.show_decrypted=!1),void 0===s.is_deterministic&&(s.is_deterministic=!1),void 0!==s.default_value&&null!==s.default_value))throw new Error("Encrypted columns do not accept a default value");if(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={},t){try{const r=this.transformTableQueryToApiRequest(e),s=[...r.filters];t&&s.push({field:"db_id",operator:"=",values:[t]});const a=e.where?.resource_id||"boltic";s.push({field:"resource_id",operator:"=",values:[a]});const n={page:r.page,filters:s,sort:r.sort,...e.fields&&{fields:e.fields}},d=await this.tablesApiClient.listTables(n);if(i(d))throw new o(d.error.message||"List tables failed",400,d.error);return d}catch(r){throw r instanceof o?r:new o(this.formatError(r),500)}}async findOne(e,t){try{if(!e.where?.id&&!e.where?.name)throw new n("Either id or name must be provided in where clause");if(e.where?.id){const r=await this.tablesApiClient.getTable(e.where.id,t?{db_id:t}:{});if(i(r)){if("TABLE_NOT_FOUND"===r.error.code)return{data:null,message:"Table not found"};throw new o(r.error.message||"Get table failed",400,r.error)}return r}{const r=[{field:"name",operator:"=",values:[e.where.name]}];t&&r.push({field:"db_id",operator:"=",values:[t]});const s=e.where?.resource_id||"boltic";r.push({field:"resource_id",operator:"=",values:[s]});const n={page:{page_no:1,page_size:1},filters:r,sort:[]},d=await this.tablesApiClient.listTables(n);if(i(d))throw new o(d.error.message||"Find table by name failed",400,d.error);const l=a(d)?d.data[0]:null;return{data:l||null,message:l?"Table found":"Table not found"}}}catch(r){throw r instanceof o||r instanceof n?r:new o(this.formatError(r),500)}}async findByName(e,t){return this.findOne({where:{name:e}},t)}async findById(e,t){return this.findOne({where:{id:e}},t)}async update(e,t,r){try{const s=await this.findByName(e,r);if(!s.data)throw new o(`Table '${e}' not found`,404);if(s.data.snapshot_url)throw new o(`Cannot update snapshot table '${e}'. Snapshots are read-only and cannot be modified.`,400);const a=await this.tablesApiClient.updateTable(s.data.id,r?{...t,db_id:r}:t);if(i(a))throw new o(a.error.message||"Update table failed",400,a.error);return a}catch(s){throw s instanceof o?s:new o(this.formatError(s),500)}}async delete(e,t){try{const r=await this.findByName(e,t);if(!r.data)throw new o(`Table '${e}' not found`,404);if(r.data.snapshot_url)throw new o(`Cannot delete snapshot table '${e}'. Snapshots are read-only and cannot be deleted.`,400);const s=await this.tablesApiClient.deleteTable(r.data.id,t?{db_id:t}:{});if(i(s))throw new o(s.error.message||"Delete table failed",400,s.error);return s}catch(r){throw r instanceof o?r:new o(this.formatError(r),500)}}async rename(e,t,r){try{return await this.update(e,{name:t},r)}catch(s){throw s instanceof o?s:new o(this.formatError(s),500)}}formatError(e){return e instanceof Error?e.message:"string"==typeof e?e:"An unexpected error occurred"}}class te extends E{constructor(e){super(e,"/v1/tables");const t=e.getConfig();this.columnsApiClient=new P(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 Z(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),a=await this.columnsApiClient.createColumn(r.id,s);return i(a),a}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),"encrypted"===r.type&&(void 0===r.show_decrypted&&(r.show_decrypted=!1),void 0===r.is_deterministic&&(r.is_deterministic=!1),void 0!==r.default_value&&null!==r.default_value))throw new Error("Encrypted columns do not accept a default value");if(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(!i(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 a=await this.columnsApiClient.createColumns(r.id,{columns:s});return i(a),a}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),a=await this.columnsApiClient.listColumns(r.id,s);return i(a),a}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 i(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 i(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 a=await this.columnsApiClient.updateColumnByName(s.id,t,r);return i(a),a}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 i(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 ee(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 t?.id||null}}const re={path:"/tables/databases",method:"POST",authenticated:!0},se={path:"/tables/databases/list",method:"POST",authenticated:!0},ie={path:"/tables/databases/{db_id}",method:"PATCH",authenticated:!0},ae={path:"/tables/databases/{db_id}",method:"DELETE",authenticated:!0},ne={path:"/tables/databases/jobs/list",method:"POST",authenticated:!0},oe={path:"/tables/databases/delete-status/{job_id}",method:"GET",authenticated:!0},de=(e,t={})=>{let r=e.path;return Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,t)}),r};class le extends b{constructor(e,t={}){super(e,t)}async createDatabase(e){try{const t=re,r=`${this.baseURL}${t.path}`;return(await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}async listDatabases(e={},t,r){try{const s=se;let i=`${this.baseURL}${s.path}`;const a=new URLSearchParams;t?.connector_id&&a.append("connector_id",t.connector_id),t?.add_default_if_missing&&a.append("add_default_if_missing",t.add_default_if_missing),a.toString()&&(i+=`?${a.toString()}`);const n=(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data;return r?.fields&&!("error"in n)?{...n,data:v(n.data,r.fields)}:n}catch(s){return this.formatErrorResponse(s)}}async updateDatabase(e,t){try{const r=ie,s=de(r,{db_id:e}),i=`${this.baseURL}${s}`;return(await this.httpAdapter.request({url:i,method:r.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async deleteDatabase(e){try{const t=ae,r=de(t,{db_id:e}),s=`${this.baseURL}${r}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}async listDatabaseJobs(e={},t){try{const r=ne,s=`${this.baseURL}${r.path}`,i=(await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data;return t?.fields&&!("error"in i)?{...i,data:v(i.data,t.fields)}:i}catch(r){return this.formatErrorResponse(r)}}async pollDeleteStatus(e){try{const t=oe,r=de(t,{job_id:e}),s=`${this.baseURL}${r}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t)}}}class ue extends E{constructor(e){super(e,"/v1/tables/databases"),this.apiClient=new le(e.getConfig().apiKey,{environment:e.getConfig().environment,region:e.getConfig().region,timeout:e.getConfig().timeout,debug:e.getConfig().debug})}async create(e){const t=await this.apiClient.createDatabase(e);return i(t)?{error:{code:"number"==typeof t.error.code?String(t.error.code):t.error.code,message:t.error.message,meta:t.error.meta}}:t}async findAll(e){const t={};if(e?.page&&(t.page=e.page),e?.sort&&(t.sort=e.sort),e?.filters){const r=e.filters.filter(e=>"status"!==e.field);t.filters=[...r,{field:"status",operator:"=",values:["ACTIVE"]}]}else t.filters=[{field:"status",operator:"=",values:["ACTIVE"]}];const r={};e?.connector_id&&(r.connector_id=e.connector_id),void 0!==e?.add_default_if_missing&&(r.add_default_if_missing=e.add_default_if_missing?"true":"false");const s=await this.apiClient.listDatabases(t,r,e);if(i(s))return{error:{code:"number"==typeof s.error.code?String(s.error.code):s.error.code,message:s.error.message,meta:s.error.meta}};if("pagination"in s&&s.pagination){const e=s.pagination;return{...s,pagination:{total_count:e.total_count,total_pages:e.total_pages??Math.ceil(e.total_count/e.per_page),current_page:e.current_page,per_page:e.per_page,type:"page"}}}return s}async findOne(e,t){const r=await this.findAll({filters:[{field:"db_internal_name",operator:"=",values:[e]}],fields:t?.fields,page:{page_no:1,page_size:1}});return i(r)?r:0===r.data.length?{error:{code:"NOT_FOUND",message:`Database with internal name '${e}' not found`,meta:[]}}:{data:r.data[0],message:"Database found"}}async getDefault(){const e=await this.findAll({filters:[{field:"is_default",operator:"=",values:[!0]}],page:{page_no:1,page_size:1}});return i(e)?e:0===e.data.length?{error:{code:"NOT_FOUND",message:"Default database not found",meta:[]}}:{data:e.data[0],message:"Default database found"}}async update(e,t){const r=await this.findOne(e);if(i(r))return{error:{code:"DATABASE_NOT_FOUND",message:`Database with internal name '${e}' not found`,meta:[]}};const s=r.data.id,a={db_name:t.db_name},n=await this.apiClient.updateDatabase(s,a);return i(n)?{error:{code:"number"==typeof n.error.code?String(n.error.code):n.error.code,message:n.error.message,meta:n.error.meta}}:n}async delete(e){const t=await this.findOne(e);if(i(t))return{error:{code:"DATABASE_NOT_FOUND",message:`Database with internal name '${e}' not found`,meta:[]}};if(t.data.is_default)return{error:{code:"CANNOT_DELETE_DEFAULT",message:"Cannot delete the default database",meta:[]}};const r=t.data.id,s=await this.apiClient.deleteDatabase(r);return i(s)?{error:{code:"number"==typeof s.error.code?String(s.error.code):s.error.code,message:s.error.message,meta:s.error.meta}}:s}async listJobs(e){const t={};void 0!==e?.deleted_by_me&&(t.deleted_by_me=e.deleted_by_me),e?.page&&(t.page=e.page),e?.sort&&(t.sort=e.sort),e?.filters&&(t.filters=e.filters);const r=await this.apiClient.listDatabaseJobs(t,e);if(i(r))return{error:{code:"number"==typeof r.error.code?String(r.error.code):r.error.code,message:r.error.message,meta:r.error.meta}};if("pagination"in r&&r.pagination){const e=r.pagination;return{...r,pagination:{total_count:e.total_count,total_pages:e.total_pages??Math.ceil(e.total_count/e.per_page),current_page:e.current_page,per_page:e.per_page,type:"page"}}}return{...r,data:r.data||[]}}async pollDeleteStatus(e){const t=await this.apiClient.pollDeleteStatus(e);return i(t)?{error:{code:"number"==typeof t.error.code?String(t.error.code):t.error.code,message:t.error.message,meta:t.error.meta}}:t}}const ce={path:"/tables/indexes/{table_id}",method:"POST",authenticated:!0},he={path:"/tables/indexes/{table_id}/list",method:"POST",authenticated:!0},pe={path:"/tables/indexes/{table_id}",method:"DELETE",authenticated:!0},me=(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 fe extends b{constructor(e,t={}){super(e,t)}async addIndex(e,t,r){try{const s=ce;let i=`${this.baseURL}${me(s,{table_id:e})}`;i=A(i,r);return(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(s){return this.formatErrorResponse(s)}}async listIndexes(e,t,r){try{const s=he;let i=`${this.baseURL}${me(s,{table_id:e})}`;i=A(i,r);return(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(s){return this.formatErrorResponse(s)}}async deleteIndex(e,t,r){try{const s=pe;let i=`${this.baseURL}${me(s,{table_id:e})}`;i=A(i,r);return(await this.httpAdapter.request({url:i,method:s.method,headers:this.buildHeaders(),data:t,timeout:this.config.timeout})).data}catch(s){return this.formatErrorResponse(s)}}}class ge{constructor(e){this.client=e;const t=e.getConfig();this.apiClient=new fe(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 ee(e)}async resolveTableId(e,t){const r=await this.tableResource.findByName(e,t);if(!r.data)throw new Error(`Table not found: ${e}`);return r.data.id}async addIndex(e,t,r){try{const s=await this.resolveTableId(e,r);return await this.apiClient.addIndex(s,t,r)}catch(s){return{error:{code:"CLIENT_ERROR",message:s?.message||"Failed to add index",meta:["IndexResource.addIndex"]}}}}async listIndexes(e,t,r){try{const s=await this.resolveTableId(e,r);return await this.apiClient.listIndexes(s,t,r)}catch(s){return{error:{code:"CLIENT_ERROR",message:s?.message||"Failed to list indexes",meta:["IndexResource.listIndexes"]}}}}async deleteIndex(e,t,r){try{const s=await this.resolveTableId(e,r),i={index_name:t};return await this.apiClient.deleteIndex(s,i,r)}catch(s){return{error:{code:"CLIENT_ERROR",message:s?.message||"Failed to delete index",meta:["IndexResource.deleteIndex"]}}}}}const _e={path:"/tables/{table_id}/records",method:"POST",authenticated:!0},be={path:"/tables/{table_id}/records/bulk-insert",method:"POST",authenticated:!0},ye={path:"/tables/{table_id}/records/list",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},we={path:"/tables/{table_id}/records/{record_id}",method:"GET",authenticated:!0,rateLimit:{requests:200,window:6e4}},Ee={path:"/tables/{table_id}/records/bulk-update",method:"PUT",authenticated:!0},Re={path:"/tables/{table_id}/records/{record_id}",method:"PATCH",authenticated:!0},Te={path:"/tables/{table_id}/records/list",method:"DELETE",authenticated:!0},ve=(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 Ae extends b{constructor(e,t={}){super(e,t)}async insertRecord(e,t){try{const{table_id:r,fields:s,...i}=e;if(!r)return this.formatErrorResponse(new Error("table_id is required for insert operation"));const a=_e;let n=`${this.baseURL}${ve(a,{table_id:r})}`;n=A(n,t);const o=(await this.httpAdapter.request({url:n,method:a.method,headers:this.buildHeaders(),data:i,timeout:this.config.timeout})).data;return s&&o.data&&(o.data=T(o.data,s)),o}catch(r){return this.formatErrorResponse(r)}}async insertManyRecords(e,t,r={validation:!0},s){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 i=be;let a=`${this.baseURL}${ve(i,{table_id:t})}`;const n=new URLSearchParams;void 0!==r.validation&&n.append("validation",r.validation.toString()),n.toString()&&(a+=`?${n.toString()}`),a=A(a,s);return(await this.httpAdapter.request({url:a,method:i.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data}catch(i){return this.formatErrorResponse(i)}}async getRecord(e,t,r={},s){try{if(!t)return this.formatErrorResponse(new Error("table_id is required for get operation"));const i=we;let a=`${this.baseURL}${ve(i,{table_id:t,record_id:e})}`;const n=new URLSearchParams;r.show_decrypted&&n.append("show_decrypted","true"),n.toString()&&(a+=`?${n.toString()}`),a=A(a,s);const o=(await this.httpAdapter.request({url:a,method:i.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data;return r.fields&&o.data&&(o.data=T(o.data,r.fields)),o}catch(i){return this.formatErrorResponse(i)}}async listRecords(e={},t){try{const{table_id:r,...s}=e;if(!r)return this.formatErrorResponse(new Error("table_id is required for list operation"));const i=ye;let a=`${this.baseURL}${ve(i,{table_id:r})}`;a=A(a,t);const n=(await this.httpAdapter.request({url:a,method:i.method,headers:this.buildHeaders(),data:s,timeout:this.config.timeout})).data;return s.fields&&n.data&&(n.data=v(n.data,s.fields)),n}catch(r){return this.formatErrorResponse(r)}}async updateRecords(e,t){try{const{table_id:r,set:s,filters:i,fields:a,show_decrypted:n,...o}=e;if(!r)return this.formatErrorResponse(new Error("table_id is required for update operation"));const d={updates:s,filters:i,...o};a&&(d.fields=a);const l=Ee;let u=`${this.baseURL}${ve(l,{table_id:r})}`;const c=new URLSearchParams;n&&c.append("show_decrypted","true"),c.toString()&&(u+=`?${c.toString()}`),u=A(u,t);const h=(await this.httpAdapter.request({url:u,method:l.method,headers:this.buildHeaders(),data:d,timeout:this.config.timeout})).data;return a&&h.data&&(h.data=v(h.data,a)),h}catch(r){return this.formatErrorResponse(r)}}async updateRecordById(e,t,r){try{const{table_id:s,show_decrypted:i,...a}=t;if(!s)return this.formatErrorResponse(new Error("table_id is required for updateById operation"));const n=Re;let o=`${this.baseURL}${ve(n,{record_id:e,table_id:s})}`;const d=new URLSearchParams;i&&d.append("show_decrypted","true"),d.toString()&&(o+=`?${d.toString()}`),o=A(o,r);const l=(await this.httpAdapter.request({url:o,method:n.method,headers:this.buildHeaders(),data:a.set,timeout:this.config.timeout})).data;return a.fields&&l.data&&(l.data=T(l.data,a.fields)),l}catch(s){return this.formatErrorResponse(s)}}async deleteRecords(e,t){try{const{table_id:r}=e;if(!r)return this.formatErrorResponse(new Error("table_id is required for delete operation"));const s=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=V(e.filters)),t}(e),i=Te;let a=`${this.baseURL}${ve(i,{table_id:r})}`;a=A(a,t);return(await this.httpAdapter.request({url:a,method:i.method,headers:this.buildHeaders(),data:s,timeout:this.config.timeout})).data}catch(r){return this.formatErrorResponse(r)}}async deleteRecordById(e,t,r){return this.deleteRecords({record_ids:[e],table_id:t.table_id},r)}}class Ie{constructor(e){this.client=e,this.apiClient=new Ae(e.getConfig().apiKey,{environment:e.getConfig().environment,region:e.getConfig().region,timeout:e.getConfig().timeout,debug:e.getConfig().debug}),this.tablesApiClient=new Z(e.getConfig().apiKey,{environment:e.getConfig().environment,region:e.getConfig().region,timeout:e.getConfig().timeout,debug:e.getConfig().debug})}async insert(e,t,r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const a=await this.ensureCompleteRecordData(e,t);if("error"in a&&a.error)return a;const n={...a,table_id:s.id},o=await this.apiClient.insertRecord(n,r);return i(o),o}catch(s){return{error:{code:"INSERT_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async insertMany(e,t,r={validation:!0},s){try{if(!t||!Array.isArray(t)||0===t.length)return{error:{code:"INVALID_INPUT",message:"Records array is required and cannot be empty"}};const a=await this.getTableInfo(e,s);if(!a)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const n=await this.apiClient.insertManyRecords(t,a.id,r,s);return i(n),n}catch(a){return{error:{code:"INSERT_MANY_ERROR",message:a instanceof Error?a.message:"Unknown error occurred"}}}}async get(e,t,r,s){try{let a=!1,n=s;"string"==typeof r?n=r:"object"==typeof r&&(a=r.show_decrypted||!1,n=r.dbId||s);const o=await this.getTableInfo(e,n);if(!o)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const d=await this.apiClient.getRecord(t,o.id,{fields:void 0,show_decrypted:a},n);return i(d),d}catch(a){return{error:{code:"GET_ERROR",message:a instanceof Error?a.message:"Unknown error occurred"}}}}async list(e,t={},r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const a={...t,table_id:s.id},n=await this.apiClient.listRecords(a,r);return i(n),n}catch(s){return{error:{code:"LIST_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async update(e,t,r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const a={...t,table_id:s.id},n=await this.apiClient.updateRecords(a,r);return i(n),n}catch(s){return{error:{code:"UPDATE_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async updateById(e,t,r,s,a){try{let n=!1,o=a;"string"==typeof s?o=s:"object"==typeof s&&(n=s.show_decrypted||!1,o=s.dbId||a);const d=await this.getTableInfo(e,o);if(!d)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const l={id:t,set:r,table_id:d.id,show_decrypted:n},u=await this.apiClient.updateRecordById(t,l,o);return i(u),u}catch(n){return{error:{code:"UPDATE_BY_ID_ERROR",message:n instanceof Error?n.message:"Unknown error occurred"}}}}async delete(e,t,r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const a={...t,table_id:s.id},n=await this.apiClient.deleteRecords(a,r);return i(n),n}catch(s){return{error:{code:"DELETE_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async deleteById(e,t,r){try{const s=await this.getTableInfo(e,r);if(!s)return{error:{code:"TABLE_NOT_FOUND",message:`Table '${e}' not found`}};const a=await this.apiClient.deleteRecordById(t,{table_id:s.id},r);return i(a),a}catch(s){return{error:{code:"DELETE_BY_ID_ERROR",message:s instanceof Error?s.message:"Unknown error occurred"}}}}async getTableInfo(e,t){try{const r=new ee(this.client),s=await r.findByName(e,t);return s.data?{id:s.data.id,snapshot_url:s.data.snapshot_url}:null}catch(r){return console.error("Error getting table info:",r),null}}async ensureCompleteRecordData(e,t){try{const r=new te(this.client),s=await r.findAll(e);if(i(s))return s;const a=Array.isArray(s.data)?s.data:[],n={...t};for(const e of a)"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 Ce{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 xe(e){return new Ce(e)}const Oe={path:"/tables/query/text-to-sql",method:"POST",authenticated:!0,rateLimit:{requests:100,window:6e4}},Ne={path:"/tables/query/execute",method:"POST",authenticated:!0,rateLimit:{requests:200,window:6e4}},$e=(e,t={})=>{let r=e.path;return Object.entries(t).forEach(([e,t])=>{r=r.replace(`{${e}}`,encodeURIComponent(t))}),r};class Se extends b{constructor(e,t={}){super(e,t)}async textToSQL(e,t){try{const r=Oe;let s=`${this.baseURL}${$e(r)}`;t&&(s+=`?db_id=${encodeURIComponent(t)}`);const i=await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout});if(i.status>=400)return this.formatErrorResponse({response:{data:i.data,status:i.status}},"SQL");const a=i.data;return this.createAsyncIterable(a.data)}catch(r){return this.formatErrorResponse(r,"SQL")}}async executeSQL(e,t){try{const r=Ne;let s=`${this.baseURL}${$e(r)}`;t&&(s+=`?db_id=${encodeURIComponent(t)}`);const i=await this.httpAdapter.request({url:s,method:r.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout});return i.status>=400?this.formatErrorResponse({response:{data:i.data,status:i.status}},"SQL"):i.data}catch(r){return this.formatErrorResponse(r,"SQL")}}async*createAsyncIterable(e){yield e}}class Le{constructor(e){const t=e.getConfig();this.sqlApiClient=new Se(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={},r){const s=function(e,t={}){return{prompt:e,current_query:t.currentQuery}}(e,t),i=await this.sqlApiClient.textToSQL(s,r);if("error"in i&&void 0!==i.error)throw i;return i}async executeSQL(e,t){const r=await this.sqlApiClient.executeSQL({query:e},t);return i(r),r}}class qe{constructor(e,t){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}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 n("Table name is required",[{field:"name",message:"Table name cannot be empty"}]);if(0===this.fields.length)throw new n("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 ke(e,t){return new qe(e,t)}const De={string:{type:"string",fallback_value:""},number:{type:"number",fallback_value:""},boolean:{type:"boolean",secondary_type:"string",fallback_value:""},int:{type:"number",fallback_value:""},integer:{type:"number",fallback_value:""},"date-time":{type:"date-time",secondary_type:"string",fallback_value:""},date:{type:"date",secondary_type:"string",fallback_value:""},json:{type:"object",fallback_value:{}},text:{type:"string",fallback_value:""},email:{type:"string",fallback_value:""},password:{type:"string",fallback_value:""},url:{type:"string",fallback_value:""},textarea:{type:"string",fallback_value:""},select:{type:"string",fallback_value:""},multiselect:{type:"string",fallback_value:""},autocomplete:{type:"array",fallback_value:[]},radio:{type:"string",fallback_value:""},radiobuttons:{type:"string",fallback_value:""},checkbox:{type:"array",fallback_value:[]},toggle:{type:"boolean",fallback_value:""},hidden:{type:"string",fallback_value:""},slider:{type:"number",fallback_value:""},datepicker:{type:"string",fallback_value:""},phoneinput:{type:"string",fallback_value:""},time:{type:"string",fallback_value:""},datetime:{type:"string",fallback_value:""},code:{type:"string",fallback_value:""},multitext:{type:"array",fallback_value:[]},array:{type:"array",fallback_value:[]},keyvalue:{type:"object",fallback_value:{}},object:{type:"object",fallback_value:{}},phone:{type:"string",fallback_value:""},"number[]":{type:"string",fallback_value:""},"number []":{type:"string",fallback_value:""},"object | any":{type:"string",fallback_value:""}},Ue={path:"/workflows/execute/activity",method:"POST",authenticated:!0},Me={path:"/workflows/run/{run_id}",method:"GET",authenticated:!0},He={path:"/integrations",method:"GET",authenticated:!0},Pe={path:"/integrations/entity/{entity}",method:"GET",authenticated:!0},Be={path:"/integrations/{integration_slug}/schema",method:"GET",authenticated:!0},Fe={path:"/integrations/{integration_slug}/fields",method:"GET",authenticated:!0};function je(e,t={}){let r=e.path;for(const[s,i]of Object.entries(t))r=r.replace(`{${s}}`,i);return r}class Ye extends b{constructor(e,t={}){super(e,t,g),this.integrationBaseURL=this.resolveAdditionalServiceURL(_)}async executeActivity(e){try{const t=Ue,r=`${this.baseURL}${t.path}`;return(await this.httpAdapter.request({url:r,method:t.method,headers:this.buildHeaders(),data:e,timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}async getExecutionById(e){try{const t=Me,r=je(t,{run_id:e}),s=`${this.baseURL}${r}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}async getIntegrations(e={}){try{const t=He,r=new URLSearchParams({page:String(e.page??1),per_page:String(e.per_page??999)}),s=`${this.baseURL}${t.path}?${r.toString()}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}async getCredentials(e){try{const t=Pe,r=je(t,{entity:e.entity.toUpperCase()}),s=new URLSearchParams({current_page:String(e.current_page??1),page_size:String(e.page_size??999)}),i=`${this.integrationBaseURL}${r}?${s.toString()}`;return(await this.httpAdapter.request({url:i,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"INTEGRATION")}}async getIntegrationResource(e){try{const t=Be,r=je(t,{integration_slug:e.integration_slug}),s=`${this.baseURL}${r}`;return(await this.httpAdapter.request({url:s,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}async getIntegrationForm(e){try{const t=Fe,r=je(t,{integration_slug:e.integration_slug}),s=new URLSearchParams({resource:e.resource,operation:e.operation,secret:e.secret}),i=`${this.baseURL}${r}?${s.toString()}`;return(await this.httpAdapter.request({url:i,method:t.method,headers:this.buildHeaders(),timeout:this.config.timeout})).data}catch(t){return this.formatErrorResponse(t,"WORKFLOW")}}}const Ke=new Set(["resource","operation"]);function We(e){return De[e]??{type:"string",fallback_value:""}}function ze(e){return new Promise(t=>setTimeout(t,e))}class Qe extends E{constructor(e){super(e,"/workflows");const t=e.getConfig();this.apiClient=new Ye(t.apiKey,{environment:t.environment,region:t.region,timeout:t.timeout,debug:t.debug})}async executeIntegration(e){const t=function(e){return{nodes:[{data:{type:e.data.type,name:e.data.name,properties:e.data.properties}}],result:e.result??{payload:{},global_variables:{}}}}(e),r=await this.apiClient.executeActivity(t);if(i(r))return r;if(e.executeOnly)return r;const s=r.data?.execution_id;return s?this.pollExecution(s):{error:{code:"MISSING_EXECUTION_ID",message:"Execute API response did not contain an execution_id",meta:[]}}}async getIntegrationExecuteById(e){return this.apiClient.getExecutionById(e)}async getIntegrations(e={}){return this.apiClient.getIntegrations(e)}async getCredentials(e){return this.apiClient.getCredentials(e)}async getIntegrationResource(e){return this.apiClient.getIntegrationResource(e)}async getIntegrationForm(e){const t=await this.apiClient.getIntegrationForm(e);if(console.log("rawResult",JSON.stringify(t,null,2)),i(t))return t;const r=(t.data?.parameters||t.data)??[],s=e.asJsonSchema?function(e,t=Ke){const r={};for(const s of e){if(t.has(s.name))continue;const e=We(s.meta?.displayType||"text"),i=s.meta?.validation?.required??!1,a=void 0!==s.meta?.value?s.meta.value:e.fallback_value,n={type:e.type,required:i,default:a};s.meta?.description&&(n.description=s.meta.description),s.meta?.options&&Array.isArray(s.meta.options)&&s.meta.options.length>0&&(n.enum=s.meta.options.map(e=>e.value)),r[s.name]=n}return{type:"object",properties:r}}(r):function(e,t=Ke){const r={};for(const s of e){if(t.has(s.name))continue;const e=We(s.meta?.displayType||"text");r[s.name]=void 0!==s.meta?.value?s.meta.value:e.fallback_value}return r}(r);if(e.asJsonSchema){const t=s;t.properties.secret&&(t.properties.secret.default=e.secret)}else{"secret"in s&&(s.secret=e.secret)}return{data:s,message:t.message}}async pollExecution(e){const t=this.client.getConfig().debug;for(let r=0;r<30;r++){const s=await this.apiClient.getExecutionById(e);if(i(s))return s;if(s.data&&Object.keys(s.data).length>0)return t&&console.log(`[WorkflowResource] Execution ${e} completed after ${r+1} poll(s)`),s;await ze(1e3)}return{error:{code:"EXECUTION_TIMEOUT",message:`Execution ${e} did not complete within 30 polling attempts`,meta:[`execution_id: ${e}`,"max_attempts: 30"]}}}}class Ge{constructor(e,t={}){this.currentDatabase=null,this.clientOptions=t,this.configManager=new R(e,t.environment||"prod",t.region||"asia-south1",t);const r=this.configManager.getConfig();this.authManager=new m({apiKey:r.apiKey,maxRetries:r.maxRetries}),this.baseClient=new w(r,this.authManager),this.tableResource=new ee(this.baseClient),this.columnResource=new te(this.baseClient),this.recordResource=new Ie(this.baseClient),this.sqlResource=new Le(this.baseClient),this.indexResource=new ge(this.baseClient),this.databaseResource=new ue(this.baseClient),this.workflowResource=new Qe(this.baseClient),this.currentDatabase=null}getCurrentDatabase(){return this.currentDatabase}async useDatabase(e){if(console.log(`Database internal name:${e}`),!e||""===e)return void(this.currentDatabase=null);const t=await this.databaseResource.findOne(e);if(console.log(`Result:${JSON.stringify(t,null,2)}`),i(t))throw console.log(`Error:${t.error.message}`),new Error(t.error.message||`Failed to switch database to internal name '${e}'`);const r=t.data;this.currentDatabase={databaseId:r.id,dbInternalName:r.db_internal_name||e}}get databases(){return{create:e=>this.databaseResource.create(e),findAll:e=>this.databaseResource.findAll(e),findOne:(e,t)=>this.databaseResource.findOne(e,t),getDefault:()=>this.databaseResource.getDefault(),update:(e,t)=>this.databaseResource.update(e,t),delete:e=>this.databaseResource.delete(e),listJobs:e=>this.databaseResource.listJobs(e),pollDeleteStatus:e=>this.databaseResource.pollDeleteStatus(e)}}get tables(){const e=this.currentDatabase?.databaseId;return{create:t=>this.tableResource.create(t,e),findAll:t=>this.tableResource.findAll(t,e),findById:t=>this.tableResource.findById(t,e),findByName:t=>this.tableResource.findByName(t,e),findOne:t=>this.tableResource.findOne(t,e),update:(t,r)=>this.tableResource.update(t,r,e),delete:t=>this.tableResource.delete(t,e),rename:(t,r)=>this.tableResource.rename(t,r,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 ke({name:e})}from(e){const t=this.currentDatabase?.databaseId;return{indexes:()=>({addIndex:r=>this.indexResource.addIndex(e,r,t),listIndexes:r=>this.indexResource.listIndexes(e,r,t),deleteIndex:r=>this.indexResource.deleteIndex(e,r,t)}),records:()=>({insert:r=>this.recordResource.insert(e,r,t),insertMany:(r,s)=>this.recordResource.insertMany(e,r,s,t),findOne:r=>this.recordResource.get(e,r,t),update:r=>this.recordResource.update(e,r,t),updateById:(r,s)=>this.recordResource.updateById(e,r,s,t),delete:r=>this.recordResource.delete(e,r,t),deleteById:r=>this.recordResource.deleteById(e,r,t)})}}get records(){const e=this.currentDatabase?.databaseId;return{insert:(t,r)=>this.recordResource.insert(t,r,e),insertMany:(t,r,s)=>this.recordResource.insertMany(t,r,s,e),findAll:(t,r)=>this.recordResource.list(t,r,e),findOne:(t,r,s)=>this.recordResource.get(t,r,s,e),update:(t,r)=>this.recordResource.update(t,r,e),updateById:(t,r,s,i)=>this.recordResource.updateById(t,r,s,i,e),delete:(t,r)=>this.recordResource.delete(t,r,e),deleteById:(t,r)=>this.recordResource.deleteById(t,r,e)}}record(e){return xe({tableName:e,recordResource:this.recordResource})}get sql(){const e=this.currentDatabase?.databaseId;return{textToSQL:(t,r)=>this.sqlResource.textToSQL(t,r,e),executeSQL:t=>this.sqlResource.executeSQL(t,e)}}get workflow(){return{executeIntegration:e=>this.workflowResource.executeIntegration(e),getIntegrationExecuteById:e=>this.workflowResource.getIntegrationExecuteById(e),getIntegrations:e=>this.workflowResource.getIntegrations(e),getCredentials:e=>this.workflowResource.getCredentials(e),getIntegrationResource:e=>this.workflowResource.getIntegrationResource(e),getIntegrationForm:e=>this.workflowResource.getIntegrationForm(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 ee(this.baseClient),this.columnResource=new te(this.baseClient),this.recordResource=new Ie(this.baseClient),this.sqlResource=new Le(this.baseClient),this.indexResource=new ge(this.baseClient),this.databaseResource=new ue(this.baseClient),this.workflowResource=new Qe(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.ALLOWED_FIELD_TYPE_CONVERSIONS=k,exports.ApiError=o,exports.BolticClient=Ge,exports.DateFormatEnum=S,exports.ENV_CONFIGS=t,exports.FIELD_SPECIFIC_KEYS_MAP=D,exports.FILTER_OPERATORS=z,exports.FieldTypeEnum=q,exports.FilterBuilder=J,exports.REGION_BASE_HOSTS=r,exports.REGION_CONFIGS=e,exports.SqlResource=Le,exports.TimeFormatEnum=L,exports.ValidationError=n,exports.buildApiFilters=function(e,t="AND"){const r=G(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=d,exports.createFilter=function(){return new J},exports.createMockResponse=function(e,t){return{data:e,pagination:t}},exports.createRecordBuilder=xe,exports.createTableBuilder=ke,exports.createTestClient=function(e={}){return new Ge(e.apiKey||"test-api-key-12345",{environment:"local",region:"asia-south1",debug:e.debug??!0,timeout:3e4,...e})},exports.formatError=u,exports.getHttpStatusCode=l,exports.isErrorResponse=i,exports.isListResponse=a,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(Q).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=V,exports.normalizeFilters=G,exports.resolveServiceURL=s;
|
|
2
|
-
//# sourceMappingURL=test-client-BgkvBtst.js.map
|