buildx-sdk 1.0.4 → 1.0.6

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/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("axios");class t{constructor(e){this.baseService=e}setAccessToken(e){this.baseService.setAccessToken(e)}getAccessToken(){return this.baseService.getAccessToken()}setRefreshToken(e){this.baseService.setRefreshToken(e)}getRefreshToken(){return this.baseService.getRefreshToken()}clearTokens(){this.baseService.clearTokens()}isAuthenticated(){return this.baseService.isAuthenticated()}storeTokens(e){"access_token"in e&&e.access_token&&this.baseService.setAccessToken(e.access_token),"refresh_token"in e&&e.refresh_token&&this.baseService.setRefreshToken(e.refresh_token)}isErrorResponse(e){return e&&"object"==typeof e&&"success"in e&&!1===e.success}hasProjectScope(){const e=this.baseService.config.projectId;return!!e&&"default"!==e}async login(e){const t=this.baseService.buildProjectUrl("/auth/login"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async loginWithGoogle(e){const t=this.baseService.buildProjectUrl("/auth/google"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async signup(e){const t=this.baseService.buildProjectUrl("/auth/signup"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async requestEotp(e){const t=this.baseService.buildProjectUrl("/auth/eotp/auth/request");return await this.baseService.post(t,e)}async requestEotpAuth(e){return this.requestEotp(e)}async requestOtpLogin(e){return this.requestEotp(e)}async verifyEotp(e){const t=this.baseService.buildProjectUrl("/auth/eotp/auth/verify"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async verifyEotpAuth(e){return this.verifyEotp(e)}async verifyOtpLogin(e){return this.verifyEotp(e)}async getCurrentUser(){const e=this.baseService.buildProjectUrl("/auth/me");return await this.baseService.get(e)}async refreshToken(){const e=this.baseService.buildProjectUrl("/auth/token"),t=await this.baseService.post(e,{});return this.isErrorResponse(t)||"access_token"in t&&t.access_token&&this.storeTokens(t),t}async updatePassword(e){const t=this.baseService.buildProjectUrl("/auth/password/update");return await this.baseService.post(t,{password:e})}async changePassword(e){const t=this.baseService.buildProjectUrl("/auth/password/update");if("string"==typeof e)return await this.baseService.post(t,{password:e});const s=e.password??e.newPassword??e.new_password,i={...e};return s&&(i.password=s),e.currentPassword&&!i.current_password&&(i.current_password=e.currentPassword),e.newPassword&&!i.new_password&&(i.new_password=e.newPassword),await this.baseService.post(t,i)}async adminUpdatePassword(e,t){const s=this.baseService.buildProjectUrl("/auth/password/update");return await this.baseService.post(s,{user_id:e,password:t})}async requestPasswordReset(e){const t=this.hasProjectScope()?this.baseService.buildProjectUrl("/auth/password/reset/request"):"/auth/password/reset/request";return await this.baseService.post(t,e)}async resetPassword(e){const t=this.hasProjectScope()?this.baseService.buildProjectUrl("/auth/password/reset"):"/auth/password/reset";return await this.baseService.post(t,e)}async updatePushToken(e){const t=this.baseService.buildProjectUrl("/users/push-tokens");return await this.baseService.post(t,{token:e})}async listUsers(e){const t=e?this.baseService.buildOrgUrl("/auth/users"):"/auth/users";return await this.baseService.get(t)}async lookupUsers(e){const t=e?this.baseService.buildOrgUrl("/auth/users/lookup"):"/auth/users/lookup";return await this.baseService.get(t)}async getUser(e,t){const s=t?this.baseService.buildOrgUrl(`/auth/user/${e}`):`/auth/user/${e}`;return await this.baseService.get(s)}async deleteUser(e){const t=this.baseService.buildProjectUrl(`/auth/user/${e}/delete`);return await this.baseService.post(t,{})}}class s{constructor(e){this.baseService=e}async list(){return await this.baseService.get("/projects")}async get(e){return await this.baseService.get(`/project/${e}`)}async create(e){return await this.baseService.post("/projects",e)}async update(e,t){return await this.baseService.patch(`/project/${e}`,t)}async deleteById(e){return await this.baseService.delete(`/project/${e}`)}async backup(e){const t=await this.baseService.axiosInstance.get(`/project/${e}/backup`,{responseType:"blob",headers:await this.baseService.getHeaders()});if("undefined"!=typeof window){const s=window.URL.createObjectURL(t.data),i=document.createElement("a");i.href=s,i.setAttribute("download",`backup_${e}.buildx`),document.body.appendChild(i),i.click(),document.body.removeChild(i),window.URL.revokeObjectURL(s)}return{success:!0,message:"Backup downloaded successfully"}}async restore(e,t){const s=new FormData;s.append("new_project_id",e),s.append("backup_file",t);const i={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data"};return await this.baseService.post("/project/import",s,{headers:i})}}class i{constructor(e,t,s){this.baseService=e,this.collectionId=t,this.wsFactory=s,this.socket=null,this.connectPromise=null,this.requestCounter=0,this.pending=new Map}async query(e,t,s=3e4){if(await this.ensureConnected(),!this.socket)throw new Error("WebSocket connection is unavailable");const i=`${Date.now()}_${++this.requestCounter}`,r=new Promise((e,t)=>{const r=setTimeout(()=>{this.pending.delete(i),t(new Error("WebSocket pagination timeout"))},s);this.pending.set(i,{resolve:e,reject:t,timeout:r})});return this.socket.send(JSON.stringify({id:i,action:e,payload:t})),r}close(){if(this.socket){try{this.socket.close()}catch(e){}this.socket=null,this.connectPromise=null;for(const[,e]of this.pending.entries())clearTimeout(e.timeout),e.reject(new Error("WebSocket closed"));this.pending.clear()}}async ensureConnected(){if(!this.socket||!this.isSocketOpen(this.socket))return this.connectPromise||(this.connectPromise=new Promise((e,t)=>{const s=globalThis.WebSocket;if(!this.wsFactory&&!s)return void t(new Error("WebSocket is not available in this runtime"));const i=this.wsFactory?this.wsFactory(this.buildSocketUrl()):new s(this.buildSocketUrl());this.socket=i;let r=!1;const a=()=>{r||(r=!0,e())},o=e=>{r||(r=!0,t(e)),this.close()},n=()=>{r||(r=!0,t(new Error("WebSocket closed before connection is ready"))),this.close()},c=e=>{let t;try{t=JSON.parse(e?.data||"{}")}catch(e){return}const s=t?.id;if(!s)return;const i=this.pending.get(s);i&&(clearTimeout(i.timeout),this.pending.delete(s),t.ok&&t.result?i.resolve(t.result):i.reject(new Error(t.error||"WebSocket pagination query failed")))};i.addEventListener?(i.addEventListener("open",a),i.addEventListener("error",o),i.addEventListener("close",n),i.addEventListener("message",c)):(i.onopen=a,i.onerror=o,i.onclose=n,i.onmessage=c)}).finally(()=>{this.connectPromise=null})),this.connectPromise}isSocketOpen(e){const t=globalThis.WebSocket?.OPEN??1;return e.readyState===t}buildSocketUrl(){const e=this.baseService.config.apiEndpoint.replace(/\/$/,"").replace(/^http:/i,"ws:").replace(/^https:/i,"wss:"),t=this.baseService.buildProjectUrl(`/${this.collectionId}/data/pagination/ws`),s=new URLSearchParams,i=this.baseService.config.apiKey;i&&s.set("api_key",i);const r=this.baseService.getAccessToken();r&&s.set("token",r);const a=s.toString();return`${e}${t}${a?`?${a}`:""}`}}class r{constructor(e){this.collectionWsClient=null,this.collectionWsCollectionId=null,this.collectionWsDisabledUntil=0,this.baseService=e}async list(e=!1,t=!1){const s=this.baseService.buildProjectUrl("/collections"),i={};e&&(i.with_stats=!0);const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,o=await this.baseService.get(a);return Array.isArray(o)&&!t?o.filter(e=>e.collection_id&&!e.collection_id.startsWith("buildx_")):o}async getSchema(e,t=1){const s=this.baseService.buildProjectUrl(`/collection/${e}`),i={};t>1&&(i.depth=t);const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s;return await this.baseService.get(a)}async set(e){const t=this.baseService.buildProjectUrl("/collections");return await this.baseService.post(t,e)}async deleteCollection(e){const t=this.baseService.buildProjectUrl(`/collections/${e}`);return await this.baseService.delete(t)}async query(e,t){const s=this.baseService.buildProjectUrl(`/${e}`),i=t?.noPopulate??(!!t?.relations&&t.relations.length>0),r=this.buildQueryParams({...t,options:i?{...t?.options||{},noPopulate:!0}:t?.options}),a=this.baseService.buildQueryString(r),o=a?`${s}${a}`:s,n=await this.baseService.get(o);if(!Array.isArray(n))return n;if(!t?.relations||0===t.relations.length)return n;const c="http"!==(t?.paginationTransport||"auto");return await this.hydrateRelations(n,t.relations,t.relationSelect,{preferWs:c,wsFactory:t.wsFactory})}async queryRaw(e,t){const s={...t,options:{...t?.options||{},noPopulate:!0}};if("http"!==(s.paginationTransport||"http")&&Date.now()>=this.collectionWsDisabledUntil)try{return await this.queryRawViaWs(e,s)}catch(e){console.warn("[buildx-sdk] WS raw query failed, fallback to HTTP",e?.message||e),this.collectionWsDisabledUntil=Date.now()+3e4,this.resetCollectionWsClient()}const i=this.baseService.buildProjectUrl(`/${e}/raw`),r=this.buildQueryParams(s),a=this.baseService.buildQueryString(r),o=a?`${i}${a}`:i;return await this.baseService.get(o)}async queryWithPagination(e,t){const s=t?.noPopulate??(!!t?.relations&&t.relations.length>0),i={...t,options:s?{...t?.options||{},noPopulate:!0}:t?.options},r=i.paginationTransport||"auto";let a;if("http"!==r&&Date.now()>=this.collectionWsDisabledUntil)try{a=await this.queryWithPaginationViaWs(e,i)}catch(t){console.warn("[buildx-sdk] WS pagination failed, fallback to HTTP",t?.message||t),this.collectionWsDisabledUntil=Date.now()+3e4,this.resetCollectionWsClient(),a=await this.queryWithPaginationViaHttp(e,i)}else a=await this.queryWithPaginationViaHttp(e,i);if(!a||!1===a.success)return a;if(!i?.relations||0===i.relations.length)return a;const o="http"!==r,n=await this.hydrateRelations(a.data||[],i.relations,i.relationSelect,{preferWs:o,wsFactory:i.wsFactory});return Array.isArray(n)?{...a,data:n}:n}async queryWithPaginationViaHttp(e,t){const s=this.baseService.buildProjectUrl(`/${e}/data/pagination`),i=this.buildQueryParams(t),r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,o=await this.baseService.get(a);return o&&!1!==o.success?{...o,meta:{...o.meta||{},transport:"http"}}:o}async queryWithPaginationViaWs(e,t){const s=this.buildQueryParams(t),i=this.getOrCreateCollectionWsClient(e,t?.wsFactory),r=await i.query("queryWithPagination",s);return r&&!1!==r.success?{...r,meta:{...r.meta||{},transport:"ws"}}:r}async queryRawViaWs(e,t){const s=this.buildQueryParams(t),i=this.getOrCreateCollectionWsClient(e,t?.wsFactory),r=await i.query("queryRaw",s);return r&&!1!==r.success?Array.isArray(r)?r:[]:r}getOrCreateCollectionWsClient(e,t){return this.collectionWsClient&&this.collectionWsCollectionId===e||(this.resetCollectionWsClient(),this.collectionWsClient=new i(this.baseService,e,t),this.collectionWsCollectionId=e),this.collectionWsClient}resetCollectionWsClient(){this.collectionWsClient&&this.collectionWsClient.close(),this.collectionWsClient=null,this.collectionWsCollectionId=null}subscribeRealtime(e,t,s){const i=this.baseService.config.apiEndpoint.replace(/\/$/,""),r=this.baseService.buildProjectUrl(`/${e}/realtime/stream`),a=new URLSearchParams,o=s?.apiKey||this.baseService.config.apiKey;o&&a.set("api_key",o);const n=s?.token||this.baseService.getAccessToken();n&&a.set("token",n),s?.lastEventId&&a.set("lastEventId",s.lastEventId);const c=a.toString(),l=`${i}${r}${c?`?${c}`:""}`,u=s?.eventSourceFactory||globalThis.EventSource;if(!u)throw new Error("EventSource is not available in this runtime. Provide eventSourceFactory in options.");const h=u(l);let d=!1;const p=()=>{d||(d=!0,t.onConnected?.())},b=e=>{try{const s=JSON.parse(e.data);t.onEvent?.(s)}catch(e){t.onError?.(e)}};return h.onopen=()=>{p()},h.onmessage=e=>b(e),h.onerror=e=>{t.onError?.(e)},h.addEventListener?.("connected",()=>{p()}),h.addEventListener?.("collection:data",e=>{b(e)}),{close:()=>h.close()}}async lookup(e,t){const s=this.baseService.buildProjectUrl(`/${e}`),i={};t&&(t.filter&&(i.filter=t.filter),t.jsonFilter&&(i.jsonFilter=t.jsonFilter),t.projection&&(i.projection=t.projection),t.options&&(i.options=t.options));const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,o=await this.baseService.get(a);return Array.isArray(o)?o.map(e=>({value:e._id,label:e._display||e.label||e.title||e.name||e.username||e.description||""})):o}buildQueryParams(e){const t={};if(!e)return t;const s=e.q||e.searchQuery;return s&&(t.q=s),e.quick_filter_fields&&(t.quick_filter_fields=e.quick_filter_fields),e.filter&&(t.filter=e.filter),e.jsonFilter&&(t.jsonFilter=e.jsonFilter),e.select&&(t.select=Array.isArray(e.select)?e.select.join(","):e.select),e.projection&&(t.projection=e.projection),e.options&&(t.options=e.options),e.sort&&(t.sort=e.sort),"number"==typeof e.limit&&(t.limit=e.limit),"number"==typeof e.skip&&e.skip>0&&(t.skip=e.skip),t}async hydrateRelations(e,t,s,i){const a=e.map(e=>({...e})),o=s||"_id,_display,name,title,username",n=t.reduce((e,t)=>(e[t.collectionId]||(e[t.collectionId]=[]),e[t.collectionId].push(t),e),{}),c=new Map;for(const[e,t]of Object.entries(n)){const s=new Set;for(const e of a)for(const i of t){const t=e[i.field];if(t)if(Array.isArray(t))for(const e of t)"string"==typeof e?s.add(e):e&&"object"==typeof e&&e._id&&s.add(e._id);else"string"==typeof t?s.add(t):t&&"object"==typeof t&&t._id&&s.add(t._id)}const n=Array.from(s).filter(t=>!c.has(`${e}:${t}`));if(n.length>0){const t=r.RELATION_QUERY_CHUNK_SIZE;for(let s=0;s<n.length;s+=t){const r=n.slice(s,s+t),a=await this.queryRaw(e,{filter:{_id:{$in:r}},select:o,paginationTransport:i?.preferWs?"auto":"http",wsFactory:i?.wsFactory});if(!Array.isArray(a))return a;for(const t of a)t?._id&&c.set(`${e}:${t._id}`,t)}}for(const s of a)for(const i of t){const t=s[i.field];if(t)if(Array.isArray(t))s[i.field]=t.map(t=>{const s="string"==typeof t?t:t?._id;return s&&c.get(`${e}:${s}`)||t});else{const r="string"==typeof t?t:t?._id;if(!r)continue;s[i.field]=c.get(`${e}:${r}`)||t}}}return a}async getDocument(e,t,s){const i=this.baseService.buildProjectUrl(`/${e}/${t}`),r={};s&&s.length>0&&(r.populate=s.join(","));const a=this.baseService.buildQueryString(r),o=a?`${i}${a}`:i;return await this.baseService.get(o)}async createDocument(e,t){const s=this.baseService.buildProjectUrl(`/${e}`);return await this.baseService.post(s,t)}async updateDocument(e,t,s){const i=this.baseService.buildProjectUrl(`/${e}/${t}`);return await this.baseService.patch(i,s)}async updateDocumentWithOptions(e,t,s,i){const r=this.baseService.buildProjectUrl(`/${e}/${t}`),a=i?.updateOnly?`${r}?mode=updateOnly`:r;return await this.baseService.patch(a,s)}async getDocumentRevisions(e,t){const s=this.baseService.buildProjectUrl(`/${e}/${t}/revisions`);return await this.baseService.get(s)}async deleteDocument(e,t){const s=this.baseService.buildProjectUrl(`/${e}/${t}`);return await this.baseService.delete(s)}async deleteByFilter(e,t){const s=this.baseService.buildProjectUrl(`/${e}/delete`);return await this.baseService.post(s,{filter:t})}async import(e,t,s){const i=new FormData;i.append("mapping",JSON.stringify(s)),i.append("file",t);const r=this.baseService.buildProjectUrl(`/${e}/import`),a={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data"};return await this.baseService.post(r,i,{headers:a})}async getDataTypes(){const e=this.baseService.buildProjectUrl("/collections/types");return await this.baseService.get(e)}async validate(e){const t=this.baseService.buildProjectUrl(`/${e}/validate`);return await this.baseService.post(t,null)}async migrate(e){const t=this.baseService.buildProjectUrl(`/${e}/migrate`);return await this.baseService.post(t,null)}}r.RELATION_QUERY_CHUNK_SIZE=200;class a{constructor(e){this.baseService=e}async upload(e,t){const s=new FormData;t&&""!==t&&s.append("prefix",t),s.append("file",e),s.append("filename",e.name||"file");const i=this.baseService.buildProjectUrl("/storage/upload"),r={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data; charset=utf-8"};return await this.baseService.post(i,s,{headers:r})}async uploadToCollection(e,t,s){const i=new FormData;s&&""!==s&&i.append("prefix",s),i.append("file",e),i.append("filename",e.name||"file"),i.append("collection_id",t);const r=this.baseService.buildProjectUrl("/storage/upload"),a={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data; charset=utf-8"};return await this.baseService.post(r,i,{headers:a})}async list(e){const t=this.baseService.buildProjectUrl(`/storage?path=${encodeURIComponent(e)}`);return await this.baseService.get(t)}async getSize(e){const t=this.baseService.buildProjectUrl(`/storage/size?path=${encodeURIComponent(e)}`);return await this.baseService.get(t)}async delete(e){const t=this.baseService.buildProjectUrl(`/storage?path=${encodeURIComponent(e)}`);return await this.baseService.delete(t)}}class o{constructor(e){this.baseService=e}async getTypes(){return await this.baseService.get("/flows/types")}async run(e,t=null,s="root",i={}){const r=this.baseService.buildProjectUrl(`/flows/${e}/run`);return await this.baseService.post(r,{session_id:t,state:s,args:i})}async getGptFlowSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/flow/node");return await this.baseService.post(t,{instruction:e})}async getGptCollectionSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/collections");return await this.baseService.post(t,{instruction:e})}async getGptLifecycleSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/lifecycle");return await this.baseService.post(t,{instruction:e})}}class n{constructor(e){this.baseService=e}async preview(e,t){const s=this.baseService.buildProjectUrl("/templates/preview");return await this.baseService.post(s,{template:e,data:t})}async render(e,t){const s=this.baseService.buildProjectUrl(`/templates/${e}/render`);return await this.baseService.post(s,t)}async renderPDF(e,t){const s=this.baseService.buildProjectUrl(`/templates/${e}/pdf`),i={...await this.baseService.getHeaders(),responseType:"blob"},r=await this.baseService.axiosInstance.post(s,t,{headers:i});if("undefined"!=typeof window){const e=window.URL.createObjectURL(r.data),t=document.createElement("a");t.href=e,t.setAttribute("download","document.pdf"),document.body.appendChild(t),t.click(),document.body.removeChild(t),window.URL.revokeObjectURL(e)}return{success:!0,message:"PDF downloaded successfully"}}}class c{constructor(e){this.baseService=e}async list(){const e=this.baseService.buildProjectUrl("/functions");return await this.baseService.get(e)}async getByName(e){const t=this.baseService.buildProjectUrl(`/functions/${e}`);return await this.baseService.get(t)}async update(e,t){const s=this.baseService.buildProjectUrl(`/functions/${e}`);return await this.baseService.post(s,t)}async getLogs(e){const t=this.baseService.buildProjectUrl(`/functions/${e}/logs`);return await this.baseService.get(t)}}class l{constructor(e){this.baseService=e}async getCollection(e){const t=this.baseService.buildProjectUrl(`/buildx/collection/${e}`);return await this.baseService.get(t)}async getDocument(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`),i=await this.baseService.get(s);return"object"==typeof i&&null!==i&&(i._display=i._display||i.label||i.title||i.name||i.username||i.description||""),i}async query(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}`),i={};t&&(t.filter&&(i.filter=t.filter),t.jsonFilter&&(i.jsonFilter=t.jsonFilter),t.select&&(i.select=Array.isArray(t.select)?t.select.join(","):t.select),t.projection&&(i.projection=t.projection),t.options&&(i.options=t.options),t.sort&&(i.sort=t.sort),t.limit&&(i.limit=t.limit));const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,o=await this.baseService.get(a);return Array.isArray(o)&&o.forEach(e=>{e._display=e._display||e.label||e.title||e.name||e.username||e.description||""}),o}async create(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}`);return await this.baseService.post(s,t)}async update(e,t,s){const i=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`);return await this.baseService.patch(i,s)}async deleteObject(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`);return await this.baseService.delete(s)}}class u{constructor(e){this.baseService=e}async list(e){const t=e?this.baseService.buildOrgUrl("/auth/api-keys"):"/auth/api-keys";return await this.baseService.get(t)}async get(e,t){const s=t?this.baseService.buildOrgUrl(`/auth/api-key/${e}`):`/auth/api-key/${e}`;return await this.baseService.get(s)}async getSecret(e,t){const s=t?this.baseService.buildOrgUrl(`/auth/api-key/${e}/secret`):`/auth/api-key/${e}/secret`;return await this.baseService.get(s)}}let h={};class d{static getInstance(e,t,s){t||(t="default");const i=(s||"https://api.buildx.ai").replace(/\/$/,"");if(h[t]){const s=h[t];s.config.apiEndpoint===i&&s.config.apiKey===e||s.updateConfig({...s.config,apiEndpoint:i,apiKey:e})}else h[t]=new d({apiEndpoint:i,projectId:t,apiKey:e});return h[t]}constructor(t){this._accessToken=null,this._refreshToken=null,this.config=t,this.axiosInstance=e.create({baseURL:t.apiEndpoint,timeout:3e4}),this.axiosInstance.interceptors.request.use(e=>(e.headers["X-API-Key"]=this.config.apiKey,e),e=>Promise.reject(e)),this.axiosInstance.interceptors.response.use(e=>e,e=>this.handleError(e))}updateConfig(e){this.config=e,this.axiosInstance.defaults.baseURL=e.apiEndpoint}setAccessToken(e){this._accessToken=e}getAccessToken(){return this._accessToken}setRefreshToken(e){this._refreshToken=e}getRefreshToken(){return this._refreshToken}clearTokens(){this._accessToken=null,this._refreshToken=null}isAuthenticated(){return null!==this._accessToken}async getHeaders(e=!1){const t=e?this._refreshToken:this._accessToken,s={"Content-Type":"application/json","X-API-Key":this.config.apiKey};return t&&(s.Authorization=`Bearer ${t}`),s}getPublicHeaders(){return{"Content-Type":"application/json","X-API-Key":this.config.apiKey}}async get(e,t){const s=await this.getHeaders();return(await this.axiosInstance.get(e,{...t,headers:{...s,...t?.headers}})).data}async post(e,t,s){const i=await this.getHeaders();return(await this.axiosInstance.post(e,t,{...s,headers:{...i,...s?.headers}})).data}async put(e,t,s){const i=await this.getHeaders();return(await this.axiosInstance.put(e,t,{...s,headers:{...i,...s?.headers}})).data}async patch(e,t,s){const i=await this.getHeaders();return(await this.axiosInstance.patch(e,t,{...s,headers:{...i,...s?.headers}})).data}async delete(e,t){const s=await this.getHeaders();return(await this.axiosInstance.delete(e,{...t,headers:{...s,...t?.headers}})).data}handleError(e){if(e.response){const{status:t,data:s}=e.response;return s&&"object"==typeof s?{error:s.error||"RequestError",message:s.message||s.description||"Something went wrong",statusCode:t,success:!1}:{error:"RequestError",message:`Request failed with status ${t}`,statusCode:t,success:!1}}return"Network Error"===e.message?{error:"NetworkError",message:"Network connection failed",statusCode:500,success:!1}:{error:"RequestError",message:e.message||"Unknown error occurred",statusCode:500,success:!1}}buildProjectUrl(e=""){const t=this.config.projectId;if(!t||"default"===t)throw new Error("Project ID is required");return`/project/${t}${e}`}buildOrgUrl(e=""){const t=this.config.organizationId||this.config.projectId;if(!t)throw new Error("Organization ID is required");return`/${t}${e}`}buildQueryString(e){const t=new URLSearchParams;Object.entries(e).forEach(([e,s])=>{null!=s&&("object"==typeof s?t.append(e,JSON.stringify(s)):t.append(e,String(s)))});const s=t.toString();return s?`?${s}`:""}}class p{constructor(e){this.config={apiEndpoint:e.apiEndpoint.replace(/\/$/,""),apiKey:e.apiKey,projectId:e.projectId,organizationId:e.organizationId},this._baseService=d.getInstance(this.config.apiKey,this.config.projectId,this.config.apiEndpoint),this._auth=new t(this._baseService),this._projects=new s(this._baseService),this._collections=new r(this._baseService),this._storage=new a(this._baseService),this._flows=new o(this._baseService),this._templates=new n(this._baseService),this._functions=new c(this._baseService),this._buildxObjects=new l(this._baseService),this._apiKeys=new u(this._baseService)}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},this._baseService.updateConfig(this.config)}auth(){return this._auth}projects(){return this._projects}collections(){return this._collections}storage(){return this._storage}flows(){return this._flows}templates(){return this._templates}functions(){return this._functions}buildxObjects(){return this._buildxObjects}apiKeys(){return this._apiKeys}}exports.ApiKeys=u,exports.Auth=t,exports.Buildx=p,exports.BuildxObjects=l,exports.Collections=r,exports.Flows=o,exports.Functions=c,exports.Projects=s,exports.Storage=a,exports.Templates=n,exports.default=p;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("axios");class t{constructor(e){this.baseService=e}setAccessToken(e){this.baseService.setAccessToken(e)}getAccessToken(){return this.baseService.getAccessToken()}setRefreshToken(e){this.baseService.setRefreshToken(e)}getRefreshToken(){return this.baseService.getRefreshToken()}clearTokens(){this.baseService.clearTokens()}isAuthenticated(){return this.baseService.isAuthenticated()}storeTokens(e){e&&"object"==typeof e&&("access_token"in e&&e.access_token&&this.baseService.setAccessToken(e.access_token),"refresh_token"in e&&e.refresh_token&&this.baseService.setRefreshToken(e.refresh_token))}isErrorResponse(e){return e&&"object"==typeof e&&"success"in e&&!1===e.success}hasProjectScope(){const e=this.baseService.config.projectId;return!!e&&"default"!==e}buildAuthUrl(e,t){const s=this.baseService.config.projectId,i=e.startsWith("/auth")?e:`/auth${e.startsWith("/")?e:`/${e}`}`;if(s&&"default"!==s)return`/${s}${i}`;if(t?.requireProjectScope)throw new Error("Project ID is required for this auth endpoint");return i}async login(e){const t=this.buildAuthUrl("/auth/login"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async loginWithGoogle(e){const t=this.buildAuthUrl("/auth/google"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async signup(e){const t=this.buildAuthUrl("/auth/signup"),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async requestEotp(e){const t=this.buildAuthUrl("/auth/eotp/auth/request",{requireProjectScope:!0});return await this.baseService.post(t,e)}async requestEotpAuth(e){return this.requestEotp(e)}async requestOtpLogin(e){return this.requestEotp(e)}async verifyEotp(e){const t=this.buildAuthUrl("/auth/eotp/auth/verify",{requireProjectScope:!0}),s=await this.baseService.post(t,e);return this.isErrorResponse(s)||this.storeTokens(s),s}async verifyEotpAuth(e){return this.verifyEotp(e)}async verifyOtpLogin(e){return this.verifyEotp(e)}async getCurrentUser(){const e=this.buildAuthUrl("/auth/me");return await this.baseService.get(e)}async refreshToken(){const e=this.buildAuthUrl("/auth/token"),t=await this.baseService.post(e,{});return this.isErrorResponse(t)||t&&"object"==typeof t&&"access_token"in t&&t.access_token&&this.storeTokens(t),t}async updatePassword(e){const t=this.buildAuthUrl("/auth/password/update");return await this.baseService.post(t,{password:e})}async changePassword(e){const t=this.buildAuthUrl("/auth/password/update");if("string"==typeof e)return await this.baseService.post(t,{password:e});const s=e.password??e.newPassword??e.new_password,i={...e};return s&&(i.password=s),e.currentPassword&&!i.current_password&&(i.current_password=e.currentPassword),e.newPassword&&!i.new_password&&(i.new_password=e.newPassword),await this.baseService.post(t,i)}async adminUpdatePassword(e,t){const s=this.buildAuthUrl("/auth/password/update");return await this.baseService.post(s,{user_id:e,password:t})}async requestPasswordReset(e){const t=this.buildAuthUrl("/auth/password/reset/request");return await this.baseService.post(t,e)}async resetPassword(e){const t=this.buildAuthUrl("/auth/password/reset");return await this.baseService.post(t,e)}async updatePushToken(e){const t=this.hasProjectScope()?`/${this.baseService.config.projectId}/users/push-tokens`:"/users/push-tokens";return await this.baseService.post(t,{token:e})}async listUsers(e){const t=e?`/${e}/auth/users`:"/auth/users";return await this.baseService.get(t)}async lookupUsers(e){const t=e?`/${e}/auth/users/lookup`:"/auth/users/lookup";return await this.baseService.get(t)}async getUser(e,t){const s=t?`/${t}/auth/user/${e}`:`/auth/user/${e}`;return await this.baseService.get(s)}async deleteUser(e){const t=this.buildAuthUrl(`/auth/user/${e}/delete`);return await this.baseService.post(t,{})}}class s{constructor(e){this.baseService=e}async list(){return await this.baseService.get("/projects")}async get(e){return await this.baseService.get(`/project/${e}`)}async create(e){return await this.baseService.post("/projects",e)}async update(e,t){return await this.baseService.patch(`/project/${e}`,t)}async deleteById(e){return await this.baseService.delete(`/project/${e}`)}async backup(e){const t=await this.baseService.axiosInstance.get(`/project/${e}/backup`,{responseType:"blob",headers:await this.baseService.getHeaders()});if("undefined"!=typeof window){const s=window.URL.createObjectURL(t.data),i=document.createElement("a");i.href=s,i.setAttribute("download",`backup_${e}.buildx`),document.body.appendChild(i),i.click(),document.body.removeChild(i),window.URL.revokeObjectURL(s)}return{success:!0,message:"Backup downloaded successfully"}}async restore(e,t){const s=new FormData;s.append("new_project_id",e),s.append("backup_file",t);const i={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data"};return await this.baseService.post("/project/import",s,{headers:i})}}class i{constructor(e,t,s){this.baseService=e,this.collectionId=t,this.wsFactory=s,this.socket=null,this.connectPromise=null,this.requestCounter=0,this.pending=new Map}async query(e,t,s=3e4){if(await this.ensureConnected(),!this.socket)throw new Error("WebSocket connection is unavailable");const i=`${Date.now()}_${++this.requestCounter}`,r=new Promise((e,t)=>{const r=setTimeout(()=>{this.pending.delete(i),t(new Error("WebSocket pagination timeout"))},s);this.pending.set(i,{resolve:e,reject:t,timeout:r})});return this.socket.send(JSON.stringify({id:i,action:e,payload:t})),r}close(){if(this.socket){try{this.socket.close()}catch(e){}this.socket=null,this.connectPromise=null;for(const[,e]of this.pending.entries())clearTimeout(e.timeout),e.reject(new Error("WebSocket closed"));this.pending.clear()}}async ensureConnected(){if(!this.socket||!this.isSocketOpen(this.socket))return this.connectPromise||(this.connectPromise=new Promise((e,t)=>{const s=globalThis.WebSocket;if(!this.wsFactory&&!s)return void t(new Error("WebSocket is not available in this runtime"));const i=this.wsFactory?this.wsFactory(this.buildSocketUrl()):new s(this.buildSocketUrl());this.socket=i;let r=!1;const a=()=>{r||(r=!0,e())},n=e=>{r||(r=!0,t(e)),this.close()},o=()=>{r||(r=!0,t(new Error("WebSocket closed before connection is ready"))),this.close()},c=e=>{let t;try{t=JSON.parse(e?.data||"{}")}catch(e){return}const s=t?.id;if(!s)return;const i=this.pending.get(s);i&&(clearTimeout(i.timeout),this.pending.delete(s),t.ok&&t.result?i.resolve(t.result):i.reject(new Error(t.error||"WebSocket pagination query failed")))};i.addEventListener?(i.addEventListener("open",a),i.addEventListener("error",n),i.addEventListener("close",o),i.addEventListener("message",c)):(i.onopen=a,i.onerror=n,i.onclose=o,i.onmessage=c)}).finally(()=>{this.connectPromise=null})),this.connectPromise}isSocketOpen(e){const t=globalThis.WebSocket?.OPEN??1;return e.readyState===t}buildSocketUrl(){const e=this.baseService.config.apiEndpoint.replace(/\/$/,"").replace(/^http:/i,"ws:").replace(/^https:/i,"wss:"),t=this.baseService.buildProjectUrl(`/${this.collectionId}/data/pagination/ws`),s=new URLSearchParams,i=this.baseService.config.apiKey;i&&s.set("api_key",i);const r=this.baseService.getAccessToken();r&&s.set("token",r);const a=s.toString();return`${e}${t}${a?`?${a}`:""}`}}class r{constructor(e){this.collectionWsClient=null,this.collectionWsCollectionId=null,this.collectionWsDisabledUntil=0,this.baseService=e}async list(e=!1,t=!1){const s=this.baseService.buildProjectUrl("/collections"),i={};e&&(i.with_stats=!0);const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,n=await this.baseService.get(a);return Array.isArray(n)&&!t?n.filter(e=>e.collection_id&&!e.collection_id.startsWith("buildx_")):n}async getSchema(e,t=1){const s=this.baseService.buildProjectUrl(`/collection/${e}`),i={};t>1&&(i.depth=t);const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s;return await this.baseService.get(a)}async set(e){const t=this.baseService.buildProjectUrl("/collections");return await this.baseService.post(t,e)}async deleteCollection(e){const t=this.baseService.buildProjectUrl(`/collections/${e}`);return await this.baseService.delete(t)}async query(e,t){const s=this.baseService.buildProjectUrl(`/${e}`),i=t?.noPopulate??(!!t?.relations&&t.relations.length>0),r=this.buildQueryParams({...t,options:i?{...t?.options||{},noPopulate:!0}:t?.options}),a=this.baseService.buildQueryString(r),n=a?`${s}${a}`:s,o=await this.baseService.get(n);if(!Array.isArray(o))return o;if(!t?.relations||0===t.relations.length)return o;const c="http"!==(t?.paginationTransport||"auto");return await this.hydrateRelations(o,t.relations,t.relationSelect,{preferWs:c,wsFactory:t.wsFactory})}async queryRaw(e,t){const s={...t,options:{...t?.options||{},noPopulate:!0}};if("http"!==(s.paginationTransport||"http")&&Date.now()>=this.collectionWsDisabledUntil)try{return await this.queryRawViaWs(e,s)}catch(e){console.warn("[buildx-sdk] WS raw query failed, fallback to HTTP",e?.message||e),this.collectionWsDisabledUntil=Date.now()+3e4,this.resetCollectionWsClient()}const i=this.baseService.buildProjectUrl(`/${e}/raw`),r=this.buildQueryParams(s),a=this.baseService.buildQueryString(r),n=a?`${i}${a}`:i;return await this.baseService.get(n)}async queryWithPagination(e,t){const s=t?.noPopulate??(!!t?.relations&&t.relations.length>0),i={...t,options:s?{...t?.options||{},noPopulate:!0}:t?.options},r=i.paginationTransport||"auto";let a;if("http"!==r&&Date.now()>=this.collectionWsDisabledUntil)try{a=await this.queryWithPaginationViaWs(e,i)}catch(t){console.warn("[buildx-sdk] WS pagination failed, fallback to HTTP",t?.message||t),this.collectionWsDisabledUntil=Date.now()+3e4,this.resetCollectionWsClient(),a=await this.queryWithPaginationViaHttp(e,i)}else a=await this.queryWithPaginationViaHttp(e,i);if(!a||!1===a.success)return a;if(!i?.relations||0===i.relations.length)return a;const n="http"!==r,o=await this.hydrateRelations(a.data||[],i.relations,i.relationSelect,{preferWs:n,wsFactory:i.wsFactory});return Array.isArray(o)?{...a,data:o}:o}async queryWithPaginationViaHttp(e,t){const s=this.baseService.buildProjectUrl(`/${e}/data/pagination`),i=this.buildQueryParams(t),r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,n=await this.baseService.get(a);return n&&!1!==n.success?{...n,meta:{...n.meta||{},transport:"http"}}:n}async queryWithPaginationViaWs(e,t){const s=this.buildQueryParams(t),i=this.getOrCreateCollectionWsClient(e,t?.wsFactory),r=await i.query("queryWithPagination",s);return r&&!1!==r.success?{...r,meta:{...r.meta||{},transport:"ws"}}:r}async queryRawViaWs(e,t){const s=this.buildQueryParams(t),i=this.getOrCreateCollectionWsClient(e,t?.wsFactory),r=await i.query("queryRaw",s);return r&&!1!==r.success?Array.isArray(r)?r:[]:r}getOrCreateCollectionWsClient(e,t){return this.collectionWsClient&&this.collectionWsCollectionId===e||(this.resetCollectionWsClient(),this.collectionWsClient=new i(this.baseService,e,t),this.collectionWsCollectionId=e),this.collectionWsClient}resetCollectionWsClient(){this.collectionWsClient&&this.collectionWsClient.close(),this.collectionWsClient=null,this.collectionWsCollectionId=null}subscribeRealtime(e,t,s){const i=this.baseService.config.apiEndpoint.replace(/\/$/,""),r=this.baseService.buildProjectUrl(`/${e}/realtime/stream`),a=new URLSearchParams,n=s?.apiKey||this.baseService.config.apiKey;n&&a.set("api_key",n);const o=s?.token||this.baseService.getAccessToken();o&&a.set("token",o),s?.lastEventId&&a.set("lastEventId",s.lastEventId);const c=a.toString(),l=`${i}${r}${c?`?${c}`:""}`,u=s?.eventSourceFactory||globalThis.EventSource;if(!u)throw new Error("EventSource is not available in this runtime. Provide eventSourceFactory in options.");const h=u(l);let p=!1;const d=()=>{p||(p=!0,t.onConnected?.())},b=e=>{try{const s=JSON.parse(e.data);t.onEvent?.(s)}catch(e){t.onError?.(e)}};return h.onopen=()=>{d()},h.onmessage=e=>b(e),h.onerror=e=>{t.onError?.(e)},h.addEventListener?.("connected",()=>{d()}),h.addEventListener?.("collection:data",e=>{b(e)}),{close:()=>h.close()}}async lookup(e,t){const s=this.baseService.buildProjectUrl(`/${e}`),i={};t&&(t.filter&&(i.filter=t.filter),t.jsonFilter&&(i.jsonFilter=t.jsonFilter),t.projection&&(i.projection=t.projection),t.options&&(i.options=t.options));const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,n=await this.baseService.get(a);return Array.isArray(n)?n.map(e=>({value:e._id,label:e._display||e.label||e.title||e.name||e.username||e.description||""})):n}buildQueryParams(e){const t={};if(!e)return t;const s=e.q||e.searchQuery;return s&&(t.q=s),e.quick_filter_fields&&(t.quick_filter_fields=e.quick_filter_fields),e.filter&&(t.filter=e.filter),e.jsonFilter&&(t.jsonFilter=e.jsonFilter),e.select&&(t.select=Array.isArray(e.select)?e.select.join(","):e.select),e.projection&&(t.projection=e.projection),e.options&&(t.options=e.options),e.sort&&(t.sort=e.sort),"number"==typeof e.limit&&(t.limit=e.limit),"number"==typeof e.skip&&e.skip>0&&(t.skip=e.skip),t}async hydrateRelations(e,t,s,i){const a=e.map(e=>({...e})),n=s||"_id,_display,name,title,username",o=t.reduce((e,t)=>(e[t.collectionId]||(e[t.collectionId]=[]),e[t.collectionId].push(t),e),{}),c=new Map;for(const[e,t]of Object.entries(o)){const s=new Set;for(const e of a)for(const i of t){const t=e[i.field];if(t)if(Array.isArray(t))for(const e of t)"string"==typeof e?s.add(e):e&&"object"==typeof e&&e._id&&s.add(e._id);else"string"==typeof t?s.add(t):t&&"object"==typeof t&&t._id&&s.add(t._id)}const o=Array.from(s).filter(t=>!c.has(`${e}:${t}`));if(o.length>0){const t=r.RELATION_QUERY_CHUNK_SIZE;for(let s=0;s<o.length;s+=t){const r=o.slice(s,s+t),a=await this.queryRaw(e,{filter:{_id:{$in:r}},select:n,paginationTransport:i?.preferWs?"auto":"http",wsFactory:i?.wsFactory});if(!Array.isArray(a))return a;for(const t of a)t?._id&&c.set(`${e}:${t._id}`,t)}}for(const s of a)for(const i of t){const t=s[i.field];if(t)if(Array.isArray(t))s[i.field]=t.map(t=>{const s="string"==typeof t?t:t?._id;return s&&c.get(`${e}:${s}`)||t});else{const r="string"==typeof t?t:t?._id;if(!r)continue;s[i.field]=c.get(`${e}:${r}`)||t}}}return a}async getDocument(e,t,s){const i=this.baseService.buildProjectUrl(`/${e}/${t}`),r={};s&&s.length>0&&(r.populate=s.join(","));const a=this.baseService.buildQueryString(r),n=a?`${i}${a}`:i;return await this.baseService.get(n)}async createDocument(e,t){const s=this.baseService.buildProjectUrl(`/${e}`);return await this.baseService.post(s,t)}async updateDocument(e,t,s){const i=this.baseService.buildProjectUrl(`/${e}/${t}`);return await this.baseService.patch(i,s)}async updateDocumentWithOptions(e,t,s,i){const r=this.baseService.buildProjectUrl(`/${e}/${t}`),a=i?.updateOnly?`${r}?mode=updateOnly`:r;return await this.baseService.patch(a,s)}async getDocumentRevisions(e,t){const s=this.baseService.buildProjectUrl(`/${e}/${t}/revisions`);return await this.baseService.get(s)}async deleteDocument(e,t){const s=this.baseService.buildProjectUrl(`/${e}/${t}`);return await this.baseService.delete(s)}async deleteByFilter(e,t){const s=this.baseService.buildProjectUrl(`/${e}/delete`);return await this.baseService.post(s,{filter:t})}async import(e,t,s){const i=new FormData;i.append("mapping",JSON.stringify(s)),i.append("file",t);const r=this.baseService.buildProjectUrl(`/${e}/import`),a={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data"};return await this.baseService.post(r,i,{headers:a})}async getDataTypes(){const e=this.baseService.buildProjectUrl("/collections/types");return await this.baseService.get(e)}async validate(e){const t=this.baseService.buildProjectUrl(`/${e}/validate`);return await this.baseService.post(t,null)}async migrate(e){const t=this.baseService.buildProjectUrl(`/${e}/migrate`);return await this.baseService.post(t,null)}}r.RELATION_QUERY_CHUNK_SIZE=200;class a{constructor(e){this.baseService=e}async upload(e,t){const s=new FormData;t&&""!==t&&s.append("prefix",t),s.append("file",e),s.append("filename",e.name||"file");const i=this.baseService.buildProjectUrl("/storage/upload"),r={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data; charset=utf-8"};return await this.baseService.post(i,s,{headers:r})}async uploadToCollection(e,t,s){const i=new FormData;s&&""!==s&&i.append("prefix",s),i.append("file",e),i.append("filename",e.name||"file"),i.append("collection_id",t);const r=this.baseService.buildProjectUrl("/storage/upload"),a={...await this.baseService.getHeaders(),"Content-Type":"multipart/form-data; charset=utf-8"};return await this.baseService.post(r,i,{headers:a})}async list(e){const t=this.baseService.buildProjectUrl(`/storage?path=${encodeURIComponent(e)}`);return await this.baseService.get(t)}async getSize(e){const t=this.baseService.buildProjectUrl(`/storage/size?path=${encodeURIComponent(e)}`);return await this.baseService.get(t)}async delete(e){const t=this.baseService.buildProjectUrl(`/storage?path=${encodeURIComponent(e)}`);return await this.baseService.delete(t)}}class n{constructor(e){this.baseService=e}async getTypes(){return await this.baseService.get("/flows/types")}async run(e,t=null,s="root",i={}){const r=this.baseService.buildProjectUrl(`/flows/${e}/run`);return await this.baseService.post(r,{session_id:t,state:s,args:i})}async getGptFlowSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/flow/node");return await this.baseService.post(t,{instruction:e})}async getGptCollectionSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/collections");return await this.baseService.post(t,{instruction:e})}async getGptLifecycleSuggestions(e){const t=this.baseService.buildProjectUrl("/ai/gpt/lifecycle");return await this.baseService.post(t,{instruction:e})}}class o{constructor(e){this.baseService=e}async preview(e,t){const s=this.baseService.buildProjectUrl("/templates/preview");return await this.baseService.post(s,{template:e,data:t})}async render(e,t){const s=this.baseService.buildProjectUrl(`/templates/${e}/render`);return await this.baseService.post(s,t)}async renderPDF(e,t){const s=this.baseService.buildProjectUrl(`/templates/${e}/pdf`),i={...await this.baseService.getHeaders(),responseType:"blob"},r=await this.baseService.axiosInstance.post(s,t,{headers:i});if("undefined"!=typeof window){const e=window.URL.createObjectURL(r.data),t=document.createElement("a");t.href=e,t.setAttribute("download","document.pdf"),document.body.appendChild(t),t.click(),document.body.removeChild(t),window.URL.revokeObjectURL(e)}return{success:!0,message:"PDF downloaded successfully"}}}class c{constructor(e){this.baseService=e}async list(){const e=this.baseService.buildProjectUrl("/functions");return await this.baseService.get(e)}async getByName(e){const t=this.baseService.buildProjectUrl(`/functions/${e}`);return await this.baseService.get(t)}async update(e,t){const s=this.baseService.buildProjectUrl(`/functions/${e}`);return await this.baseService.post(s,t)}async getLogs(e){const t=this.baseService.buildProjectUrl(`/functions/${e}/logs`);return await this.baseService.get(t)}}class l{constructor(e){this.baseService=e}async getCollection(e){const t=this.baseService.buildProjectUrl(`/buildx/collection/${e}`);return await this.baseService.get(t)}async getDocument(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`),i=await this.baseService.get(s);return"object"==typeof i&&null!==i&&(i._display=i._display||i.label||i.title||i.name||i.username||i.description||""),i}async query(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}`),i={};t&&(t.filter&&(i.filter=t.filter),t.jsonFilter&&(i.jsonFilter=t.jsonFilter),t.select&&(i.select=Array.isArray(t.select)?t.select.join(","):t.select),t.projection&&(i.projection=t.projection),t.options&&(i.options=t.options),t.sort&&(i.sort=t.sort),t.limit&&(i.limit=t.limit));const r=this.baseService.buildQueryString(i),a=r?`${s}${r}`:s,n=await this.baseService.get(a);return Array.isArray(n)&&n.forEach(e=>{e._display=e._display||e.label||e.title||e.name||e.username||e.description||""}),n}async create(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}`);return await this.baseService.post(s,t)}async update(e,t,s){const i=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`);return await this.baseService.patch(i,s)}async deleteObject(e,t){const s=this.baseService.buildProjectUrl(`/buildx/${e}/${t}`);return await this.baseService.delete(s)}}class u{constructor(e){this.baseService=e}async list(e){const t=e?`/${e}/auth/api-keys`:"/auth/api-keys";return await this.baseService.get(t)}async get(e,t){const s=t?`/${t}/auth/api-key/${e}`:`/auth/api-key/${e}`;return await this.baseService.get(s)}async getSecret(e,t){const s=t?`/${t}/auth/api-key/${e}/secret`:`/auth/api-key/${e}/secret`;return await this.baseService.get(s)}}let h={};class p{static getInstance(e,t,s){t||(t="default");const i=(s||"https://api.buildx.ai").replace(/\/$/,"");if(h[t]){const s=h[t];s.config.apiEndpoint===i&&s.config.apiKey===e||s.updateConfig({...s.config,apiEndpoint:i,apiKey:e})}else h[t]=new p({apiEndpoint:i,projectId:t,apiKey:e});return h[t]}constructor(t){this._accessToken=null,this._refreshToken=null,this.config=t,this.axiosInstance=e.create({baseURL:t.apiEndpoint,timeout:3e4}),this.axiosInstance.interceptors.request.use(e=>(e.headers["X-API-Key"]=this.config.apiKey,e),e=>Promise.reject(e)),this.axiosInstance.interceptors.response.use(e=>e,e=>this.handleError(e))}updateConfig(e){this.config=e,this.axiosInstance.defaults.baseURL=e.apiEndpoint}setAccessToken(e){this._accessToken=e}getAccessToken(){return this._accessToken}setRefreshToken(e){this._refreshToken=e}getRefreshToken(){return this._refreshToken}clearTokens(){this._accessToken=null,this._refreshToken=null}isAuthenticated(){return null!==this._accessToken}async getHeaders(e=!1){const t=e?this._refreshToken:this._accessToken,s={"Content-Type":"application/json","X-API-Key":this.config.apiKey};return t&&(s.Authorization=`Bearer ${t}`),s}getPublicHeaders(){return{"Content-Type":"application/json","X-API-Key":this.config.apiKey}}async get(e,t){const s=await this.getHeaders(),i=await this.axiosInstance.get(e,{...t,headers:{...s,...t?.headers}});return this.unwrapResponse(i)}async post(e,t,s){const i=await this.getHeaders(),r=await this.axiosInstance.post(e,t,{...s,headers:{...i,...s?.headers}});return this.unwrapResponse(r)}async put(e,t,s){const i=await this.getHeaders(),r=await this.axiosInstance.put(e,t,{...s,headers:{...i,...s?.headers}});return this.unwrapResponse(r)}async patch(e,t,s){const i=await this.getHeaders(),r=await this.axiosInstance.patch(e,t,{...s,headers:{...i,...s?.headers}});return this.unwrapResponse(r)}async delete(e,t){const s=await this.getHeaders(),i=await this.axiosInstance.delete(e,{...t,headers:{...s,...t?.headers}});return this.unwrapResponse(i)}unwrapResponse(e){return e&&"object"==typeof e&&"data"in e?e.data:e}handleError(e){if(e.response){const{status:t,data:s}=e.response;return s&&"object"==typeof s?{error:s.error||"RequestError",message:s.message||s.description||"Something went wrong",statusCode:t,success:!1}:{error:"RequestError",message:`Request failed with status ${t}`,statusCode:t,success:!1}}return"Network Error"===e.message?{error:"NetworkError",message:"Network connection failed",statusCode:500,success:!1}:{error:"RequestError",message:e.message||"Unknown error occurred",statusCode:500,success:!1}}buildProjectUrl(e=""){const t=this.config.projectId;if(!t||"default"===t)throw new Error("Project ID is required");return`/project/${t}${e}`}buildOrgUrl(e=""){const t=this.config.organizationId||this.config.projectId;if(!t)throw new Error("Organization ID is required");return`/${t}${e}`}buildQueryString(e){const t=new URLSearchParams;Object.entries(e).forEach(([e,s])=>{null!=s&&("object"==typeof s?t.append(e,JSON.stringify(s)):t.append(e,String(s)))});const s=t.toString();return s?`?${s}`:""}}class d{constructor(e){this.config={apiEndpoint:e.apiEndpoint.replace(/\/$/,""),apiKey:e.apiKey,projectId:e.projectId,organizationId:e.organizationId},this._baseService=p.getInstance(this.config.apiKey,this.config.projectId,this.config.apiEndpoint),this._auth=new t(this._baseService),this._projects=new s(this._baseService),this._collections=new r(this._baseService),this._storage=new a(this._baseService),this._flows=new n(this._baseService),this._templates=new o(this._baseService),this._functions=new c(this._baseService),this._buildxObjects=new l(this._baseService),this._apiKeys=new u(this._baseService)}getConfig(){return{...this.config}}updateConfig(e){this.config={...this.config,...e},this._baseService.updateConfig(this.config)}auth(){return this._auth}projects(){return this._projects}collections(){return this._collections}storage(){return this._storage}flows(){return this._flows}templates(){return this._templates}functions(){return this._functions}buildxObjects(){return this._buildxObjects}apiKeys(){return this._apiKeys}}exports.ApiKeys=u,exports.Auth=t,exports.Buildx=d,exports.BuildxObjects=l,exports.Collections=r,exports.Flows=n,exports.Functions=c,exports.Projects=s,exports.Storage=a,exports.Templates=o,exports.default=d;
2
2
  //# sourceMappingURL=index.cjs.map