@squidcloud/client
Version:
A typescript implementation of the Squid client
1 lines • 163 kB
JavaScript
(()=>{"use strict";var e={86:e=>{e.exports=require("ws")},150:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const s=i(642);t.default=s.PromisePool,r(i(273),t),r(i(642),t),r(i(837),t),r(i(426),t),r(i(858),t),r(i(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class i extends Error{constructor(e){super(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e){return new this(e)}}t.ValidationError=i},234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=i(642),r=i(172),s=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],taskTimeout:0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw r.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}isValidConcurrency(e){return"number"==typeof e&&e>=1}withTaskTimeout(e){return this.meta.taskTimeout=e,this}concurrency(){return this.meta.concurrency}useCorrespondingResults(e){return this.meta.shouldResultsCorrespond=e,this}shouldUseCorrespondingResults(){return this.meta.shouldResultsCorrespond}taskTimeout(){return this.meta.taskTimeout}for(e){return this.meta.items=e,this}items(){return this.meta.items}itemsCount(){const e=this.items();return Array.isArray(e)?e.length:NaN}tasks(){return this.meta.tasks}activeTaskCount(){return this.activeTasksCount()}activeTasksCount(){return this.tasks().length}processedItems(){return this.meta.processedItems}processedCount(){return this.processedItems().length}processedPercentage(){return this.processedCount()/this.itemsCount()*100}results(){return this.meta.results}errors(){return this.meta.errors}withHandler(e){return this.handler=e,this}hasErrorHandler(){return!!this.errorHandler}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers=e,this}onTaskFinished(e){return this.onTaskFinishedHandlers=e,this}hasReachedConcurrencyLimit(){return this.activeTasksCount()>=this.concurrency()}stop(){throw this.markAsStopped(),new o.StopThePromisePoolError}markAsStopped(){return this.meta.stopped=!0,this}isStopped(){return this.meta.stopped}async start(){return await this.validateInputs().prepareResultsArray().process()}validateInputs(){if("function"!=typeof this.handler)throw r.ValidationError.createFrom("The first parameter for the .process(fn) method must be a function");const e=this.taskTimeout();if(!(null==e||"number"==typeof e&&e>=0))throw r.ValidationError.createFrom(`"timeout" must be undefined or a number. A number must be 0 or up. Received "${String(e)}" (${typeof e})`);if(!this.areItemsValid())throw r.ValidationError.createFrom(`"items" must be an array, an iterable or an async iterable. Received "${typeof this.items()}"`);if(this.errorHandler&&"function"!=typeof this.errorHandler)throw r.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw r.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw r.ValidationError.createFrom(`The error handler must be a function. Received "${typeof e}"`)}),this}areItemsValid(){const e=this.items();return!!Array.isArray(e)||"function"==typeof e[Symbol.iterator]||"function"==typeof e[Symbol.asyncIterator]}prepareResultsArray(){const e=this.items();return Array.isArray(e)&&this.shouldUseCorrespondingResults()?(this.meta.results=Array(e.length).fill(n.PromisePool.notRun),this):this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=n.PromisePool.notRun),this.startProcessing(t,e),e+=1,await this.waitForProcessingSlot()}return await this.drained()}async waitForProcessingSlot(){for(;this.hasReachedConcurrencyLimit();)await this.waitForActiveTaskToFinish()}async waitForActiveTaskToFinish(){await Promise.race(this.tasks())}startProcessing(e,t){const i=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(i)}).catch(async n=>{await this.handleErrorFor(n,e,t),this.removeActive(i)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(i),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[i,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise((i,n)=>{t=setTimeout(()=>{n(new s.PromisePoolError(`Task in promise pool timed out after ${this.taskTimeout()}ms`,e))},this.taskTimeout())}),()=>clearTimeout(t)]}save(e,t){return this.shouldUseCorrespondingResults()?this.results()[t]=e:this.results().push(e),this}removeActive(e){return this.tasks().splice(this.tasks().indexOf(e),1),this}async handleErrorFor(e,t,i){if(this.shouldUseCorrespondingResults()&&(this.results()[i]=n.PromisePool.failed),!this.isStoppingThePoolError(e)){if(this.isValidationError(e))throw this.markAsStopped(),e;this.hasErrorHandler()?await this.runErrorHandlerFor(e,t):this.saveErrorFor(e,t)}}isStoppingThePoolError(e){return e instanceof o.StopThePromisePoolError}isValidationError(e){return e instanceof r.ValidationError}async runErrorHandlerFor(e,t){try{await(this.errorHandler?.(e,t,this))}catch(e){this.rethrowIfNotStoppingThePool(e)}}runOnTaskStartedHandlers(e){this.onTaskStartedHandlers.forEach(t=>{t(e,this)})}runOnTaskFinishedHandlers(e){this.onTaskFinishedHandlers.forEach(t=>{t(e,this)})}rethrowIfNotStoppingThePool(e){if(!this.isStoppingThePoolError(e))throw e}saveErrorFor(e,t){this.errors().push(s.PromisePoolError.createFrom(e,t))}async drained(){return await this.drainActiveTasks(),{errors:this.errors(),results:this.results()}}async drainActiveTasks(){await Promise.all(this.tasks())}}},273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},426:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(234);class r{constructor(e){this.timeout=void 0,this.concurrency=10,this.items=e??[],this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[],this.shouldResultsCorrespond=!1}withConcurrency(e){return this.concurrency=e,this}static withConcurrency(e){return(new this).withConcurrency(e)}withTaskTimeout(e){return this.timeout=e,this}static withTaskTimeout(e){return(new this).withTaskTimeout(e)}for(e){const t=new r(e).withConcurrency(this.concurrency);return"function"==typeof this.errorHandler&&t.handleError(this.errorHandler),"number"==typeof this.timeout?t.withTaskTimeout(this.timeout):t}static for(e){return(new this).for(e)}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers.push(e),this}onTaskFinished(e){return this.onTaskFinishedHandlers.push(e),this}useCorrespondingResults(){return this.shouldResultsCorrespond=!0,this}async process(e){return(new n.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=r,r.notRun=Symbol("notRun"),r.failed=Symbol("failed")},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class i extends Error{constructor(e,t){super(),this.raw=e,this.item=t,this.name=this.constructor.name,this.message=this.messageFrom(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e,t){return new this(e,t)}messageFrom(e){return e instanceof Error||"object"==typeof e?e.message:"string"==typeof e||"number"==typeof e?e.toString():""}}t.PromisePoolError=i},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i}},t={};function i(n){var r=t[n];if(void 0!==r)return r.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,i),s.exports}i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};i.r(n),i.d(n,{AI_AGENTS_INTEGRATION_ID:()=>Qe,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Fe,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Re,AI_CHAT_MESSAGE_SOURCE:()=>pe,AI_EMBEDDINGS_MODEL_NAMES:()=>ke,AI_IMAGE_MODEL_NAMES:()=>Ne,AI_PROVIDER_TYPES:()=>me,AI_STATUS_MESSAGE_PARENT_MESSAGE_ID_TAG:()=>ge,AI_STATUS_MESSAGE_RESULT_TAG:()=>fe,ALL_OPERATORS:()=>rt,ANTHROPIC_CHAT_MODEL_NAMES:()=>Se,API_INJECTION_FIELD_TYPES:()=>Pe,ARRAY_OPERATORS:()=>nt,AUTH_INTEGRATION_TYPES:()=>Ge,AdminClient:()=>l,AiAgentClient:()=>ne,AiAgentReference:()=>te,AiAssistantClient:()=>se,AiAudioClient:()=>oe,AiClient:()=>at,AiImageClient:()=>ae,AiKnowledgeBaseClient:()=>le,AiKnowledgeBaseReference:()=>ue,AiMatchMakingClient:()=>he,ApiClient:()=>ut,ApiKeysSecretClient:()=>u,AuthManager:()=>lt,BUILT_IN_AGENT_ID:()=>G,BUILT_IN_DB_INTEGRATION_ID:()=>We,BUILT_IN_QUEUE_INTEGRATION_ID:()=>ze,BUILT_IN_STORAGE_INTEGRATION_ID:()=>Je,BackendFunctionManager:()=>qt,BaseQueryBuilder:()=>zt,CLIENT_CONNECTION_STATES:()=>ot,CLIENT_ID_GENERATOR_KEY:()=>xt,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>Pt,Changes:()=>Zt,ClientIdService:()=>jt,CollectionReference:()=>ni,CollectionReferenceFactory:()=>si,ConnectionDetails:()=>oi,DATA_INTEGRATION_TYPES:()=>$e,DEFAULT_SHORT_ID_LENGTH:()=>K,DataManager:()=>fi,DereferencedJoin:()=>ei,DestructManager:()=>mi,DistributedLockImpl:()=>Ii,DistributedLockManager:()=>bi,DocumentReference:()=>Ht,DocumentReferenceFactory:()=>Si,DocumentStore:()=>wi,EMPTY_CHAT_ID:()=>re,ENVIRONMENT_IDS:()=>$,ExtractionClient:()=>Mi,FETCH_BEYOND_LIMIT:()=>mn,FLUX_MODEL_NAMES:()=>qe,GEMINI_CHAT_MODEL_NAMES:()=>Ie,GRAPHQL_INTEGRATION_TYPES:()=>Ve,GROK_CHAT_MODEL_NAMES:()=>ve,GroupedJoin:()=>ii,HTTP_INTEGRATION_TYPES:()=>He,HttpStatus:()=>Le,INTEGRATION_SCHEMA_TYPES:()=>Ke,INTEGRATION_TYPES:()=>Ue,IntegrationClient:()=>a,JobClient:()=>Ti,JoinQueryBuilder:()=>Xt,LastUsedValueExecuteFunctionCache:()=>At,LimitUnderflowState:()=>ln,LocalQueryManager:()=>Vi,METRIC_DOMAIN:()=>tt,METRIC_FUNCTIONS:()=>et,METRIC_INTERVAL_ALIGNMENT:()=>it,MatchMaker:()=>de,MutationSender:()=>_i,NOOP_FN:()=>En,NativeQueryManager:()=>ki,NotificationClient:()=>Ei,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Oe,OPENAI_AUDIO_MODEL_NAMES:()=>De,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Ce,OPENAI_CHAT_MODEL_NAMES:()=>be,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>Te,OPENAI_IMAGE_MODEL_NAMES:()=>Ee,OPEN_AI_CREATE_SPEECH_FORMATS:()=>je,ObservabilityClient:()=>Oi,Pagination:()=>Kt,PersonalStorageClient:()=>qi,QueryBuilder:()=>Yt,QueryBuilderFactory:()=>Wt,QuerySender:()=>Ki,QuerySubscriptionManager:()=>bn,QueueManagerFactory:()=>wn,QueueManagerImpl:()=>Tn,RAG_TYPES:()=>xe,RERANK_PROVIDERS:()=>ye,RateLimiter:()=>_n,RpcManager:()=>xn,SQUID_BUILT_IN_INTEGRATION_IDS:()=>Ye,SQUID_METRIC_NAMES:()=>Xe,SQUID_REGIONS:()=>st,STABLE_DIFFUSION_MODEL_NAMES:()=>Ae,SchedulerClient:()=>Pn,SecretClient:()=>c,SocketManager:()=>Qn,Squid:()=>Wn,SquidClientError:()=>Cn,StorageClient:()=>Hn,VENDOR_AI_CHAT_MODEL_NAMES:()=>we,VOYAGE_EMBEDDING_MODEL_NAMES:()=>_e,WebClient:()=>Kn,base64ToFile:()=>ee,compareArgsByReference:()=>Ot,compareArgsBySerializedValue:()=>Dt,deserializeQuery:()=>Ri,generateId:()=>H,generateShortId:()=>z,generateShortIds:()=>J,generateUUID:()=>V,getConsoleUrl:()=>o,getCustomizationFlag:()=>Nt,isBuiltInIntegrationId:()=>Ze,isPlaceholderParam:()=>Be,isVendorAiChatModelName:()=>Me,rawSquidHttpDelete:()=>Rn,rawSquidHttpGet:()=>An,rawSquidHttpPatch:()=>Nn,rawSquidHttpPost:()=>Dn,rawSquidHttpPut:()=>qn,tryDeserializing:()=>jn,visitQueryResults:()=>Ni});const r=["aiData","api","application","application-kotlin","auth","backend-function","connector","integration","internal-storage","internalCodeExecutor","mutation","named-query","native-query","observability","openapi","query","queue","quota","scheduler","secret","storage","webhooks","ws","personalStorage","internal-extraction","notification"];function s(e,t,i,n,s){let o="https",a=`${n||t}.${s||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=r.includes(i.replace(/^\//,"").split("/")[0]||"")?"8001":"8000",/android$/.test(e)?a="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(a="localhost"));const u=o+"://"+a+(c?`:${c}`:""),l=i.replace(/^\/+/,"");return l?`${u}/${l}`:u}function o(e,t,i=""){return s(function(e,t){return t||(e.includes("sandbox")?"us-east-1.aws.sandbox":e.includes("local")?"local":e.includes("staging")?"us-central1.gcp.staging":"us-east-1.aws")}(e,t),"console",i)}class a{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=o(t,n,`openapi/iac/applications/${i}/integrations`)}async list(e){const t=await this.rpcManager.get(this.iacBaseUrl);return e?t.filter(t=>t.type===e):t}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getIntegrationSchema(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}/schema`)}async delete(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}async deleteMany(e){await Promise.all(e.map(e=>this.delete(e)))}async upsertIntegration(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e.id}`,e)}}class c{constructor(e){this.rpcManager=e}async get(e){const t={key:e};return await this.rpcManager.post("secret/get",t)||void 0}getAll(){return this.rpcManager.post("secret/getAll",{})}async upsert(e,t){return this.upsertMany([{key:e,value:t}]).then(e=>e[0])}async upsertMany(e){if(0===e.length)return[];const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e,t=!1){const i={keys:[e],force:t};return this.rpcManager.post("secret/delete",i)}async deleteMany(e,t=!1){if(0===e.length)return;const i={keys:e,force:t};return this.rpcManager.post("secret/delete",i)}get apiKeys(){return new u(this.rpcManager)}}class u{constructor(e){this.rpcManager=e}get(e){const t={key:e};return this.rpcManager.post("secret/api-key/get",t)}getAll(){return this.rpcManager.post("secret/api-key/getAll",{})}upsert(e){const t={key:e};return this.rpcManager.post("secret/api-key/upsert",t)}delete(e){const t={key:e};return this.rpcManager.post("secret/api-key/delete",t)}}class l{constructor(e,t,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=n,this.integrationClient=new a(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new c(this.rpcManager)}integrations(){return this.integrationClient}secrets(){return this.secretClient}}const h=require("rxjs");function d(e){return"function"==typeof e}function p(e){return function(t){if(function(e){return d(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}var g=function(e,t){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},g(e,t)};function f(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}g(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function y(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,r,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return o}function b(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var I,v=((I=function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}(function(e){Error.call(e),e.stack=(new Error).stack})).prototype=Object.create(Error.prototype),I.prototype.constructor=I,I);function S(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var w=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,i,n,r;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=y(s),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(d(c))try{c()}catch(e){r=e instanceof v?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=y(u),h=l.next();!h.done;h=l.next()){var p=h.value;try{M(p)}catch(e){r=null!=r?r:[],e instanceof v?r=b(b([],m(r)),m(e.errors)):r.push(e)}}}catch(e){i={error:e}}finally{try{h&&!h.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(r)throw new v(r)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)M(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&S(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&S(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function M(e){d(e)?e():e.unsubscribe()}w.EMPTY;var T={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var r=T.delegate;return(null==r?void 0:r.setTimeout)?r.setTimeout.apply(r,b([e,t],m(i))):setTimeout.apply(void 0,b([e,t],m(i)))},clearTimeout:function(e){var t=T.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function _(){}var k=E("C",void 0,void 0);function E(e,t,i){return{kind:e,value:t,error:i}}var C=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof w||i&&"closed"in i&&d(i.remove)&&d(i.add)&&d(i.unsubscribe))&&t.add(n)):n.destination=N,n}return f(t,e),t.create=function(e,t,i){return new D(e,t,i)},t.prototype.next=function(e){this.isStopped?q(function(e){return E("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?q(E("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?q(k,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(w);Function.prototype.bind;var O=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){A(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){A(e)}else A(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){A(e)}},e}(),D=function(e){function t(t,i,n){var r,s=e.call(this)||this;return r=d(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,s.destination=new O(r),s}return f(t,e),t}(C);function A(e){!function(e){T.setTimeout(function(){throw e})}(e)}function q(e,t){var i=null;i&&T.setTimeout(function(){return i(e,t)})}var N={closed:!0,next:_,error:function(e){throw e},complete:_};function R(e,t,i,n,r){return new F(e,t,i,n,r)}var F=function(e){function t(t,i,n,r,s,o){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=r?function(e){try{r(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return f(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(C);function j(e,t){return p(function(i,n){var r=0;i.subscribe(R(n,function(i){n.next(e.call(t,i,r++))}))})}function x(e){return null!=e}let P=e=>new Error(e);function B(e,t,...i){e||function(e,...t){const i=Q(e);if("object"==typeof i)throw i;throw P(i||"Assertion error",...t)}(t,...i)}function L(e,t,...i){return B(e,t,...i),e}function Q(e){return void 0===e?"":"string"==typeof e?e:e()}function U(e,t,i){const n=Q(e);if("object"==typeof n)throw n;return`${n?`${n}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}const $=["dev","prod"],G="built_in_agent";function V(){return globalThis.crypto.randomUUID()}function H(){return V()}const K=18,W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function z(e=K,t=""){B(t.length<e,"ID prefix is too long");let i="";for(let t=0;t<e;t++)i+=W.charAt(Math.floor(Math.random()*W.length));return t.length>0&&(i=t+i.substring(t.length)),i}function J({count:e,length:t,prefix:i}){B(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(z(t||K,i||""));return[...n]}const Y=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Z(e){for(const t in e){const i=e[t];if("string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i&&void 0!==i)throw new Error(`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`);if(Y.includes(t))throw new Error(`Invalid metadata key ${t} - cannot be an internal key. Internal keys: ${Y.join(", ")}`);if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}function X(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)X(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)X(t);else for(const t in e){if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata filter key ${t} - can only contain letters, numbers, and underscores`);if(Y.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${Y.join(", ")}`);const i=e[t];if("object"!=typeof i&&"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof i}`)}}function ee(e,t,i){const n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new File([r],t,{type:i||"application/octet-stream"})}class te{constructor(e,t,i,n,r){this.agentId=e,this.ongoingChatSequences=t,this.rpcManager=i,this.socketManager=n,this.jobClient=r}async get(){const e=await this.rpcManager.post("ai/agent/getAgent",{agentId:this.agentId});return e?.agent}async upsert(e){await this.rpcManager.post("ai/agent/upsertAgent",{...e,id:this.agentId})}async delete(){await this.rpcManager.post("ai/agent/deleteAgent",{agentId:this.agentId})}async updateInstructions(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,instructions:e}})}async updateModel(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,model:e}})}async updateConnectedAgents(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,connectedAgents:e}})}async getContext(e){return await this.rpcManager.post("ai/agent/getContext",{agentId:this.agentId,contextId:e})}async listContexts(){return(await this.rpcManager.post("ai/agent/listContexts",{agentId:this.agentId})).contexts||[]}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/agent/deleteContexts",{agentId:this.agentId,contextIds:e})}async upsertContext(e,t){const{failures:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&Z(t.metadata);return await this.rpcManager.post("ai/agent/upsertContexts",{agentId:this.agentId,contextRequests:e},t)}async provideFeedback(e){await this.rpcManager.post("ai/agent/provideFeedback",{agentId:this.agentId,feedback:e})}async resetFeedback(){await this.rpcManager.post("ai/agent/resetFeedback",{agentId:this.agentId})}async updateGuardrails(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,guardrails:{...t.options?.guardrails,...e}}})}async updateCustomGuardrails(e){await this.rpcManager.post("ai/agent/upsertCustomGuardrails",{agentId:this.agentId,customGuardrail:e})}async deleteCustomGuardrail(){await this.rpcManager.post("ai/agent/deleteCustomGuardrails",{agentId:this.agentId})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),r=await L(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:r.transcribedPrompt}}async search(e){B(this.agentId!==G,"Cannot search the built-in agent");const t={options:e,agentId:this.agentId};return(await this.rpcManager.post("ai/chatbot/search",t)).chunks}async ask(e,t,i){const n=await this.askInternal(e,!1,t,i);return this.replaceFileTags(n.responseString,n.annotations)}replaceFileTags(e,t={}){let i=e;for(const[e,n]of Object.entries(t)){let t="";const r=n.aiFileUrl.fileName?n.aiFileUrl.fileName:n.aiFileUrl.url;switch(n.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${r}](${n.aiFileUrl.url})`}i=i.replace(`\${id:${e}}`,t)}return i}async askWithAnnotations(e,t,i){const n=await this.askInternal(e,!1,t,i);return{responseString:n.responseString,annotations:n.annotations}}async askAsync(e,t,i){const n={agentId:this.agentId,prompt:e,options:i,jobId:t};await this.rpcManager.post("ai/chatbot/askAsync",n)}observeStatusUpdates(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiStatus"===e.type&&e.agentId===this.agentId),j(e=>({agentId:this.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,messageId:e.messageId})))}async getChatHistory(e){const t={agentId:this.agentId,memoryId:e};return(await this.rpcManager.post("ai/chatbot/history",t)).messages}async transcribeAndAsk(e,t,i){return await this.askInternal(e,!1,t,i)}async transcribeAndAskWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),r=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:ee(r.base64File,`voice.${r.extension}`,r.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),r=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:ee(r.base64File,`voice.${r.extension}`,r.mimeType)}}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&X(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)X(i.contextMetadataFilterForKnowledgeBase[e]);n=n||V(),i={...ie,...i||{}};const r="string"==typeof e;let s="ai/chatbot/";s+=r||t?!r&&t?"transcribeAndAskWithVoiceResponse":r&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:r?e:void 0,options:i,jobId:n},a=r?void 0:[e];return await this.rpcManager.post(s,o,a,"file"),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&X(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)X(t.contextMetadataFilterForKnowledgeBase[e]);const n=V(),r=void 0===(t={...ie,...t||{}}).smoothTyping||t.smoothTyping;let s="";const o=new h.Subject,a=new h.Subject;this.ongoingChatSequences[n]=a;let c=-1;a.pipe((0,h.tap)(({tokenIndex:e})=>{void 0!==e&&e<c&&console.warn("Received token index out of order",e,c),void 0!==e&&(c=e)}),(0,h.concatMap)(({value:e,complete:t,annotations:i})=>t?(0,h.of)({value:e,complete:t,annotations:i}):(0,h.of)(e).pipe(r?(0,h.delay)(0):(0,h.tap)(),j(e=>({value:e,complete:!1,annotations:void 0})))),(0,h.takeWhile)(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:i})=>{s+=e,t&&i&&(s=this.replaceFileTags(s,i)),o.next(s)},error:e=>{console.error(e)},complete:()=>{o.complete()}});const u="string"==typeof e;i=i||V();const l={agentId:this.agentId,jobId:i,prompt:u?e:void 0,options:t,clientRequestId:n},d={responseStream:o.pipe((0,h.finalize)(()=>{delete this.ongoingChatSequences[n]}),(0,h.share)())};return u?this.rpcManager.post("ai/chatbot/chat",l).catch(e=>{o.error(e),o.complete()}):this.rpcManager.post("ai/chatbot/transcribeAndChat",l,[e],"file").catch(e=>{throw o.error(e),o.complete(),e}),d.serverResponse=this.jobClient.awaitJob(i).catch(e=>{o.error(e),o.complete()}),d}}const ie={smoothTyping:!0,responseFormat:"text"};class ne{constructor(e,t,i){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiChatbot"===e.type),j(e=>e)).subscribe(e=>{this.handleChatResponse(e).then()})}agent(e){return new te(e,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient)}async listAgents(){return(await this.rpcManager.post("ai/agent/listAgents",{})).agents}async handleChatResponse(e){const t=this.ongoingChatSequences[e.clientRequestId];if(!t)return;const{token:i,complete:n,tokenIndex:r,annotations:s}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:s});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===r?void 0:r,annotations:s});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===r?void 0:r,annotations:s})}}const re="__squid_empty_chat_id";class se{constructor(e){this.rpcManager=e}async createAssistant(e,t,i,n){const r={name:e,instructions:t,functions:i,toolTypes:n};return(await this.rpcManager.post("ai/assistant/createAssistant",r)).assistantId}async deleteAssistant(e){const t={assistantId:e};await this.rpcManager.post("ai/assistant/deleteAssistant",t)}async createThread(e){const t={assistantId:e};return(await this.rpcManager.post("ai/assistant/createThread",t)).threadId}async deleteThread(e){const t={threadId:e};await this.rpcManager.post("ai/assistant/deleteThread",t)}async queryAssistant(e,t,i,n,r){const s={assistantId:e,threadId:t,prompt:i,fileIds:n,options:r};return(await this.rpcManager.post("ai/assistant/queryAssistant",s)).answer}async addFileToAssistant(e,t){const i={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",i,[t],"file")).fileId}async removeFileFromAssistant(e,t){const i={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",i)}async addFileToThread(e,t){const i={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",i,[t],"file")).fileId}}class oe{constructor(e){this.rpcManager=e}async transcribe(e,t={modelName:"whisper-1"}){return this.rpcManager.post("ai/audio/transcribe",t,[e])}async createSpeech(e,t){const i={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",i);return ee(n.base64File,`audio.${n.extension}`,n.mimeType)}}class ae{constructor(e){this.rpcManager=e}async generate(e,t){const i={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",i)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function ce(e){for(const t in e){const i=e[t];B("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),B(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class ue{constructor(e,t,i){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async delete(){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:this.knowledgeBaseId})}async listContexts(){return(await this.rpcManager.post("ai/knowledge-base/listContexts",{id:this.knowledgeBaseId})).contexts||[]}async getContext(e){return(await this.rpcManager.post("ai/knowledge-base/getContext",{knowledgeBaseId:this.knowledgeBaseId,contextId:e})).context}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/knowledge-base/deleteContexts",{knowledgeBaseId:this.knowledgeBaseId,contextIds:e})}async upsertContext(e,t){const{failures:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&ce(t.metadata);const i=V();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:i},t),await this.jobClient.awaitJob(i)}async search(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return(await this.rpcManager.post("ai/knowledge-base/search",t)).chunks}async downloadContext(e){const t={knowledgeBaseId:this.knowledgeBaseId,contextId:e};return await this.rpcManager.post("ai/knowledge-base/downloadContext",t)}}class le{constructor(e,t){this.rpcManager=e,this.jobClient=t}knowledgeBase(e){return new ue(e,this.rpcManager,this.jobClient)}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async delete(e){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:e})}}class he{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new de(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new de(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class de{constructor(e,t){this.matchMaker=e,this.rpcManager=t,this.id=e.id}async insertEntity(e){await this.rpcManager.post("matchMaking/insertEntity",{matchMakerId:this.id,entity:e})}async insertManyEntities(e){await this.rpcManager.post("matchMaking/insertEntities",{matchMakerId:this.id,entities:e})}async delete(){await this.rpcManager.post("matchMaking/deleteMatchMaker",{matchMakerId:this.id})}async deleteEntity(e){await this.rpcManager.post("matchMaking/deleteEntity",{entityId:e,matchMakerId:this.id})}async findMatches(e,t={}){return(await this.rpcManager.post("matchMaking/findMatches",{matchMakerId:this.id,entityId:e,options:t})).matches}async findMatchesForEntity(e,t={}){return(await this.rpcManager.post("matchMaking/findMatchesForEntity",{matchMakerId:this.id,entity:e,options:t})).matches}async listEntities(e,t={}){return await this.rpcManager.post("matchMaking/listEntities",{categoryId:e,options:t,matchMakerId:this.id})}async getEntity(e){return(await this.rpcManager.post("matchMaking/getEntity",{matchMakerId:this.id,entityId:e})).entity}getMatchMakerDetails(){return this.matchMaker}}const pe=["user","ai"],ge="parent",fe="result",ye=["cohere","none"],me=["anthropic","flux","gemini","openai","grok","stability","voyage","external"],be=["o1","o3","o3-mini","o4-mini","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"],Ie=["gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"],ve=["grok-3","grok-3-fast","grok-3-mini","grok-3-mini-fast","grok-4"],Se=["claude-3-7-sonnet-latest","claude-opus-4-20250514","claude-opus-4-1-20250805","claude-sonnet-4-20250514"],we=[...be,...Se,...Ie,...ve];function Me(e){return we.includes(e)}const Te=["text-embedding-3-small"],_e=["voyage-3-large"],ke=[...Te,..._e],Ee=["dall-e-3"],Ce=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],Oe=["tts-1","tts-1-hd","gpt-4o-mini-tts"],De=[...Ce,...Oe],Ae=["stable-diffusion-core"],qe=["flux-pro-1.1","flux-kontext-pro"],Ne=[...Ee,...Ae,...qe],Re=[...Ce],Fe=[...Oe],je=["mp3","opus","aac","flac","wav","pcm"],xe=["contextual","basic"],Pe=["secret","regular"];function Be(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const Le={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,MOVED_TEMPORARILY:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,REQUEST_TOO_LONG:413,REQUEST_URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,REQUESTED_RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,INSUFFICIENT_SPACE_ON_RESOURCE:419,METHOD_FAILURE:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},Qe="ai_agents",Ue=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","built_in_db","built_in_gcs","built_in_queue","built_in_s3","cassandra","clickhouse","cloudsql","cockroach","cognito","connected_knowledgebases","confluence","confluent","datadog","db2","descope","documentdb","dynamodb","elasticsearch","firebase_auth","firestore","gcs","google_docs","google_drive","graphql","hubspot","jira","jwt_hmac","jwt_rsa","kafka","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","oracledb","pinecone","postgres","redis","s3","salesforce_crm","sap_hana","sentry","servicenow","snowflake","spanner","xata","zendesk","mail","slack","mcp","a2a"],$e=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch"],Ge=["auth0","jwt_rsa","jwt_hmac","cognito","okta","descope","firebase_auth"],Ve=["graphql","linear"],He=["api"],Ke=["data","api","graphql"],We="built_in_db",ze="built_in_queue",Je="built_in_storage",Ye=[We,ze,Je];function Ze(e){return Ye.includes(e)}const Xe=["squid_functionExecution_count","squid_functionExecution_time"],et=["sum","max","min","average","median","p95","p99","count"],tt=["user","squid"],it=["align-by-start-time","align-by-end-time"],nt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],rt=[...nt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],st=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],ot=["CONNECTED","DISCONNECTED","REMOVED"];class at{constructor(e,t,i){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.aiAssistantClient=new se(this.rpcManager)}agent(e=G){return this.getAiAgentClient().agent(e)}knowledgeBase(e){return this.getAiKnowledgeBaseClient().knowledgeBase(e)}async listAgents(){return this.getAiAgentClient().listAgents()}async listKnowledgeBases(){return this.getAiKnowledgeBaseClient().listKnowledgeBases()}assistant(){return this.aiAssistantClient}image(){return new ae(this.rpcManager)}audio(){return new oe(this.rpcManager)}matchMaking(){return new he(this.rpcManager)}executeAiQuery(e,t,i){const n={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",n)}executeAiApiCall(e,t,i,n){const r={integrationId:e,prompt:t,allowedEndpoints:i,provideExplanation:n};return this.rpcManager.post("ai/query/executeApiQuery",r)}async getApplicationAiSettings(){return(await this.rpcManager.post("ai/settings/getApplicationAiSettings",{})).settings}async setApplicationAiSettings(e){const t={settings:e};await this.rpcManager.post("ai/settings/setApplicationAiSettings",t)}async setAiProviderApiKeySecret(e,t){const i={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",i)).settings}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new ne(this.rpcManager,this.socketManager,this.jobClient)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new le(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const ct={headers:{},queryParams:{},pathParams:{}};class ut{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,n){return this.request(e,t,i,n,"post")}async delete(e,t,i,n){return this.request(e,t,i,n,"delete")}async patch(e,t,i,n){return this.request(e,t,i,n,"patch")}async put(e,t,i,n){return this.request(e,t,i,n,"put")}async request(e,t,i,n,r){const s={integrationId:e,endpointId:t,body:i,options:{...ct,...this.convertOptionsToStrings(n||{})},overrideMethod:r};return await this.rpcManager.rawPost("api/callApi",s,void 0,void 0,!1)}convertOptionsToStrings(e){return{headers:this.convertToStrings(e.headers),queryParams:this.convertToStrings(e.queryParams),pathParams:this.convertToStrings(e.pathParams)}}convertToStrings(e){if(!e)return{};const t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,String(t)]);return Object.fromEntries(t)}}class lt{constructor(e,t){this.apiKey=e,this.authProvider=t}setAuthProvider(e){this.authProvider=e}async getAuthData(){return{token:await this.getTokenFromAuthProvider(),integrationId:this.authProvider?.integrationId}}async getTokenFromAuthProvider(){const e=this.authProvider?.getToken();return"object"==typeof e?await e:e}getApiKey(){return this.apiKey}async getToken(){if(this.apiKey)return{type:"ApiKey",token:this.apiKey};const e=await this.getTokenFromAuthProvider();return e?{type:"Bearer",token:e,integrationId:this.authProvider?.integrationId}:void 0}}const ht=/[.\[\]]/;function dt(e,t){if(!e)return;const i=t.split(ht);let n,r=e;for(;r&&i.length;){const e=i.shift();if(e){if("object"!=typeof r||!(e in r))return;n=r[e],r=n}}return n}function pt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function gt(e,t,i,n="."){const r=t.split(n);let s=e;for(;r.length;){const e=L(r.shift());if(r.length){const t=s[e],i=pt(t)?St(t)??{}:{};s[e]=i,s=i}else s[e]=i}}function ft(e,t,i="."){const n=t.split(i);let r=e;for(;n.length;){const e=L(n.shift());if(n.length){const t=pt(r[e])?St(r[e])??{}:{};r[e]=t,r=t}else delete r[e]}}function yt(e,t,i){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(i,n)}}function mt(e){return null==e}function bt(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const i=typeof e;if(i!==typeof t)return!1;if("object"!==i)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!r.includes(i)||!bt(e[i],t[i]))return!1;return!0}function It(e,t){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=vt(e[n],t);return i}function vt(e,t){const i=t?t(e):void 0;if(void 0!==i)return i;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return It(e,t);if(e instanceof Map)return new Map(It(Array.from(e),t));if(e instanceof Set)return new Set(It(Array.from(e),t));if(ArrayBuffer.isView(e))return(n=e)instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const r={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(r[i]=vt(e[i],t));return r}function St(e){return"object"!=typeof e||null===e?e:e instanceof Date?new Date(e):Array.isArray(e)?[...e]:e instanceof Map?new Map(Array.from(e)):e instanceof Set?new Set(Array.from(e)):{...e}}function wt(e,t){if(e===t||mt(e)&&mt(t))return 0;if(mt(e))return-1;if(mt(t))return 1;const i=typeof e,n=typeof t;return i!==n?i<n?-1:1:"number"==typeof e?(B("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(B("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(B("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(B("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function Mt(e,t){return e.reduce((e,i)=>{const n=t(i);return e[n]?e[n].push(i):e[n]=[i],e},{})}function Tt(e){if(Array.isArray(e))return e.map(e=>Tt(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),i={};return t.sort().forEach(t=>{i[t]=Tt(e[t])}),i}function _t(e){return kt(Tt(e))}function kt(e){if(void 0===e)return null;const t=vt(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function Et(e){return vt(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,i=t.$date;return i&&1===Object.keys(t).length?new Date(i):void 0})}function Ct(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=kt(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return btoa(i)}}const Ot=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},Dt=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(kt(e[i])!==kt(t[i]))return!1;return!0};class At{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||Ot,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&i(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}class qt{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){const{argsArray:i,fileArray:n}=this.transformFileArgs(t),r="string"==typeof e?e:e.functionName,s="string"==typeof e?void 0:e.caching,o=s?.cache;if(o){const e=o.get(i);if(e.found)return Promise.resolve(e.value)}const a="string"==typeof e?void 0:e.deduplication;if(a){const e="boolean"==typeof a?Ot:a.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,i));if(t)return t.promise}const c=this.createExecuteCallPromise(r,i,n,o);return a&&(this.inFlightDedupCalls.push({functionName:r,args:i,promise:c}),c.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==c)})),c}createExecuteCallPromise(e,t,i,n){const r=`backend-function/execute?${encodeURIComponent(e)}`,s={functionName:e,paramsArrayStr:kt(t)};return(0,h.firstValueFrom)((0,h.race)((0,h.from)(this.rpcManager.post(r,s,i.length>0?i:[])).pipe(j(e=>{if(!e.success)throw new Error(e.payload);const i=Et(e.payload);if(i?.__isSquidBase64File__){const e=i;return ee(e.base64,e.filename,e.mimetype)}return n&&n.set(t,i),i}))))}transformFileArgs(e){const t=[],i=[];let n=0;for(const r of e)if("undefined"!=typeof File)if(r instanceof File){i.push(r);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(this.isArrayOfFiles(r)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:r.map((e,t)=>(i.push(r[t]),n++))};t.push(e)}else t.push(r);else t.push(r);return{argsArray:t,fileArray:i}}isArrayOfFiles(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e