@squidcloud/client
Version:
A typescript implementation of the Squid client
1 lines • 263 kB
JavaScript
import*as e from"ws";import*as t from"rxjs";var r={150:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0});const o=r(642);t.default=o.PromisePool,i(r(273),t),i(r(642),t),i(r(837),t),i(r(426),t),i(r(858),t),i(r(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class r 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=r},220:t=>{t.exports=e},234:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=r(642),i=r(172),o=r(837),s=r(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 i.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 s.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 i.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 i.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 i.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 i.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach((e=>{if(e&&"function"!=typeof e)throw i.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)})),this.onTaskFinishedHandlers.forEach((e=>{if(e&&"function"!=typeof e)throw i.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 r=this.createTaskFor(e,t).then((e=>{this.save(e,t).removeActive(r)})).catch((async n=>{await this.handleErrorFor(n,e,t),this.removeActive(r)})).finally((()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)}));this.tasks().push(r),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[r,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),r()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise(((r,n)=>{t=setTimeout((()=>{n(new o.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,r){if(this.shouldUseCorrespondingResults()&&(this.results()[r]=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 s.StopThePromisePoolError}isValidationError(e){return e instanceof i.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(o.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,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=r(234);class i{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 i(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=i,i.notRun=Symbol("notRun"),i.failed=Symbol("failed")},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class r 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=r},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class r extends Error{}t.StopThePromisePoolError=r}},n={};function i(e){var t=n[e];if(void 0!==t)return t.exports;var o=n[e]={exports:{}};return r[e].call(o.exports,o,o.exports,i),o.exports}i.d=(e,t)=>{for(var r in t)i.o(t,r)&&!i.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},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);var o={};i.d(o,{V_:()=>st,j6:()=>et,Wq:()=>Xe,jo:()=>Qe,dH:()=>Ge,iU:()=>Ze,z2:()=>De,CD:()=>wt,xV:()=>Le,GK:()=>gt,UF:()=>St,wz:()=>ut,n6:()=>Nn,Zj:()=>te,PZ:()=>X,OF:()=>s,Wo:()=>ne,o7:()=>Fn,Ts:()=>re,w2:()=>Rn,OW:()=>oe,AX:()=>Sn,wc:()=>se,xd:()=>q,lO:()=>pt,q7:()=>ft,y4:()=>yt,dR:()=>Ae,Rr:()=>Nt,eb:()=>Ot,_G:()=>xe,an:()=>Pe,sk:()=>Ft,ku:()=>Ce,YS:()=>Vt,i0:()=>Gt,j3:()=>Wt,o0:()=>ct,aJ:()=>G,M1:()=>er,pu:()=>Bt,Ol:()=>rr,t1:()=>ir,MJ:()=>nr,T1:()=>At,ff:()=>sr,Vq:()=>ar,Vd:()=>N,pF:()=>R,VD:()=>Pn,Rd:()=>Hr,h3:()=>Ke,oL:()=>Fe,$1:()=>lt,x6:()=>Ut,wi:()=>dt,t3:()=>ot,bi:()=>ht,RZ:()=>at,km:()=>On,y3:()=>Lt,Y6:()=>Te,V$:()=>Lr,w4:()=>wr,Gp:()=>mt,N1:()=>bt,hC:()=>_t,Ic:()=>qn,r2:()=>cr,Cd:()=>sn,Lh:()=>ur,F3:()=>ze,h1:()=>Ye,eS:()=>He,hp:()=>qe,lZ:()=>Ve,Eh:()=>We,U_:()=>Ne,sW:()=>Re,lV:()=>tt,Jk:()=>vn,dK:()=>kt,TN:()=>Dn,oS:()=>qt,qk:()=>Dt,IG:()=>Or,nd:()=>zr,Ds:()=>Zr,L5:()=>en,vs:()=>rt,nY:()=>nt,v$:()=>tn,Zv:()=>yn,fN:()=>Be,HV:()=>vt,xD:()=>It,VF:()=>Je,dC:()=>wn,_V:()=>_n,dr:()=>Tn,Pd:()=>Bn,cV:()=>an,LN:()=>xn,Pq:()=>$e,M0:()=>Ln,Z:()=>Z,Xv:()=>Me,Nb:()=>Ee,CO:()=>dr,$C:()=>$,jd:()=>H,SD:()=>z,LV:()=>In,mW:()=>Ue,uF:()=>it,YM:()=>hn,ld:()=>un,dO:()=>dn,D:()=>cn,Yi:()=>ln,gI:()=>fn,wQ:()=>lr});class s{constructor(e){this.rpcManager=e}async createAssistant(e,t,r,n){const i={name:e,instructions:t,functions:r,toolTypes:n};return(await this.rpcManager.post("ai/assistant/createAssistant",i)).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,r,n,i){const o={assistantId:e,threadId:t,prompt:r,fileIds:n,options:i};return(await this.rpcManager.post("ai/assistant/queryAssistant",o)).answer}async addFileToAssistant(e,t){const r={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",r,[t],"file")).fileId}async removeFileFromAssistant(e,t){const r={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",r)}async addFileToThread(e,t){const r={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",r,[t],"file")).fileId}}const a=(c={BehaviorSubject:()=>t.BehaviorSubject,NEVER:()=>t.NEVER,Observable:()=>t.Observable,ReplaySubject:()=>t.ReplaySubject,Subject:()=>t.Subject,combineLatest:()=>t.combineLatest,combineLatestWith:()=>t.combineLatestWith,concatMap:()=>t.concatMap,debounceTime:()=>t.debounceTime,defaultIfEmpty:()=>t.defaultIfEmpty,defer:()=>t.defer,delay:()=>t.delay,distinctUntilChanged:()=>t.distinctUntilChanged,filter:()=>t.filter,finalize:()=>t.finalize,first:()=>t.first,firstValueFrom:()=>t.firstValueFrom,from:()=>t.from,interval:()=>t.interval,lastValueFrom:()=>t.lastValueFrom,map:()=>t.map,merge:()=>t.merge,of:()=>t.of,pairwise:()=>t.pairwise,race:()=>t.race,share:()=>t.share,skip:()=>t.skip,startWith:()=>t.startWith,switchAll:()=>t.switchAll,switchMap:()=>t.switchMap,take:()=>t.take,takeUntil:()=>t.takeUntil,takeWhile:()=>t.takeWhile,tap:()=>t.tap,timer:()=>t.timer},u={},i.d(u,c),u);var c,u;function l(e){return"function"==typeof e}function d(e){return function(t){if(function(e){return l(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 h=function(e,t){return h=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},h(e,t)};function p(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}h(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function f(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.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 y(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s}function g(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var v,b=((v=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),v.prototype.constructor=v,v);function m(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var _=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,r,n,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var s=f(o),a=s.next();!a.done;a=s.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else o.remove(this);var c=this.initialTeardown;if(l(c))try{c()}catch(e){i=e instanceof b?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var d=f(u),h=d.next();!h.done;h=d.next()){var p=h.value;try{S(p)}catch(e){i=null!=i?i:[],e instanceof b?i=g(g([],y(i)),y(e.errors)):i.push(e)}}}catch(e){r={error:e}}finally{try{h&&!h.done&&(n=d.return)&&n.call(d)}finally{if(r)throw r.error}}}if(i)throw new b(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)S(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).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)&&m(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&m(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function S(e){l(e)?e():e.unsubscribe()}_.EMPTY;var w={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var i=w.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,g([e,t],y(r))):setTimeout.apply(void 0,g([e,t],y(r)))},clearTimeout:function(e){var t=w.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function I(){}var O=M("C",void 0,void 0);function M(e,t,r){return{kind:e,value:t,error:r}}var E=function(e){function t(t){var r,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((r=t)instanceof _||r&&"closed"in r&&l(r.remove)&&l(r.add)&&l(r.unsubscribe))&&t.add(n)):n.destination=C,n}return p(t,e),t.create=function(e,t,r){return new A(e,t,r)},t.prototype.next=function(e){this.isStopped?j(function(e){return M("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?j(M("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?j(O,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}(_);Function.prototype.bind;var T=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){k(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){k(e)}else k(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){k(e)}},e}(),A=function(e){function t(t,r,n){var i,o=e.call(this)||this;return i=l(t)||!t?{next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:t,o.destination=new T(i),o}return p(t,e),t}(E);function k(e){!function(e){w.setTimeout((function(){throw e}))}(e)}function j(e,t){var r=null;r&&w.setTimeout((function(){return r(e,t)}))}var C={closed:!0,next:I,error:function(e){throw e},complete:I};function x(e,t,r,n,i){return new P(e,t,r,n,i)}var P=function(e){function t(t,r,n,i,o,s){var a=e.call(this,t)||this;return a.onFinalize=o,a.shouldUnsubscribe=s,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=i?function(e){try{i(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 p(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(E);function D(e,t){return d((function(r,n){var i=0;r.subscribe(x(n,(function(r){n.next(e.call(t,r,i++))})))}))}const N="__squid_empty_chat_id",R=["dev","prod"],q="built_in_agent";function F(e){return null!=e}let L=e=>new Error(e);function B(e,t,...r){e||function(e,...t){const r=U(e);if("object"==typeof r)throw r;throw L(r||"Assertion error",...t)}(t,...r)}function Q(e,t,...r){return B(e,t,...r),e}function U(e){return void 0===e?"":"string"==typeof e?e:e()}function V(e,t,r){const n=U(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}>`}(r)}`}function $(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)}))}const G=18,W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function H(e=G,t=""){B(t.length<e,"ID prefix is too long");let r="";for(let t=0;t<e;t++)r+=W.charAt(Math.floor(Math.random()*W.length));return t.length>0&&(r=t+r.substring(t.length)),r}function z({count:e,length:t,prefix:r}){B(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(H(t||G,r||""));return[...n]}const Y=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function J(e){for(const t in e){const r=e[t];if("string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r&&void 0!==r)throw new Error(`Invalid metadata value for key ${t} - cannot be of type ${typeof r}`);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 K(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)K(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)K(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 r=e[t];if("object"!=typeof r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof r}`)}}function Z(e,t,r){const n=atob(e),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);const o=r||"application/octet-stream",s=new Blob([i],{type:o});return new File([s],t,{type:o})}class X{constructor(e,t,r,n,i){this.agentId=e,this.ongoingChatSequences=t,this.statusUpdates=r,this.rpcManager=n,this.socketManager=i}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){await this.upsertContexts([e],t?[t]:void 0)}async upsertContexts(e,t){for(const t of e)t.metadata&&J(t.metadata);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){return this.chatInternal(e,t).responseStream}async transcribeAndChat(e,t){const r=this.chatInternal(e,t),n=await Q(r.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:r.responseStream,transcribedPrompt:n.transcribedPrompt}}async search(e){B(this.agentId!==q,"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){return(await this.askInternal(e,!1,t)).responseString}observeStatusUpdates(e){this.socketManager.notifyWebSocketIsNeeded();const{chatId:t}=e||{};return this.createStatusSubject(t),t?this.statusUpdates[this.agentId][t].asObservable():(0,a.merge)(...Object.values(this.statusUpdates[this.agentId]))}async transcribeAndAsk(e,t){return await this.askInternal(e,!1,t)}async transcribeAndAskWithVoiceResponse(e,t){const r=await this.askInternal(e,!0,t),n=r.voiceResponse;return{responseString:r.responseString,transcribedPrompt:r.transcribedPrompt,voiceResponseFile:Z(n.base64File,`voice.${n.extension}`,n.mimeType)}}async askWithVoiceResponse(e,t){const r=await this.askInternal(e,!0,t),n=r.voiceResponse;return{responseString:r.responseString,voiceResponseFile:Z(n.base64File,`voice.${n.extension}`,n.mimeType)}}async askInternal(e,t,r){r?.contextMetadataFilter&&K(r.contextMetadataFilter),r={...ee,...r||{}};const n="string"==typeof e;let i="ai/chatbot/";i+=n||t?!n&&t?"transcribeAndAskWithVoiceResponse":n&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:n?e:void 0,options:r},s=n?void 0:[e];return await this.rpcManager.post(i,o,s,"file")}createStatusSubject(e){this.statusUpdates[this.agentId]||(this.statusUpdates[this.agentId]={});const t=e||N;this.statusUpdates[this.agentId][t]||(this.statusUpdates[this.agentId][t]=new a.Subject)}chatInternal(e,t){this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&K(t.contextMetadataFilter);const r=$(),n=void 0===(t={...ee,...t||{}}).smoothTyping||t.smoothTyping;let i="";const o=new a.Subject,s=new a.Subject;this.ongoingChatSequences[r]=s;let c=-1;s.pipe((0,a.tap)((({tokenIndex:e})=>{void 0!==e&&e<c&&console.warn("Received token index out of order",e,c),void 0!==e&&(c=e)})),(0,a.concatMap)((({value:e,complete:t})=>t?(0,a.of)({value:e,complete:t}):(0,a.of)(e).pipe(n?(0,a.delay)(0):(0,a.tap)(),D((e=>({value:e,complete:!1})))))),(0,a.takeWhile)((({complete:e})=>!e),!0)).subscribe({next:({value:e})=>{i+=e,o.next(i)},error:e=>{console.error(e)},complete:()=>{o.complete()}});const u="string"==typeof e,l={agentId:this.agentId,prompt:u?e:void 0,options:t,clientRequestId:r},d={responseStream:o.pipe((0,a.finalize)((()=>{delete this.ongoingChatSequences[r]})),(0,a.share)())};return u?this.rpcManager.post("ai/chatbot/chat",l).catch((e=>{o.error(e),o.complete()})):d.serverResponse=this.rpcManager.post("ai/chatbot/transcribeAndChat",l,[e],"file").catch((e=>{throw o.error(e),o.complete(),e})),d}}const ee={smoothTyping:!0,responseFormat:"text"};class te{constructor(e,t){this.rpcManager=e,this.socketManager=t,this.ongoingChatSequences={},this.statusUpdates={},this.socketManager.observeNotifications().pipe((0,a.filter)((e=>"aiChatbot"===e.type)),D((e=>e))).subscribe((e=>{this.handleChatResponse(e).then()})),this.socketManager.observeNotifications().pipe((0,a.filter)((e=>"aiStatus"===e.type)),D((e=>e))).subscribe((e=>{this.handleStatusMessage(e).then()}))}agent(e){return new X(e,this.ongoingChatSequences,this.statusUpdates,this.rpcManager,this.socketManager)}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:r,complete:n,tokenIndex:i}=e.payload;if(n&&!r.length)t.next({value:"",complete:!0,tokenIndex:void 0});else if(r.match(/\[.*?]\((.*?)\)/g))t.next({value:r,complete:n,tokenIndex:void 0===i?void 0:i});else for(let e=0;e<r.length;e++)t.next({value:r[e],complete:n&&e===r.length-1,tokenIndex:void 0===i?void 0:i})}async handleStatusMessage(e){const{agentId:t,chatId:r,payload:n}=e,{title:i,tags:o}=n,s=this.getStatusSubject(t,r);s?.next({agentId:t,chatId:r,title:i,tags:o})}getStatusSubject(e,t){if(!this.statusUpdates[e])return;const r=t||N;return this.statusUpdates[e][r]}}class re{constructor(e){this.rpcManager=e}async generate(e,t){const r={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",r)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}class ne{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 r={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",r);return Z(n.base64File,`audio.${n.extension}`,n.mimeType)}}const ie={headers:{},queryParams:{},pathParams:{}};class oe{constructor(e){this.rpcManager=e}async get(e,t,r){return this.request(e,t,void 0,r,"get")}async post(e,t,r,n){return this.request(e,t,r,n,"post")}async delete(e,t,r,n){return this.request(e,t,r,n,"delete")}async patch(e,t,r,n){return this.request(e,t,r,n,"patch")}async put(e,t,r,n){return this.request(e,t,r,n,"put")}async request(e,t,r,n,i){const o={integrationId:e,endpointId:t,body:r,options:{...ie,...this.convertOptionsToStrings(n||{})},overrideMethod:i};return await this.rpcManager.rawPost("api/callApi",o,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 se{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 ae=/[.\[\]]/;function ce(e,t){if(!e)return;const r=t.split(ae);let n,i=e;for(;i&&r.length;){const e=r.shift();if(e){if("object"!=typeof i||!(e in i))return;n=i[e],i=n}}return n}function ue(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function le(e,t,r,n="."){const i=t.split(n);let o=e;for(;i.length;){const e=Q(i.shift());if(i.length){const t=o[e],r=ue(t)?ve(t)??{}:{};o[e]=r,o=r}else o[e]=r}}function de(e,t,r="."){const n=t.split(r);let i=e;for(;n.length;){const e=Q(n.shift());if(n.length){const t=ue(i[e])?ve(i[e])??{}:{};i[e]=t,i=t}else delete i[e]}}function he(e,t,r){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(r,n)}}function pe(e){return null==e}function fe(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const r=typeof e;if(r!==typeof t)return!1;if("object"!==r)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const r of n)if(!i.includes(r)||!fe(e[r],t[r]))return!1;return!0}function ye(e,t){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=ge(e[n],t);return r}function ge(e,t){const r=t?t(e):void 0;if(void 0!==r)return r;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return ye(e,t);if(e instanceof Map)return new Map(ye(Array.from(e),t));if(e instanceof Set)return new Set(ye(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 i={};for(const r in e)Object.hasOwnProperty.call(e,r)&&(i[r]=ge(e[r],t));return i}function ve(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 be(e,t){if(e===t||pe(e)&&pe(t))return 0;if(pe(e))return-1;if(pe(t))return 1;const r=typeof e,n=typeof t;return r!==n?r<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 me(e,t){return e.reduce(((e,r)=>{const n=t(r);return e[n]?e[n].push(r):e[n]=[r],e}),{})}function _e(e){if(Array.isArray(e))return e.map((e=>_e(e)));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),r={};return t.sort().forEach((t=>{r[t]=_e(e[t])})),r}function Se(e){return we(_e(e))}function we(e){if(void 0===e)return null;const t=ge(e,(e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0));return JSON.stringify(t)}function Ie(e){return ge(JSON.parse(e),(e=>{if(null===e||"object"!=typeof e)return;const t=e,r=t.$date;return r&&1===Object.keys(t).length?new Date(r):void 0}))}function Oe(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=we(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let r="";for(let t=0;t<e.length;t++)r+=String.fromCharCode(e[t]);return btoa(r)}}const Me=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},Ee=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(we(e[r])!==we(t[r]))return!1;return!0};class Te{constructor(e){this.options=e}get(e){const t=this.cachedEntry,r=this.options.argsComparator||Me,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&r(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}class Ae{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){const{argsArray:r,fileArray:n}=this.transformFileArgs(t),i="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,s=o?.cache;if(s){const e=s.get(r);if(e.found)return Promise.resolve(e.value)}const a="string"==typeof e?void 0:e.deduplication;if(a){const e="boolean"==typeof a?Me:a.argsComparator,t=this.inFlightDedupCalls.find((t=>t.functionName===i&&e(t.args,r)));if(t)return t.promise}const c=this.createExecuteCallPromise(i,r,n,s);return a&&(this.inFlightDedupCalls.push({functionName:i,args:r,promise:c}),c.finally((()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter((e=>e.promise!==c))}))),c}createExecuteCallPromise(e,t,r,n){const i=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:we(t)};return(0,a.firstValueFrom)((0,a.race)((0,a.from)(this.rpcManager.post(i,o,r.length>0?r:[])).pipe(D((e=>{if(!e.success)throw new Error(e.payload);const r=Ie(e.payload);if(r?.__isSquidBase64File__){const e=r;return new File([Buffer.from(e.base64,"base64")],e.filename,{type:e.mimetype})}return n&&n.set(t,r),r})))))}transformFileArgs(e){const t=[],r=[];let n=0;for(const i of e)if("undefined"!=typeof File)if(i instanceof File){r.push(i);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(this.isArrayOfFiles(i)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:i.map(((e,t)=>(r.push(i[t]),n++)))};t.push(e)}else t.push(i);else t.push(i);return{argsArray:t,fileArray:r}}isArrayOfFiles(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every((e=>e instanceof File))}}function ke(){if("undefined"!=typeof window)return window;if(void 0!==i.g)return i.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}!function(e=!0){ke().SQUID_LOG_DEBUG_ENABLED=e}(function(){let e="";return"undefined"!=typeof window&&window.location?e=new URLSearchParams(window.location.search).get("SQUID_DEBUG")||"":"undefined"!=typeof process&&process.env&&(e=process.env.SQUID_DEBUG||""),"1"===e||"true"===e}());class je{static debug(...e){(function(){const e=ke();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=ke();return!0===e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Ce{constructor(e){this.destructManager=e,this.clientTooOldSubject=new a.BehaviorSubject(!1),this.isTenant=!0===ke().squidTenant,this.clientIdSubject=new a.BehaviorSubject(this.generateClientId()),this.destructManager.onDestruct((()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()}))}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe((0,a.filter)((e=>e)),(0,a.map)((()=>{})))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe((0,a.skip)(1),(0,a.filter)((e=>!e)),(0,a.map)((()=>{})))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientId(){const e=ke()[xe];if(e)return e();let t=`${this.isTenant?"tenant-":""}${$()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}generateClientRequestId(){const e=ke()[Pe];return e?e():$()}}const xe="SQUID_CLIENT_ID_GENERATOR",Pe="SQUID_CLIENT_REQUEST_ID_GENERATOR",De=["anthropic","flux","gemini","openai","squid","stability","voyage"],Ne=["o1","o1-mini"],Re=[...Ne,"o3","o3-mini","o4-mini"],qe=["gpt-4o","gpt-4o-mini","gpt-4.1-nano","gpt-4.1-mini","gpt-4.1",...Re],Fe=["gemini-1.5-pro","gemini-2.0-flash"],Le=["claude-3-7-sonnet-latest","claude-opus-4-20250514","claude-sonnet-4-20250514"],Be=["dictionary"],Qe=[...qe,...Le,...Fe,...Be];function Ue(e){return Qe.includes(e)}const Ve=["text-embedding-3-small"],$e=["voyage-3-large"],Ge=[...Ve,...$e],We=["dall-e-3"],He=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],ze=["tts-1","tts-1-hd","gpt-4o-mini-tts"],Ye=[...He,...ze],Je=["stable-diffusion-core"],Ke=["flux-pro-1.1"],Ze=[...We,...Je,...Ke],Xe=[...He],et=[...ze],tt=["mp3","opus","aac","flac","wav","pcm"],rt=["contextual","basic"],nt=["cohere","none"];function it(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const ot={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},st="ai_agents",at=["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","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"],ct=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch"],ut=["auth0","jwt_rsa","jwt_hmac","cognito","okta","descope","firebase_auth"],lt=["graphql","linear"],dt=["api","confluence"],ht=["data","api","graphql"],pt="built_in_db",ft="built_in_queue",yt="built_in_storage",gt=["secret","regular"],vt=["squid_functionExecution_count","squid_functionExecution_time"],bt=["sum","max","min","average","median","p95","p99","count"],mt=["user","squid"],_t=["align-by-start-time","align-by-end-time"],St=["in","not in","array_includes_some","array_includes_all","array_not_includes"],wt=[...St,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],It=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],Ot=["CONNECTED","DISCONNECTED","REMOVED"],Mt="__squidId";function Et(e){return Ie(e)}function Tt(...e){const[t,r,n]=e,i="object"==typeof t?t:{docId:t,collectionName:r,integrationId:n};return i.integrationId||(i.integrationId=void 0),Se(i)}class At{constructor(e,t,r){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=r,this.refId=$()}get squidDocId(){return this._squidDocId}get data(){return ge(this.dataRef)}get dataRef(){return Q(this.dataManager.getProperties(this.squidDocId),(()=>{const{collectionName:e,integrationId:t,docId:r}=Et(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:r,collectionName:e,integrationId:t},null,2)}`}))}get hasData(){return!!this.dataManager.getProperties(this.squidDocId)}async snapshot(){if(this.hasSquidPlaceholderId())throw new Error("Cannot invoke snapshot of a document that was created locally without storing it on the server.");if(this.isTracked()&&this.hasData)return this.data;const e=await this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshot();return Q(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0}snapshots(){return this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshots().pipe((0,a.map)((e=>(Q(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0))))}peek(){return this.isTracked()&&this.hasData?this.data:void 0}isDirty(){return this.dataManager.isDirty(this.squidDocId)}isTracked(){return this.dataManager.isTracked(this.squidDocId)}async update(e,t){const r={};Object.entries(e).forEach((([e,t])=>{const n=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};r[e]=[n]}));const n={type:"update",squidDocIdObj:Et(this.squidDocId),properties:r};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,r){return this.update({[e]:ge(t)},r)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,r){const n={type:"applyNumericFn",fn:"increment",value:t},i={type:"update",squidDocIdObj:Et(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(i,r)}decrementInPath(e,t,r){return this.incrementInPath(e,-t,r)}async insert(e,t){const r=Et(this.squidDocId),n=r.integrationId;let i=Ie(r.docId);if(i[Mt]&&(i={}),n===pt&&i.__id)try{const e=Ie(i.__id);i={...i,...e}}catch{}const o={type:"insert",squidDocIdObj:r,properties:{...e,__docId__:r.docId,...i}};return this.dataManager.applyOutgoingMutation(o,t)}async delete(e){const t={type:"delete",squidDocIdObj:Et(this.squidDocId)};return this.dataManager.applyOutgoingMutation(t,e)}migrateDocIds(e){const t=e[this.squidDocId];t&&(this._squidDocId=t)}hasSquidPlaceholderId(){const e=Ie(this._squidDocId);if("object"==typeof e&&e.docId){const t=Ie(e.docId);if("object"==typeof t&&Object.keys(t).includes(Mt))return!0}return!1}}Error;class kt{constructor(e,t={}){this.internalStateObserver=new a.BehaviorSubject(null),this.firstElement=null,this.isDestroyed=new a.BehaviorSubject(!1),this.snapshotSubject=new a.Subject,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,B(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe((0,a.switchAll)()).subscribe((e=>this.dataReceived(e))),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...t},this.goToFirstPage()}goToFirstPage(){this.onFirstPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).snapshots(this.paginateOptions.subscribe);this.snapshotSubject.next(e)}compareObjects(e,t){if(e===t||pe(e)&&pe(t))return 0;if(pe(e))return-1;if(pe(t))return 1;const r=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:i}of r){const r=be(ce(e,n),ce(t,n));if(0!==r)return i?r:-r}return 0}async dataReceived(e){const t=e.map((e=>this.templateSnapshotEmitter.extractData(e)));if(0===e.length)return void(this.onFirstPage?this.internalStateObserver.next({numBefore:0,numAfter:0,data:e,extractedData:t}):this.goToFirstPage());if(null===this.firstElement)if(null!==this.lastElement){const r=t.filter((e=>1===this.compareObjects(e,this.lastElement))).length;this.firstElement=t[e.length-r-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const r=t.filter((e=>-1===this.compareObjects(e,this.firstElement))).length,n=Math.max(0,e.length-r-this.paginateOptions.pageSize);r!==e.length?this.internalStateObserver.next({numBefore:r,numAfter:n,data:e,extractedData:t}):this.prevInternal({numBefore:r,numAfter:n,data:e,extractedData:t})}doNewQuery(e,t){if(this.onFirstPage=!1,t){const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder();e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map((t=>({fieldName:t.fieldName,operator:t.asc?"<=":">=",value:ce(e,t.fieldName)||null})))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe((0,a.map)((e=>e.reverse()))))}else{const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize);e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map((t=>({fieldName:t.fieldName,operator:t.asc?">=":"<=",value:ce(e,t.fieldName)||null})))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await(0,a.firstValueFrom)((0,a.race)(this.isDestroyed.pipe((0,a.filter)(Boolean),(0,a.map)((()=>({data:[],extractedData:[],numBefore:0,numAfter:0})))),this.internalStateObserver.pipe((0,a.filter)((e=>null!==e)),(0,a.take)(1))))}internalStateToState(e){const{data:t,numBefore:r,numAfter:n,extractedData:i}=e;return{data:t.filter(((e,t)=>-1!==this.compareObjects(i[t],this.firstElement))).slice(0,this.paginateOptions.pageSize),hasNext:n>0,hasPrev:r>0}}unsubscribe(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.internalStateObserver.complete(),this.snapshotSubject.complete()}prevInternal(e){const{numBefore:t,numAfter:r,extractedData:n}=e;this.firstElement=null,this.lastElement=n[t-1],this.internalStateObserver.next(null),this.doNewQuery(n[n.length-r-1],!0)}async prev(){return this.prevInternal(await this.waitForInternalState()),await this.waitForData()}async next(){const{numBefore:e,extractedData:t}=await this.waitForInternalState();return e+this.paginateOptions.pageSize<t.length&&(this.firstElement=t[e+this.paginateOptions.pageSize]),this.internalStateObserver.next(null),this.doNewQuery(t[e],!1),await this.waitForData()}async waitForData(){return this.internalStateToState(await this.waitForInternalState())}observeState(){return this.internalStateObserver.pipe((0,a.filter)((e=>null!==e)),(0,a.map)((e=>this.internalStateToState(e))))}async first(){return await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.goToFirstPage(),await this.waitForData()}async refreshPage(){const{extractedData:e}=await this.waitForInternalState();return this.internalStateObserver.next(null),this.onFirstPage?this.goToFirstPage():this.doNewQuery(e[0],!1),await this.waitForData()}async last(){await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.navigatingToLastPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder().snapshots(this.paginateOptions.subscribe).pipe((0,a.map)((e=>e.reverse())));return this.snapshotSubject.next(e),await this.waitForData()}}function jt(e,t,r){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===r)return fe(e,t);if("!="===r)return!fe(e,t);switch(r){case"<":return!pe(e)&&(!!pe(t)||t<e);case"<=":return!!pe(t)||!pe(e)&&t<=e;case">":return!pe(t)&&(!!pe(e)||t>e);case">=":return!!pe(e)||!pe(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Ct(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Ct(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Ct(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Ct(t,e,!0));case"array_includes_some":{const r=t;return Array.isArray(t)&&Array.isArray(e)&&e.some((e=>Q(r,"VALUE_CANNOT_BE_NULL").some((t=>fe(t,e)))))}case"array_includes_all":{const r=t;return Array.isArray(e)&&Array.isArray(t)&&e.every((e=>Q(r,"VALUE_CANNOT_BE_NULL").some((t=>fe(t,e)))))}case"array_not_includes":{const r=t;return Array.isArray(t)&&Array.isArray(e)&&e.every((e=>!Q(r,"VALUE_CANNOT_BE_NULL").some((t=>fe(t,e)))))}default:throw new Error(`Unsupported operator comparison: ${r}`)}}fun