@squidcloud/client 1.0.423 → 1.0.424
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/internal-common/src/metric-name.d.ts +9 -0
- package/dist/internal-common/src/public-types/ai-agent-integrations.public-types.d.ts +12 -0
- package/dist/internal-common/src/public-types/ai-agent.public-types.d.ts +4 -8
- package/dist/internal-common/src/public-types-backend/api-call.public-context.d.ts +30 -0
- package/dist/internal-common/src/public-types-backend/mutation.public-context.d.ts +148 -0
- package/dist/internal-common/src/public-types-backend/native-query.public-context.d.ts +72 -0
- package/dist/internal-common/src/public-types-backend/query.public-context.d.ts +177 -0
- package/dist/internal-common/src/types/ai-agent.types.d.ts +199 -0
- package/dist/internal-common/src/types/ai-assistant.types.d.ts +1 -0
- package/dist/internal-common/src/types/ai-knowledge-base.types.d.ts +202 -0
- package/dist/internal-common/src/types/ai-matchmaking.types.d.ts +59 -0
- package/dist/internal-common/src/types/backend-function.types.d.ts +1 -0
- package/dist/internal-common/src/types/communication.types.d.ts +1 -0
- package/dist/internal-common/src/types/document.types.d.ts +1 -0
- package/dist/internal-common/src/types/file.types.d.ts +6 -0
- package/dist/internal-common/src/types/headers.types.d.ts +17 -0
- package/dist/internal-common/src/types/mutation.types.d.ts +1 -0
- package/dist/internal-common/src/types/notification.types.d.ts +5 -0
- package/dist/internal-common/src/types/observability.types.d.ts +78 -0
- package/dist/internal-common/src/types/query.types.d.ts +13 -0
- package/dist/internal-common/src/types/secret.types.d.ts +7 -0
- package/dist/internal-common/src/types/socket.types.d.ts +1 -0
- package/dist/internal-common/src/types/stage.d.ts +9 -0
- package/dist/internal-common/src/types/time-units.d.ts +1 -0
- package/dist/internal-common/src/types/url-shortener.types.d.ts +41 -0
- package/dist/internal-common/src/utils/array.d.ts +7 -0
- package/dist/internal-common/src/utils/e2e-test-utils.d.ts +2 -0
- package/dist/internal-common/src/utils/global.utils.d.ts +1 -0
- package/dist/internal-common/src/utils/http.d.ts +5 -0
- package/dist/internal-common/src/utils/lock.manager.d.ts +14 -0
- package/dist/internal-common/src/utils/metric-utils.d.ts +4 -0
- package/dist/internal-common/src/utils/metrics.types.d.ts +7 -0
- package/dist/internal-common/src/utils/object.d.ts +58 -0
- package/dist/internal-common/src/utils/serialization.d.ts +17 -0
- package/dist/internal-common/src/utils/squid.constants.d.ts +1 -0
- package/dist/internal-common/src/utils/trace-id-generator.d.ts +1 -0
- package/dist/internal-common/src/utils/validation.d.ts +19 -0
- package/dist/internal-common/src/websocket.impl.d.ts +26 -0
- package/dist/typescript-client/src/version.d.ts +1 -1
- package/package.json +1 -1
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"ws";import{BehaviorSubject as t,NEVER as n,Observable as i,ReplaySubject as s,Subject as r,combineLatest as o,combineLatestWith as a,concatMap as c,debounceTime as u,defaultIfEmpty as l,defer as h,delay as d,distinctUntilChanged as p,filter as g,finalize as f,first as y,firstValueFrom as m,interval as b,lastValueFrom as I,map as v,of as w,pairwise as S,race as M,share as k,skip as T,startWith as C,switchAll as O,switchMap as _,take as E,takeUntil as q,takeWhile as D,tap as A,timer as R}from"rxjs";var N={150:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0});const r=n(642);t.default=r.PromisePool,s(n(273),t),s(n(642),t),s(n(837),t),s(n(426),t),s(n(858),t),s(n(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class n 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=n},220:t=>{t.exports=e},234:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const i=n(642),s=n(172),r=n(837),o=n(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 s.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 s.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 s.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 s.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 s.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.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(i.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]=i.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 n=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(n)}).catch(async i=>{await this.handleErrorFor(i,e,t),this.removeActive(n)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(n),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[n,i]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),n()]).finally(i)}createTaskTimeout(e){let t;return[async()=>new Promise((n,i)=>{t=setTimeout(()=>{i(new r.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,n){if(this.shouldUseCorrespondingResults()&&(this.results()[n]=i.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 s.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(r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const i=n(234);class s{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 s(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 i.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=s,s.notRun=Symbol("notRun"),s.failed=Symbol("failed")},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class n 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=n},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class n extends Error{}t.StopThePromisePoolError=n}},x={};function F(e){var t=x[e];if(void 0!==t)return t.exports;var n=x[e]={exports:{}};return N[e].call(n.exports,n,n.exports,F),n.exports}F.d=(e,t)=>{for(var n in t)F.o(t,n)&&!F.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},F.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),F.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const j=["aiData","api","application","application-kotlin","auth","backend-function","connector","integration","internal-storage","internalCodeExecutor","mutation","native-query","observability","openapi","query","queue","quota","scheduler","secret","storage","webhooks","ws","personalStorage","internal-extraction","notification"];function P(e,t,n,i,s,r){let o="https",a=`${i||t}.${s||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=j.includes(n.replace(/^\//,"").split("/")[0]||"")||r?"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=n.replace(/^\/+/,"");return l?`${u}/${l}`:u}function B(e,t,n=""){return P(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",n)}class Q{constructor(e,t,n,i){this.rpcManager=e,this.iacBaseUrl=B(t,i,`openapi/iac/applications/${n}/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 setIntegrationSchema(e,t){await this.rpcManager.put(`${this.iacBaseUrl}/${e}/schema`,t)}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 L{constructor(e){this.rpcManager=e}get apiKeys(){return new U(this.rpcManager)}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 n={keys:[e],force:t};return this.rpcManager.post("secret/delete",n)}async deleteMany(e,t=!1){if(0===e.length)return;const n={keys:e,force:t};return this.rpcManager.post("secret/delete",n)}}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 ${constructor(e,t,n,i){this.rpcManager=e,this.region=t,this.appId=n,this.consoleRegion=i,this.integrationClient=new Q(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new L(this.rpcManager)}integrations(){return this.integrationClient}secrets(){return this.secretClient}}function G(e){return"function"==typeof e}function H(e){return function(t){if(function(e){return G(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 W=function(e,t){return W=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},W(e,t)};function V(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}W(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function K(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function z(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,s,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function J(e,t,n){if(n||2===arguments.length)for(var i,s=0,r=t.length;s<r;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var Y,Z=((Y=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),Y.prototype.constructor=Y,Y);function X(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var ee=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,n,i,s;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=K(r),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 r.remove(this);var c=this.initialTeardown;if(G(c))try{c()}catch(e){s=e instanceof Z?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=K(u),h=l.next();!h.done;h=l.next()){var d=h.value;try{te(d)}catch(e){s=null!=s?s:[],e instanceof Z?s=J(J([],z(s)),z(e.errors)):s.push(e)}}}catch(e){n={error:e}}finally{try{h&&!h.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}if(s)throw new Z(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)te(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).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)&&X(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&X(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function te(e){G(e)?e():e.unsubscribe()}ee.EMPTY;var ne={setTimeout:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var s=ne.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,J([e,t],z(n))):setTimeout.apply(void 0,J([e,t],z(n)))},clearTimeout:function(e){var t=ne.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function ie(){}var se=re("C",void 0,void 0);function re(e,t,n){return{kind:e,value:t,error:n}}var oe=function(e){function t(t){var n,i=e.call(this)||this;return i.isStopped=!1,t?(i.destination=t,((n=t)instanceof ee||n&&"closed"in n&&G(n.remove)&&G(n.add)&&G(n.unsubscribe))&&t.add(i)):i.destination=he,i}return V(t,e),t.create=function(e,t,n){return new ce(e,t,n)},t.prototype.next=function(e){this.isStopped?le(function(e){return re("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?le(re("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?le(se,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}(ee);Function.prototype.bind;var ae=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){ue(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){ue(e)}else ue(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){ue(e)}},e}(),ce=function(e){function t(t,n,i){var s,r=e.call(this)||this;return s=G(t)||!t?{next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=i?i:void 0}:t,r.destination=new ae(s),r}return V(t,e),t}(oe);function ue(e){!function(e){ne.setTimeout(function(){throw e})}(e)}function le(e,t){var n=null;n&&ne.setTimeout(function(){return n(e,t)})}var he={closed:!0,next:ie,error:function(e){throw e},complete:ie};function de(e,t,n,i,s){return new pe(e,t,n,i,s)}var pe=function(e){function t(t,n,i,s,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=s?function(e){try{s(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=i?function(){try{i()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return V(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(oe);function ge(e,t){return H(function(n,i){var s=0;n.subscribe(de(i,function(n){i.next(e.call(t,n,s++))}))})}function fe(e){return null!=e}let ye=e=>new Error(e);function me(e,t,...n){e||function(e,...t){const n=Ie(e);if("object"==typeof n)throw n;throw ye(n||"Assertion error",...t)}(t,...n)}function be(e,t,...n){return me(e,t,...n),e}function Ie(e){return void 0===e?"":"string"==typeof e?e:e()}function ve(e,t,n){const i=Ie(e);if("object"==typeof i)throw i;return`${i?`${i}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(n)}`}function we(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():Se()}function Se(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function Me(){return we()}const ke=18;function Te(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()))}function Ce(e=18,t="",n=""){me(t.length<e,"ID prefix is too long"),me(!t||!n||n.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let i="";for(let t=0;t<e;t++)i+=Te();if(t.length>0&&(i=t+i.substring(t.length)),n)for(;i.charAt(t.length)===n[t.length];)i=i.substring(0,t.length)+Te()+i.substring(t.length+1);return i}function Oe({count:e,length:t,prefix:n}){me(e>=0,`Invalid IDs count: ${e}`);const i=new Set;for(;i.size<e;)i.add(Ce(t||18,n||""));return[...i]}const _e=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Ee(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)Ee(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)Ee(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(_e.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${_e.join(", ")}`);const n=e[t];if("object"!=typeof n&&"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof n}`)}}function qe(e,t,n){const i=atob(e),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return new File([s],t,{type:n||"application/octet-stream"})}class De{constructor(e,t,n,i,s,r,o){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=n,this.rpcManager=i,this.socketManager=s,this.jobClient=r,this.backendFunctionManager=o}async get(){const e=await this.post("ai/agent/getAgent",{agentId:this.agentId});return e?.agent}async upsert(e){await this.post("ai/agent/upsertAgent",{...e,id:this.agentId})}async delete(){await this.post("ai/agent/deleteAgent",{agentId:this.agentId})}async updateInstructions(e){await this.setAgentOptionInPath("instructions",e)}async updateModel(e){await this.setAgentOptionInPath("model",e)}async updateConnectedAgents(e){await this.setAgentOptionInPath("connectedAgents",e)}async updateGuardrails(e){const t=await this.get();me(t,"Agent not found");const n={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",n)}async updateCustomGuardrails(e){await this.post("ai/agent/upsertCustomGuardrails",{agentId:this.agentId,customGuardrail:e})}async deleteCustomGuardrail(){await this.post("ai/agent/deleteCustomGuardrails",{agentId:this.agentId})}async regenerateApiKey(){return await this.post("ai/agent/regenerateApiKey",{agentId:this.agentId})}async getApiKey(){return await this.post("ai/agent/getApiKey",{agentId:this.agentId})}chat(e,t,n){return this.chatInternal(e,t,n).responseStream}async transcribeAndChat(e,t,n){const i=this.chatInternal(e,t,n),s=await be(i.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:i.responseStream,transcribedPrompt:s.transcribedPrompt}}async ask(e,t,n){const i=await this.askInternal(e,!1,t,n);return this.replaceFileTags(i.responseString,i.annotations)}async askWithAnnotations(e,t,n){const i=await this.askInternal(e,!1,t,n);return{responseString:i.responseString,annotations:i.annotations}}async askAsync(e,t,n){const i={agentId:this.agentId,prompt:e,options:n,jobId:t};await this.post("ai/chatbot/askAsync",i)}observeStatusUpdates(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"aiStatus"===e.type&&e.agentId===this.agentId),ge(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.post("ai/chatbot/history",t)).messages}async transcribeAndAsk(e,t,n){return await this.askInternal(e,!1,t,n)}async transcribeAndAskWithVoiceResponse(e,t,n){const i=await this.askInternal(e,!0,t,n),s=i.voiceResponse;return{responseString:i.responseString,transcribedPrompt:i.transcribedPrompt,voiceResponseFile:qe(s.base64File,`voice.${s.extension}`,s.mimeType)}}async askWithVoiceResponse(e,t,n){const i=await this.askInternal(e,!0,t,n),s=i.voiceResponse;return{responseString:i.responseString,voiceResponseFile:qe(s.base64File,`voice.${s.extension}`,s.mimeType)}}async setAgentOptionInPath(e,t){await this.post("ai/agent/setAgentOptionInPath",{agentId:this.agentId,path:e,value:t})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}replaceFileTags(e,t={}){let n=e;for(const[e,i]of Object.entries(t)){let t="";const s=i.aiFileUrl.fileName?i.aiFileUrl.fileName:i.aiFileUrl.url;switch(i.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${s}](${i.aiFileUrl.url})`}n=n.replace(`\${id:${e}}`,t)}return n}async askInternal(e,t,n,i){if(n?.contextMetadataFilter&&Ee(n.contextMetadataFilter),n?.contextMetadataFilterForKnowledgeBase)for(const e in n.contextMetadataFilterForKnowledgeBase)Ee(n.contextMetadataFilterForKnowledgeBase[e]);i=i||we(),n={...Ae,...n||{}};const s="string"==typeof e;let r="ai/chatbot/";r+=s||t?!s&&t?"transcribeAndAskWithVoiceResponse":s&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:s?e:void 0,options:n,jobId:i},a=s?void 0:[e];return await this.post(r,o,a,"file"),await this.jobClient.awaitJob(i)}chatInternal(e,t,n){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&Ee(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)Ee(t.contextMetadataFilterForKnowledgeBase[e]);const i=we(),s=void 0===(t={...Ae,...t||{}}).smoothTyping||t.smoothTyping;let o="";const a=new r,u=new r;this.ongoingChatSequences[i]=u;let l=-1;u.pipe(A(({tokenIndex:e})=>{void 0!==e&&e<l&&console.warn("Received token index out of order",e,l),void 0!==e&&(l=e)}),c(({value:e,complete:t,annotations:n})=>t?w({value:e,complete:t,annotations:n}):w(e).pipe(s?d(0):A(),ge(e=>({value:e,complete:!1,annotations:void 0})))),D(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:n})=>{o+=e,t&&n&&(o=this.replaceFileTags(o,n)),a.next(o)},error:e=>{console.error(e)},complete:()=>{a.complete()}});const h="string"==typeof e;n=n||we();const p={agentId:this.agentId,jobId:n,prompt:h?e:void 0,options:t,clientRequestId:i},g={responseStream:a.pipe(f(()=>{delete this.ongoingChatSequences[i]}),k())};return h?this.post("ai/chatbot/chat",p).catch(e=>{a.error(e),a.complete()}):this.post("ai/chatbot/transcribeAndChat",p,[e],"file").catch(e=>{throw a.error(e),a.complete(),e}),g.serverResponse=this.jobClient.awaitJob(n).catch(e=>{a.error(e),a.complete()}),g}async post(e,t,n=[],i="files"){const s={};return this.agentApiKey&&(s["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,n,i,s)}}const Ae={smoothTyping:!0,responseFormat:"text"};class Re{constructor(e,t,n,i){this.rpcManager=e,this.socketManager=t,this.jobClient=n,this.backendFunctionManager=i,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe(g(e=>"aiChatbot"===e.type),ge(e=>e)).subscribe(e=>{this.handleChatResponse(e)})}agent(e,t=void 0){return new De(e,t?.apiKey,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)}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:n,complete:i,tokenIndex:s,annotations:r}=e.payload;if(i&&!n.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(n.match(/\[.*?]\((.*?)\)/g))t.next({value:n,complete:i,tokenIndex:void 0===s?void 0:s,annotations:r});else for(let e=0;e<n.length;e++)t.next({value:n[e],complete:i&&e===n.length-1,tokenIndex:void 0===s?void 0:s,annotations:r})}}const Ne="__squid_empty_chat_id";class xe{constructor(e){this.rpcManager=e}async createAssistant(e,t,n,i){const s={name:e,instructions:t,functions:n,toolTypes:i};return(await this.rpcManager.post("ai/assistant/createAssistant",s)).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,n,i,s){const r={assistantId:e,threadId:t,prompt:n,fileIds:i,options:s};return(await this.rpcManager.post("ai/assistant/queryAssistant",r)).answer}async addFileToAssistant(e,t){const n={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",n,[t],"file")).fileId}async removeFileFromAssistant(e,t){const n={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",n)}async addFileToThread(e,t){const n={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",n,[t],"file")).fileId}}class Fe{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 n={input:e,options:t},i=await this.rpcManager.post("ai/audio/createSpeech",n);return qe(i.base64File,`audio.${i.extension}`,i.mimeType)}}class je{constructor(e,t){this.provider=e,this.rpcManager=t}async uploadFile(e){const t={provider:this.provider,expirationInSeconds:e.expirationInSeconds};return(await this.rpcManager.post("ai/files/uploadFile",t,[e.file],"file")).fileId}async deleteFile(e){const t={fileId:e,provider:this.provider};return(await this.rpcManager.post("ai/files/deleteFile",t)).deleted}}class Pe{constructor(e){this.rpcManager=e}async generate(e,t){const n={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",n)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function Be(e){for(const t in e){const n=e[t];me("string"==typeof n||"number"==typeof n||"boolean"==typeof n||void 0===n,`Invalid metadata value for key ${t} - cannot be of type ${typeof n}`),me(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class Qe{constructor(e,t,n){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=n}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(e){return(await this.rpcManager.post("ai/knowledge-base/listContexts",{id:this.knowledgeBaseId,truncateTextAfter:e})).contexts||[]}async listContextIds(){return(await this.rpcManager.post("ai/knowledge-base/listContextIds",{id:this.knowledgeBaseId})).contextIds||[]}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:n}=await this.upsertContexts([e],t?[t]:void 0);return n.length>0?{failure:n[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&Be(t.metadata);const n=we();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:n},t),await this.jobClient.awaitJob(n)}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 searchContextsWithPrompt(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithPrompt",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}async searchContextsWithContextId(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithContextId",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}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 Qe(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 Ue{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new $e(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new $e(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class $e{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 Ge=["user","ai"],He="parent",We="result",Ve=["cohere","none"],Ke=["anthropic","flux","gemini","openai","grok","stability","voyage","external"],ze=["o1","o3","o3-mini","o4-mini","gpt-5","gpt-5-mini","gpt-5-nano","gpt-5.1","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"],Je=["gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"],Ye=["grok-3","grok-3-fast","grok-3-mini","grok-3-mini-fast","grok-4","grok-4-fast-reasoning","grok-4-fast-non-reasoning","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],Ze=["claude-3-7-sonnet-latest","claude-haiku-4-5-20251001","claude-opus-4-20250514","claude-opus-4-1-20250805","claude-opus-4-5-20251101","claude-sonnet-4-20250514","claude-sonnet-4-5-20250929"],Xe=[...ze,...Ze,...Je,...Ye];function et(e){return Xe.includes(e)}const tt=["text-embedding-3-small"],nt=["voyage-3-large"],it=[...tt,...nt],st=["dall-e-3"],rt=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],ot=["tts-1","tts-1-hd","gpt-4o-mini-tts"],at=[...rt,...ot],ct=["stable-diffusion-core"],ut=["flux-pro-1.1","flux-kontext-pro"],lt=[...st,...ct,...ut],ht=[...rt],dt=[...ot],pt=["mp3","opus","aac","flac","wav","pcm"];function gt(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const ft=["contextual","basic"],yt=["secret","regular"];function mt(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const bt=["dev","prod"],It="built_in_agent",vt={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},wt="ai_agents",St=["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_calendar","google_docs","google_drive","graphql","hubspot","jira","jwt_hmac","jwt_rsa","kafka","keycloak","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","legend","teams","openai_compatible"],Mt=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch","legend"],kt=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth"],Tt=["graphql","linear"],Ct=["api"],Ot=["data","api","graphql"],_t="built_in_db",Et="built_in_queue",qt="built_in_storage",Dt=[_t,Et,qt];function At(e){return Dt.includes(e)}const Rt=["squid_functionExecution_count","squid_functionExecution_time"],Nt=["sum","max","min","average","median","p95","p99","count"],xt=["user","squid"],Ft=["align-by-start-time","align-by-end-time"],jt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],Pt=[...jt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],Bt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],Qt=["CONNECTED","DISCONNECTED","REMOVED"];class Lt{constructor(e,t,n,i){this.socketManager=e,this.rpcManager=t,this.jobClient=n,this.backendFunctionManager=i,this.aiAssistantClient=new xe(this.rpcManager)}agent(e=It,t=void 0){return this.getAiAgentClient().agent(e,t)}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 Pe(this.rpcManager)}audio(){return new Fe(this.rpcManager)}matchMaking(){return new Ue(this.rpcManager)}files(e){return new je(e,this.rpcManager)}executeAiQuery(e,t,n){const i={integrationId:e,prompt:t,options:n};return this.rpcManager.post("ai/query/executeDataQuery",i)}executeAiApiCall(e,t,n,i){const s={integrationId:e,prompt:t,options:n,sessionContext:i};return this.rpcManager.post("ai/query/executeApiQuery",s)}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 n={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",n)).settings}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Re(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new Le(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const Ut={headers:{},queryParams:{},pathParams:{}};class $t{constructor(e){this.rpcManager=e}async get(e,t,n){return this.request(e,t,void 0,n,"get")}async post(e,t,n,i){return this.request(e,t,n,i,"post")}async delete(e,t,n,i){return this.request(e,t,n,i,"delete")}async patch(e,t,n,i){return this.request(e,t,n,i,"patch")}async put(e,t,n,i){return this.request(e,t,n,i,"put")}async request(e,t,n,i,s){const r={integrationId:e,endpointId:t,body:n,options:{...Ut,...this.convertOptionsToStrings(i||{})},overrideMethod:s};return await this.rpcManager.rawPost("api/callApi",r,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 Gt{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}}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}async getTokenFromAuthProvider(){const e=this.authProvider?.getToken();return"object"==typeof e?await e:e}}const Ht=/[.\[\]]/;function Wt(e,t){if(!e)return;const n=t.split(Ht);let i,s=e;for(;s&&n.length;){const e=n.shift();if(e){if("object"!=typeof s||!(e in s))return;i=s[e],s=i}}return i}function Vt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Kt(e,t,n,i="."){const s=t.split(i);let r=e;for(;s.length;){const e=be(s.shift());if(s.length){const t=r[e],n=Vt(t)?tn(t)??{}:{};r[e]=n,r=n}else r[e]=n}}function zt(e,t,n="."){const i=t.split(n);let s=e;for(;i.length;){const e=be(i.shift());if(i.length){const t=Vt(s[e])?tn(s[e])??{}:{};s[e]=t,s=t}else delete s[e]}}function Jt(e,t,n){if(e.has(t)){const i=e.get(t);e.delete(t),e.set(n,i)}}function Yt(e){return null==e}function Zt(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const n=typeof e;if(n!==typeof t)return!1;if("object"!==n)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(const n of i)if(!s.includes(n)||!Zt(e[n],t[n]))return!1;return!0}function Xt(e,t){const n=new Array(e.length);for(let i=0;i<e.length;i++)n[i]=en(e[i],t);return n}function en(e,t){const n=t?t(e):void 0;if(void 0!==n)return n;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return Xt(e,t);if(e instanceof Map)return new Map(Xt(Array.from(e),t));if(e instanceof Set)return new Set(Xt(Array.from(e),t));if(ArrayBuffer.isView(e))return(i=e)instanceof Buffer?Buffer.from(i):new i.constructor(i.buffer.slice(),i.byteOffset,i.length);var i;const s={};for(const n in e)Object.hasOwnProperty.call(e,n)&&(s[n]=en(e[n],t));return s}function tn(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 nn(e,t){if(e===t||Yt(e)&&Yt(t))return 0;if(Yt(e))return-1;if(Yt(t))return 1;const n=typeof e,i=typeof t;return n!==i?n<i?-1:1:"number"==typeof e?(me("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(me("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(me("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(me("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function sn(e,t){return e.reduce((e,n)=>{const i=t(n);return e[i]?e[i].push(n):e[i]=[n],e},{})}function rn(e){if(Array.isArray(e))return e.map(e=>rn(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),n={};return t.sort().forEach(t=>{n[t]=rn(e[t])}),n}function on(e){return an(rn(e))}function an(e){if(void 0===e)return null;const t=en(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function cn(e){return en(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,n=t.$date;return n&&1===Object.keys(t).length?new Date(n):void 0})}function un(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=an(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let n="";for(let t=0;t<e.length;t++)n+=String.fromCharCode(e[t]);return btoa(n)}}const ln=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},hn=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(an(e[n])!==an(t[n]))return!1;return!0};class dn{constructor(e){this.options=e}get(e){const t=this.cachedEntry,n=this.options.argsComparator||ln,i=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+i&&n(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function pn(e){const t=[],n=[];let i=0;for(const s of e)if("undefined"!=typeof File)if(s instanceof File){n.push(s);const e={type:"file",__squid_placeholder__:!0,fileIndex:i++};t.push(e)}else if(gn(s)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:s.map((e,t)=>(n.push(s[t]),i++))};t.push(e)}else t.push(s);else t.push(s);return{argsArray:t,fileArray:n}}function gn(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class fn{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...n){const{argsArray:i,fileArray:s}=pn(n),r="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,a=o?.cache;if(a){const e=a.get(i);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?ln:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,i));if(t)return t.promise}const u=this.createExecuteCallPromise(r,i,s,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:i,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,n,i,s={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:an(t)},a=cn((await this.rpcManager.post(r,o,n.length>0?n:[],"files",s)).payload);if(a?.__isSquidBase64File__){const e=a;return qe(e.base64,e.filename,e.mimetype)}return i&&i.set(t,a),a}}function yn(e){if("undefined"!=typeof globalThis)return globalThis[e]}function mn(){if("undefined"!=typeof window)return window;if(void 0!==F.g)return F.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}!function(e=!0){mn().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 bn{static debug(...e){(function(){const e=mn();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=mn();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class In{constructor(e){this.destructManager=e,this.clientTooOldSubject=new t(!1),this.isTenant=!0===mn().squidTenant,this.clientIdSubject=new t(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe(g(e=>e),v(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe(T(1),g(e=>!e),v(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=mn()[wn];return e?e():we()}generateClientId(){const e=mn()[vn];if(e)return e();let t=`${this.isTenant?"tenant-":""}${we()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const vn="SQUID_CLIENT_ID_GENERATOR",wn="SQUID_CLIENT_REQUEST_ID_GENERATOR",Sn="__squidId";function Mn(e){return cn(e)}function kn(...e){const[t,n,i]=e,s="object"==typeof t?t:{docId:t,collectionName:n,integrationId:i};return s.integrationId||(s.integrationId=void 0),on(s)}function Tn(e,t,n){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===n)return Zt(e,t);if("!="===n)return!Zt(e,t);switch(n){case"<":return!Yt(e)&&(!!Yt(t)||t<e);case"<=":return!!Yt(t)||!Yt(e)&&t<=e;case">":return!Yt(t)&&(!!Yt(e)||t>e);case">=":return!!Yt(e)||!Yt(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Cn(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Cn(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Cn(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Cn(t,e,!0));case"array_includes_some":{const n=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>be(n,"VALUE_CANNOT_BE_NULL").some(t=>Zt(t,e)))}case"array_includes_all":{const n=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>be(n,"VALUE_CANNOT_BE_NULL").some(t=>Zt(t,e)))}case"array_not_includes":{const n=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!be(n,"VALUE_CANNOT_BE_NULL").some(t=>Zt(t,e)))}default:throw new Error(`Unsupported operator comparison: ${n}`)}}function Cn(e,t,n){n||(e=e.toLowerCase(),t=t.toLowerCase());const i=function(e){let t="";for(let n=0;n<e.length;++n)"\\"===e[n]?n+1<e.length&&["%","_"].includes(e[n+1])?(t+=e[n+1],n++):n+1<e.length&&"\\"===e[n+1]?(t+="\\\\",n++):t+="\\":"%"===e[n]?t+="[\\s\\S]*":"_"===e[n]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[n])&&(t+="\\"),t+=e[n]);return t}(t);return new RegExp(`^${i}$`).test(e)}function On(e,t){return`${e}_${t}`}function _n(e){return"fieldName"in e}class En{constructor(e,t,n){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=n,this.refId=we()}get squidDocId(){return this._squidDocId}get data(){return en(this.dataRef)}get dataRef(){return be(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:n}=Mn(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:n,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 be(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(v(e=>(be(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)}async update(e,t){const n={};Object.entries(e).forEach(([e,t])=>{const i=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};n[e]=[i]});const i={type:"update",squidDocIdObj:Mn(this.squidDocId),properties:n};return this.dataManager.applyOutgoingMutation(i,t)}async setInPath(e,t,n){return this.update({[e]:en(t)},n)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,n){const i={type:"applyNumericFn",fn:"increment",value:t},s={type:"update",squidDocIdObj:Mn(this.squidDocId),properties:{[e]:[i]}};return this.dataManager.applyOutgoingMutation(s,n)}decrementInPath(e,t,n){return this.incrementInPath(e,-t,n)}async insert(e,t){const n=Mn(this.squidDocId),i=n.integrationId;let s=cn(n.docId);if(s[Sn]&&(s={}),i===_t&&s.__id)try{const e=cn(s.__id);s={...s,...e}}catch{}const r={type:"insert",squidDocIdObj:n,properties:{...e,__docId__:n.docId,...s}};return this.dataManager.applyOutgoingMutation(r,t)}async delete(e){const t={type:"delete",squidDocIdObj:Mn(this.squidDocId)};return this.dataManager.applyOutgoingMutation(t,e)}migrateDocIds(e){const t=e[this.squidDocId];t&&(this._squidDocId=t)}isTracked(){return this.dataManager.isTracked(this.squidDocId)}hasSquidPlaceholderId(){const e=cn(this._squidDocId);if("object"==typeof e&&e.docId){const t=cn(e.docId);if("object"==typeof t&&Object.keys(t).includes(Sn))return!0}return!1}}class qn{constructor(e,n={}){this.internalStateObserver=new t(null),this.firstElement=null,this.isDestroyed=new t(!1),this.snapshotSubject=new r,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,me(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe(O()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...n},this.goToFirstPage()}unsubscribe(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.internalStateObserver.complete(),this.snapshotSubject.complete()}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(g(e=>null!==e),v(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(v(e=>e.reverse()));return this.snapshotSubject.next(e),await this.waitForData()}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||Yt(e)&&Yt(t))return 0;if(Yt(e))return-1;if(Yt(t))return 1;const n=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:i,asc:s}of n){const n=nn(Wt(e,i),Wt(t,i));if(0!==n)return s?n:-n}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 n=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-n-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const n=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,i=Math.max(0,e.length-n-this.paginateOptions.pageSize);n!==e.length?this.internalStateObserver.next({numBefore:n,numAfter:i,data:e,extractedData:t}):this.prevInternal({numBefore:n,numAfter:i,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:Wt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe(v(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:Wt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await m(M(this.isDestroyed.pipe(g(Boolean),v(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe(g(e=>null!==e),E(1))))}internalStateToState(e){const{data:t,numBefore:n,numAfter:i,extractedData:s}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(s[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:i>0,hasPrev:n>0}}prevInternal(e){const{numBefore:t,numAfter:n,extractedData:i}=e;this.firstElement=null,this.lastElement=i[t-1],this.internalStateObserver.next(null),this.doNewQuery(i[i.length-n-1],!0)}}Error;class Dn{constructor(e,t,n,i){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=n,this.documentIdentityService=i}getForDocument(e){const{collectionName:t,integrationId:n,docId:i}=Mn(e),s=cn(i),r=this.get(t,n);for(const[e,t]of Object.entries(s))r.where(e,"==",t);return r}get(e,t){return new Nn(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService)}}class An{constructor(){this.containsEmptyInCondition=!1}eq(e,t){return this.where(e,"==",t)}neq(e,t){return this.where(e,"!=",t)}in(e,t){return this.where(e,"in",t)}nin(e,t){return this.where(e,"not in",t)}gt(e,t){return this.where(e,">",t)}gte(e,t){return this.where(e,">=",t)}lt(e,t){return this.where(e,"<",t)}lte(e,t){return this.where(e,"<=",t)}like(e,t,n){return this.throwIfInvalidLikePattern(t),this.where(e,n?"like_cs":"like",t)}notLike(e,t,n){return this.throwIfInvalidLikePattern(t),this.where(e,n?"not like_cs":"not like",t)}arrayIncludesSome(e,t){return this.where(e,"array_includes_some",t)}arrayIncludesAll(e,t){return this.where(e,"array_includes_all",t)}arrayNotIncludes(e,t){return this.where(e,"array_not_includes",t)}throwIfInvalidLikePattern(e){if(/\\(?![%_\\])/.test(e))throw new Error("Invalid pattern. Cannot have any \\ which are not followed by _, % or \\")}}class Rn{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return m(this.snapshots(!1).pipe(l([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(ge(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Rn(this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new qn(this,e)}}class Nn extends An{constructor(e,t,n,i,s,r,o){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=n,this.localQueryManager=i,this.documentReferenceFactory=s,this.queryBuilderFactory=r,this.documentIdentityService=o,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}get hash(){return un(this.build())}where(e,t,n){if(me(Pt.includes(t),`Invalid operator: ${t}`),"in"===t||"not in"===t){const i=Array.isArray(n)?[...n]:[n];"in"===t&&0===i.length&&(this.containsEmptyInCondition=!0);for(const n of i)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:n});return this}return this.query.conditions.push({fieldName:e,operator:t,value:n}),this}limit(e){return function(e){var t;me(function(e){return"number"==typeof e}(t=e),()=>ve("Limit needs to be a number","Not a number",t)),-1!==e&&(me(e>0,"query limit has to be greater than 0"),me(Math.floor(e)===e,"query limit has to be an integer"),me(e<=2e4,"Limit can be maximum 20000"))}(e),this.query.limit=e,this}getLimit(){return this.query.limit}limitBy(e,...t){const n=this.query.sortOrder.map(e=>e.fieldName);return me(Zt(t.sort(),n.slice(0,t.length).sort()),"All fields in limitBy must be appear in the first fields in the sortBy list."),this.query.limitBy={limit:e,fields:t,reverseSort:!1},this}sortBy(e,t=!0){const n={asc:t,fieldName:e};return function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var n,i,s,r;me((n=t,i=["fieldName","asc"],!Array.isArray(n)&&[...Object.keys(n)].every(e=>i.includes(e))),"Field sort should only contain a fieldName and asc"),me((s=t.asc,r="boolean",Array.isArray(s)?s.every(e=>typeof e===r):typeof s===r),"Asc needs to be boolean")}(n),me(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.sortOrder.push(n),this}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}getSortOrder(){return this.query.sortOrder}snapshot(){return m(this.snapshots(!1).pipe(l([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new t([]);const n=this.build();return this.querySubscriptionManager.processQuery(n,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(ge(e=>e.map(e=>{me(1===Object.keys(e).length);const t=kn(be(e[this.collectionName]).__docId__,this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)})))}changes(){let e,t=new Set;return this.snapshots().pipe(a(this.documentIdentityService.observeChanges().pipe(_(t=>(Object.entries(t).forEach(([t,n])=>{!function(e,t,n){const i=e[t];void 0!==i&&(e[n]=i,delete e[t])}(e||{},t,n)}),n)),C({}))),ge(([n])=>{let i=[];const s=[],r=[];if(e){for(const r of n){const n=r.squidDocId,o=r.dataRef;if(t.has(o))delete e[n],t.delete(o);else if(e[n]){s.push(r);const i=e[n];delete e[n],t.delete(i)}else i.push(r)}for(const e of t)r.push(e)}else i=n;e={},t=new Set;for(const i of n){const n=i.dataRef;e[i.squidDocId]=n,t.add(n)}return new xn(i,s,r)}))}dereference(){return new Rn(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new Nn(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService);return e.query=en(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){return e.length?(this.query.conditions.push({fields:e}),this):this}flipSortOrder(){return this.query.sortOrder=this.query.sortOrder.map(e=>({...e,asc:!e.asc})),this.query.limitBy&&(this.query.limitBy.reverseSort=!this.query.limitBy.reverseSort),this}serialize(){return{type:"simple",dereference:!1,query:this.build()}}extractData(e){return e.dataRef}paginate(e){return new qn(this,e)}mergeConditions(){const e=[],t=sn(this.query.conditions.filter(_n)||[],e=>e.fieldName);for(const n of Object.values(t)){const t=sn(n,e=>e.operator);for(const[n,i]of Object.entries(t)){if("=="===n||"!="===n){e.push(...i);continue}const t=[...i];t.sort((e,t)=>nn(e.value,t.value)),">"===n||">="===n?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!_n(e)),...e]}}class xn{constructor(e,t,n){this.inserts=e,this.updates=t,this.deletes=n}}class Fn extends An{constructor(e,t,n,i,s,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=n,this.documentReferenceFactory=i,this.queryBuilderFactory=s,this.rootAlias=r,this.latestAlias=o,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,n){return this.queryBuilder.where(e,t,n),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}sortBy(e,t=!0){return this.queryBuilder.sortBy(e,t),this}join(e,t,n,i){const s=i?.leftAlias??this.latestAlias,r={...n,leftAlias:s,isInner:i?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[s].push(t),new Fn(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,t,o,{...this.joins,[t]:e.build()},{...this.joinConditions,[t]:r},this.queryBuilder)}snapshot(){return m(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new t([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,en(this.joins),en(this.joinConditions),e,!1).pipe(ge(e=>e.map(e=>{const t={};for(const[n,i]of Object.entries(e)){const e=n===this.rootAlias?this.collectionName:this.joins[n].collectionName,s=n===this.rootAlias?this.integrationId:this.joins[n].integrationId,r=i?kn(i.__docId__,e,s):void 0;t[n]=r?this.documentReferenceFactory.create(r,this.queryBuilderFactory):void 0}return t})))}peek(){throw new Error("peek is not currently supported for join queries")}grouped(){return new Bn(this)}dereference(){return new jn(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Fn(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,en(this.leftToRight),en(this.joins),en(this.joinConditions),this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e[this.rootAlias].dataRef}serialize(){return{type:"join",grouped:!1,dereference:!1,root:{alias:this.rootAlias,query:this.build()},leftToRight:this.leftToRight,joins:this.joins,joinConditions:this.joinConditions}}paginate(e){if(this.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new qn(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class jn{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(ge(e=>e.map(e=>function(e,t){const n={},i=Object.keys(e);for(const s of i){const i=e[s];n[s]=t(i)}return n}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new jn(this.joinQueryBuilder.clone())}addCompositeCondition(e){return this.joinQueryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.joinQueryBuilder.flipSortOrder(),this}limit(e){return this.joinQueryBuilder.limit(e),this}extractData(e){return e[this.joinQueryBuilder.rootAlias]}paginate(e){if(this.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new qn(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class Pn{constructor(e){this.groupedJoin=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(ge(e=>e.map(e=>this.dereference(e,this.groupedJoin.joinQueryBuilder.rootAlias))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.groupedJoin.getSortOrders()}clone(){return new Pn(this.groupedJoin.clone())}addCompositeCondition(e){return this.groupedJoin.addCompositeCondition(e),this}flipSortOrder(){return this.groupedJoin.flipSortOrder(),this}limit(e){return this.groupedJoin.limit(e),this}getLimit(){return this.groupedJoin.getLimit()}extractData(e){return e[this.groupedJoin.joinQueryBuilder.rootAlias]}serialize(){return{...this.groupedJoin.joinQueryBuilder.serialize(),dereference:!0,grouped:!0}}paginate(e){if(this.groupedJoin.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new qn(this,e)}dereference(e,t){const n=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(n.length){const i={[t]:e[t].data};for(const t of n)i[t]=e[t].map(e=>this.dereference(e,t));return i}return e.data}}class Bn{constructor(e){this.joinQueryBuilder=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(ge(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new Pn(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new Bn(this.joinQueryBuilder.clone())}addCompositeCondition(e){return this.joinQueryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.joinQueryBuilder.flipSortOrder(),this}limit(e){return this.joinQueryBuilder.limit(e),this}getLimit(){return this.joinQueryBuilder.getLimit()}extractData(e){return Object.keys(this.joinQueryBuilder.leftToRight).length>1?e[this.joinQueryBuilder.rootAlias].dataRef:e.dataRef}serialize(){return{...this.joinQueryBuilder.serialize(),grouped:!0}}paginate(e){if(this.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new qn(this,e)}groupData(e,t){const n=sn(e,e=>e[t]?.squidDocId);return Object.values(n).filter(e=>void 0!==e[0][t]).map(e=>{const n=this.joinQueryBuilder.leftToRight[t],i=e[0][t];if(0===n.length)return i;const s={[t]:i};for(const t of n)s[t]=this.groupData(e,t);return s})}}class Qn{constructor(e,t,n,i,s,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=n,this.queryBuilderFactory=i,this.querySubscriptionManager=s,this.dataManager=r,this.refId=we()}doc(e){if(e&&"string"!=typeof e&&"object"!=typeof e&&!Array.isArray(e))throw new Error("Invalid doc id. Can be only object or string.");if(this.integrationId!==_t)if(e){if("object"!=typeof e)throw new Error("Invalid doc id. String doc ids are only supported for the built_in_db integration. For all other integrations, the doc id must be an object.")}else e={[Sn]:we()};else e=e&&"string"!=typeof e?{__id:on(e)}:{__id:e||we()};const t=kn(on(e),this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)}async insertMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const n of e)await this.doc(n.id).insert(n.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const n of e)n instanceof En?await n.delete(t):await this.doc(n).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new Fn(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new Ln(...e)}}class Ln{constructor(...e){if(0===e.length)throw new Error("At least one query builder must be provided");this.snapshotEmitters=e.map(e=>e.clone());const t=Math.max(...this.snapshotEmitters.map(e=>{const t=e.getLimit();return-1===t?1e3:t}));this.snapshotEmitters.forEach(e=>e.limit(t));const n=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==n.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<n.length;e++)if(t[e].fieldName!==n[e].fieldName||t[e].asc!==n[e].asc)throw new Error("All the queries must have the same sort order")}}snapshot(){return m(this.snapshots(!1))}snapshots(e=!0){const t=this.snapshotEmitters.map(t=>t.snapshots(e));return this.or(this.snapshotEmitters[0].getSortOrders(),...t)}peek(){throw new Error("peek is not currently supported for merged queries")}clone(){return new Ln(...this.snapshotEmitters.map(e=>e.clone()))}getSortOrders(){return this.snapshotEmitters[0].getSortOrders()}addCompositeCondition(e){for(const t of this.snapshotEmitters)t.addCompositeCondition(e);return this}limit(e){return this.snapshotEmitters.forEach(t=>t.limit(e)),this}getLimit(){return this.snapshotEmitters[0].getLimit()}flipSortOrder(){return this.snapshotEmitters.forEach(e=>e.flipSortOrder()),this}serialize(){return{type:"merged",queries:this.snapshotEmitters.map(e=>e.serialize())}}extractData(e){return this.snapshotEmitters[0].extractData(e)}paginate(e){return new qn(this,e)}or(e,...t){return o([...t]).pipe(v(t=>{const n=new Set,i=t.flat(),s=[];for(const e of i)n.has(this.extractData(e))||(n.add(this.extractData(e)),s.push(e));return s.sort((t,n)=>{for(const{fieldName:i,asc:s}of e){const e=Wt(this.extractData(t),i),r=Wt(this.extractData(n),i);if(!Tn(e,r,"=="))return Tn(r,e,"<")?s?-1:1:s?1:-1}return 0}).slice(0,this.getLimit())}))}}class Un{constructor(e,t,n,i){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=n,this.dataManager=i,this.collections=new Map}get(e,t){let n=this.collections.get(t);n||(n=new Map,this.collections.set(t,n));let i=n.get(e);return i||(i=new Qn(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),n.set(e,i)),i}}class $n{constructor(e,t){this.clientIdService=e,this.socketManager=t,this.isConnected=!1,this.socketManager.observeConnectionReady().subscribe(e=>{this.isConnected=e})}get connected(){return this.isConnected}get clientId(){return this.clientIdService.getClientId()}observeConnected(){return this.socketManager.observeConnectionReady()}}var Gn=F(150);function Hn(e,t){switch(t.type){case"applyNumericFn":return function(e,t){if("increment"===t.fn)return null==e?t.value:e+t.value;throw new Error("Unknown numeric function: "+JSON.stringify(t))}(e,t);case"applyStringFn":return function(e,t){switch(t.fn){case"trim":return"string"!=typeof e?e:e.trim();case"extendString":return null==e?t.value:e+t.value;default:throw new Error("Unknown string function: "+JSON.stringify(t))}}(e,t);case"update":return"object"==typeof t.value?en(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function Wn(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function Vn(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(me("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const n=en(e);t=en(t);for(const[e]of Wn(n)){const i=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&i>t.split(".").length)&&delete n.properties[e]}for(const[e,i]of Wn(t))n.properties[e]=Kn([...n.properties[e]||[],...i]);return n}(e,t);const n=en(e);for(const[e,i]of Wn(t)){const t=i;for(const i of t){const t=Hn(Wt(n.properties,e),i);void 0===t?zt(n.properties,e):Kt(n.properties,e,t)}}return n}function Kn(e){let t=0;for(;t+1<e.length;){const n=zn(e[t],e[t+1]);n?e.splice(t,2,n):++t}return e}function zn(e,t){return"removeProperty"===t.type||"update"===t.type?t:"applyNumericFn"===t.type?(me("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type?(me("increment"===e.fn,"Unrecognized applyNumericFn"),{type:"applyNumericFn",fn:"increment",value:e.value+t.value}):"update"===e.type?{type:"update",value:e.value+t.value}:t):"extendString"===t.fn?"update"===e.type?{type:"update",value:e.value+t.value}:"applyStringFn"===e.type?"trim"===e.fn?null:{type:"applyStringFn",fn:"extendString",value:e.value+t.value}:t:null}function Jn(e){const t={};for(const n of e){const e=`${n.squidDocIdObj.integrationId}/${n.squidDocIdObj.collectionName}/${n.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(n)}const n=[];for(const e in t){const i=t[e].reduce((e,t)=>be(Vn(e,t),"Merge result cannot be null"));n.push(i)}return n}const Yn="dataManager_runInTransaction";class Zn{constructor(e,n,i,s,o,a,c,u,l){this.documentStore=e,this.mutationSender=n,this.socketManager=i,this.querySubscriptionManager=s,this.queryBuilderFactory=o,this.lockManager=a,this.destructManager=c,this.documentIdentityService=u,this.querySender=l,this.docIdToLocalTimestamp=new Map,this.batchClientRequestIds=new Set,this.docIdToServerTimestamp=new Map,this.pendingIncomingUpdates=new Map,this.pendingOutgoingMutations=new Map,this.pendingOutgoingMutationsChanged=new r,this.outgoingMutationsEmpty=new t(!0),this.knownDirtyDocs=new Set,this.failedDocsToResync=[],this.refreshDocIdToTimestamp=new Map,this.handleIncomingMessagesForTests=!0,this.destructManager.onDestruct(()=>{this.destruct()}),this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.handleNotifications(),this.startDeleteExpiredTimestampsJob(),this.handleOrphanDocs(),this.outgoingMutationsEmpty.subscribe(e=>{this.querySender.safeToSendQueriesToServer.next(e)})}getProperties(e){return this.documentStore.getDocumentOrUndefined(e)}isDirty(e){if(this.knownDirtyDocs.has(e))return!0;if(this.pendingOutgoingMutations.get(e)?.length)return!0;const t=this.docIdToServerTimestamp.get(e),n=t&&!t.expireTimestamp?t.timestamp:void 0,i=this.docIdToLocalTimestamp.get(e);return!((!i||n)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&i===n)}async runInTransaction(e,t){if(t)return me(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(Yn)?this.lockManager.lockSync(Yn):await this.lockManager.lock(Yn);let n=Xn;const i=()=>n!==Xn;return new Promise(async(t,s)=>{try{let r;this.currentTransactionId=we();try{r=await e(this.currentTransactionId)}catch(e){n=e}finally{this.finishTransaction(i()?void 0:{resolve:()=>t(r),reject:s})}}catch(e){n=i()?n:e}finally{try{this.lockManager.release(Yn)}catch(e){n=i()?n:e}}i()&&s(n)})}async applyOutgoingMutation(e,t){const n=kn(e.squidDocIdObj);this.knownDirtyDocs.add(n),t||this.lockManager.canGetLock(Yn)||(await this.lockManager.lock(Yn),this.lockManager.release(Yn)),this.knownDirtyDocs.delete(n);const i=this.pendingOutgoingMutations.get(n)?.slice(-1)[0];if(i&&!i.sentToServer)i.mutation=be(Jn([i.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},i=this.pendingOutgoingMutations.get(n)||[];i.push(t),this.pendingOutgoingMutations.set(n,i),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(n),i="delete"===e.type?void 0:"update"===e.type?function(e,t){if(!e)return;const n={...e},i=Wn(t);for(const[e,t]of i){const i=t;for(const t of i){const i=Hn(Wt(n,e),t);void 0===i?zt(n,e):Kt(n,e,i)}}return n}(t,e):{...e.properties};this.updateDocumentFromSnapshot(n,i)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(n,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(n,i).forEach(e=>this.batchClientRequestIds.add(e)))},t)}isTracked(e){if(this.pendingIncomingUpdates.get(e))return!0;const t=this.pendingOutgoingMutations.get(e);return!(!t||!t.length)||this.querySubscriptionManager.hasOngoingQueryForDocId(e)}isForgotten(e){return this.documentStore.hasData(e)&&!this.isTracked(e)}isLocalOnly(e){return!this.hasBeenAcknowledged(e)&&this.documentStore.hasData(e)}hasBeenAcknowledged(e){return this.docIdToServerTimestamp.has(e)}async runInTransactionSync(e,t){if(t)return me(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(Yn);try{this.currentTransactionId=we();try{return e(this.currentTransactionId)}catch(e){console.error("error while executing callback function in transaction",e)}finally{this.finishTransaction()}}catch(e){console.error("error while executing transaction",e)}finally{this.lockManager.release(Yn)}}removeInternalProperties(e){if("delete"===e.type)return e;const t={...e,properties:{...e.properties}};return delete t.properties.__docId__,delete t.properties.__ts__,t}handleNotifications(){this.socketManager.observeNotifications().pipe(g(e=>"mutations"===e.type),ge(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),E(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),E(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t=e.reduce((e,t)=>this.querySubscriptionManager.hasOngoingQuery(t.clientRequestId)?(e[t.squidDocId]={properties:t.doc,timestamp:t.mutationTimestamp},e):e,{});this.applyIncomingUpdates(t)}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId),n={};for(const i of e.docs){const e=kn(i.__docId__,t.collectionName,t.integrationId);n[e]={properties:i,timestamp:i.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(n,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)})}applyIncomingUpdates(e,t){let n=!1;const i=new Set,s=new Set;for(const[t,r]of Object.entries(e)){const e=this.pendingIncomingUpdates.get(t),o=this.docIdToServerTimestamp.get(t);e&&e.timestamp>r.timestamp?n=!0:o&&o.timestamp>r.timestamp?s.add(t):(this.pendingIncomingUpdates.set(t,r),i.add(t))}return this.runInTransactionSync(()=>{for(const e of i)this.maybeApplyIncomingUpdate(e);for(const e of s)this.refreshQueryMapping(e)},t),n}maybeApplyIncomingUpdate(e){const t=this.pendingIncomingUpdates.get(e);if(!t)return;const n=this.pendingOutgoingMutations.get(e);n&&n.length||(this.updateDocumentFromSnapshot(e,t.properties),this.acknowledgeDocument(e,t.timestamp,!t.properties),this.docIdToLocalTimestamp.set(e,t.timestamp),this.pendingIncomingUpdates.delete(e),this.refreshQueryMapping(e))}refreshQueryMapping(e){const t=this.documentStore.getDocumentOrUndefined(e);this.querySubscriptionManager.setClientRequestIdsForLocalDoc(e,t).forEach(e=>{this.batchClientRequestIds.add(e)}),t&&(this.querySubscriptionManager.findQueriesForDocument(t,e).length||this.forgetDocument(e,!1))}destruct(){this.stopDeleteExpiredTimestampsJob()}stopDeleteExpiredTimestampsJob(){void 0!==this.deleteExpiredTimestampsInterval&&(clearInterval(this.deleteExpiredTimestampsInterval),this.deleteExpiredTimestampsInterval=void 0)}startDeleteExpiredTimestampsJob(){this.deleteExpiredTimestampsInterval=setInterval(()=>{const e=[...this.docIdToServerTimestamp.entries()].filter(([e,t])=>!(!t.expireTimestamp||t.expireTimestamp>Date.now()||this.isTracked(e)));for(const[t]of e)this.docIdToServerTimestamp.delete(t),this.forgetDocument(t,!0)},1e4)}updateDocumentFromSnapshot(e,t){const n=this.documentStore.getDocumentOrUndefined(e);return!(!n&&!t||n===t)&&((!n||!t||on({...t,__ts__:void 0})!==on(n))&&(this.documentStore.saveDocument(e,t),!0))}finishTransaction(e){this.currentTransactionId=void 0;const t=[...this.batchClientRequestIds.values()];this.batchClientRequestIds.clear(),this.querySubscriptionManager.notifyAllSubscriptions(t),this.sendAllUnsentOutgoingMutations(e)}async sendAllUnsentOutgoingMutations(e){const t=this.groupOutgoingMutationsByIntegrationId();try{await Gn.PromisePool.for(t).withConcurrency(t.length||1).useCorrespondingResults().handleError(e=>{throw e}).process(async([e,t])=>{await this.sendMutationsForIntegration([...t],e)}),this.pendingOutgoingMutations.size||this.outgoingMutationsEmpty.next(!0),await this.refreshUpdatedDocuments(),this.hasPendingSentMutations()?(await m(this.pendingOutgoingMutationsChanged.pipe(g(()=>!this.hasPendingSentMutations()))),e?.resolve()):e?.resolve()}catch(t){this.pendingOutgoingMutations.size||(this.outgoingMutationsEmpty.next(!0),await this.resyncFailedUpdates()),e?.reject(t)}}async sendMutationsForIntegration(e,t){try{const{timestamp:n,idResolutionMap:i={},refreshList:s=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(i),s.forEach(e=>{this.refreshDocIdToTimestamp.set(i[e]||e,n)});for(const t of e){let e=this.removeOutgoingMutation(t);i[e]&&(e=i[e]),this.acknowledgeDocument(e,n),this.isTracked(e)||(this.setExpiration(e,!0),this.forgetDocument(e,!1))}}catch(t){for(const t of e){const e=this.removeOutgoingMutation(t);this.forgetDocument(e,!1),(this.hasBeenAcknowledged(e)||"insert"===t.mutation.type)&&this.failedDocsToResync.push(e)}throw t}}removeOutgoingMutation(e){const t=kn(e.mutation.squidDocIdObj),n=be(this.pendingOutgoingMutations.get(t));return n.splice(n.indexOf(e),1),n.length||this.pendingOutgoingMutations.delete(t),this.pendingOutgoingMutationsChanged.next(),t}async resyncFailedUpdates(){const e=[...this.failedDocsToResync];this.failedDocsToResync.splice(0);for(const t of e){const{docId:e}=Mn(t);this.setExpiration(t,!0);try{const n=e.includes(Sn)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(be(n.length<=1,"Got more than one doc for the same id:"+t),!n.length){this.forgetDocument(t,!1);const e=this.querySubscriptionManager.setClientRequestIdsForLocalDoc(t,void 0);this.querySubscriptionManager.notifyAllSubscriptions(e)}}catch(e){this.querySubscriptionManager.errorOutAllQueries(t,e)}}}async refreshUpdatedDocuments(){const e=[];for(const[t,n]of this.refreshDocIdToTimestamp.entries()){const i=this.docIdToServerTimestamp.get(t)?.timestamp;i&&i>n||e.push(t)}this.refreshDocIdToTimestamp.clear(),await Promise.allSettled(e.map(e=>this.queryBuilderFactory.getForDocument(e).snapshot()))}groupOutgoingMutationsByIntegrationId(){const e={};for(const[,t]of[...this.pendingOutgoingMutations.entries()]){const n=t[t.length-1];if(n&&!n.sentToServer){const t=n.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(n),n.sentToServer=!0}}return Object.entries(e)}handleOrphanDocs(){this.querySubscriptionManager.onOrphanDocuments.subscribe(e=>{for(const t of e)this.isTracked(t)||this.forgetDocument(t,!1)})}acknowledgeDocument(e,t,n=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,n)}setExpiration(e,t){const n=this.docIdToServerTimestamp.get(e);n&&(n.expireTimestamp=t?Date.now()+2e4:void 0)}forgetDocument(e,t){this.docIdToLocalTimestamp.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const n=kn(t.mutation.squidDocIdObj),i=e[n];i&&(t.mutation.squidDocIdObj=Mn(i))})}),Object.entries(e).forEach(([e,t])=>{Jt(this.pendingOutgoingMutations,e,t),Jt(this.docIdToLocalTimestamp,e,t),Jt(this.docIdToServerTimestamp,e,t)})}hasPendingSentMutations(){for(const e of this.pendingOutgoingMutations.values())for(const t of e)if(t.sentToServer)return!0;return!1}}const Xn=Symbol("undefined");class ei{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new t(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe(g(Boolean),ge(()=>{}))}onPreDestruct(e){this.preDestructors.push(e)}onDestruct(e){this.destructors.push(e)}async destruct(){this.reportDestructed();const e=this.preDestructors.concat(this.destructors);let t=e.shift();for(;t;){try{await t()}catch(e){console.error("Error while destructing Squid",e)}t=e.shift()}}reportDestructed(){this.isDestructing||this.isDestructedSubject.next(!0)}}class ti{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe(g(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe(g(e=>"lockReleased"===e.type)),this.lockWaitForConnectionThreshold=2e3,t.onPreDestruct(()=>{this.releaseAllLocks()}),this.socketManager.observeConnectionReady().subscribe(e=>{e||this.releaseAllLocks()}),this.releaseLockMessagesFromServer.subscribe(e=>{const t=this.ongoingLocks[e.payload.lockId];t?.release()})}async lock(e,t){"number"==typeof t&&(t={acquisitionTimeoutMillis:t});const n=t?.acquisitionTimeoutMillis??2e3,i=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),me(await m(M(R(this.lockWaitForConnectionThreshold).pipe(ge(()=>!1)),this.socketManager.observeConnectionReady().pipe(g(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const s=we(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:n,maxHoldTimeMillis:i,clientRequestId:s}};this.socketManager.postMessage(r);const o=await m(M(R(n+4e3).pipe(E(1),ge(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:s}}))),this.acquireLockMessagesFromServer.pipe(g(e=>e.payload.clientRequestId===s)))),a=o.payload.lockId;me(!this.destructManager.isDestructing,"Squid client is in destructuring phase"),me(a,()=>`Failed to acquire lock: ${o.payload.error}`);const c=new ni(a,e,s,this.ongoingLocks,this.socketManager);return this.ongoingLocks[a]=c,c}releaseAllLocks(){for(const[e,t]of Object.entries(this.ongoingLocks))t.release(),delete this.ongoingLocks[e]}}class ni{constructor(e,t,n,i,s){this.lockId=e,this.resourceId=t,this.clientRequestId=n,this.ongoingLocks=i,this.socketManager=s,this.released=!1,this.onReleaseSubject=new r}async release(){if(this.released)return;this.released=!0,delete this.ongoingLocks[this.lockId];const e={type:"releaseLock",payload:{lockId:this.lockId,clientRequestId:this.clientRequestId}};try{await this.socketManager.sendMessage(e)}finally{this.onReleaseSubject.next(),this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}class ii{constructor(e,n){this.documentStore=e,this.destructManager=n,this.changeNotifier=new t({}),this.destructManager.onDestruct(()=>{this.changeNotifier.complete()})}migrate(e){Object.entries(e).forEach(([e,t])=>{this.documentStore.migrateDocId(e,t)}),this.changeNotifier.next(e)}observeChanges(){return this.changeNotifier.asObservable()}}class si{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t){let n=this.documents.get(e);if(n)return n;n=new En(e,be(this.dataManager,"dataManager not found"),t);const{integrationId:i,collectionName:s}=Mn(e);this.documents.set(e,n);const r=this.getCollectionKey(i,s),o=this.documentsForCollection.get(r)||[];return this.documentsForCollection.set(r,o.concat(n)),n}setDataManager(e){this.dataManager=e}getDocumentsForCollection(e,t){const n=this.getCollectionKey(e,t);return(this.documentsForCollection.get(n)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const n=Mn(e),i=Mn(t);Jt(this.documents,n.docId,i.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class ri{constructor(){this.squidDocIdToDoc=new Map}saveDocument(e,t){const n=this.squidDocIdToDoc.get(e);if(void 0===n&&!t)return;if(void 0!==n){if(t){const n=en(t),i=this.removeInternalProperties(n);return this.squidDocIdToDoc.set(e,i),i}return void this.squidDocIdToDoc.delete(e)}const i=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,i),t}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocument(e){return be(this.getDocumentOrUndefined(e))}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}group(e,t){return Object.values(sn(e,e=>on(t.map(t=>Wt(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const n=[...e].map(e=>this.squidDocIdToDoc.get(e)).filter(fe),{sortOrder:i,limitBy:s}=t,r=n.sort((e,t)=>this.compareSquidDocs(e,t,i)),o=t.limit<0?2e3:t.limit;if(!s)return r.slice(0,o);const{limit:a,fields:c,reverseSort:u}=s,l=this.group(r,c);let h;return h=u?l.map(e=>e.slice(-a)):l.map(e=>e.slice(0,a)),h.flat().slice(0,o)}migrateDocId(e,t){const n=this.getDocumentOrUndefined(e);if(!n)return;Jt(this.squidDocIdToDoc,e,t);const i=Mn(t),s=cn(i.docId);this.saveDocument(t,{...n,...s,__docId__:i.docId})}compareSquidDocs(e,t,n){for(const{fieldName:i,asc:s}of n){const n=nn(Wt(e,i),Wt(t,i));if(0!==n)return s?n:-n}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class oi{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const n={authCode:e,externalAuthConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/saveAuthCode",n)}async getAccessToken(e){const t={externalAuthConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/getAccessToken",t)}}class ai{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const n={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",n,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const n={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",n)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class ci{constructor(e,t,n){this.socketManager=e,this.rpcManager=t,this.clientIdService=n,this.isListening=!1,this.listeners={},this.clientIdService.observeClientId().pipe(p(),T(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))bn.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e})})}async getJob(e){return(await this.rpcManager.post("job/getJob",{jobId:e})).job}async awaitJob(e){this.maybeListenToJobs(),await this.socketManager.awaitConnectionReady();const t=this.listeners[e]||new s(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}),m(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe(g(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,n=t.id,i=this.listeners[n];i&&("completed"===t.status?i.next(t.result):"failed"===t.status?i.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",n),delete this.listeners[n])}))}}class ui{constructor(e,t,n){this.rpcManager=e,this.lockManager=t,this.querySender=n}async sendMutations(e,t){const n=Jn(e),i=n.map(e=>`sendMutation_${kn(e.squidDocIdObj)}`);await this.lockManager.lock(...i),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:n,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw bn.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(n,null,2)}),e}finally{this.lockManager.release(...i)}}}class li{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class hi{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.observeNotifications().pipe(g(e=>"userNotification"===e.type),v(e=>e.payload))}async publishNotification(e,t){return await this.rpcManager.post("/notification/publishNotification",{clientIds:t,payload:e})}async publishSystemNotification(e,t){return await this.rpcManager.post("/notification/publishSystemNotification",{clientIds:t,payload:e})}}const di={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class pi{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},n=Object.keys(t).filter(e=>!gi.test(e)||e.length>=fi);me(0===n.length,()=>`Tag name is not allowed: ${n.join(",")}`),this.isReporting=!0;const i={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},s=this.rpcManager.post("/observability/metrics",{metrics:[i]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==s),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(s)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...di,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const n=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:n,noDataBehavior:i}=e,s=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:n,pointIntervalAlignment:i}){if("align-by-start-time"===i)return e;const s=t-e;let r=t-Math.floor(s/n)*n;return r>e&&(r-=n),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:n,pointIntervalAlignment:i}){if("align-by-end-time"===i)return t-n;const s=t-e;let r=e+Math.floor(s/n)*n;return r>=t&&(r-=n),r}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const n=[];for(let t=0;t<e.groupByTags.length;t++){const i=e.groupByTags[t],s=a[i]?.[0]||"";n.push(s)}t.push({tagValues:n,points:[]})}else"return-result-group-with-default-values"===i&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[n,i]of Object.entries(a)){const s=e.groupByTags.indexOf(n);if(!(s<0))for(let e=0;e<t.length;e++){const n=t[e],r=new Set(i);for(let e=0;e<t.length;e++){const i=t[e];n.tagValues.every((e,t)=>t===s||e===i.tagValues[t])&&r.delete(i.tagValues[s])}if(0!==r.size)for(const e of r){const i={tagValues:[...n.tagValues],points:[]};i.tagValues[s]=e,t.push(i)}}}for(const i of t){if(0!==i.points.length){const e=i.points[0][0],t=i.points[i.points.length-1][0];me(e>=r,()=>`Invalid first point time: ${e}`),me(t<=o,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:s,u=Array.isArray(e.fn)?e.fn.map(c):[s];for(let e=r;e<=o;e+=n){const n=i.points[a];n?n[0]===e?(t.push(n),a++):(me(n[0]>e,()=>`Result point has invalid time: ${n[0]}`),t.push([e,...u])):t.push([e,...u])}i.points=t}}(t,n.resultGroups),n}}const gi=/^[a-zA-Z0-9_-]+$/,fi=1e3;async function yi(e,t,n=500){const i=Date.now(),s=e.paginate({pageSize:n,subscribe:!1});let r=0,o=await s.waitForData();for(;;){for(const e of o.data)r++,await t(e.data);if(!o.hasNext)break;o=await s.next()}return{count:r,time:Date.now()-i}}function mi(e,t){switch(t.type){case"simple":return function(e,t){const{query:n,dereference:i}=t,{collectionName:s,integrationId:r}=n;let o=e.collection(s,r).query();return o=bi(o,n),i?o.dereference():o}(e,t);case"join":return function(e,t){const{root:n,joins:i,joinConditions:s,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=n.query;let u=e.collection(a,c).joinQuery(n.alias);return u=bi(u,n.query),Object.entries(i).map(([t,n])=>{const{collectionName:i,integrationId:r}=n,{left:o,right:a,leftAlias:c}=s[t];let l=e.collection(i,r).query();l=bi(l,n),u=u.join(l,t,{left:o,right:a},{leftAlias:c})}),r&&o?u.grouped().dereference():r?u.dereference():o?u.grouped():u}(e,t);case"merged":return function(e,t){const{queries:n}=t,{collectionName:i,integrationId:s}=Ii(n[0]),r=n.map(t=>mi(e,t));return e.collection(i,s).or(...r)}(e,t)}}function bi(e,t){const{conditions:n,limit:i,sortOrder:s}=t;for(const t of n){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:n,operator:i,value:s}=t;e.where(n,i,s)}e.limit(i);for(const{fieldName:t,asc:n}of s)e.sortBy(t,n);return e}function Ii(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:n}=e.query;return{collectionName:t,integrationId:n}}case"join":{const{collectionName:t,integrationId:n}=e.root.query;return{collectionName:t,integrationId:n}}case"merged":return Ii(e.queries[0])}}const vi={"in:in":(e,t)=>e.every(e=>t.includes(e)),"in:not in":(e,t)=>e.every(e=>!t.includes(e)),"not in:not in":(e,t)=>t.every(t=>e.includes(t)),">:not in":(e,t)=>t.every(t=>e>=t),">=:not in":(e,t)=>t.every(t=>e>t),"<:not in":(e,t)=>t.every(t=>e<=t),"<=:not in":(e,t)=>t.every(t=>e<t),">:>":(e,t)=>e>=t,">=:>":(e,t)=>e>t,"in:>":(e,t)=>e.every(e=>e>t),">:>=":(e,t)=>e>=t,">=:>=":(e,t)=>e>=t,"in:>=":(e,t)=>e.every(e=>e>=t),"<:<":(e,t)=>e<=t,"<=:<":(e,t)=>e<t,"in:<":(e,t)=>e.every(e=>e<t),"<:<=":(e,t)=>e<=t,"<=:<=":(e,t)=>e<=t,"in:<=":(e,t)=>e.every(e=>e<=t),"like:like":(e,t)=>wi(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>wi(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>wi(e,t)&&Mi(t),"like_cs:like_cs":(e,t)=>wi(e,t),"like:not like":(e,t)=>!Si(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!Si(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!Si(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!Si(e,t),"not like:like":(e,t)=>Ti(e,t),"not like_cs:like":(e,t)=>Ti(e,t),"not like:like_cs":(e,t)=>Ti(e,t),"not like_cs:like_cs":(e,t)=>Ti(e,t),"not like:not like":(e,t)=>wi(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>wi(t,e)&&Mi(e),"not like:not like_cs":(e,t)=>wi(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>wi(t,e),"in:like":(e,t)=>e.every(e=>Tn(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Tn(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>Tn(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>Tn(t,e,"not like_cs")),"like:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&!!t.find(t=>t.toLowerCase()===e.toLowerCase()),"like_cs:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&t.includes(e),"not like:in":(e,t)=>e.length>0&&ki(e)||Ci(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&ki(e)||Ci(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&ki(t)||Ci(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&ki(t)||Ci(t)&&e.includes(""),"not in:not like":(e,t)=>!t.includes("%")&&!t.includes("_")&&!!e.find(e=>e.toLowerCase()===t.toLowerCase()),"not in:not like_cs":(e,t)=>!t.includes("%")&&!t.includes("_")&&e.includes(t),"like:not in":(e,t)=>t.every(t=>Tn(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Tn(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Tn(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Tn(e,t,"like_cs")),"array_includes_some:array_includes_some":(e,t)=>e.every(e=>t.includes(e)),"array_includes_all:array_includes_all":(e,t)=>e.every(e=>t.includes(e)),"array_not_includes:array_not_includes":(e,t)=>t.every(t=>e.includes(t)),"array_includes_some:array_not_includes":(e,t)=>e.every(e=>!t.includes(e)),"array_not_includes:array_includes_some":(e,t)=>t.every(t=>!e.includes(t)),"array_includes_all:array_includes_some":(e,t)=>e.every(e=>t.includes(e)),"array_includes_some:array_includes_all":(e,t)=>e.every(e=>t.includes(e)),"array_not_includes:array_includes_all":(e,t)=>t.every(t=>!e.includes(t)),"array_includes_all:array_not_includes":(e,t)=>e.every(e=>!t.includes(e))};function wi(e,t,n=0,i=0){if(i>=t.length)return n>=e.length;if(n>=e.length)return ki(t.substring(i));const s=e[n],r=t[i];return"%"===s&&"%"===r?wi(e,t,n+1,i+1)||wi(e,t,n+1,i):"%"!==s&&("%"===r?wi(e,t,n,i+1)||wi(e,t,n+1,i):(s===r||"_"===r)&&wi(e,t,n+1,i+1))}function Si(e,t,n=0,i=0){if(n>=e.length&&i>=t.length)return!0;if(n>=e.length)return ki(t.substring(i));if(i>=t.length)return ki(e.substring(n));const s=n<e.length?e[n]:"",r=i<t.length?t[i]:"";return"%"===s&&"%"===r?Si(e,t,n+1,i+1)||Si(e,t,n,i+1)||Si(e,t,n+1,i):"%"===s||"%"===r?Si(e,t,n,i+1)||Si(e,t,n+1,i):(s===r||"_"===s||"_"===r)&&Si(e,t,n+1,i+1)}function Mi(e){return!/[a-zA-Z]/.test(e)}function ki(e){return e.split("").every(e=>"%"===e)}function Ti(e,t){return e.length>0&&ki(e)||t.length>0&&ki(t)||Ci(e)&&0===t.length}function Ci(e){let t=!1,n=!1;for(const i of e)switch(i){case"%":t=!0;break;case"_":if(n)return!1;n=!0;break;default:return!1}return t&&n}class Oi{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(_n))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){return!e.find((e,t)=>!Zt(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,n){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:n})}isSubqueryOfCondition(e){return!!this.parsedConditions.filter(t=>t.fieldName===e.fieldName).find(t=>this.evaluateSubset(t,e))}isSubqueryOfConditions(e){return this.parseConditions(e).every(e=>this.isSubqueryOfCondition(e))}isSubqueryOfQuery(e){if(e.collectionName!==this.collectionName||e.integrationId!==this.integrationId)return!1;const t=e.conditions.filter(_n),n=this.isSubqueryOfConditions(t),i=this.sortedBy(e.sortOrder),s=-1===e.limit||this.limit>-1&&this.limit<e.limit;return n&&i&&s}getConditionsFor(...e){return this.parsedConditions.filter(t=>e.includes(t.fieldName))}getConditionsForField(e){return this.parsedConditions.filter(t=>t.fieldName===e)}documentMatchesQuery(e){for(const t of this.parsedConditions){const n=t.fieldName,i=t.operator,s=Wt(e,n);if("in"===i){if(t.value.includes(s))continue;return!1}if("not in"!==i){if(!Tn(t.value,s,i))return!1}else if(t.value.includes(s))return!1}return!0}evaluateSubset(e,t){const{operator:n,value:i}=e,{operator:s,value:r}=this.parseConditions([t])[0],o=vi[`${n}:${s}`];return!!o&&o(i,r)}parseConditions(e){const t=[],n=new Map,i=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":i.set(e.fieldName,(i.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),n.forEach((e,n)=>{t.push({fieldName:n,operator:"in",value:e})}),i.forEach((e,n)=>{t.push({fieldName:n,operator:"not in",value:e})}),t}}class _i{constructor(e,t,n){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=n}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:n}=e,i=new Oi(e),s=this.documentReferenceFactory.getDocumentsForCollection(t,n).filter(e=>i.documentMatchesQuery(e.data)),r={};return s.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[kn(e.__docId__,n,t)])}}function Ei(e,t){return H(function(n,i){var s=0;n.subscribe(de(i,function(n){return e.call(t,n,s++)&&i.next(n)}))})}class qi{constructor(e,n){this.rpcManager=e,this.destructManager=n,this.safeToSendQueriesToServer=new t(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new t(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new r,n=m(t);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:t}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),n):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.safeToSendQueriesToServer.pipe(Ei(Boolean),E(1)).subscribe(()=>{this.processQueryBatch()})},0),n)}async waitForAllQueriesToFinish(){return m(this.inflightQueriesCount.pipe(Ei(e=>0===e))).then(()=>{})}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=Array.from(e.map(({queryRequest:e})=>e).reduce((e,t)=>(e.set(t.clientRequestId,t),e),new Map).values()),n=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const n=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:i}of e){const e=t.clientRequestId,s=n.errors[e],r=n.results[e];s?i.error(s):i.next(r)}}catch(e){n.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Di={d:(e,t)=>{for(var n in t)Di.o(t,n)&&!Di.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function Ai(e,t,...n){e||function(e,...t){const n=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof n)throw n;throw(e=>new Error(e))(n||"Assertion error",...t)}(t,...n)}function Ri(e,t){switch(t.type){case"set":return function(e,t,n){if(void 0===n)return Ni(e,t);if(0===t.length)return Ai("object"==typeof n&&null!==n&&!Array.isArray(n),()=>`Root state must be a record. Trying to set '${n}', type: ${typeof n}`),n;function i(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let s=e;for(let e=0;e<t.length-1&&void 0!==s;e++){const n=t[e];Ai(!Array.isArray(s)||i(n),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${n}'`),s=s[n],Ai(void 0===s||"object"==typeof s&&null!==s,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===s?"<null>":typeof s}'`)}const r=t[t.length-1];return Ai(!Array.isArray(s)||i(r),()=>`Invalid array index Path: '${t}`),(null==s?void 0:s[r])===n?e:xi(e,t,n)}(e,t.path,t.value);case"delete":return Ni(e,t.path);case"batch":return t.actions.reduce((e,t)=>Ri(e,t),e)}}function Ni(e,t){Ai(0!==t.length,"Can't delete an empty path");let n=e;for(let i=0;i<t.length-1;i++){const s=t[i];if(n=n[s],void 0===n)return e;Ai("object"==typeof n&&null!==n,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,i+1)}', type: ${null===n?"<null>":typeof n}`)}const i=t[t.length-1];return void 0===n[i]?e:xi(e,t,void 0)}function xi(e,t,n){function i(e,n){Ai(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[n]}const s=Object.assign({},e);let r=s;for(let e=0;e<t.length-1;e++){const s=t[e],o=r[s];Ai(void 0===o||"object"==typeof o&&null!==o,()=>`Internal error: sub-path has an invalid type and can't be patched: '${t.slice(0,e+1)}', type: '${null===o?null:typeof o}'`);const a=void 0===o?void 0===n?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return i(r,s),r;r[s]=a,r=a}const o=t[t.length-1];return void 0===n?i(r,o):r[o]=n,s}function Fi(e,t){const n=[];if("set"===e.type||"delete"===e.type)n.push(e.path);else if("batch"===e.type)for(const t of e.actions)n.push(...Fi(t,"as-is"));return"unique-and-sorted"===t?Bi(n):n}function ji(e,t){if(e.length<t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function Pi(e){const t=[...e];return t.sort((e,t)=>{for(let n=0;n<e.length;n++){if(n===t.length)return 1;const i=e[n].localeCompare(t[n]);if(0!==i)return i}return e.length-t.length}),t}function Bi(e){const t=Pi(e),n=t;for(let e=0;e<t.length-1;e++){const i=t[e];for(let s=e+1;s<t.length;s++){const r=t[s];i.length===r.length&&ji(i,r)&&(n[s]=void 0,e++)}}return n.filter(e=>void 0!==e)}const Qi=(Li={Observable:()=>i,Subject:()=>r},Ui={},Di.d(Ui,Li),Ui);var Li,Ui;const $i=(Gi={filter:()=>Ei,map:()=>ge},Hi={},Di.d(Hi,Gi),Hi);var Gi,Hi,Wi;class Vi{constructor(){this.root={children:new Map,childrenWithValue:0}}get(e){var t;return null===(t=this.getNode(e))||void 0===t?void 0:t.value}getOrSet(e,t){const n=this._buildPath(e);if(void 0!==n.value)return n.value;const i=t(e);return this._setNodeValue(n,i,void 0===i),i}set(e,t){const n=void 0===t?this._findNode(e):this._buildPath(e);n&&this._setNodeValue(n,t,!0)}delete(e){const t=this._findNode(e);if(void 0===t)return;if(void 0===t.parent){if(t!==this.root)throw new Error("Only root node can have no parent.");return this.root.value=void 0,this.root.children.clear(),void(this.root.childrenWithValue=0)}const n=(void 0===t.value?0:1)+t.childrenWithValue;n>0&&this._updateChildrenWithValue(t,-n),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const n=this.getNode(e);return void 0===n?0:n.childrenWithValue+("node-and-children"===t&&void 0!==n.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const n=[];let i=this.root,s=t(i.value,n);if(s!==Vi.StopFillToken){this._setNodeValue(i,s,!1);for(let r=0;r<e.length;r++){const o=e[r];n.push(o);let a=i.children.get(o);if(s=t(null==a?void 0:a.value,n),s===Vi.StopFillToken)break;a||(a={children:new Map,parent:i,childrenWithValue:0},i.children.set(o,a)),this._setNodeValue(a,s,!1),i=a}this._runGc(i)}}visitDfs(e,t,n=[]){const i=this.getNode(n);void 0!==i&&this._visitDfs(e,i,t,[...n])}_visitDfs(e,t,n,i){if("pre-order"===e&&!1===n(t.value,i))return!1;for(const[s,r]of t.children){if(i.push(s),!this._visitDfs(e,r,n,i))return!1;i.pop()}return"in-order"!==e||!1!==n(t.value,i)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const n of e)if(t=t.children.get(n),!t)return;return t}_findNode(e){let t=this.root;for(let n=0;n<e.length&&t;n++)t=t.children.get(e[n]);return t}_buildPath(e){let t=this.root;for(let n=0;n<e.length;n++){const i=e[n];let s=t.children.get(i);s||(s={children:new Map,parent:t,childrenWithValue:0},t.children.set(i,s)),t=s}return t}_setNodeValue(e,t,n){if(e.value!==t){const n=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,n)}n&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let n=e.parent;n;n=n.parent)if(n.childrenWithValue+=t,n.childrenWithValue<0)throw new Error("Internal error: negative counter value!")}_runGc(e){void 0===e.value&&(0===e.childrenWithValue&&e.children.clear(),e.parent&&this._runGc(e.parent))}}Vi.StopFillToken=Symbol("Trie.StopFillToken");class Ki extends Qi.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class zi{constructor(e){this.rootState=e,this.observersTrie=new Vi,this.batchDepth=0,this.appliedBatchActions=[],this.rootStateBeforeBatchStart=this.rootState,this.stubForUnusedPaths=[]}get state(){return this.rootState}get state$(){return this.observe([])}get(e){return this._get(this.rootState,e)}observe(e,t=[]){return this._observeChanges(e,t,"new-value-only").pipe((0,$i.map)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,n){(null==n?void 0:n(this.get(e),t,e))||this._apply({type:"set",path:e,value:t})}delete(e){this._apply({type:"delete",path:e})}reset(e){this.observersTrie.visitDfs("pre-order",e=>null==e?void 0:e.complete()),this.observersTrie.delete([]),this.rootState=e}runInBatch(e){this.batchDepth++;try{e()}finally{if(this.batchDepth--,0===this.batchDepth&&this.appliedBatchActions.length>0){const e={type:"batch",actions:this.appliedBatchActions};this.appliedBatchActions=[],this._notify(e)}}}_apply(e){0===this.batchDepth&&(this.rootStateBeforeBatchStart=this.rootState),this.rootState=Ri(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Fi(e,"unique-and-sorted"),n=this.selectChildPathsWithObservers(t),i=Bi([...t,...n]),s=new Vi;for(const e of i)s.fillPath(e,()=>!0);s.visitDfs("pre-order",(t,n)=>{const i=this.observersTrie.get(n);if(i){const t=this.get(n),s=i.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,n):void 0;i.next({action:e,value:t,oldValue:s})}})}_observeChanges(e,t=[],n){const i=0===t.length?void 0:new Vi;for(const e of t)null==i||i.set(e,!0);return new Qi.Observable(t=>{const s=this.observersTrie.getOrSet(e,()=>new Ki);s.isAllDetailsMode=s.isAllDetailsMode||"all-details"===n;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=s.pipe((0,$i.filter)(({action:e})=>void 0===i||Fi(e,"as-is").some(e=>!i.get(e))),(0,$i.map)(({action:t,value:n,oldValue:i})=>{let r=this.stubForUnusedPaths;if(s.isAllDetailsMode){const n=Fi(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=Pi(e),n=t;for(let e=0;e<n.length-1;e++){const i=t[e];for(let s=e+1;s<t.length;s++)ji(t[s],i)&&(n[s]=void 0,e++)}return n.filter(e=>void 0!==e)}(e.length>0?n.filter(t=>ji(t,e)).map(t=>t.slice(e.length)):n)}return{value:n,oldValue:i,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),s.observed||this.observersTrie.delete(e)}})}_get(e,t){let n=e;for(let e=0;e<t.length&&void 0!==n;e++){const i=t[e];n=null==n?void 0:n[i]}return n}selectChildPathsWithObservers(e){const t=[];for(const n of e)this.observersTrie.count(n,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,n)=>{e&&t.push([...n])},n);return t}}function Ji(e,t,n=(e,t)=>e>t?1:e<t?-1:0,i=0,s=e.length-1){if(s<i)return-1;const r=Math.trunc((i+s)/2);return 0===n(t,e[r])?r:n(t,e[r])>0?Ji(e,t,n,r+1,s):Ji(e,t,n,i,r-1)}function Yi(e,t,n=(e,t)=>e>t?1:e<t?-1:0){if(-1!==Ji(e,t,n))return;let i;for(i=e.length-1;i>=0&&n(e[i],t)>0;i--)e[i+1]=e[i];e[i+1]=t}function Zi(e,t,n=(e,t)=>e>t?1:e<t?-1:0){const i=Ji(e,t,n);i>-1&&e.splice(i,1)}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Wi||(Wi={}));const Xi=100;class es{constructor(e,t,n,i,s,o,a){this.rpcManager=e,this.clientIdService=t,this.documentStore=n,this.destructManager=i,this.documentIdentityService=s,this.querySender=o,this.socketManager=a,this.onOrphanDocuments=new r,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new ns,this.queryResultsSubject=new r,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe(()=>{this.refreshOngoingQueries()}),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}dumpSubscriptionInfo(){console.log("Ongoing queries:",this.ongoingQueries),console.log("ClientRequestId to local documents:",this.clientRequestIdToLocalDocuments),console.log("Local documents to clientRequestId:",this.localDocumentToClientRequestIds)}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return be(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);t?.gotInitialResponse&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:n,integrationId:i}=Mn(t),s=this.queryMappingManager.getMapping(n,i);return s?function(e,t){const n=[...e.unconditional||[]],i=new Map;for(const[n,s]of Object.entries(e.conditional||{})){const e=cn(n);let r;if(_n(e)){const n=Wt(t,e.fieldName)??null;r=Tn(e.value,n,e.operator)}else r=ts(e,t);if(r)for(const e of s)i.set(e,(i.get(e)||0)+1)}for(const[t,s]of i.entries())s>=e.queriesMetadata[t].condCount&&n.push(t);return n}(s,e):[]}setClientRequestIdsForLocalDoc(e,t){const n=this.localDocumentToClientRequestIds.get(e)||new Set,i=new Set(t?this.findQueriesForDocument(t,e).map(e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId):[]),s=new Set([...n,...i]);for(const t of[...n]){if(i.has(t))continue;n.delete(t);const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),n.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of i){let n=this.localDocumentToClientRequestIds.get(e);n||(n=new Set,this.localDocumentToClientRequestIds.set(e,n)),n.add(t);let i=this.clientRequestIdToLocalDocuments.get(t);i||(i=new Set,this.clientRequestIdToLocalDocuments.set(t,i)),i.add(e)}return[...s]}errorOutAllQueries(e,t){const n=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of n){const n=this.ongoingQueries.get(e);n&&(this.destructManager.isDestructing?n.dataSubject.complete():n.dataSubject.error(t),n.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const n of e){const e=this.ongoingQueries.get(n);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const i=this.clientRequestIdToLocalDocuments.get(n)||new Set,s=this.documentStore.sortAndLimitDocs(i,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(s,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=be(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case Wi.UNKNOWN:e.limitUnderflowState=i.size===e.query.limit+100?Wi.ENABLED:Wi.DISABLED;break;case Wi.DISABLED:break;case Wi.ENABLED:if(i.size<e.query.limit+20){e.limitUnderflowState=Wi.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(s)}for(const e of t){const t=this.collectAllObservables(e);be(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new Oi(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,n,i,r,a){return r&&this.socketManager.notifyWebSocketIsNeeded(),h(()=>{const c=this.createOngoingQueryGraph(e,t,n,i,r,!0);a&&(c.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(c),c.allObservables=new s(1);const u=c.allObservables.pipe(_(e=>o(e).pipe(ge(e=>this.joinResults(e,i,c)))),Ei(()=>this.allOngoingQueriesGotInitialResult(c)),C(void 0),S(),Ei(([e,t])=>!Zt(e,t)),ge(([,e])=>e),r?A():E(1),f(()=>{c.dataSubject.complete(),c.done=!0,this.completeAllSupportedQueries(c),c.allObservables?.complete()})),l=this.collectAllObservables(c);return c.allObservables.next(l),u}).pipe(k())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}unsubscribe(){const e=[...this.ongoingQueries.values()];for(const t of e)t.dataSubject.complete(),t.allObservables?.complete()}hasSubscription(e){return!!this.ongoingQueries.get(e)?.subscribe}isValidParent(e){if(!e.activated||e.isInFlight||e.isEmptyForJoin||e.done||!e.subscribe||!e.gotInitialResponse||!e.dataSubject.value)return!1;const t=-1===e.query.limit?1e3:e.query.limit;return e.dataSubject.value.length<t}findValidParentOfOngoingQuery(e){if(e.forceFetchFromServer)return;const t=new Oi(e.query);for(const n of this.ongoingQueries.values()){if(e===n)return;if(this.isValidParent(n)&&t.isSubqueryOfQuery(n.query))return n}}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const n=[];for(const i of t){const t=be(this.localDocumentToClientRequestIds.get(i));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(i),n.push(i))}n.length&&this.onOrphanDocuments.next(n)}registerQueryFinalizer(e){const t=e.clientRequestId,n=On(this.clientIdService.getClientId(),t);e.dataSubject.pipe(f(async()=>{if(e.unsubscribeBlockerCount.value>0&&await m(M(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Ei(e=>0===e)))),this.queryMappingManager.removeQuery(n),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const n={clientRequestId:t};this.rpcManager.post("query/unsubscribe",n).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)}),Ei(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,n,i,s,r,o,a={}){if(a[n])return a[n];const c=this.clientIdService.generateClientRequestId(),u=[],l={clientRequestId:c,activated:o,alias:n,query:e,subscribe:r,dataSubject:new t(null),supportedQueries:u,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new t(0),queryRegistered:new t(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:r?Wi.UNKNOWN:Wi.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(c,l),a[n]=l;for(const[e,t]of Object.entries(s)){const o=t.leftAlias;if(o!==n&&e!==n)continue;const c=o===n?e:o;if(o===n){const e=this.createOngoingQueryGraph(i[c],c,i,s,r,!1,a);e.joinCondition=t,u.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(i[c],c,i,s,r,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const n=e.alias;t.push(e.dataSubject.pipe(Ei(Boolean),ge(e=>({docs:e,alias:n}))));for(const n of e.supportedQueries)this.collectAllObservables(n,t);return t}joinResults(e,t,n){const i=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let s=i[n.alias].map(e=>({[n.alias]:e}));const r=this.getOngoingQueriesBfs(n),o=new Set;for(let e=1;e<r.length;e++){const n=r[e].alias;o.has(n)||(o.add(n),s=this.join(s,n,i[n],t[n]))}return s}join(e,t,n,i){if(!e.length)return e;const s=Object.keys(e[0]);if(!i||!s.includes(i.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(n||[]).forEach(e=>{const t=this.transformKey(e[i.right]);r.has(t)||r.set(t,[]),be(r.get(t)).push(e)}),e.flatMap(e=>{const n=r.get(this.transformKey(e[i.leftAlias]?.[i.left]))||[];return n.length?n.map(n=>({...e,[t]:n})):i.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],n=[e];for(;n.length;){const e=be(n.shift());e.isEmptyForJoin||(t.push(e),n.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,n){const i=be(n.joinCondition),s=n.query;if(n.activated){if(!n.canExpandForJoin)return!1;const r=be(n.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===n.alias),o=new Set(e.map(e=>e[i.left]??null));for(const e of r)e.query.conditions.filter(_n).filter(e=>e.fieldName===i.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const a=en(s);a.conditions=a.conditions.filter(e=>!_n(e)||e.fieldName!==i.right),[...o].forEach(e=>{a.conditions.push({fieldName:i.right,operator:"==",value:e})});const c={...n,query:a,activated:!0,gotInitialResponse:!1,dataSubject:new t(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),be(n.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(n.activated=!0,s.conditions.filter(_n).filter(e=>e.fieldName===i.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(n),n.canExpandForJoin=!1,!0;const t=e.map(e=>e[i.left]??null).map(e=>({fieldName:i.right,operator:"==",value:e}));return t.length?(s.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(n)):n.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every(e=>this.allOngoingQueriesGotInitialResult(e)))}async completeAllSupportedQueries(e){const t=[...e.supportedQueries||[]];for(;t.length;){const e=be(t.shift());t.push(...e.supportedQueries||[]),await m(e.unsubscribeBlockerCount.pipe(Ei(e=>0===e))),e.dataSubject.complete()}}transformKey(e){return e instanceof Date?`DATE AS string KEY: ${e.toISOString()}`:e}preDestruct(){this.unsubscribe()}sendQueryToServerOrUseParentQuery(e,t=!1){if(this.destructManager.isDestructing)return;const n=e.query,i=e.clientRequestId,s=On(this.clientIdService.getClientId(),i);this.queryMappingManager.addQuery(n,s),this.ongoingQueries.set(i,e);const r=t?void 0:this.findValidParentOfOngoingQuery(e);r?this.useParentOngoingQuery(e,r):this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const n={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},i=new Oi(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await m(t.queryRegistered.pipe(Ei(Boolean)))}catch(t){return this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(e.dataSubject.error(t),e.queryRegistered.error(t)),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",n).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(n=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,n),e.dataSubject.error(n)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const s=M(e.queryRegistered.pipe(Ei(Boolean),d(2e3),E(1)),this.destructManager.observeIsDestructing().pipe(E(1)));t.dataSubject.pipe(D(()=>!e.done),q(s),Ei(Boolean),A(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),ge(e=>e.filter(e=>i.documentMatchesQuery(e)))).subscribe({next:t=>{for(const n of t)this.setClientRequestIdsForLocalDoc(kn(n.__docId__,e.query.collectionName,e.query.integrationId),n);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,n=t>0&&e.subscribe?t+100:t,i={query:{...e.query,limit:n},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(i).then(t=>{e.isInFlight=!1,e.queryRegistered.next(!0),this.queryResultsSubject.next(t)}).catch(t=>{e.isInFlight=!1,this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(bn.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0})}refreshOngoingQueries(){for(const e of this.ongoingQueries.values())this.sendQueryToServerOrUseParentQuery(e,!0)}migrateDocIds(e){const t=Object.keys(e);for(const n of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{n.has(t)&&(n.delete(t),n.add(e[t]))});t.forEach(t=>{Jt(this.localDocumentToClientRequestIds,t,e[t])})}}function ts(e,t){for(const n of e.fields){const e=Wt(t,n.fieldName)??null;if(Tn(n.value,e,n.operator))return!0;if(Tn(n.value,e,"!="))return!1}return!1}class ns{constructor(){this.stateService=new zi({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let n=0;const i=new Set;for(const s of e.conditions){if(_n(s)&&["=="].includes(s.operator)){const e=un(s.fieldName);i.has(e)||(n++,i.add(e))}else n++;const r=this.getConditionStatePath(e,s),o=[...this.stateService.get(r)||[]];Yi(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const n=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],i=[...this.stateService.get(n)||[]];Yi(i,t),this.stateService.set(n,i)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],n)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const n of t.conditions){const i=this.getConditionStatePath(t,n),s=[...this.stateService.get(i)||[]];Zi(s,e),s.length?this.stateService.set(i,s):this.stateService.delete(i)}if(!t.conditions.length){const n=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],i=[...this.stateService.get(n)||[]];Zi(i,e),this.stateService.set(n,i)}this.stateService.delete(this.getQueryMetadataStatePath(t,e))}),t}getMapping(e,t){return this.stateService.get(["queryMapping",e,t,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",(n=t,on(n))];var n}}class is{constructor(){this.locks={}}async lock(...e){if(this.canGetLock(...e))return void this.lockSync(...e);const t=Object.entries(this.locks).filter(([t])=>e.includes(t)).map(([,e])=>e);await I(o(t).pipe(g(e=>!e.includes(!0)),E(1))),await this.lock(...e)}release(...e){for(const t of e){const e=be(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){me(this.canGetLock(...e),"Cannot acquire lock sync");for(const n of e)this.locks[n]=new t(!0)}}class ss{constructor(e,t,n){this.rpcManager=e,this.socketManager=t,this.queueManagers=new Map,this.socketManager.observeNotifications().subscribe(e=>{const t=this.getOrUndefined(e.integrationId,e.topicName);t&&t.onMessages(e.payload)}),n.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let n=this.queueManagers.get(e);n||(n=new Map,this.queueManagers.set(e,n));let i=n.get(t);return i||(i=new os(e,t,this.rpcManager,this.socketManager),n.set(t,i)),i}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const rs="subscriptionMutex";class os{constructor(e,t,n,i){this.integrationId=e,this.topicName=t,this.rpcManager=n,this.socketManager=i,this.messagesSubject=new r,this.subscriberCount=0,this.lockManager=new is}async produce(e){await this.lockManager.lock(rs);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(rs)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),h(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe(f(()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}async performSubscribe(){await this.lockManager.lock(rs);try{await this.rpcManager.post("queue/subscribe",{integrationId:this.integrationId,topicName:this.topicName})}catch(e){this.messagesSubject.error(e),this.messagesSubject.complete(),this.subscriberCount=0,this.messagesSubject=new r}finally{this.lockManager.release(rs)}}async performUnsubscribe(){await this.lockManager.lock(rs);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(rs)}}}class as{constructor(e,t){this.capacity=e,this.seconds=t,this.tokens=e,this.refillRatePerMs=e/(1e3*t),this.lastRefillTimestamp=Date.now()}async consume(){this.attemptConsume()||await m(b(10).pipe(g(()=>this.attemptConsume()),y()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}const cs="x-squid-traceid",us="x-squid-client-version";function ls(e="n_"){return`${e}${Ce(10).toLowerCase()}`}const hs=e=>e();class ds extends Error{constructor(e,t,n,i,s){super(e),this.statusCode=t,this.url=n,this.headers=i,this.body=s}}const ps="1.0.423";async function gs(e){const t=await Is({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage});return t.body=vs(t.body),t}async function fs(e){const t=await Is({...e,method:"GET",files:[],filesFieldName:""});return t.body=vs(t.body),t}async function ys(e){const t=await Is({...e,method:"PUT"});return t.body=vs(t.body),t}async function ms(e){const t=await Is({...e,method:"PATCH"});return t.body=vs(t.body),t}async function bs(e){const t=await Is({...e,method:"DELETE",files:[],filesFieldName:""});return t.body=vs(t.body),t}async function Is({headers:e,files:t,filesFieldName:n,message:i,url:s,extractErrorMessage:r,method:o}){const a=new Headers(e);a.append(cs,ls("c_")),a.append(us,ps);const c={method:o,headers:a,body:void 0};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const i of t)e.append(n||"files",i,i.name);e.append("body",an(i)),c.body=e}else void 0!==i&&(a.append("Content-Type","application/json"),c.body=an(i));else"DELETE"===o&&void 0!==i&&(a.append("Content-Type","application/json"),c.body=an(i));try{const e=await fetch(s,c),t={};if(e.headers.forEach((e,n)=>{t[n]=e}),!e.ok){const n=await e.text(),i=vs(n);if(!r)throw new ds(n,e.status,s,t,i);let o;try{o="string"==typeof i?i:i?.message||n}catch{}throw o||(o=e.statusText),new ds(o,e.status,s,t,i)}const n=await e.text();return bn.debug(`received response from url ${s}: ${JSON.stringify(n)}`),{body:n,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw bn.debug(`Unable to perform fetch request to url: ${s}`,e),e}}function vs(e){if(e){try{return cn(e)}catch{}return e}}class ws{constructor(e,n,i,s,r,o){this.region=e,this.appId=n,this.authManager=r,this.clientIdService=o,this.staticHeaders={},this.onGoingRpcCounter=new t(0);for(const[e,t]of Object.entries(s))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe(e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")}),i.onDestruct(async()=>{await this.awaitAllSettled()});const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new as(60*a,5),ai:new as(20*a,5),secret:new as(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:n}=await this.authManager.getAuthData();if(!t)return{};let i=`Bearer ${t}`;return n&&(i+=`; IntegrationId ${n}`),{Authorization:i}}async awaitAllSettled(){await m(this.onGoingRpcCounter.pipe(g(e=>0===e)))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,n=[],i="files",s={}){return(await this.rawPost(e,t,n,i,!0,s)).body}async rawPost(e,t,n=[],i="files",s=!0,r={}){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o,...r};bn.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await gs({url:c,headers:a,message:t,files:n,filesFieldName:i,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async get(e,t,n=!0){return(await this.rawGet(e,t,n)).body}async rawGet(e,t,n=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const i=await this.getAuthHeaders(),s={...this.staticHeaders,...i};let r=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);if(t&&Object.keys(t).length>0){const e=new URLSearchParams;Object.entries(t).forEach(([t,n])=>{e.append(t,String(n))}),r+=`?${e.toString()}`}return bn.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await fs({url:r,headers:s,extractErrorMessage:n})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async put(e,t,n=[],i="files"){return(await this.rawPut(e,t,n,i)).body}async rawPut(e,t,n=[],i="files",s=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const r=await this.getAuthHeaders(),o={...this.staticHeaders,...r};bn.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await ys({url:a,headers:o,message:t,files:n,filesFieldName:i,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async patch(e,t,n=[],i="files"){return(await this.rawPatch(e,t,n,i)).body}async rawPatch(e,t,n=[],i="files",s=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const r=await this.getAuthHeaders(),o={...this.staticHeaders,...r};bn.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await ms({url:a,headers:o,message:t,files:n,filesFieldName:i,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async delete(e,t,n=!0){return(await this.rawDelete(e,t,n)).body}async rawDelete(e,t,n=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const i=await this.getAuthHeaders(),s={...this.staticHeaders,...i};bn.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const r=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await bs({url:r,headers:s,message:t,extractErrorMessage:n})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?be(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?be(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):be(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class Ss{constructor(e){this.rpcManager=e}async list(){return(await this.rpcManager.post("/scheduler/listSchedulers",{})).schedulers}async enable(e){await this.update(this.createUpdateSchedulerOptions(e,!0))}async disable(e){await this.update(this.createUpdateSchedulerOptions(e,!1))}async update(e){const t={schedulers:e};await this.rpcManager.post("scheduler/updateSchedulers",t)}createUpdateSchedulerOptions(e,t){return Array.isArray(e)?e.map(e=>({schedulerId:e,enabled:t})):[{schedulerId:e,enabled:t}]}}function Ms(){}const ks="undefined"!=typeof process&&process.versions?.node?F(220):mn().WebSocket;class Ts{constructor(e,n,i,s=hs,o,a){this.clientIdService=e,this.region=n,this.appId=i,this.messageNotificationWrapper=s,this.destructManager=o,this.authManager=a,this.webSocketObserver=new r,this.allMessagesObserver=new r,this.connectionReady=new t(!1),this.seenMessageIds=new Set,this.destructSubject=new r,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new t(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe(g(Boolean),E(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe(T(1),g(e=>!e),_(()=>M(R(this.clientTooOldThreshold),this.connectionReady.pipe(g(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?bn.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(bn.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe(g(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe(g(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?bn.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?bn.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(bn.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),bn.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}getClientInfo(){this.postMessage({type:"getClientInfo"})}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe(p())}async awaitConnectionReady(){await m(this.observeConnectionReady().pipe(g(Boolean)))}notifyWebSocketIsNeeded(){this.webSocketNeededSubject.next(!0)}postMessage(e){this.sendMessageImpl(e)}sendMessage(e){return this.sendMessageImpl(e)}disconnectForTest(){this.connectionReady.next(!1),this.socket?.close(4998)}keepAlive(){this.lastTick&&(Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(bn.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.webSocketNeededSubject.next(!0),await m(this.connectionReady.pipe(g(Boolean)));const t=await this.authManager.getToken();if(this.connectionReady.value)try{me(this.socket,"Socket is undefined in sendMessageAsync");const n=an({message:e,authToken:t});bn.debug(this.clientIdService.getClientId(),"Sending message to socket: ",n),this.socket.send(n)}catch(t){this.socket?.connected?console.error("Websocket message is ignored due to a non-recoverable error",t):(this.connectionReady.next(!1),await this.sendMessageImpl(e))}else await this.sendMessageImpl(e)}sendKillMessage(){this.socket?.connected&&this.socket.send(an({message:{type:"kill"}}))}closeCurrentSocketSilently(){if(this.socket)try{this.socket.close()}catch(e){}}connect(){this.closeCurrentSocketSilently(),this.connectionReady.value&&this.connectionReady.next(!1);const e=P(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();bn.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const n=`${e}?clientId=${t}`;this.socket=function(e,t={}){let n,i=0,s=1;const r={connected:!1,closeCalled:!1,open(){n=new(ks?.WebSocket??ks)(e,t.protocols||[]),n.onmessage=t.onmessage?e=>{e.data&&t.onmessage?t.onmessage(e):console.log("No data received from websockets, please contact support@getsquid.ai with this message.")}:Ms,n.onopen=function(e){r.connected=!0,(t.onopen||Ms)(e),i=0},n.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return bn.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Ms)(e),void r.reconnect(e);(t.onclose||Ms)(e)},n.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||Ms)(e)}},reconnect(e){const n=void 0!==t.maxAttempts?t.maxAttempts:1/0;s&&i++<n?s=setTimeout(function(){(t.onreconnect||Ms)(e),bn.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||Ms)(e)},json(e){n.send(JSON.stringify(e))},send(e){n.send(e)},close(e=4999,t){r.closeCalled=!0;try{r.connected=!1,clearTimeout(s),s=void 0,n.close(e,t)}catch(e){}}};return r.open(),r}(n,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{bn.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{bn.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):bn.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{bn.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):bn.debug(t,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}onConnectionReady(){this.connectionReady.next(!0),this.connectedAtLeastOnce?this.postMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return bn.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=cn(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),bn.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new r;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe(A(e=>t.push(e)),u(100)).subscribe(async()=>{const e=[...t.splice(0)];this.postMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await m(R(0)),this.connectionReady.next(!1),await m(R(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Cs(e){var t,n;n="Invalid application ID",me(function(e){return"string"==typeof e}(t=e),()=>ve(n,"Not a string",t));const[i,s,r,o]=e.split("-");return me(!o,`Invalid application ID: ${e}`),{appId:i,environmentId:s??"prod",squidDeveloperId:r}}function Os(e,t){return`${Cs(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function _s(e,t,n){return`${Os(e,t)}${n?`-${n}`:""}`}function Es(e){const t=Cs(e);return Os(t.appId,t.environmentId)}class qs{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,n){const i={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:n};await this.rpcManager.post("storage/uploadFile",i,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const n={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",n)}async listDirectoryContents(e){const t={integrationId:this.integrationId,dirPathInBucket:e};return await this.rpcManager.post("storage/listDirectoryContents",t)}async deleteFile(e){await this.deleteFiles([e])}async deleteFiles(e){const t={integrationId:this.integrationId,filePathsInBucket:e};await this.rpcManager.post("storage/deleteFiles",t)}}class Ds{constructor(e,t,n,i,s){this.rpcManager=e,this.region=t,this.appId=n,this.apiKey=i,this.consoleRegion=s}async aiSearch(e){return await this.rpcManager.post("web/aiSearch",{query:e})}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e,t){me(this.apiKey,"API key is required to create a short URL");const n=B(this.region,this.consoleRegion,"openapi/sqd/shorten"),i={url:e,appId:this.appId,secondsToLive:t},s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!s.ok)throw console.error("Error making POST request to shorten endpoint",s.statusText),new Error(`${s.statusText}: ${s.text}`);return await s.json()}async createShortUrls(e,t){me(this.apiKey,"API key is required to create a short URL");const n=B(this.region,this.consoleRegion,"openapi/sqd/shortenMany"),i={urls:e,appId:this.appId,secondsToLive:t},s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!s.ok)throw console.error("Error making POST request to shortenMany endpoint",s.statusText),new Error(`${s.statusText}: ${s.text}`);return await s.json()}async deleteShortUrl(e){me(this.apiKey,"API key is required to delete a short URL");const t=B(this.region,this.consoleRegion,"openapi/sqd/delete"),n={id:e,appId:this.appId},i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!i.ok)throw console.error("Error making POST request to delete endpoint",i.statusText),new Error(i.statusText)}async deleteShortUrls(e){me(this.apiKey,"API key is required to delete a short URL");const t=B(this.region,this.consoleRegion,"openapi/sqd/deleteMany"),n={ids:e,appId:this.appId},i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!i.ok)throw console.error("Error making POST request to delete endpoint",i.statusText),new Error(i.statusText)}}class As{constructor(e,t,n){this.rpcManager=e,this.region=t,this.appId=n}async executeWebhook(e,t={}){const{headers:n={},queryParams:i={},body:s,files:r=[]}=t,o=await this.rpcManager.getAuthHeaders(),a={...this.rpcManager.getStaticHeaders(),...o,...n};let c=P(this.region,this.appId,`webhooks/${encodeURIComponent(e)}`);if(i&&Object.keys(i).length>0){const e=new URLSearchParams;Object.entries(i).forEach(([t,n])=>{e.append(t,String(n))}),c+=`?${e.toString()}`}const u=new Headers(a);let l;if(u.append(cs,ls("c_")),u.append(us,ps),r&&r.length>0){const e=new FormData;for(const t of r)e.append("file",t,t.name);s&&"object"==typeof s&&Object.entries(s).forEach(([t,n])=>{e.append(t,String(n))}),l=e}else u.append("Content-Type","application/json"),l=an(s||{});const h=await fetch(c,{method:"POST",headers:u,body:l}),d={};if(h.headers.forEach((e,t)=>{d[t]=e}),!h.ok){const e=await h.text();let t;try{t=JSON.parse(e)}catch{t=e}const n="string"==typeof t?t:t?.message||h.statusText;throw new ds(n,h.status,c,d,t)}const p=await h.text();let g;try{g=JSON.parse(p)}catch{g=p}return g}}class Rs{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new ei,me(e.appId,"APP_ID_MUST_BE_PROVIDED");for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this))){const t=this[e];"function"!=typeof t||"constructor"===e||e.startsWith("_")||(this[e]=t.bind(this))}const t="prod"!==e.environmentId&&e.squidDeveloperId,n=_s(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new In(this.destructManager),bn.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new Gt(e.apiKey,e.authProvider),this.socketManager=new Ts(this.clientIdService,e.region,n,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new ws(e.region,n,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new hi(this.socketManager,this.rpcManager),this.jobClient=new ci(this.socketManager,this.rpcManager,this.clientIdService),this.backendFunctionManager=new fn(this.rpcManager),this.aiClient=new Lt(this.socketManager,this.rpcManager,this.jobClient,this.backendFunctionManager),this.apiClient=new $t(this.rpcManager),this.documentStore=new ri,this.lockManager=new is,this.distributedLockManager=new ti(this.socketManager,this.destructManager),this.documentIdentityService=new ii(this.documentStore,this.destructManager),this.documentReferenceFactory=new si(this.documentIdentityService),this.querySender=new qi(this.rpcManager,this.destructManager),this.observabilityClient=new pi(this.rpcManager),this.schedulerClient=new Ss(this.rpcManager),this._appId=n,this.querySubscriptionManager=new es(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager),this.localQueryManager=new _i(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new ui(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Dn(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new Zn(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new Un(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.webhookManager=new As(this.rpcManager,e.region,n),this.nativeQueryManager=new li(this.rpcManager),this._connectionDetails=new $n(this.clientIdService,this.socketManager),this.queueManagerFactory=new ss(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new $(this.rpcManager,this.options.region,Es(n),this.options.consoleRegion),this.webClient=new Ds(this.rpcManager,this.options.region,Es(n),this.options.apiKey,this.options.consoleRegion)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}static getInstance(e){const t=on(e);let n=Rs.squidInstancesMap[t];return n||(n=new Rs(e),Rs.squidInstancesMap[t]=n,n)}static getInstances(){return Object.values(Rs.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=_t){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...t){return this._validateNotDestructed(),this.backendFunctionManager.executeFunction(e,...t)}executeFunctionWithHeaders(e,t,...n){return this._validateNotDestructed(),this.backendFunctionManager.executeFunctionWithHeaders(e,t,...n)}executeWebhook(e,t){return this._validateNotDestructed(),this.webhookManager.executeWebhook(e,t)}executeNativeRelationalQuery(e,t,n={}){const i={type:"relational",query:t,params:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativePureQuery(e,t,n={}){const i={type:"pure",query:t,params:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativeMongoQuery(e,t,n){const i={type:"mongo",collectionName:t,aggregationPipeline:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativeElasticQuery(e,t,n,i="_search",s="GET"){const r={type:"elasticsearch",index:t,endpoint:i,method:s,body:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(r)}ai(){return this._validateNotDestructed(),this.aiClient}job(){return this._validateNotDestructed(),this.jobClient}api(){return this._validateNotDestructed(),this.apiClient}admin(){return this._validateNotDestructed(),this.adminClient}web(){return this._validateNotDestructed(),this.webClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new qs(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new oi(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new ai(this.rpcManager)}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t){const n=await this.acquireLock(e);try{return await t(n)}finally{n.release()}}queue(e,t=Et){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(Rs.squidInstancesMap).find(([,e])=>e===this);e&&delete Rs.squidInstancesMap[e[0]]})}get isDestructed(){return this.destructManager.isDestructing}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}getNotificationClient(){return this._validateNotDestructed(),this.notificationClient}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}internal(){const{rpcManager:e}=this;return{getApplicationUrl:(e,t,n)=>P(e,t,n),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,n)=>_s(e,t,n)}}_validateNotDestructed(){me(!this.destructManager.isDestructing,"The client was already destructed.")}}export{wt as AI_AGENTS_INTEGRATION_ID,dt as AI_AUDIO_CREATE_SPEECH_MODEL_NAMES,ht as AI_AUDIO_TRANSCRIPTION_MODEL_NAMES,Ge as AI_CHAT_MESSAGE_SOURCE,it as AI_EMBEDDINGS_MODEL_NAMES,lt as AI_IMAGE_MODEL_NAMES,Ke as AI_PROVIDER_TYPES,He as AI_STATUS_MESSAGE_PARENT_MESSAGE_ID_TAG,We as AI_STATUS_MESSAGE_RESULT_TAG,Pt as ALL_OPERATORS,Ze as ANTHROPIC_CHAT_MODEL_NAMES,yt as API_INJECTION_FIELD_TYPES,jt as ARRAY_OPERATORS,kt as AUTH_INTEGRATION_TYPES,$ as AdminClient,Re as AiAgentClient,De as AiAgentReference,xe as AiAssistantClient,Fe as AiAudioClient,Lt as AiClient,je as AiFilesClient,Pe as AiImageClient,Le as AiKnowledgeBaseClient,Qe as AiKnowledgeBaseReference,Ue as AiMatchMakingClient,$t as ApiClient,U as ApiKeysSecretClient,Gt as AuthManager,It as BUILT_IN_AGENT_ID,_t as BUILT_IN_DB_INTEGRATION_ID,Et as BUILT_IN_QUEUE_INTEGRATION_ID,qt as BUILT_IN_STORAGE_INTEGRATION_ID,fn as BackendFunctionManager,An as BaseQueryBuilder,Qt as CLIENT_CONNECTION_STATES,vn as CLIENT_ID_GENERATOR_KEY,wn as CLIENT_REQUEST_ID_GENERATOR_KEY,xn as Changes,In as ClientIdService,Qn as CollectionReference,Un as CollectionReferenceFactory,$n as ConnectionDetails,Mt as DATA_INTEGRATION_TYPES,ke as DEFAULT_SHORT_ID_LENGTH,Zn as DataManager,jn as DereferencedJoin,ei as DestructManager,ni as DistributedLockImpl,ti as DistributedLockManager,En as DocumentReference,si as DocumentReferenceFactory,ri as DocumentStore,Ne as EMPTY_CHAT_ID,bt as ENVIRONMENT_IDS,oi as ExternalAuthClient,ai as ExtractionClient,Xi as FETCH_BEYOND_LIMIT,ut as FLUX_MODEL_NAMES,Je as GEMINI_CHAT_MODEL_NAMES,Tt as GRAPHQL_INTEGRATION_TYPES,Ye as GROK_CHAT_MODEL_NAMES,Bn as GroupedJoin,Ct as HTTP_INTEGRATION_TYPES,vt as HttpStatus,Ot as INTEGRATION_SCHEMA_TYPES,St as INTEGRATION_TYPES,Q as IntegrationClient,ci as JobClient,Fn as JoinQueryBuilder,dn as LastUsedValueExecuteFunctionCache,Wi as LimitUnderflowState,_i as LocalQueryManager,xt as METRIC_DOMAIN,Nt as METRIC_FUNCTIONS,Ft as METRIC_INTERVAL_ALIGNMENT,$e as MatchMaker,ui as MutationSender,hs as NOOP_FN,li as NativeQueryManager,hi as NotificationClient,ot as OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES,at as OPENAI_AUDIO_MODEL_NAMES,rt as OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES,ze as OPENAI_CHAT_MODEL_NAMES,tt as OPENAI_EMBEDDINGS_MODEL_NAMES,st as OPENAI_IMAGE_MODEL_NAMES,pt as OPEN_AI_CREATE_SPEECH_FORMATS,pi as ObservabilityClient,qn as Pagination,Nn as QueryBuilder,Dn as QueryBuilderFactory,qi as QuerySender,es as QuerySubscriptionManager,ss as QueueManagerFactory,os as QueueManagerImpl,ft as RAG_TYPES,Ve as RERANK_PROVIDERS,as as RateLimiter,ws as RpcManager,Dt as SQUID_BUILT_IN_INTEGRATION_IDS,Rt as SQUID_METRIC_NAMES,Bt as SQUID_REGIONS,ct as STABLE_DIFFUSION_MODEL_NAMES,Ss as SchedulerClient,L as SecretClient,Ts as SocketManager,Rs as Squid,ds as SquidClientError,qs as StorageClient,Xe as VENDOR_AI_CHAT_MODEL_NAMES,nt as VOYAGE_EMBEDDING_MODEL_NAMES,Ds as WebClient,As as WebhookManager,qe as base64ToFile,ln as compareArgsByReference,hn as compareArgsBySerializedValue,mi as deserializeQuery,Me as generateId,Ce as generateShortId,Oe as generateShortIds,we as generateUUID,Se as generateUUIDPolyfill,B as getConsoleUrl,yn as getCustomizationFlag,At as isBuiltInIntegrationId,gt as isIntegrationModelSpec,mt as isPlaceholderParam,et as isVendorAiChatModelName,bs as rawSquidHttpDelete,fs as rawSquidHttpGet,ms as rawSquidHttpPatch,gs as rawSquidHttpPost,ys as rawSquidHttpPut,pn as transformFileArgs,vs as tryDeserializing,yi as visitQueryResults};
|
|
1
|
+
import*as e from"ws";import{BehaviorSubject as t,NEVER as n,Observable as i,ReplaySubject as s,Subject as r,combineLatest as o,combineLatestWith as a,concatMap as c,debounceTime as u,defaultIfEmpty as l,defer as h,delay as d,distinctUntilChanged as p,filter as g,finalize as f,first as y,firstValueFrom as m,interval as b,lastValueFrom as I,map as v,of as w,pairwise as S,race as M,share as k,skip as T,startWith as C,switchAll as O,switchMap as _,take as E,takeUntil as q,takeWhile as D,tap as A,timer as R}from"rxjs";var N={150:function(e,t,n){var i=this&&this.__createBinding||(Object.create?function(e,t,n,i){void 0===i&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}:function(e,t,n,i){void 0===i&&(i=n),e[i]=t[n]}),s=this&&this.__exportStar||function(e,t){for(var n in e)"default"===n||Object.prototype.hasOwnProperty.call(t,n)||i(t,e,n)};Object.defineProperty(t,"__esModule",{value:!0});const r=n(642);t.default=r.PromisePool,s(n(273),t),s(n(642),t),s(n(837),t),s(n(426),t),s(n(858),t),s(n(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class n 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=n},220:t=>{t.exports=e},234:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const i=n(642),s=n(172),r=n(837),o=n(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 s.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 s.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 s.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 s.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 s.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw s.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(i.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]=i.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 n=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(n)}).catch(async i=>{await this.handleErrorFor(i,e,t),this.removeActive(n)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(n),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[n,i]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),n()]).finally(i)}createTaskTimeout(e){let t;return[async()=>new Promise((n,i)=>{t=setTimeout(()=>{i(new r.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,n){if(this.shouldUseCorrespondingResults()&&(this.results()[n]=i.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 s.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(r.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,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const i=n(234);class s{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 s(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 i.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=s,s.notRun=Symbol("notRun"),s.failed=Symbol("failed")},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class n 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=n},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class n extends Error{}t.StopThePromisePoolError=n}},x={};function F(e){var t=x[e];if(void 0!==t)return t.exports;var n=x[e]={exports:{}};return N[e].call(n.exports,n,n.exports,F),n.exports}F.d=(e,t)=>{for(var n in t)F.o(t,n)&&!F.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},F.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),F.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const j=["aiData","api","application","application-kotlin","auth","backend-function","connector","integration","internal-storage","internalCodeExecutor","mutation","native-query","observability","openapi","query","queue","quota","scheduler","secret","storage","webhooks","ws","personalStorage","internal-extraction","notification"];function P(e,t,n,i,s,r){let o="https",a=`${i||t}.${s||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=j.includes(n.replace(/^\//,"").split("/")[0]||"")||r?"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=n.replace(/^\/+/,"");return l?`${u}/${l}`:u}function B(e,t,n=""){return P(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",n)}class Q{constructor(e,t,n,i){this.rpcManager=e,this.iacBaseUrl=B(t,i,`openapi/iac/applications/${n}/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 setIntegrationSchema(e,t){await this.rpcManager.put(`${this.iacBaseUrl}/${e}/schema`,t)}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 L{constructor(e){this.rpcManager=e}get apiKeys(){return new U(this.rpcManager)}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 n={keys:[e],force:t};return this.rpcManager.post("secret/delete",n)}async deleteMany(e,t=!1){if(0===e.length)return;const n={keys:e,force:t};return this.rpcManager.post("secret/delete",n)}}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 ${constructor(e,t,n,i){this.rpcManager=e,this.region=t,this.appId=n,this.consoleRegion=i,this.integrationClient=new Q(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new L(this.rpcManager)}integrations(){return this.integrationClient}secrets(){return this.secretClient}}function G(e){return"function"==typeof e}function H(e){return function(t){if(function(e){return G(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 W=function(e,t){return W=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},W(e,t)};function V(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}W(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function K(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],i=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&i>=e.length&&(e=void 0),{value:e&&e[i++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function z(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var i,s,r=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(i=r.next()).done;)o.push(i.value)}catch(e){s={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(s)throw s.error}}return o}function J(e,t,n){if(n||2===arguments.length)for(var i,s=0,r=t.length;s<r;s++)!i&&s in t||(i||(i=Array.prototype.slice.call(t,0,s)),i[s]=t[s]);return e.concat(i||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var Y,Z=((Y=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),Y.prototype.constructor=Y,Y);function X(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var ee=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,n,i,s;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=K(r),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 r.remove(this);var c=this.initialTeardown;if(G(c))try{c()}catch(e){s=e instanceof Z?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=K(u),h=l.next();!h.done;h=l.next()){var d=h.value;try{te(d)}catch(e){s=null!=s?s:[],e instanceof Z?s=J(J([],z(s)),z(e.errors)):s.push(e)}}}catch(e){n={error:e}}finally{try{h&&!h.done&&(i=l.return)&&i.call(l)}finally{if(n)throw n.error}}}if(s)throw new Z(s)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)te(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).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)&&X(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&X(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function te(e){G(e)?e():e.unsubscribe()}ee.EMPTY;var ne={setTimeout:function(e,t){for(var n=[],i=2;i<arguments.length;i++)n[i-2]=arguments[i];var s=ne.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,J([e,t],z(n))):setTimeout.apply(void 0,J([e,t],z(n)))},clearTimeout:function(e){var t=ne.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function ie(){}var se=re("C",void 0,void 0);function re(e,t,n){return{kind:e,value:t,error:n}}var oe=function(e){function t(t){var n,i=e.call(this)||this;return i.isStopped=!1,t?(i.destination=t,((n=t)instanceof ee||n&&"closed"in n&&G(n.remove)&&G(n.add)&&G(n.unsubscribe))&&t.add(i)):i.destination=he,i}return V(t,e),t.create=function(e,t,n){return new ce(e,t,n)},t.prototype.next=function(e){this.isStopped?le(function(e){return re("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?le(re("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?le(se,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}(ee);Function.prototype.bind;var ae=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){ue(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){ue(e)}else ue(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){ue(e)}},e}(),ce=function(e){function t(t,n,i){var s,r=e.call(this)||this;return s=G(t)||!t?{next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=i?i:void 0}:t,r.destination=new ae(s),r}return V(t,e),t}(oe);function ue(e){!function(e){ne.setTimeout(function(){throw e})}(e)}function le(e,t){var n=null;n&&ne.setTimeout(function(){return n(e,t)})}var he={closed:!0,next:ie,error:function(e){throw e},complete:ie};function de(e,t,n,i,s){return new pe(e,t,n,i,s)}var pe=function(e){function t(t,n,i,s,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=s?function(e){try{s(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=i?function(){try{i()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return V(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(oe);function ge(e,t){return H(function(n,i){var s=0;n.subscribe(de(i,function(n){i.next(e.call(t,n,s++))}))})}function fe(e){return null!=e}let ye=e=>new Error(e);function me(e,t,...n){e||function(e,...t){const n=Ie(e);if("object"==typeof n)throw n;throw ye(n||"Assertion error",...t)}(t,...n)}function be(e,t,...n){return me(e,t,...n),e}function Ie(e){return void 0===e?"":"string"==typeof e?e:e()}function ve(e,t,n){const i=Ie(e);if("object"==typeof i)throw i;return`${i?`${i}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(n)}`}function we(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():Se()}function Se(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}function Me(){return we()}const ke=18;function Te(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()))}function Ce(e=18,t="",n=""){me(t.length<e,"ID prefix is too long"),me(!t||!n||n.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let i="";for(let t=0;t<e;t++)i+=Te();if(t.length>0&&(i=t+i.substring(t.length)),n)for(;i.charAt(t.length)===n[t.length];)i=i.substring(0,t.length)+Te()+i.substring(t.length+1);return i}function Oe({count:e,length:t,prefix:n}){me(e>=0,`Invalid IDs count: ${e}`);const i=new Set;for(;i.size<e;)i.add(Ce(t||18,n||""));return[...i]}const _e=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Ee(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)Ee(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)Ee(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(_e.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${_e.join(", ")}`);const n=e[t];if("object"!=typeof n&&"string"!=typeof n&&"number"!=typeof n&&"boolean"!=typeof n)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof n}`)}}function qe(e,t,n){const i=atob(e),s=new Uint8Array(i.length);for(let e=0;e<i.length;e++)s[e]=i.charCodeAt(e);return new File([s],t,{type:n||"application/octet-stream"})}class De{constructor(e,t,n,i,s,r,o){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=n,this.rpcManager=i,this.socketManager=s,this.jobClient=r,this.backendFunctionManager=o}async get(){const e=await this.post("ai/agent/getAgent",{agentId:this.agentId});return e?.agent}async upsert(e){await this.post("ai/agent/upsertAgent",{...e,id:this.agentId})}async delete(){await this.post("ai/agent/deleteAgent",{agentId:this.agentId})}async updateInstructions(e){await this.setAgentOptionInPath("instructions",e)}async updateModel(e){await this.setAgentOptionInPath("model",e)}async updateConnectedAgents(e){await this.setAgentOptionInPath("connectedAgents",e)}async updateGuardrails(e){const t=await this.get();me(t,"Agent not found");const n={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",n)}async updateCustomGuardrails(e){await this.post("ai/agent/upsertCustomGuardrails",{agentId:this.agentId,customGuardrail:e})}async deleteCustomGuardrail(){await this.post("ai/agent/deleteCustomGuardrails",{agentId:this.agentId})}async regenerateApiKey(){return await this.post("ai/agent/regenerateApiKey",{agentId:this.agentId})}async getApiKey(){return await this.post("ai/agent/getApiKey",{agentId:this.agentId})}chat(e,t,n){return this.chatInternal(e,t,n).responseStream}async transcribeAndChat(e,t,n){const i=this.chatInternal(e,t,n),s=await be(i.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:i.responseStream,transcribedPrompt:s.transcribedPrompt}}async ask(e,t,n){const i=await this.askInternal(e,!1,t,n);return this.replaceFileTags(i.responseString,i.annotations)}async askWithAnnotations(e,t,n){const i=await this.askInternal(e,!1,t,n);return{responseString:i.responseString,annotations:i.annotations}}async askAsync(e,t,n){const i={agentId:this.agentId,prompt:e,options:n,jobId:t};await this.post("ai/chatbot/askAsync",i)}observeStatusUpdates(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"aiStatus"===e.type&&e.agentId===this.agentId),ge(e=>({agentId:this.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,body:e.payload.body,parentStatusUpdateId:e.payload.parentStatusUpdateId,messageId:e.messageId})))}async getChatHistory(e){const t={agentId:this.agentId,memoryId:e};return(await this.post("ai/chatbot/history",t)).messages}async transcribeAndAsk(e,t,n){return await this.askInternal(e,!1,t,n)}async transcribeAndAskWithVoiceResponse(e,t,n){const i=await this.askInternal(e,!0,t,n),s=i.voiceResponse;return{responseString:i.responseString,transcribedPrompt:i.transcribedPrompt,voiceResponseFile:qe(s.base64File,`voice.${s.extension}`,s.mimeType)}}async askWithVoiceResponse(e,t,n){const i=await this.askInternal(e,!0,t,n),s=i.voiceResponse;return{responseString:i.responseString,voiceResponseFile:qe(s.base64File,`voice.${s.extension}`,s.mimeType)}}async setAgentOptionInPath(e,t){await this.post("ai/agent/setAgentOptionInPath",{agentId:this.agentId,path:e,value:t})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}replaceFileTags(e,t={}){let n=e;for(const[e,i]of Object.entries(t)){let t="";const s=i.aiFileUrl.fileName?i.aiFileUrl.fileName:i.aiFileUrl.url;switch(i.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${s}](${i.aiFileUrl.url})`}n=n.replace(`\${id:${e}}`,t)}return n}async askInternal(e,t,n,i){if(n?.contextMetadataFilter&&Ee(n.contextMetadataFilter),n?.contextMetadataFilterForKnowledgeBase)for(const e in n.contextMetadataFilterForKnowledgeBase)Ee(n.contextMetadataFilterForKnowledgeBase[e]);i=i||we(),n={...Ae,...n||{}};const s="string"==typeof e;let r="ai/chatbot/";r+=s||t?!s&&t?"transcribeAndAskWithVoiceResponse":s&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:s?e:void 0,options:n,jobId:i},a=s?void 0:[e];return await this.post(r,o,a,"file"),await this.jobClient.awaitJob(i)}chatInternal(e,t,n){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&Ee(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)Ee(t.contextMetadataFilterForKnowledgeBase[e]);const i=we(),s=void 0===(t={...Ae,...t||{}}).smoothTyping||t.smoothTyping;let o="";const a=new r,u=new r;this.ongoingChatSequences[i]=u;let l=-1;u.pipe(A(({tokenIndex:e})=>{void 0!==e&&e<l&&console.warn("Received token index out of order",e,l),void 0!==e&&(l=e)}),c(({value:e,complete:t,annotations:n})=>t?w({value:e,complete:t,annotations:n}):w(e).pipe(s?d(0):A(),ge(e=>({value:e,complete:!1,annotations:void 0})))),D(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:n})=>{o+=e,t&&n&&(o=this.replaceFileTags(o,n)),a.next(o)},error:e=>{console.error(e)},complete:()=>{a.complete()}});const h="string"==typeof e;n=n||we();const p={agentId:this.agentId,jobId:n,prompt:h?e:void 0,options:t,clientRequestId:i},g={responseStream:a.pipe(f(()=>{delete this.ongoingChatSequences[i]}),k())};return h?this.post("ai/chatbot/chat",p).catch(e=>{a.error(e),a.complete()}):this.post("ai/chatbot/transcribeAndChat",p,[e],"file").catch(e=>{throw a.error(e),a.complete(),e}),g.serverResponse=this.jobClient.awaitJob(n).catch(e=>{a.error(e),a.complete()}),g}async post(e,t,n=[],i="files"){const s={};return this.agentApiKey&&(s["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,n,i,s)}}const Ae={smoothTyping:!0,responseFormat:"text"};class Re{constructor(e,t,n,i){this.rpcManager=e,this.socketManager=t,this.jobClient=n,this.backendFunctionManager=i,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe(g(e=>"aiChatbot"===e.type),ge(e=>e)).subscribe(e=>{this.handleChatResponse(e)})}agent(e,t=void 0){return new De(e,t?.apiKey,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)}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:n,complete:i,tokenIndex:s,annotations:r}=e.payload;if(i&&!n.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(n.match(/\[.*?]\((.*?)\)/g))t.next({value:n,complete:i,tokenIndex:void 0===s?void 0:s,annotations:r});else for(let e=0;e<n.length;e++)t.next({value:n[e],complete:i&&e===n.length-1,tokenIndex:void 0===s?void 0:s,annotations:r})}}const Ne="__squid_empty_chat_id";class xe{constructor(e){this.rpcManager=e}async createAssistant(e,t,n,i){const s={name:e,instructions:t,functions:n,toolTypes:i};return(await this.rpcManager.post("ai/assistant/createAssistant",s)).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,n,i,s){const r={assistantId:e,threadId:t,prompt:n,fileIds:i,options:s};return(await this.rpcManager.post("ai/assistant/queryAssistant",r)).answer}async addFileToAssistant(e,t){const n={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",n,[t],"file")).fileId}async removeFileFromAssistant(e,t){const n={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",n)}async addFileToThread(e,t){const n={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",n,[t],"file")).fileId}}class Fe{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 n={input:e,options:t},i=await this.rpcManager.post("ai/audio/createSpeech",n);return qe(i.base64File,`audio.${i.extension}`,i.mimeType)}}class je{constructor(e,t){this.provider=e,this.rpcManager=t}async uploadFile(e){const t={provider:this.provider,expirationInSeconds:e.expirationInSeconds};return(await this.rpcManager.post("ai/files/uploadFile",t,[e.file],"file")).fileId}async deleteFile(e){const t={fileId:e,provider:this.provider};return(await this.rpcManager.post("ai/files/deleteFile",t)).deleted}}class Pe{constructor(e){this.rpcManager=e}async generate(e,t){const n={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",n)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function Be(e){for(const t in e){const n=e[t];me("string"==typeof n||"number"==typeof n||"boolean"==typeof n||void 0===n,`Invalid metadata value for key ${t} - cannot be of type ${typeof n}`),me(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class Qe{constructor(e,t,n){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=n}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(e){return(await this.rpcManager.post("ai/knowledge-base/listContexts",{id:this.knowledgeBaseId,truncateTextAfter:e})).contexts||[]}async listContextIds(){return(await this.rpcManager.post("ai/knowledge-base/listContextIds",{id:this.knowledgeBaseId})).contextIds||[]}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:n}=await this.upsertContexts([e],t?[t]:void 0);return n.length>0?{failure:n[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&Be(t.metadata);const n=we();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:n},t),await this.jobClient.awaitJob(n)}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 searchContextsWithPrompt(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithPrompt",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}async searchContextsWithContextId(e){return(await this.rpcManager.post("ai/knowledge-base/searchContextsWithContextId",{...e,knowledgeBaseId:this.knowledgeBaseId})).results}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 Qe(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 Ue{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new $e(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new $e(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class $e{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 Ge=["user","ai"],He=["cohere","none"],We=["anthropic","flux","gemini","openai","grok","stability","voyage","external"],Ve=["o1","o3","o3-mini","o4-mini","gpt-5","gpt-5-mini","gpt-5-nano","gpt-5.1","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"],Ke=["gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"],ze=["grok-3","grok-3-fast","grok-3-mini","grok-3-mini-fast","grok-4","grok-4-fast-reasoning","grok-4-fast-non-reasoning","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],Je=["claude-3-7-sonnet-latest","claude-haiku-4-5-20251001","claude-opus-4-20250514","claude-opus-4-1-20250805","claude-opus-4-5-20251101","claude-sonnet-4-20250514","claude-sonnet-4-5-20250929"],Ye=[...Ve,...Je,...Ke,...ze];function Ze(e){return Ye.includes(e)}const Xe=["text-embedding-3-small"],et=["voyage-3-large"],tt=[...Xe,...et],nt=["dall-e-3"],it=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],st=["tts-1","tts-1-hd","gpt-4o-mini-tts"],rt=[...it,...st],ot=["stable-diffusion-core"],at=["flux-pro-1.1","flux-kontext-pro"],ct=[...nt,...ot,...at],ut=[...it],lt=[...st],ht=["mp3","opus","aac","flac","wav","pcm"];function dt(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const pt=["contextual","basic"],gt=["secret","regular"];function ft(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const yt=["dev","prod"],mt="built_in_agent",bt={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},It="ai_agents",vt=["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_calendar","google_docs","google_drive","graphql","hubspot","jira","jwt_hmac","jwt_rsa","kafka","keycloak","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","legend","teams","openai_compatible"],wt=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch","legend"],St=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth"],Mt=["graphql","linear"],kt=["api"],Tt=["data","api","graphql"],Ct="built_in_db",Ot="built_in_queue",_t="built_in_storage",Et=[Ct,Ot,_t];function qt(e){return Et.includes(e)}const Dt=["squid_functionExecution_count","squid_functionExecution_time"],At=["sum","max","min","average","median","p95","p99","count"],Rt=["user","squid"],Nt=["align-by-start-time","align-by-end-time"],xt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],Ft=[...xt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],jt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],Pt=["CONNECTED","DISCONNECTED","REMOVED"];class Bt{constructor(e,t,n,i){this.socketManager=e,this.rpcManager=t,this.jobClient=n,this.backendFunctionManager=i,this.aiAssistantClient=new xe(this.rpcManager)}agent(e=mt,t=void 0){return this.getAiAgentClient().agent(e,t)}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 Pe(this.rpcManager)}audio(){return new Fe(this.rpcManager)}matchMaking(){return new Ue(this.rpcManager)}files(e){return new je(e,this.rpcManager)}executeAiQuery(e,t,n){const i={integrationId:e,prompt:t,options:n};return this.rpcManager.post("ai/query/executeDataQuery",i)}executeAiApiCall(e,t,n,i){const s={integrationId:e,prompt:t,options:n,sessionContext:i};return this.rpcManager.post("ai/query/executeApiQuery",s)}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 n={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",n)).settings}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Re(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new Le(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const Qt={headers:{},queryParams:{},pathParams:{}};class Lt{constructor(e){this.rpcManager=e}async get(e,t,n){return this.request(e,t,void 0,n,"get")}async post(e,t,n,i){return this.request(e,t,n,i,"post")}async delete(e,t,n,i){return this.request(e,t,n,i,"delete")}async patch(e,t,n,i){return this.request(e,t,n,i,"patch")}async put(e,t,n,i){return this.request(e,t,n,i,"put")}async request(e,t,n,i,s){const r={integrationId:e,endpointId:t,body:n,options:{...Qt,...this.convertOptionsToStrings(i||{})},overrideMethod:s};return await this.rpcManager.rawPost("api/callApi",r,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 Ut{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}}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}async getTokenFromAuthProvider(){const e=this.authProvider?.getToken();return"object"==typeof e?await e:e}}const $t=/[.\[\]]/;function Gt(e,t){if(!e)return;const n=t.split($t);let i,s=e;for(;s&&n.length;){const e=n.shift();if(e){if("object"!=typeof s||!(e in s))return;i=s[e],s=i}}return i}function Ht(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Wt(e,t,n,i="."){const s=t.split(i);let r=e;for(;s.length;){const e=be(s.shift());if(s.length){const t=r[e],n=Ht(t)?Xt(t)??{}:{};r[e]=n,r=n}else r[e]=n}}function Vt(e,t,n="."){const i=t.split(n);let s=e;for(;i.length;){const e=be(i.shift());if(i.length){const t=Ht(s[e])?Xt(s[e])??{}:{};s[e]=t,s=t}else delete s[e]}}function Kt(e,t,n){if(e.has(t)){const i=e.get(t);e.delete(t),e.set(n,i)}}function zt(e){return null==e}function Jt(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const n=typeof e;if(n!==typeof t)return!1;if("object"!==n)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(const n of i)if(!s.includes(n)||!Jt(e[n],t[n]))return!1;return!0}function Yt(e,t){const n=new Array(e.length);for(let i=0;i<e.length;i++)n[i]=Zt(e[i],t);return n}function Zt(e,t){const n=t?t(e):void 0;if(void 0!==n)return n;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return Yt(e,t);if(e instanceof Map)return new Map(Yt(Array.from(e),t));if(e instanceof Set)return new Set(Yt(Array.from(e),t));if(ArrayBuffer.isView(e))return(i=e)instanceof Buffer?Buffer.from(i):new i.constructor(i.buffer.slice(),i.byteOffset,i.length);var i;const s={};for(const n in e)Object.hasOwnProperty.call(e,n)&&(s[n]=Zt(e[n],t));return s}function Xt(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 en(e,t){if(e===t||zt(e)&&zt(t))return 0;if(zt(e))return-1;if(zt(t))return 1;const n=typeof e,i=typeof t;return n!==i?n<i?-1:1:"number"==typeof e?(me("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(me("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(me("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(me("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function tn(e,t){return e.reduce((e,n)=>{const i=t(n);return e[i]?e[i].push(n):e[i]=[n],e},{})}function nn(e){if(Array.isArray(e))return e.map(e=>nn(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),n={};return t.sort().forEach(t=>{n[t]=nn(e[t])}),n}function sn(e){return rn(nn(e))}function rn(e){if(void 0===e)return null;const t=Zt(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function on(e){return Zt(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,n=t.$date;return n&&1===Object.keys(t).length?new Date(n):void 0})}function an(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=rn(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let n="";for(let t=0;t<e.length;t++)n+=String.fromCharCode(e[t]);return btoa(n)}}const cn=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0},un=(e,t)=>{if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(rn(e[n])!==rn(t[n]))return!1;return!0};class ln{constructor(e){this.options=e}get(e){const t=this.cachedEntry,n=this.options.argsComparator||cn,i=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+i&&n(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function hn(e){const t=[],n=[];let i=0;for(const s of e)if("undefined"!=typeof File)if(s instanceof File){n.push(s);const e={type:"file",__squid_placeholder__:!0,fileIndex:i++};t.push(e)}else if(dn(s)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:s.map((e,t)=>(n.push(s[t]),i++))};t.push(e)}else t.push(s);else t.push(s);return{argsArray:t,fileArray:n}}function dn(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class pn{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...n){const{argsArray:i,fileArray:s}=hn(n),r="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,a=o?.cache;if(a){const e=a.get(i);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?cn:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,i));if(t)return t.promise}const u=this.createExecuteCallPromise(r,i,s,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:i,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,n,i,s={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:rn(t)},a=on((await this.rpcManager.post(r,o,n.length>0?n:[],"files",s)).payload);if(a?.__isSquidBase64File__){const e=a;return qe(e.base64,e.filename,e.mimetype)}return i&&i.set(t,a),a}}function gn(e){if("undefined"!=typeof globalThis)return globalThis[e]}function fn(){if("undefined"!=typeof window)return window;if(void 0!==F.g)return F.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}!function(e=!0){fn().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 yn{static debug(...e){(function(){const e=fn();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=fn();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class mn{constructor(e){this.destructManager=e,this.clientTooOldSubject=new t(!1),this.isTenant=!0===fn().squidTenant,this.clientIdSubject=new t(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe(g(e=>e),v(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe(T(1),g(e=>!e),v(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=fn()[In];return e?e():we()}generateClientId(){const e=fn()[bn];if(e)return e();let t=`${this.isTenant?"tenant-":""}${we()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const bn="SQUID_CLIENT_ID_GENERATOR",In="SQUID_CLIENT_REQUEST_ID_GENERATOR",vn="__squidId";function wn(e){return on(e)}function Sn(...e){const[t,n,i]=e,s="object"==typeof t?t:{docId:t,collectionName:n,integrationId:i};return s.integrationId||(s.integrationId=void 0),sn(s)}function Mn(e,t,n){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===n)return Jt(e,t);if("!="===n)return!Jt(e,t);switch(n){case"<":return!zt(e)&&(!!zt(t)||t<e);case"<=":return!!zt(t)||!zt(e)&&t<=e;case">":return!zt(t)&&(!!zt(e)||t>e);case">=":return!!zt(e)||!zt(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&kn(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&kn(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&kn(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&kn(t,e,!0));case"array_includes_some":{const n=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>be(n,"VALUE_CANNOT_BE_NULL").some(t=>Jt(t,e)))}case"array_includes_all":{const n=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>be(n,"VALUE_CANNOT_BE_NULL").some(t=>Jt(t,e)))}case"array_not_includes":{const n=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!be(n,"VALUE_CANNOT_BE_NULL").some(t=>Jt(t,e)))}default:throw new Error(`Unsupported operator comparison: ${n}`)}}function kn(e,t,n){n||(e=e.toLowerCase(),t=t.toLowerCase());const i=function(e){let t="";for(let n=0;n<e.length;++n)"\\"===e[n]?n+1<e.length&&["%","_"].includes(e[n+1])?(t+=e[n+1],n++):n+1<e.length&&"\\"===e[n+1]?(t+="\\\\",n++):t+="\\":"%"===e[n]?t+="[\\s\\S]*":"_"===e[n]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[n])&&(t+="\\"),t+=e[n]);return t}(t);return new RegExp(`^${i}$`).test(e)}function Tn(e,t){return`${e}_${t}`}function Cn(e){return"fieldName"in e}class On{constructor(e,t,n){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=n,this.refId=we()}get squidDocId(){return this._squidDocId}get data(){return Zt(this.dataRef)}get dataRef(){return be(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:n}=wn(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:n,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 be(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(v(e=>(be(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)}async update(e,t){const n={};Object.entries(e).forEach(([e,t])=>{const i=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};n[e]=[i]});const i={type:"update",squidDocIdObj:wn(this.squidDocId),properties:n};return this.dataManager.applyOutgoingMutation(i,t)}async setInPath(e,t,n){return this.update({[e]:Zt(t)},n)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,n){const i={type:"applyNumericFn",fn:"increment",value:t},s={type:"update",squidDocIdObj:wn(this.squidDocId),properties:{[e]:[i]}};return this.dataManager.applyOutgoingMutation(s,n)}decrementInPath(e,t,n){return this.incrementInPath(e,-t,n)}async insert(e,t){const n=wn(this.squidDocId),i=n.integrationId;let s=on(n.docId);if(s[vn]&&(s={}),i===Ct&&s.__id)try{const e=on(s.__id);s={...s,...e}}catch{}const r={type:"insert",squidDocIdObj:n,properties:{...e,__docId__:n.docId,...s}};return this.dataManager.applyOutgoingMutation(r,t)}async delete(e){const t={type:"delete",squidDocIdObj:wn(this.squidDocId)};return this.dataManager.applyOutgoingMutation(t,e)}migrateDocIds(e){const t=e[this.squidDocId];t&&(this._squidDocId=t)}isTracked(){return this.dataManager.isTracked(this.squidDocId)}hasSquidPlaceholderId(){const e=on(this._squidDocId);if("object"==typeof e&&e.docId){const t=on(e.docId);if("object"==typeof t&&Object.keys(t).includes(vn))return!0}return!1}}class _n{constructor(e,n={}){this.internalStateObserver=new t(null),this.firstElement=null,this.isDestroyed=new t(!1),this.snapshotSubject=new r,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,me(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe(O()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...n},this.goToFirstPage()}unsubscribe(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.internalStateObserver.complete(),this.snapshotSubject.complete()}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(g(e=>null!==e),v(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(v(e=>e.reverse()));return this.snapshotSubject.next(e),await this.waitForData()}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||zt(e)&&zt(t))return 0;if(zt(e))return-1;if(zt(t))return 1;const n=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:i,asc:s}of n){const n=en(Gt(e,i),Gt(t,i));if(0!==n)return s?n:-n}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 n=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-n-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const n=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,i=Math.max(0,e.length-n-this.paginateOptions.pageSize);n!==e.length?this.internalStateObserver.next({numBefore:n,numAfter:i,data:e,extractedData:t}):this.prevInternal({numBefore:n,numAfter:i,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:Gt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe(v(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:Gt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await m(M(this.isDestroyed.pipe(g(Boolean),v(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe(g(e=>null!==e),E(1))))}internalStateToState(e){const{data:t,numBefore:n,numAfter:i,extractedData:s}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(s[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:i>0,hasPrev:n>0}}prevInternal(e){const{numBefore:t,numAfter:n,extractedData:i}=e;this.firstElement=null,this.lastElement=i[t-1],this.internalStateObserver.next(null),this.doNewQuery(i[i.length-n-1],!0)}}Error;class En{constructor(e,t,n,i){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=n,this.documentIdentityService=i}getForDocument(e){const{collectionName:t,integrationId:n,docId:i}=wn(e),s=on(i),r=this.get(t,n);for(const[e,t]of Object.entries(s))r.where(e,"==",t);return r}get(e,t){return new An(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService)}}class qn{constructor(){this.containsEmptyInCondition=!1}eq(e,t){return this.where(e,"==",t)}neq(e,t){return this.where(e,"!=",t)}in(e,t){return this.where(e,"in",t)}nin(e,t){return this.where(e,"not in",t)}gt(e,t){return this.where(e,">",t)}gte(e,t){return this.where(e,">=",t)}lt(e,t){return this.where(e,"<",t)}lte(e,t){return this.where(e,"<=",t)}like(e,t,n){return this.throwIfInvalidLikePattern(t),this.where(e,n?"like_cs":"like",t)}notLike(e,t,n){return this.throwIfInvalidLikePattern(t),this.where(e,n?"not like_cs":"not like",t)}arrayIncludesSome(e,t){return this.where(e,"array_includes_some",t)}arrayIncludesAll(e,t){return this.where(e,"array_includes_all",t)}arrayNotIncludes(e,t){return this.where(e,"array_not_includes",t)}throwIfInvalidLikePattern(e){if(/\\(?![%_\\])/.test(e))throw new Error("Invalid pattern. Cannot have any \\ which are not followed by _, % or \\")}}class Dn{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return m(this.snapshots(!1).pipe(l([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(ge(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Dn(this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new _n(this,e)}}class An extends qn{constructor(e,t,n,i,s,r,o){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=n,this.localQueryManager=i,this.documentReferenceFactory=s,this.queryBuilderFactory=r,this.documentIdentityService=o,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}get hash(){return an(this.build())}where(e,t,n){if(me(Ft.includes(t),`Invalid operator: ${t}`),"in"===t||"not in"===t){const i=Array.isArray(n)?[...n]:[n];"in"===t&&0===i.length&&(this.containsEmptyInCondition=!0);for(const n of i)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:n});return this}return this.query.conditions.push({fieldName:e,operator:t,value:n}),this}limit(e){return function(e){var t;me(function(e){return"number"==typeof e}(t=e),()=>ve("Limit needs to be a number","Not a number",t)),-1!==e&&(me(e>0,"query limit has to be greater than 0"),me(Math.floor(e)===e,"query limit has to be an integer"),me(e<=2e4,"Limit can be maximum 20000"))}(e),this.query.limit=e,this}getLimit(){return this.query.limit}limitBy(e,...t){const n=this.query.sortOrder.map(e=>e.fieldName);return me(Jt(t.sort(),n.slice(0,t.length).sort()),"All fields in limitBy must be appear in the first fields in the sortBy list."),this.query.limitBy={limit:e,fields:t,reverseSort:!1},this}sortBy(e,t=!0){const n={asc:t,fieldName:e};return function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var n,i,s,r;me((n=t,i=["fieldName","asc"],!Array.isArray(n)&&[...Object.keys(n)].every(e=>i.includes(e))),"Field sort should only contain a fieldName and asc"),me((s=t.asc,r="boolean",Array.isArray(s)?s.every(e=>typeof e===r):typeof s===r),"Asc needs to be boolean")}(n),me(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.sortOrder.push(n),this}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}getSortOrder(){return this.query.sortOrder}snapshot(){return m(this.snapshots(!1).pipe(l([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new t([]);const n=this.build();return this.querySubscriptionManager.processQuery(n,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(ge(e=>e.map(e=>{me(1===Object.keys(e).length);const t=Sn(be(e[this.collectionName]).__docId__,this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)})))}changes(){let e,t=new Set;return this.snapshots().pipe(a(this.documentIdentityService.observeChanges().pipe(_(t=>(Object.entries(t).forEach(([t,n])=>{!function(e,t,n){const i=e[t];void 0!==i&&(e[n]=i,delete e[t])}(e||{},t,n)}),n)),C({}))),ge(([n])=>{let i=[];const s=[],r=[];if(e){for(const r of n){const n=r.squidDocId,o=r.dataRef;if(t.has(o))delete e[n],t.delete(o);else if(e[n]){s.push(r);const i=e[n];delete e[n],t.delete(i)}else i.push(r)}for(const e of t)r.push(e)}else i=n;e={},t=new Set;for(const i of n){const n=i.dataRef;e[i.squidDocId]=n,t.add(n)}return new Rn(i,s,r)}))}dereference(){return new Dn(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new An(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService);return e.query=Zt(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){return e.length?(this.query.conditions.push({fields:e}),this):this}flipSortOrder(){return this.query.sortOrder=this.query.sortOrder.map(e=>({...e,asc:!e.asc})),this.query.limitBy&&(this.query.limitBy.reverseSort=!this.query.limitBy.reverseSort),this}serialize(){return{type:"simple",dereference:!1,query:this.build()}}extractData(e){return e.dataRef}paginate(e){return new _n(this,e)}mergeConditions(){const e=[],t=tn(this.query.conditions.filter(Cn)||[],e=>e.fieldName);for(const n of Object.values(t)){const t=tn(n,e=>e.operator);for(const[n,i]of Object.entries(t)){if("=="===n||"!="===n){e.push(...i);continue}const t=[...i];t.sort((e,t)=>en(e.value,t.value)),">"===n||">="===n?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!Cn(e)),...e]}}class Rn{constructor(e,t,n){this.inserts=e,this.updates=t,this.deletes=n}}class Nn extends qn{constructor(e,t,n,i,s,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=n,this.documentReferenceFactory=i,this.queryBuilderFactory=s,this.rootAlias=r,this.latestAlias=o,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,n){return this.queryBuilder.where(e,t,n),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}sortBy(e,t=!0){return this.queryBuilder.sortBy(e,t),this}join(e,t,n,i){const s=i?.leftAlias??this.latestAlias,r={...n,leftAlias:s,isInner:i?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[s].push(t),new Nn(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,t,o,{...this.joins,[t]:e.build()},{...this.joinConditions,[t]:r},this.queryBuilder)}snapshot(){return m(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new t([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,Zt(this.joins),Zt(this.joinConditions),e,!1).pipe(ge(e=>e.map(e=>{const t={};for(const[n,i]of Object.entries(e)){const e=n===this.rootAlias?this.collectionName:this.joins[n].collectionName,s=n===this.rootAlias?this.integrationId:this.joins[n].integrationId,r=i?Sn(i.__docId__,e,s):void 0;t[n]=r?this.documentReferenceFactory.create(r,this.queryBuilderFactory):void 0}return t})))}peek(){throw new Error("peek is not currently supported for join queries")}grouped(){return new jn(this)}dereference(){return new xn(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Nn(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,Zt(this.leftToRight),Zt(this.joins),Zt(this.joinConditions),this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e[this.rootAlias].dataRef}serialize(){return{type:"join",grouped:!1,dereference:!1,root:{alias:this.rootAlias,query:this.build()},leftToRight:this.leftToRight,joins:this.joins,joinConditions:this.joinConditions}}paginate(e){if(this.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new _n(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class xn{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(ge(e=>e.map(e=>function(e,t){const n={},i=Object.keys(e);for(const s of i){const i=e[s];n[s]=t(i)}return n}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new xn(this.joinQueryBuilder.clone())}addCompositeCondition(e){return this.joinQueryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.joinQueryBuilder.flipSortOrder(),this}limit(e){return this.joinQueryBuilder.limit(e),this}extractData(e){return e[this.joinQueryBuilder.rootAlias]}paginate(e){if(this.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new _n(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class Fn{constructor(e){this.groupedJoin=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(ge(e=>e.map(e=>this.dereference(e,this.groupedJoin.joinQueryBuilder.rootAlias))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.groupedJoin.getSortOrders()}clone(){return new Fn(this.groupedJoin.clone())}addCompositeCondition(e){return this.groupedJoin.addCompositeCondition(e),this}flipSortOrder(){return this.groupedJoin.flipSortOrder(),this}limit(e){return this.groupedJoin.limit(e),this}getLimit(){return this.groupedJoin.getLimit()}extractData(e){return e[this.groupedJoin.joinQueryBuilder.rootAlias]}serialize(){return{...this.groupedJoin.joinQueryBuilder.serialize(),dereference:!0,grouped:!0}}paginate(e){if(this.groupedJoin.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new _n(this,e)}dereference(e,t){const n=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(n.length){const i={[t]:e[t].data};for(const t of n)i[t]=e[t].map(e=>this.dereference(e,t));return i}return e.data}}class jn{constructor(e){this.joinQueryBuilder=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(ge(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new Fn(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new jn(this.joinQueryBuilder.clone())}addCompositeCondition(e){return this.joinQueryBuilder.addCompositeCondition(e),this}flipSortOrder(){return this.joinQueryBuilder.flipSortOrder(),this}limit(e){return this.joinQueryBuilder.limit(e),this}getLimit(){return this.joinQueryBuilder.getLimit()}extractData(e){return Object.keys(this.joinQueryBuilder.leftToRight).length>1?e[this.joinQueryBuilder.rootAlias].dataRef:e.dataRef}serialize(){return{...this.joinQueryBuilder.serialize(),grouped:!0}}paginate(e){if(this.joinQueryBuilder.hasIsInner())throw Error("Cannot paginate on joins when isInner is enabled.");return new _n(this,e)}groupData(e,t){const n=tn(e,e=>e[t]?.squidDocId);return Object.values(n).filter(e=>void 0!==e[0][t]).map(e=>{const n=this.joinQueryBuilder.leftToRight[t],i=e[0][t];if(0===n.length)return i;const s={[t]:i};for(const t of n)s[t]=this.groupData(e,t);return s})}}class Pn{constructor(e,t,n,i,s,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=n,this.queryBuilderFactory=i,this.querySubscriptionManager=s,this.dataManager=r,this.refId=we()}doc(e){if(e&&"string"!=typeof e&&"object"!=typeof e&&!Array.isArray(e))throw new Error("Invalid doc id. Can be only object or string.");if(this.integrationId!==Ct)if(e){if("object"!=typeof e)throw new Error("Invalid doc id. String doc ids are only supported for the built_in_db integration. For all other integrations, the doc id must be an object.")}else e={[vn]:we()};else e=e&&"string"!=typeof e?{__id:sn(e)}:{__id:e||we()};const t=Sn(sn(e),this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)}async insertMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const n of e)await this.doc(n.id).insert(n.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const n of e)n instanceof On?await n.delete(t):await this.doc(n).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new Nn(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new Bn(...e)}}class Bn{constructor(...e){if(0===e.length)throw new Error("At least one query builder must be provided");this.snapshotEmitters=e.map(e=>e.clone());const t=Math.max(...this.snapshotEmitters.map(e=>{const t=e.getLimit();return-1===t?1e3:t}));this.snapshotEmitters.forEach(e=>e.limit(t));const n=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==n.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<n.length;e++)if(t[e].fieldName!==n[e].fieldName||t[e].asc!==n[e].asc)throw new Error("All the queries must have the same sort order")}}snapshot(){return m(this.snapshots(!1))}snapshots(e=!0){const t=this.snapshotEmitters.map(t=>t.snapshots(e));return this.or(this.snapshotEmitters[0].getSortOrders(),...t)}peek(){throw new Error("peek is not currently supported for merged queries")}clone(){return new Bn(...this.snapshotEmitters.map(e=>e.clone()))}getSortOrders(){return this.snapshotEmitters[0].getSortOrders()}addCompositeCondition(e){for(const t of this.snapshotEmitters)t.addCompositeCondition(e);return this}limit(e){return this.snapshotEmitters.forEach(t=>t.limit(e)),this}getLimit(){return this.snapshotEmitters[0].getLimit()}flipSortOrder(){return this.snapshotEmitters.forEach(e=>e.flipSortOrder()),this}serialize(){return{type:"merged",queries:this.snapshotEmitters.map(e=>e.serialize())}}extractData(e){return this.snapshotEmitters[0].extractData(e)}paginate(e){return new _n(this,e)}or(e,...t){return o([...t]).pipe(v(t=>{const n=new Set,i=t.flat(),s=[];for(const e of i)n.has(this.extractData(e))||(n.add(this.extractData(e)),s.push(e));return s.sort((t,n)=>{for(const{fieldName:i,asc:s}of e){const e=Gt(this.extractData(t),i),r=Gt(this.extractData(n),i);if(!Mn(e,r,"=="))return Mn(r,e,"<")?s?-1:1:s?1:-1}return 0}).slice(0,this.getLimit())}))}}class Qn{constructor(e,t,n,i){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=n,this.dataManager=i,this.collections=new Map}get(e,t){let n=this.collections.get(t);n||(n=new Map,this.collections.set(t,n));let i=n.get(e);return i||(i=new Pn(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),n.set(e,i)),i}}class Ln{constructor(e,t){this.clientIdService=e,this.socketManager=t,this.isConnected=!1,this.socketManager.observeConnectionReady().subscribe(e=>{this.isConnected=e})}get connected(){return this.isConnected}get clientId(){return this.clientIdService.getClientId()}observeConnected(){return this.socketManager.observeConnectionReady()}}var Un=F(150);function $n(e,t){switch(t.type){case"applyNumericFn":return function(e,t){if("increment"===t.fn)return null==e?t.value:e+t.value;throw new Error("Unknown numeric function: "+JSON.stringify(t))}(e,t);case"applyStringFn":return function(e,t){switch(t.fn){case"trim":return"string"!=typeof e?e:e.trim();case"extendString":return null==e?t.value:e+t.value;default:throw new Error("Unknown string function: "+JSON.stringify(t))}}(e,t);case"update":return"object"==typeof t.value?Zt(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function Gn(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function Hn(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(me("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const n=Zt(e);t=Zt(t);for(const[e]of Gn(n)){const i=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&i>t.split(".").length)&&delete n.properties[e]}for(const[e,i]of Gn(t))n.properties[e]=Wn([...n.properties[e]||[],...i]);return n}(e,t);const n=Zt(e);for(const[e,i]of Gn(t)){const t=i;for(const i of t){const t=$n(Gt(n.properties,e),i);void 0===t?Vt(n.properties,e):Wt(n.properties,e,t)}}return n}function Wn(e){let t=0;for(;t+1<e.length;){const n=Vn(e[t],e[t+1]);n?e.splice(t,2,n):++t}return e}function Vn(e,t){return"removeProperty"===t.type||"update"===t.type?t:"applyNumericFn"===t.type?(me("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type?(me("increment"===e.fn,"Unrecognized applyNumericFn"),{type:"applyNumericFn",fn:"increment",value:e.value+t.value}):"update"===e.type?{type:"update",value:e.value+t.value}:t):"extendString"===t.fn?"update"===e.type?{type:"update",value:e.value+t.value}:"applyStringFn"===e.type?"trim"===e.fn?null:{type:"applyStringFn",fn:"extendString",value:e.value+t.value}:t:null}function Kn(e){const t={};for(const n of e){const e=`${n.squidDocIdObj.integrationId}/${n.squidDocIdObj.collectionName}/${n.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(n)}const n=[];for(const e in t){const i=t[e].reduce((e,t)=>be(Hn(e,t),"Merge result cannot be null"));n.push(i)}return n}const zn="dataManager_runInTransaction";class Jn{constructor(e,n,i,s,o,a,c,u,l){this.documentStore=e,this.mutationSender=n,this.socketManager=i,this.querySubscriptionManager=s,this.queryBuilderFactory=o,this.lockManager=a,this.destructManager=c,this.documentIdentityService=u,this.querySender=l,this.docIdToLocalTimestamp=new Map,this.batchClientRequestIds=new Set,this.docIdToServerTimestamp=new Map,this.pendingIncomingUpdates=new Map,this.pendingOutgoingMutations=new Map,this.pendingOutgoingMutationsChanged=new r,this.outgoingMutationsEmpty=new t(!0),this.knownDirtyDocs=new Set,this.failedDocsToResync=[],this.refreshDocIdToTimestamp=new Map,this.handleIncomingMessagesForTests=!0,this.destructManager.onDestruct(()=>{this.destruct()}),this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.handleNotifications(),this.startDeleteExpiredTimestampsJob(),this.handleOrphanDocs(),this.outgoingMutationsEmpty.subscribe(e=>{this.querySender.safeToSendQueriesToServer.next(e)})}getProperties(e){return this.documentStore.getDocumentOrUndefined(e)}isDirty(e){if(this.knownDirtyDocs.has(e))return!0;if(this.pendingOutgoingMutations.get(e)?.length)return!0;const t=this.docIdToServerTimestamp.get(e),n=t&&!t.expireTimestamp?t.timestamp:void 0,i=this.docIdToLocalTimestamp.get(e);return!((!i||n)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&i===n)}async runInTransaction(e,t){if(t)return me(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(zn)?this.lockManager.lockSync(zn):await this.lockManager.lock(zn);let n=Yn;const i=()=>n!==Yn;return new Promise(async(t,s)=>{try{let r;this.currentTransactionId=we();try{r=await e(this.currentTransactionId)}catch(e){n=e}finally{this.finishTransaction(i()?void 0:{resolve:()=>t(r),reject:s})}}catch(e){n=i()?n:e}finally{try{this.lockManager.release(zn)}catch(e){n=i()?n:e}}i()&&s(n)})}async applyOutgoingMutation(e,t){const n=Sn(e.squidDocIdObj);this.knownDirtyDocs.add(n),t||this.lockManager.canGetLock(zn)||(await this.lockManager.lock(zn),this.lockManager.release(zn)),this.knownDirtyDocs.delete(n);const i=this.pendingOutgoingMutations.get(n)?.slice(-1)[0];if(i&&!i.sentToServer)i.mutation=be(Kn([i.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},i=this.pendingOutgoingMutations.get(n)||[];i.push(t),this.pendingOutgoingMutations.set(n,i),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(n),i="delete"===e.type?void 0:"update"===e.type?function(e,t){if(!e)return;const n={...e},i=Gn(t);for(const[e,t]of i){const i=t;for(const t of i){const i=$n(Gt(n,e),t);void 0===i?Vt(n,e):Wt(n,e,i)}}return n}(t,e):{...e.properties};this.updateDocumentFromSnapshot(n,i)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(n,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(n,i).forEach(e=>this.batchClientRequestIds.add(e)))},t)}isTracked(e){if(this.pendingIncomingUpdates.get(e))return!0;const t=this.pendingOutgoingMutations.get(e);return!(!t||!t.length)||this.querySubscriptionManager.hasOngoingQueryForDocId(e)}isForgotten(e){return this.documentStore.hasData(e)&&!this.isTracked(e)}isLocalOnly(e){return!this.hasBeenAcknowledged(e)&&this.documentStore.hasData(e)}hasBeenAcknowledged(e){return this.docIdToServerTimestamp.has(e)}async runInTransactionSync(e,t){if(t)return me(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(zn);try{this.currentTransactionId=we();try{return e(this.currentTransactionId)}catch(e){console.error("error while executing callback function in transaction",e)}finally{this.finishTransaction()}}catch(e){console.error("error while executing transaction",e)}finally{this.lockManager.release(zn)}}removeInternalProperties(e){if("delete"===e.type)return e;const t={...e,properties:{...e.properties}};return delete t.properties.__docId__,delete t.properties.__ts__,t}handleNotifications(){this.socketManager.observeNotifications().pipe(g(e=>"mutations"===e.type),ge(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),E(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),E(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t=e.reduce((e,t)=>this.querySubscriptionManager.hasOngoingQuery(t.clientRequestId)?(e[t.squidDocId]={properties:t.doc,timestamp:t.mutationTimestamp},e):e,{});this.applyIncomingUpdates(t)}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId),n={};for(const i of e.docs){const e=Sn(i.__docId__,t.collectionName,t.integrationId);n[e]={properties:i,timestamp:i.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(n,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)})}applyIncomingUpdates(e,t){let n=!1;const i=new Set,s=new Set;for(const[t,r]of Object.entries(e)){const e=this.pendingIncomingUpdates.get(t),o=this.docIdToServerTimestamp.get(t);e&&e.timestamp>r.timestamp?n=!0:o&&o.timestamp>r.timestamp?s.add(t):(this.pendingIncomingUpdates.set(t,r),i.add(t))}return this.runInTransactionSync(()=>{for(const e of i)this.maybeApplyIncomingUpdate(e);for(const e of s)this.refreshQueryMapping(e)},t),n}maybeApplyIncomingUpdate(e){const t=this.pendingIncomingUpdates.get(e);if(!t)return;const n=this.pendingOutgoingMutations.get(e);n&&n.length||(this.updateDocumentFromSnapshot(e,t.properties),this.acknowledgeDocument(e,t.timestamp,!t.properties),this.docIdToLocalTimestamp.set(e,t.timestamp),this.pendingIncomingUpdates.delete(e),this.refreshQueryMapping(e))}refreshQueryMapping(e){const t=this.documentStore.getDocumentOrUndefined(e);this.querySubscriptionManager.setClientRequestIdsForLocalDoc(e,t).forEach(e=>{this.batchClientRequestIds.add(e)}),t&&(this.querySubscriptionManager.findQueriesForDocument(t,e).length||this.forgetDocument(e,!1))}destruct(){this.stopDeleteExpiredTimestampsJob()}stopDeleteExpiredTimestampsJob(){void 0!==this.deleteExpiredTimestampsInterval&&(clearInterval(this.deleteExpiredTimestampsInterval),this.deleteExpiredTimestampsInterval=void 0)}startDeleteExpiredTimestampsJob(){this.deleteExpiredTimestampsInterval=setInterval(()=>{const e=[...this.docIdToServerTimestamp.entries()].filter(([e,t])=>!(!t.expireTimestamp||t.expireTimestamp>Date.now()||this.isTracked(e)));for(const[t]of e)this.docIdToServerTimestamp.delete(t),this.forgetDocument(t,!0)},1e4)}updateDocumentFromSnapshot(e,t){const n=this.documentStore.getDocumentOrUndefined(e);return!(!n&&!t||n===t)&&((!n||!t||sn({...t,__ts__:void 0})!==sn(n))&&(this.documentStore.saveDocument(e,t),!0))}finishTransaction(e){this.currentTransactionId=void 0;const t=[...this.batchClientRequestIds.values()];this.batchClientRequestIds.clear(),this.querySubscriptionManager.notifyAllSubscriptions(t),this.sendAllUnsentOutgoingMutations(e)}async sendAllUnsentOutgoingMutations(e){const t=this.groupOutgoingMutationsByIntegrationId();try{await Un.PromisePool.for(t).withConcurrency(t.length||1).useCorrespondingResults().handleError(e=>{throw e}).process(async([e,t])=>{await this.sendMutationsForIntegration([...t],e)}),this.pendingOutgoingMutations.size||this.outgoingMutationsEmpty.next(!0),await this.refreshUpdatedDocuments(),this.hasPendingSentMutations()?(await m(this.pendingOutgoingMutationsChanged.pipe(g(()=>!this.hasPendingSentMutations()))),e?.resolve()):e?.resolve()}catch(t){this.pendingOutgoingMutations.size||(this.outgoingMutationsEmpty.next(!0),await this.resyncFailedUpdates()),e?.reject(t)}}async sendMutationsForIntegration(e,t){try{const{timestamp:n,idResolutionMap:i={},refreshList:s=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(i),s.forEach(e=>{this.refreshDocIdToTimestamp.set(i[e]||e,n)});for(const t of e){let e=this.removeOutgoingMutation(t);i[e]&&(e=i[e]),this.acknowledgeDocument(e,n),this.isTracked(e)||(this.setExpiration(e,!0),this.forgetDocument(e,!1))}}catch(t){for(const t of e){const e=this.removeOutgoingMutation(t);this.forgetDocument(e,!1),(this.hasBeenAcknowledged(e)||"insert"===t.mutation.type)&&this.failedDocsToResync.push(e)}throw t}}removeOutgoingMutation(e){const t=Sn(e.mutation.squidDocIdObj),n=be(this.pendingOutgoingMutations.get(t));return n.splice(n.indexOf(e),1),n.length||this.pendingOutgoingMutations.delete(t),this.pendingOutgoingMutationsChanged.next(),t}async resyncFailedUpdates(){const e=[...this.failedDocsToResync];this.failedDocsToResync.splice(0);for(const t of e){const{docId:e}=wn(t);this.setExpiration(t,!0);try{const n=e.includes(vn)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(be(n.length<=1,"Got more than one doc for the same id:"+t),!n.length){this.forgetDocument(t,!1);const e=this.querySubscriptionManager.setClientRequestIdsForLocalDoc(t,void 0);this.querySubscriptionManager.notifyAllSubscriptions(e)}}catch(e){this.querySubscriptionManager.errorOutAllQueries(t,e)}}}async refreshUpdatedDocuments(){const e=[];for(const[t,n]of this.refreshDocIdToTimestamp.entries()){const i=this.docIdToServerTimestamp.get(t)?.timestamp;i&&i>n||e.push(t)}this.refreshDocIdToTimestamp.clear(),await Promise.allSettled(e.map(e=>this.queryBuilderFactory.getForDocument(e).snapshot()))}groupOutgoingMutationsByIntegrationId(){const e={};for(const[,t]of[...this.pendingOutgoingMutations.entries()]){const n=t[t.length-1];if(n&&!n.sentToServer){const t=n.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(n),n.sentToServer=!0}}return Object.entries(e)}handleOrphanDocs(){this.querySubscriptionManager.onOrphanDocuments.subscribe(e=>{for(const t of e)this.isTracked(t)||this.forgetDocument(t,!1)})}acknowledgeDocument(e,t,n=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,n)}setExpiration(e,t){const n=this.docIdToServerTimestamp.get(e);n&&(n.expireTimestamp=t?Date.now()+2e4:void 0)}forgetDocument(e,t){this.docIdToLocalTimestamp.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const n=Sn(t.mutation.squidDocIdObj),i=e[n];i&&(t.mutation.squidDocIdObj=wn(i))})}),Object.entries(e).forEach(([e,t])=>{Kt(this.pendingOutgoingMutations,e,t),Kt(this.docIdToLocalTimestamp,e,t),Kt(this.docIdToServerTimestamp,e,t)})}hasPendingSentMutations(){for(const e of this.pendingOutgoingMutations.values())for(const t of e)if(t.sentToServer)return!0;return!1}}const Yn=Symbol("undefined");class Zn{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new t(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe(g(Boolean),ge(()=>{}))}onPreDestruct(e){this.preDestructors.push(e)}onDestruct(e){this.destructors.push(e)}async destruct(){this.reportDestructed();const e=this.preDestructors.concat(this.destructors);let t=e.shift();for(;t;){try{await t()}catch(e){console.error("Error while destructing Squid",e)}t=e.shift()}}reportDestructed(){this.isDestructing||this.isDestructedSubject.next(!0)}}class Xn{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe(g(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe(g(e=>"lockReleased"===e.type)),this.lockWaitForConnectionThreshold=2e3,t.onPreDestruct(()=>{this.releaseAllLocks()}),this.socketManager.observeConnectionReady().subscribe(e=>{e||this.releaseAllLocks()}),this.releaseLockMessagesFromServer.subscribe(e=>{const t=this.ongoingLocks[e.payload.lockId];t?.release()})}async lock(e,t){"number"==typeof t&&(t={acquisitionTimeoutMillis:t});const n=t?.acquisitionTimeoutMillis??2e3,i=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),me(await m(M(R(this.lockWaitForConnectionThreshold).pipe(ge(()=>!1)),this.socketManager.observeConnectionReady().pipe(g(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const s=we(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:n,maxHoldTimeMillis:i,clientRequestId:s}};this.socketManager.postMessage(r);const o=await m(M(R(n+4e3).pipe(E(1),ge(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:s}}))),this.acquireLockMessagesFromServer.pipe(g(e=>e.payload.clientRequestId===s)))),a=o.payload.lockId;me(!this.destructManager.isDestructing,"Squid client is in destructuring phase"),me(a,()=>`Failed to acquire lock: ${o.payload.error}`);const c=new ei(a,e,s,this.ongoingLocks,this.socketManager);return this.ongoingLocks[a]=c,c}releaseAllLocks(){for(const[e,t]of Object.entries(this.ongoingLocks))t.release(),delete this.ongoingLocks[e]}}class ei{constructor(e,t,n,i,s){this.lockId=e,this.resourceId=t,this.clientRequestId=n,this.ongoingLocks=i,this.socketManager=s,this.released=!1,this.onReleaseSubject=new r}async release(){if(this.released)return;this.released=!0,delete this.ongoingLocks[this.lockId];const e={type:"releaseLock",payload:{lockId:this.lockId,clientRequestId:this.clientRequestId}};try{await this.socketManager.sendMessage(e)}finally{this.onReleaseSubject.next(),this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}class ti{constructor(e,n){this.documentStore=e,this.destructManager=n,this.changeNotifier=new t({}),this.destructManager.onDestruct(()=>{this.changeNotifier.complete()})}migrate(e){Object.entries(e).forEach(([e,t])=>{this.documentStore.migrateDocId(e,t)}),this.changeNotifier.next(e)}observeChanges(){return this.changeNotifier.asObservable()}}class ni{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t){let n=this.documents.get(e);if(n)return n;n=new On(e,be(this.dataManager,"dataManager not found"),t);const{integrationId:i,collectionName:s}=wn(e);this.documents.set(e,n);const r=this.getCollectionKey(i,s),o=this.documentsForCollection.get(r)||[];return this.documentsForCollection.set(r,o.concat(n)),n}setDataManager(e){this.dataManager=e}getDocumentsForCollection(e,t){const n=this.getCollectionKey(e,t);return(this.documentsForCollection.get(n)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const n=wn(e),i=wn(t);Kt(this.documents,n.docId,i.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class ii{constructor(){this.squidDocIdToDoc=new Map}saveDocument(e,t){const n=this.squidDocIdToDoc.get(e);if(void 0===n&&!t)return;if(void 0!==n){if(t){const n=Zt(t),i=this.removeInternalProperties(n);return this.squidDocIdToDoc.set(e,i),i}return void this.squidDocIdToDoc.delete(e)}const i=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,i),t}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocument(e){return be(this.getDocumentOrUndefined(e))}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}group(e,t){return Object.values(tn(e,e=>sn(t.map(t=>Gt(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const n=[...e].map(e=>this.squidDocIdToDoc.get(e)).filter(fe),{sortOrder:i,limitBy:s}=t,r=n.sort((e,t)=>this.compareSquidDocs(e,t,i)),o=t.limit<0?2e3:t.limit;if(!s)return r.slice(0,o);const{limit:a,fields:c,reverseSort:u}=s,l=this.group(r,c);let h;return h=u?l.map(e=>e.slice(-a)):l.map(e=>e.slice(0,a)),h.flat().slice(0,o)}migrateDocId(e,t){const n=this.getDocumentOrUndefined(e);if(!n)return;Kt(this.squidDocIdToDoc,e,t);const i=wn(t),s=on(i.docId);this.saveDocument(t,{...n,...s,__docId__:i.docId})}compareSquidDocs(e,t,n){for(const{fieldName:i,asc:s}of n){const n=en(Gt(e,i),Gt(t,i));if(0!==n)return s?n:-n}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class si{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const n={authCode:e,externalAuthConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/saveAuthCode",n)}async getAccessToken(e){const t={externalAuthConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/getAccessToken",t)}}class ri{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const n={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",n,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const n={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",n)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class oi{constructor(e,t,n){this.socketManager=e,this.rpcManager=t,this.clientIdService=n,this.isListening=!1,this.listeners={},this.clientIdService.observeClientId().pipe(p(),T(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))yn.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e})})}async getJob(e){return(await this.rpcManager.post("job/getJob",{jobId:e})).job}async awaitJob(e){this.maybeListenToJobs(),await this.socketManager.awaitConnectionReady();const t=this.listeners[e]||new s(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}),m(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe(g(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,n=t.id,i=this.listeners[n];i&&("completed"===t.status?i.next(t.result):"failed"===t.status?i.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",n),delete this.listeners[n])}))}}class ai{constructor(e,t,n){this.rpcManager=e,this.lockManager=t,this.querySender=n}async sendMutations(e,t){const n=Kn(e),i=n.map(e=>`sendMutation_${Sn(e.squidDocIdObj)}`);await this.lockManager.lock(...i),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:n,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw yn.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(n,null,2)}),e}finally{this.lockManager.release(...i)}}}class ci{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class ui{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.observeNotifications().pipe(g(e=>"userNotification"===e.type),v(e=>e.payload))}async publishNotification(e,t){return await this.rpcManager.post("/notification/publishNotification",{clientIds:t,payload:e})}async publishSystemNotification(e,t){return await this.rpcManager.post("/notification/publishSystemNotification",{clientIds:t,payload:e})}}const li={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class hi{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},n=Object.keys(t).filter(e=>!di.test(e)||e.length>=pi);me(0===n.length,()=>`Tag name is not allowed: ${n.join(",")}`),this.isReporting=!0;const i={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},s=this.rpcManager.post("/observability/metrics",{metrics:[i]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==s),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(s)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...li,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const n=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:n,noDataBehavior:i}=e,s=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:n,pointIntervalAlignment:i}){if("align-by-start-time"===i)return e;const s=t-e;let r=t-Math.floor(s/n)*n;return r>e&&(r-=n),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:n,pointIntervalAlignment:i}){if("align-by-end-time"===i)return t-n;const s=t-e;let r=e+Math.floor(s/n)*n;return r>=t&&(r-=n),r}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const n=[];for(let t=0;t<e.groupByTags.length;t++){const i=e.groupByTags[t],s=a[i]?.[0]||"";n.push(s)}t.push({tagValues:n,points:[]})}else"return-result-group-with-default-values"===i&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[n,i]of Object.entries(a)){const s=e.groupByTags.indexOf(n);if(!(s<0))for(let e=0;e<t.length;e++){const n=t[e],r=new Set(i);for(let e=0;e<t.length;e++){const i=t[e];n.tagValues.every((e,t)=>t===s||e===i.tagValues[t])&&r.delete(i.tagValues[s])}if(0!==r.size)for(const e of r){const i={tagValues:[...n.tagValues],points:[]};i.tagValues[s]=e,t.push(i)}}}for(const i of t){if(0!==i.points.length){const e=i.points[0][0],t=i.points[i.points.length-1][0];me(e>=r,()=>`Invalid first point time: ${e}`),me(t<=o,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:s,u=Array.isArray(e.fn)?e.fn.map(c):[s];for(let e=r;e<=o;e+=n){const n=i.points[a];n?n[0]===e?(t.push(n),a++):(me(n[0]>e,()=>`Result point has invalid time: ${n[0]}`),t.push([e,...u])):t.push([e,...u])}i.points=t}}(t,n.resultGroups),n}}const di=/^[a-zA-Z0-9_-]+$/,pi=1e3;async function gi(e,t,n=500){const i=Date.now(),s=e.paginate({pageSize:n,subscribe:!1});let r=0,o=await s.waitForData();for(;;){for(const e of o.data)r++,await t(e.data);if(!o.hasNext)break;o=await s.next()}return{count:r,time:Date.now()-i}}function fi(e,t){switch(t.type){case"simple":return function(e,t){const{query:n,dereference:i}=t,{collectionName:s,integrationId:r}=n;let o=e.collection(s,r).query();return o=yi(o,n),i?o.dereference():o}(e,t);case"join":return function(e,t){const{root:n,joins:i,joinConditions:s,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=n.query;let u=e.collection(a,c).joinQuery(n.alias);return u=yi(u,n.query),Object.entries(i).map(([t,n])=>{const{collectionName:i,integrationId:r}=n,{left:o,right:a,leftAlias:c}=s[t];let l=e.collection(i,r).query();l=yi(l,n),u=u.join(l,t,{left:o,right:a},{leftAlias:c})}),r&&o?u.grouped().dereference():r?u.dereference():o?u.grouped():u}(e,t);case"merged":return function(e,t){const{queries:n}=t,{collectionName:i,integrationId:s}=mi(n[0]),r=n.map(t=>fi(e,t));return e.collection(i,s).or(...r)}(e,t)}}function yi(e,t){const{conditions:n,limit:i,sortOrder:s}=t;for(const t of n){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:n,operator:i,value:s}=t;e.where(n,i,s)}e.limit(i);for(const{fieldName:t,asc:n}of s)e.sortBy(t,n);return e}function mi(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:n}=e.query;return{collectionName:t,integrationId:n}}case"join":{const{collectionName:t,integrationId:n}=e.root.query;return{collectionName:t,integrationId:n}}case"merged":return mi(e.queries[0])}}const bi={"in:in":(e,t)=>e.every(e=>t.includes(e)),"in:not in":(e,t)=>e.every(e=>!t.includes(e)),"not in:not in":(e,t)=>t.every(t=>e.includes(t)),">:not in":(e,t)=>t.every(t=>e>=t),">=:not in":(e,t)=>t.every(t=>e>t),"<:not in":(e,t)=>t.every(t=>e<=t),"<=:not in":(e,t)=>t.every(t=>e<t),">:>":(e,t)=>e>=t,">=:>":(e,t)=>e>t,"in:>":(e,t)=>e.every(e=>e>t),">:>=":(e,t)=>e>=t,">=:>=":(e,t)=>e>=t,"in:>=":(e,t)=>e.every(e=>e>=t),"<:<":(e,t)=>e<=t,"<=:<":(e,t)=>e<t,"in:<":(e,t)=>e.every(e=>e<t),"<:<=":(e,t)=>e<=t,"<=:<=":(e,t)=>e<=t,"in:<=":(e,t)=>e.every(e=>e<=t),"like:like":(e,t)=>Ii(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Ii(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Ii(e,t)&&wi(t),"like_cs:like_cs":(e,t)=>Ii(e,t),"like:not like":(e,t)=>!vi(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!vi(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!vi(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!vi(e,t),"not like:like":(e,t)=>Mi(e,t),"not like_cs:like":(e,t)=>Mi(e,t),"not like:like_cs":(e,t)=>Mi(e,t),"not like_cs:like_cs":(e,t)=>Mi(e,t),"not like:not like":(e,t)=>Ii(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Ii(t,e)&&wi(e),"not like:not like_cs":(e,t)=>Ii(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Ii(t,e),"in:like":(e,t)=>e.every(e=>Mn(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Mn(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>Mn(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>Mn(t,e,"not like_cs")),"like:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&!!t.find(t=>t.toLowerCase()===e.toLowerCase()),"like_cs:in":(e,t)=>!e.includes("%")&&!e.includes("_")&&t.includes(e),"not like:in":(e,t)=>e.length>0&&Si(e)||ki(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Si(e)||ki(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Si(t)||ki(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Si(t)||ki(t)&&e.includes(""),"not in:not like":(e,t)=>!t.includes("%")&&!t.includes("_")&&!!e.find(e=>e.toLowerCase()===t.toLowerCase()),"not in:not like_cs":(e,t)=>!t.includes("%")&&!t.includes("_")&&e.includes(t),"like:not in":(e,t)=>t.every(t=>Mn(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Mn(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Mn(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Mn(e,t,"like_cs")),"array_includes_some:array_includes_some":(e,t)=>e.every(e=>t.includes(e)),"array_includes_all:array_includes_all":(e,t)=>e.every(e=>t.includes(e)),"array_not_includes:array_not_includes":(e,t)=>t.every(t=>e.includes(t)),"array_includes_some:array_not_includes":(e,t)=>e.every(e=>!t.includes(e)),"array_not_includes:array_includes_some":(e,t)=>t.every(t=>!e.includes(t)),"array_includes_all:array_includes_some":(e,t)=>e.every(e=>t.includes(e)),"array_includes_some:array_includes_all":(e,t)=>e.every(e=>t.includes(e)),"array_not_includes:array_includes_all":(e,t)=>t.every(t=>!e.includes(t)),"array_includes_all:array_not_includes":(e,t)=>e.every(e=>!t.includes(e))};function Ii(e,t,n=0,i=0){if(i>=t.length)return n>=e.length;if(n>=e.length)return Si(t.substring(i));const s=e[n],r=t[i];return"%"===s&&"%"===r?Ii(e,t,n+1,i+1)||Ii(e,t,n+1,i):"%"!==s&&("%"===r?Ii(e,t,n,i+1)||Ii(e,t,n+1,i):(s===r||"_"===r)&&Ii(e,t,n+1,i+1))}function vi(e,t,n=0,i=0){if(n>=e.length&&i>=t.length)return!0;if(n>=e.length)return Si(t.substring(i));if(i>=t.length)return Si(e.substring(n));const s=n<e.length?e[n]:"",r=i<t.length?t[i]:"";return"%"===s&&"%"===r?vi(e,t,n+1,i+1)||vi(e,t,n,i+1)||vi(e,t,n+1,i):"%"===s||"%"===r?vi(e,t,n,i+1)||vi(e,t,n+1,i):(s===r||"_"===s||"_"===r)&&vi(e,t,n+1,i+1)}function wi(e){return!/[a-zA-Z]/.test(e)}function Si(e){return e.split("").every(e=>"%"===e)}function Mi(e,t){return e.length>0&&Si(e)||t.length>0&&Si(t)||ki(e)&&0===t.length}function ki(e){let t=!1,n=!1;for(const i of e)switch(i){case"%":t=!0;break;case"_":if(n)return!1;n=!0;break;default:return!1}return t&&n}class Ti{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Cn))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){return!e.find((e,t)=>!Jt(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,n){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:n})}isSubqueryOfCondition(e){return!!this.parsedConditions.filter(t=>t.fieldName===e.fieldName).find(t=>this.evaluateSubset(t,e))}isSubqueryOfConditions(e){return this.parseConditions(e).every(e=>this.isSubqueryOfCondition(e))}isSubqueryOfQuery(e){if(e.collectionName!==this.collectionName||e.integrationId!==this.integrationId)return!1;const t=e.conditions.filter(Cn),n=this.isSubqueryOfConditions(t),i=this.sortedBy(e.sortOrder),s=-1===e.limit||this.limit>-1&&this.limit<e.limit;return n&&i&&s}getConditionsFor(...e){return this.parsedConditions.filter(t=>e.includes(t.fieldName))}getConditionsForField(e){return this.parsedConditions.filter(t=>t.fieldName===e)}documentMatchesQuery(e){for(const t of this.parsedConditions){const n=t.fieldName,i=t.operator,s=Gt(e,n);if("in"===i){if(t.value.includes(s))continue;return!1}if("not in"!==i){if(!Mn(t.value,s,i))return!1}else if(t.value.includes(s))return!1}return!0}evaluateSubset(e,t){const{operator:n,value:i}=e,{operator:s,value:r}=this.parseConditions([t])[0],o=bi[`${n}:${s}`];return!!o&&o(i,r)}parseConditions(e){const t=[],n=new Map,i=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":i.set(e.fieldName,(i.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),n.forEach((e,n)=>{t.push({fieldName:n,operator:"in",value:e})}),i.forEach((e,n)=>{t.push({fieldName:n,operator:"not in",value:e})}),t}}class Ci{constructor(e,t,n){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=n}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:n}=e,i=new Ti(e),s=this.documentReferenceFactory.getDocumentsForCollection(t,n).filter(e=>i.documentMatchesQuery(e.data)),r={};return s.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[Sn(e.__docId__,n,t)])}}function Oi(e,t){return H(function(n,i){var s=0;n.subscribe(de(i,function(n){return e.call(t,n,s++)&&i.next(n)}))})}class _i{constructor(e,n){this.rpcManager=e,this.destructManager=n,this.safeToSendQueriesToServer=new t(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new t(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new r,n=m(t);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:t}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),n):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.safeToSendQueriesToServer.pipe(Oi(Boolean),E(1)).subscribe(()=>{this.processQueryBatch()})},0),n)}async waitForAllQueriesToFinish(){return m(this.inflightQueriesCount.pipe(Oi(e=>0===e))).then(()=>{})}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=Array.from(e.map(({queryRequest:e})=>e).reduce((e,t)=>(e.set(t.clientRequestId,t),e),new Map).values()),n=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const n=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:i}of e){const e=t.clientRequestId,s=n.errors[e],r=n.results[e];s?i.error(s):i.next(r)}}catch(e){n.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Ei={d:(e,t)=>{for(var n in t)Ei.o(t,n)&&!Ei.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function qi(e,t,...n){e||function(e,...t){const n=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof n)throw n;throw(e=>new Error(e))(n||"Assertion error",...t)}(t,...n)}function Di(e,t){switch(t.type){case"set":return function(e,t,n){if(void 0===n)return Ai(e,t);if(0===t.length)return qi("object"==typeof n&&null!==n&&!Array.isArray(n),()=>`Root state must be a record. Trying to set '${n}', type: ${typeof n}`),n;function i(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let s=e;for(let e=0;e<t.length-1&&void 0!==s;e++){const n=t[e];qi(!Array.isArray(s)||i(n),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${n}'`),s=s[n],qi(void 0===s||"object"==typeof s&&null!==s,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===s?"<null>":typeof s}'`)}const r=t[t.length-1];return qi(!Array.isArray(s)||i(r),()=>`Invalid array index Path: '${t}`),(null==s?void 0:s[r])===n?e:Ri(e,t,n)}(e,t.path,t.value);case"delete":return Ai(e,t.path);case"batch":return t.actions.reduce((e,t)=>Di(e,t),e)}}function Ai(e,t){qi(0!==t.length,"Can't delete an empty path");let n=e;for(let i=0;i<t.length-1;i++){const s=t[i];if(n=n[s],void 0===n)return e;qi("object"==typeof n&&null!==n,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,i+1)}', type: ${null===n?"<null>":typeof n}`)}const i=t[t.length-1];return void 0===n[i]?e:Ri(e,t,void 0)}function Ri(e,t,n){function i(e,n){qi(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[n]}const s=Object.assign({},e);let r=s;for(let e=0;e<t.length-1;e++){const s=t[e],o=r[s];qi(void 0===o||"object"==typeof o&&null!==o,()=>`Internal error: sub-path has an invalid type and can't be patched: '${t.slice(0,e+1)}', type: '${null===o?null:typeof o}'`);const a=void 0===o?void 0===n?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return i(r,s),r;r[s]=a,r=a}const o=t[t.length-1];return void 0===n?i(r,o):r[o]=n,s}function Ni(e,t){const n=[];if("set"===e.type||"delete"===e.type)n.push(e.path);else if("batch"===e.type)for(const t of e.actions)n.push(...Ni(t,"as-is"));return"unique-and-sorted"===t?ji(n):n}function xi(e,t){if(e.length<t.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function Fi(e){const t=[...e];return t.sort((e,t)=>{for(let n=0;n<e.length;n++){if(n===t.length)return 1;const i=e[n].localeCompare(t[n]);if(0!==i)return i}return e.length-t.length}),t}function ji(e){const t=Fi(e),n=t;for(let e=0;e<t.length-1;e++){const i=t[e];for(let s=e+1;s<t.length;s++){const r=t[s];i.length===r.length&&xi(i,r)&&(n[s]=void 0,e++)}}return n.filter(e=>void 0!==e)}const Pi=(Bi={Observable:()=>i,Subject:()=>r},Qi={},Ei.d(Qi,Bi),Qi);var Bi,Qi;const Li=(Ui={filter:()=>Oi,map:()=>ge},$i={},Ei.d($i,Ui),$i);var Ui,$i,Gi;class Hi{constructor(){this.root={children:new Map,childrenWithValue:0}}get(e){var t;return null===(t=this.getNode(e))||void 0===t?void 0:t.value}getOrSet(e,t){const n=this._buildPath(e);if(void 0!==n.value)return n.value;const i=t(e);return this._setNodeValue(n,i,void 0===i),i}set(e,t){const n=void 0===t?this._findNode(e):this._buildPath(e);n&&this._setNodeValue(n,t,!0)}delete(e){const t=this._findNode(e);if(void 0===t)return;if(void 0===t.parent){if(t!==this.root)throw new Error("Only root node can have no parent.");return this.root.value=void 0,this.root.children.clear(),void(this.root.childrenWithValue=0)}const n=(void 0===t.value?0:1)+t.childrenWithValue;n>0&&this._updateChildrenWithValue(t,-n),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const n=this.getNode(e);return void 0===n?0:n.childrenWithValue+("node-and-children"===t&&void 0!==n.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const n=[];let i=this.root,s=t(i.value,n);if(s!==Hi.StopFillToken){this._setNodeValue(i,s,!1);for(let r=0;r<e.length;r++){const o=e[r];n.push(o);let a=i.children.get(o);if(s=t(null==a?void 0:a.value,n),s===Hi.StopFillToken)break;a||(a={children:new Map,parent:i,childrenWithValue:0},i.children.set(o,a)),this._setNodeValue(a,s,!1),i=a}this._runGc(i)}}visitDfs(e,t,n=[]){const i=this.getNode(n);void 0!==i&&this._visitDfs(e,i,t,[...n])}_visitDfs(e,t,n,i){if("pre-order"===e&&!1===n(t.value,i))return!1;for(const[s,r]of t.children){if(i.push(s),!this._visitDfs(e,r,n,i))return!1;i.pop()}return"in-order"!==e||!1!==n(t.value,i)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const n of e)if(t=t.children.get(n),!t)return;return t}_findNode(e){let t=this.root;for(let n=0;n<e.length&&t;n++)t=t.children.get(e[n]);return t}_buildPath(e){let t=this.root;for(let n=0;n<e.length;n++){const i=e[n];let s=t.children.get(i);s||(s={children:new Map,parent:t,childrenWithValue:0},t.children.set(i,s)),t=s}return t}_setNodeValue(e,t,n){if(e.value!==t){const n=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,n)}n&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let n=e.parent;n;n=n.parent)if(n.childrenWithValue+=t,n.childrenWithValue<0)throw new Error("Internal error: negative counter value!")}_runGc(e){void 0===e.value&&(0===e.childrenWithValue&&e.children.clear(),e.parent&&this._runGc(e.parent))}}Hi.StopFillToken=Symbol("Trie.StopFillToken");class Wi extends Pi.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class Vi{constructor(e){this.rootState=e,this.observersTrie=new Hi,this.batchDepth=0,this.appliedBatchActions=[],this.rootStateBeforeBatchStart=this.rootState,this.stubForUnusedPaths=[]}get state(){return this.rootState}get state$(){return this.observe([])}get(e){return this._get(this.rootState,e)}observe(e,t=[]){return this._observeChanges(e,t,"new-value-only").pipe((0,Li.map)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,n){(null==n?void 0:n(this.get(e),t,e))||this._apply({type:"set",path:e,value:t})}delete(e){this._apply({type:"delete",path:e})}reset(e){this.observersTrie.visitDfs("pre-order",e=>null==e?void 0:e.complete()),this.observersTrie.delete([]),this.rootState=e}runInBatch(e){this.batchDepth++;try{e()}finally{if(this.batchDepth--,0===this.batchDepth&&this.appliedBatchActions.length>0){const e={type:"batch",actions:this.appliedBatchActions};this.appliedBatchActions=[],this._notify(e)}}}_apply(e){0===this.batchDepth&&(this.rootStateBeforeBatchStart=this.rootState),this.rootState=Di(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Ni(e,"unique-and-sorted"),n=this.selectChildPathsWithObservers(t),i=ji([...t,...n]),s=new Hi;for(const e of i)s.fillPath(e,()=>!0);s.visitDfs("pre-order",(t,n)=>{const i=this.observersTrie.get(n);if(i){const t=this.get(n),s=i.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,n):void 0;i.next({action:e,value:t,oldValue:s})}})}_observeChanges(e,t=[],n){const i=0===t.length?void 0:new Hi;for(const e of t)null==i||i.set(e,!0);return new Pi.Observable(t=>{const s=this.observersTrie.getOrSet(e,()=>new Wi);s.isAllDetailsMode=s.isAllDetailsMode||"all-details"===n;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=s.pipe((0,Li.filter)(({action:e})=>void 0===i||Ni(e,"as-is").some(e=>!i.get(e))),(0,Li.map)(({action:t,value:n,oldValue:i})=>{let r=this.stubForUnusedPaths;if(s.isAllDetailsMode){const n=Ni(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=Fi(e),n=t;for(let e=0;e<n.length-1;e++){const i=t[e];for(let s=e+1;s<t.length;s++)xi(t[s],i)&&(n[s]=void 0,e++)}return n.filter(e=>void 0!==e)}(e.length>0?n.filter(t=>xi(t,e)).map(t=>t.slice(e.length)):n)}return{value:n,oldValue:i,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),s.observed||this.observersTrie.delete(e)}})}_get(e,t){let n=e;for(let e=0;e<t.length&&void 0!==n;e++){const i=t[e];n=null==n?void 0:n[i]}return n}selectChildPathsWithObservers(e){const t=[];for(const n of e)this.observersTrie.count(n,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,n)=>{e&&t.push([...n])},n);return t}}function Ki(e,t,n=(e,t)=>e>t?1:e<t?-1:0,i=0,s=e.length-1){if(s<i)return-1;const r=Math.trunc((i+s)/2);return 0===n(t,e[r])?r:n(t,e[r])>0?Ki(e,t,n,r+1,s):Ki(e,t,n,i,r-1)}function zi(e,t,n=(e,t)=>e>t?1:e<t?-1:0){if(-1!==Ki(e,t,n))return;let i;for(i=e.length-1;i>=0&&n(e[i],t)>0;i--)e[i+1]=e[i];e[i+1]=t}function Ji(e,t,n=(e,t)=>e>t?1:e<t?-1:0){const i=Ki(e,t,n);i>-1&&e.splice(i,1)}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Gi||(Gi={}));const Yi=100;class Zi{constructor(e,t,n,i,s,o,a){this.rpcManager=e,this.clientIdService=t,this.documentStore=n,this.destructManager=i,this.documentIdentityService=s,this.querySender=o,this.socketManager=a,this.onOrphanDocuments=new r,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new es,this.queryResultsSubject=new r,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe(()=>{this.refreshOngoingQueries()}),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}dumpSubscriptionInfo(){console.log("Ongoing queries:",this.ongoingQueries),console.log("ClientRequestId to local documents:",this.clientRequestIdToLocalDocuments),console.log("Local documents to clientRequestId:",this.localDocumentToClientRequestIds)}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return be(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);t?.gotInitialResponse&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:n,integrationId:i}=wn(t),s=this.queryMappingManager.getMapping(n,i);return s?function(e,t){const n=[...e.unconditional||[]],i=new Map;for(const[n,s]of Object.entries(e.conditional||{})){const e=on(n);let r;if(Cn(e)){const n=Gt(t,e.fieldName)??null;r=Mn(e.value,n,e.operator)}else r=Xi(e,t);if(r)for(const e of s)i.set(e,(i.get(e)||0)+1)}for(const[t,s]of i.entries())s>=e.queriesMetadata[t].condCount&&n.push(t);return n}(s,e):[]}setClientRequestIdsForLocalDoc(e,t){const n=this.localDocumentToClientRequestIds.get(e)||new Set,i=new Set(t?this.findQueriesForDocument(t,e).map(e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId):[]),s=new Set([...n,...i]);for(const t of[...n]){if(i.has(t))continue;n.delete(t);const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),n.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of i){let n=this.localDocumentToClientRequestIds.get(e);n||(n=new Set,this.localDocumentToClientRequestIds.set(e,n)),n.add(t);let i=this.clientRequestIdToLocalDocuments.get(t);i||(i=new Set,this.clientRequestIdToLocalDocuments.set(t,i)),i.add(e)}return[...s]}errorOutAllQueries(e,t){const n=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of n){const n=this.ongoingQueries.get(e);n&&(this.destructManager.isDestructing?n.dataSubject.complete():n.dataSubject.error(t),n.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const n of e){const e=this.ongoingQueries.get(n);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const i=this.clientRequestIdToLocalDocuments.get(n)||new Set,s=this.documentStore.sortAndLimitDocs(i,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(s,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=be(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case Gi.UNKNOWN:e.limitUnderflowState=i.size===e.query.limit+100?Gi.ENABLED:Gi.DISABLED;break;case Gi.DISABLED:break;case Gi.ENABLED:if(i.size<e.query.limit+20){e.limitUnderflowState=Gi.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(s)}for(const e of t){const t=this.collectAllObservables(e);be(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new Ti(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,n,i,r,a){return r&&this.socketManager.notifyWebSocketIsNeeded(),h(()=>{const c=this.createOngoingQueryGraph(e,t,n,i,r,!0);a&&(c.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(c),c.allObservables=new s(1);const u=c.allObservables.pipe(_(e=>o(e).pipe(ge(e=>this.joinResults(e,i,c)))),Oi(()=>this.allOngoingQueriesGotInitialResult(c)),C(void 0),S(),Oi(([e,t])=>!Jt(e,t)),ge(([,e])=>e),r?A():E(1),f(()=>{c.dataSubject.complete(),c.done=!0,this.completeAllSupportedQueries(c),c.allObservables?.complete()})),l=this.collectAllObservables(c);return c.allObservables.next(l),u}).pipe(k())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}unsubscribe(){const e=[...this.ongoingQueries.values()];for(const t of e)t.dataSubject.complete(),t.allObservables?.complete()}hasSubscription(e){return!!this.ongoingQueries.get(e)?.subscribe}isValidParent(e){if(!e.activated||e.isInFlight||e.isEmptyForJoin||e.done||!e.subscribe||!e.gotInitialResponse||!e.dataSubject.value)return!1;const t=-1===e.query.limit?1e3:e.query.limit;return e.dataSubject.value.length<t}findValidParentOfOngoingQuery(e){if(e.forceFetchFromServer)return;const t=new Ti(e.query);for(const n of this.ongoingQueries.values()){if(e===n)return;if(this.isValidParent(n)&&t.isSubqueryOfQuery(n.query))return n}}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const n=[];for(const i of t){const t=be(this.localDocumentToClientRequestIds.get(i));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(i),n.push(i))}n.length&&this.onOrphanDocuments.next(n)}registerQueryFinalizer(e){const t=e.clientRequestId,n=Tn(this.clientIdService.getClientId(),t);e.dataSubject.pipe(f(async()=>{if(e.unsubscribeBlockerCount.value>0&&await m(M(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Oi(e=>0===e)))),this.queryMappingManager.removeQuery(n),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const n={clientRequestId:t};this.rpcManager.post("query/unsubscribe",n).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)}),Oi(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,n,i,s,r,o,a={}){if(a[n])return a[n];const c=this.clientIdService.generateClientRequestId(),u=[],l={clientRequestId:c,activated:o,alias:n,query:e,subscribe:r,dataSubject:new t(null),supportedQueries:u,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new t(0),queryRegistered:new t(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:r?Gi.UNKNOWN:Gi.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(c,l),a[n]=l;for(const[e,t]of Object.entries(s)){const o=t.leftAlias;if(o!==n&&e!==n)continue;const c=o===n?e:o;if(o===n){const e=this.createOngoingQueryGraph(i[c],c,i,s,r,!1,a);e.joinCondition=t,u.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(i[c],c,i,s,r,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const n=e.alias;t.push(e.dataSubject.pipe(Oi(Boolean),ge(e=>({docs:e,alias:n}))));for(const n of e.supportedQueries)this.collectAllObservables(n,t);return t}joinResults(e,t,n){const i=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let s=i[n.alias].map(e=>({[n.alias]:e}));const r=this.getOngoingQueriesBfs(n),o=new Set;for(let e=1;e<r.length;e++){const n=r[e].alias;o.has(n)||(o.add(n),s=this.join(s,n,i[n],t[n]))}return s}join(e,t,n,i){if(!e.length)return e;const s=Object.keys(e[0]);if(!i||!s.includes(i.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(n||[]).forEach(e=>{const t=this.transformKey(e[i.right]);r.has(t)||r.set(t,[]),be(r.get(t)).push(e)}),e.flatMap(e=>{const n=r.get(this.transformKey(e[i.leftAlias]?.[i.left]))||[];return n.length?n.map(n=>({...e,[t]:n})):i.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],n=[e];for(;n.length;){const e=be(n.shift());e.isEmptyForJoin||(t.push(e),n.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,n){const i=be(n.joinCondition),s=n.query;if(n.activated){if(!n.canExpandForJoin)return!1;const r=be(n.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===n.alias),o=new Set(e.map(e=>e[i.left]??null));for(const e of r)e.query.conditions.filter(Cn).filter(e=>e.fieldName===i.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const a=Zt(s);a.conditions=a.conditions.filter(e=>!Cn(e)||e.fieldName!==i.right),[...o].forEach(e=>{a.conditions.push({fieldName:i.right,operator:"==",value:e})});const c={...n,query:a,activated:!0,gotInitialResponse:!1,dataSubject:new t(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),be(n.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(n.activated=!0,s.conditions.filter(Cn).filter(e=>e.fieldName===i.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(n),n.canExpandForJoin=!1,!0;const t=e.map(e=>e[i.left]??null).map(e=>({fieldName:i.right,operator:"==",value:e}));return t.length?(s.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(n)):n.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every(e=>this.allOngoingQueriesGotInitialResult(e)))}async completeAllSupportedQueries(e){const t=[...e.supportedQueries||[]];for(;t.length;){const e=be(t.shift());t.push(...e.supportedQueries||[]),await m(e.unsubscribeBlockerCount.pipe(Oi(e=>0===e))),e.dataSubject.complete()}}transformKey(e){return e instanceof Date?`DATE AS string KEY: ${e.toISOString()}`:e}preDestruct(){this.unsubscribe()}sendQueryToServerOrUseParentQuery(e,t=!1){if(this.destructManager.isDestructing)return;const n=e.query,i=e.clientRequestId,s=Tn(this.clientIdService.getClientId(),i);this.queryMappingManager.addQuery(n,s),this.ongoingQueries.set(i,e);const r=t?void 0:this.findValidParentOfOngoingQuery(e);r?this.useParentOngoingQuery(e,r):this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const n={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},i=new Ti(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await m(t.queryRegistered.pipe(Oi(Boolean)))}catch(t){return this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(e.dataSubject.error(t),e.queryRegistered.error(t)),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",n).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(n=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,n),e.dataSubject.error(n)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const s=M(e.queryRegistered.pipe(Oi(Boolean),d(2e3),E(1)),this.destructManager.observeIsDestructing().pipe(E(1)));t.dataSubject.pipe(D(()=>!e.done),q(s),Oi(Boolean),A(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),ge(e=>e.filter(e=>i.documentMatchesQuery(e)))).subscribe({next:t=>{for(const n of t)this.setClientRequestIdsForLocalDoc(Sn(n.__docId__,e.query.collectionName,e.query.integrationId),n);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,n=t>0&&e.subscribe?t+100:t,i={query:{...e.query,limit:n},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(i).then(t=>{e.isInFlight=!1,e.queryRegistered.next(!0),this.queryResultsSubject.next(t)}).catch(t=>{e.isInFlight=!1,this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(yn.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0})}refreshOngoingQueries(){for(const e of this.ongoingQueries.values())this.sendQueryToServerOrUseParentQuery(e,!0)}migrateDocIds(e){const t=Object.keys(e);for(const n of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{n.has(t)&&(n.delete(t),n.add(e[t]))});t.forEach(t=>{Kt(this.localDocumentToClientRequestIds,t,e[t])})}}function Xi(e,t){for(const n of e.fields){const e=Gt(t,n.fieldName)??null;if(Mn(n.value,e,n.operator))return!0;if(Mn(n.value,e,"!="))return!1}return!1}class es{constructor(){this.stateService=new Vi({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let n=0;const i=new Set;for(const s of e.conditions){if(Cn(s)&&["=="].includes(s.operator)){const e=an(s.fieldName);i.has(e)||(n++,i.add(e))}else n++;const r=this.getConditionStatePath(e,s),o=[...this.stateService.get(r)||[]];zi(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const n=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],i=[...this.stateService.get(n)||[]];zi(i,t),this.stateService.set(n,i)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],n)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const n of t.conditions){const i=this.getConditionStatePath(t,n),s=[...this.stateService.get(i)||[]];Ji(s,e),s.length?this.stateService.set(i,s):this.stateService.delete(i)}if(!t.conditions.length){const n=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],i=[...this.stateService.get(n)||[]];Ji(i,e),this.stateService.set(n,i)}this.stateService.delete(this.getQueryMetadataStatePath(t,e))}),t}getMapping(e,t){return this.stateService.get(["queryMapping",e,t,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",(n=t,sn(n))];var n}}class ts{constructor(){this.locks={}}async lock(...e){if(this.canGetLock(...e))return void this.lockSync(...e);const t=Object.entries(this.locks).filter(([t])=>e.includes(t)).map(([,e])=>e);await I(o(t).pipe(g(e=>!e.includes(!0)),E(1))),await this.lock(...e)}release(...e){for(const t of e){const e=be(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){me(this.canGetLock(...e),"Cannot acquire lock sync");for(const n of e)this.locks[n]=new t(!0)}}class ns{constructor(e,t,n){this.rpcManager=e,this.socketManager=t,this.queueManagers=new Map,this.socketManager.observeNotifications().subscribe(e=>{const t=this.getOrUndefined(e.integrationId,e.topicName);t&&t.onMessages(e.payload)}),n.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let n=this.queueManagers.get(e);n||(n=new Map,this.queueManagers.set(e,n));let i=n.get(t);return i||(i=new ss(e,t,this.rpcManager,this.socketManager),n.set(t,i)),i}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const is="subscriptionMutex";class ss{constructor(e,t,n,i){this.integrationId=e,this.topicName=t,this.rpcManager=n,this.socketManager=i,this.messagesSubject=new r,this.subscriberCount=0,this.lockManager=new ts}async produce(e){await this.lockManager.lock(is);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(is)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),h(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe(f(()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}async performSubscribe(){await this.lockManager.lock(is);try{await this.rpcManager.post("queue/subscribe",{integrationId:this.integrationId,topicName:this.topicName})}catch(e){this.messagesSubject.error(e),this.messagesSubject.complete(),this.subscriberCount=0,this.messagesSubject=new r}finally{this.lockManager.release(is)}}async performUnsubscribe(){await this.lockManager.lock(is);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(is)}}}class rs{constructor(e,t){this.capacity=e,this.seconds=t,this.tokens=e,this.refillRatePerMs=e/(1e3*t),this.lastRefillTimestamp=Date.now()}async consume(){this.attemptConsume()||await m(b(10).pipe(g(()=>this.attemptConsume()),y()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}const os="x-squid-traceid",as="x-squid-client-version";function cs(e="n_"){return`${e}${Ce(10).toLowerCase()}`}const us=e=>e();class ls extends Error{constructor(e,t,n,i,s){super(e),this.statusCode=t,this.url=n,this.headers=i,this.body=s}}const hs="1.0.424";async function ds(e){const t=await ms({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage});return t.body=bs(t.body),t}async function ps(e){const t=await ms({...e,method:"GET",files:[],filesFieldName:""});return t.body=bs(t.body),t}async function gs(e){const t=await ms({...e,method:"PUT"});return t.body=bs(t.body),t}async function fs(e){const t=await ms({...e,method:"PATCH"});return t.body=bs(t.body),t}async function ys(e){const t=await ms({...e,method:"DELETE",files:[],filesFieldName:""});return t.body=bs(t.body),t}async function ms({headers:e,files:t,filesFieldName:n,message:i,url:s,extractErrorMessage:r,method:o}){const a=new Headers(e);a.append(os,cs("c_")),a.append(as,hs);const c={method:o,headers:a,body:void 0};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const i of t)e.append(n||"files",i,i.name);e.append("body",rn(i)),c.body=e}else void 0!==i&&(a.append("Content-Type","application/json"),c.body=rn(i));else"DELETE"===o&&void 0!==i&&(a.append("Content-Type","application/json"),c.body=rn(i));try{const e=await fetch(s,c),t={};if(e.headers.forEach((e,n)=>{t[n]=e}),!e.ok){const n=await e.text(),i=bs(n);if(!r)throw new ls(n,e.status,s,t,i);let o;try{o="string"==typeof i?i:i?.message||n}catch{}throw o||(o=e.statusText),new ls(o,e.status,s,t,i)}const n=await e.text();return yn.debug(`received response from url ${s}: ${JSON.stringify(n)}`),{body:n,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw yn.debug(`Unable to perform fetch request to url: ${s}`,e),e}}function bs(e){if(e){try{return on(e)}catch{}return e}}class Is{constructor(e,n,i,s,r,o){this.region=e,this.appId=n,this.authManager=r,this.clientIdService=o,this.staticHeaders={},this.onGoingRpcCounter=new t(0);for(const[e,t]of Object.entries(s))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe(e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")}),i.onDestruct(async()=>{await this.awaitAllSettled()});const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new rs(60*a,5),ai:new rs(20*a,5),secret:new rs(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:n}=await this.authManager.getAuthData();if(!t)return{};let i=`Bearer ${t}`;return n&&(i+=`; IntegrationId ${n}`),{Authorization:i}}async awaitAllSettled(){await m(this.onGoingRpcCounter.pipe(g(e=>0===e)))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,n=[],i="files",s={}){return(await this.rawPost(e,t,n,i,!0,s)).body}async rawPost(e,t,n=[],i="files",s=!0,r={}){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o,...r};yn.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await ds({url:c,headers:a,message:t,files:n,filesFieldName:i,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async get(e,t,n=!0){return(await this.rawGet(e,t,n)).body}async rawGet(e,t,n=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const i=await this.getAuthHeaders(),s={...this.staticHeaders,...i};let r=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);if(t&&Object.keys(t).length>0){const e=new URLSearchParams;Object.entries(t).forEach(([t,n])=>{e.append(t,String(n))}),r+=`?${e.toString()}`}return yn.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await ps({url:r,headers:s,extractErrorMessage:n})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async put(e,t,n=[],i="files"){return(await this.rawPut(e,t,n,i)).body}async rawPut(e,t,n=[],i="files",s=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const r=await this.getAuthHeaders(),o={...this.staticHeaders,...r};yn.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await gs({url:a,headers:o,message:t,files:n,filesFieldName:i,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async patch(e,t,n=[],i="files"){return(await this.rawPatch(e,t,n,i)).body}async rawPatch(e,t,n=[],i="files",s=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const r=await this.getAuthHeaders(),o={...this.staticHeaders,...r};yn.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await fs({url:a,headers:o,message:t,files:n,filesFieldName:i,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async delete(e,t,n=!0){return(await this.rawDelete(e,t,n)).body}async rawDelete(e,t,n=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const i=await this.getAuthHeaders(),s={...this.staticHeaders,...i};yn.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const r=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await ys({url:r,headers:s,message:t,extractErrorMessage:n})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?be(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?be(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):be(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class vs{constructor(e){this.rpcManager=e}async list(){return(await this.rpcManager.post("/scheduler/listSchedulers",{})).schedulers}async enable(e){await this.update(this.createUpdateSchedulerOptions(e,!0))}async disable(e){await this.update(this.createUpdateSchedulerOptions(e,!1))}async update(e){const t={schedulers:e};await this.rpcManager.post("scheduler/updateSchedulers",t)}createUpdateSchedulerOptions(e,t){return Array.isArray(e)?e.map(e=>({schedulerId:e,enabled:t})):[{schedulerId:e,enabled:t}]}}function ws(){}const Ss="undefined"!=typeof process&&process.versions?.node?F(220):fn().WebSocket;class Ms{constructor(e,n,i,s=us,o,a){this.clientIdService=e,this.region=n,this.appId=i,this.messageNotificationWrapper=s,this.destructManager=o,this.authManager=a,this.webSocketObserver=new r,this.allMessagesObserver=new r,this.connectionReady=new t(!1),this.seenMessageIds=new Set,this.destructSubject=new r,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new t(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe(g(Boolean),E(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe(T(1),g(e=>!e),_(()=>M(R(this.clientTooOldThreshold),this.connectionReady.pipe(g(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?yn.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(yn.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe(g(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe(g(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?yn.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?yn.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(yn.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),yn.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}getClientInfo(){this.postMessage({type:"getClientInfo"})}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe(p())}async awaitConnectionReady(){await m(this.observeConnectionReady().pipe(g(Boolean)))}notifyWebSocketIsNeeded(){this.webSocketNeededSubject.next(!0)}postMessage(e){this.sendMessageImpl(e)}sendMessage(e){return this.sendMessageImpl(e)}disconnectForTest(){this.connectionReady.next(!1),this.socket?.close(4998)}keepAlive(){this.lastTick&&(Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(yn.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.webSocketNeededSubject.next(!0),await m(this.connectionReady.pipe(g(Boolean)));const t=await this.authManager.getToken();if(this.connectionReady.value)try{me(this.socket,"Socket is undefined in sendMessageAsync");const n=rn({message:e,authToken:t});yn.debug(this.clientIdService.getClientId(),"Sending message to socket: ",n),this.socket.send(n)}catch(t){this.socket?.connected?console.error("Websocket message is ignored due to a non-recoverable error",t):(this.connectionReady.next(!1),await this.sendMessageImpl(e))}else await this.sendMessageImpl(e)}sendKillMessage(){this.socket?.connected&&this.socket.send(rn({message:{type:"kill"}}))}closeCurrentSocketSilently(){if(this.socket)try{this.socket.close()}catch(e){}}connect(){this.closeCurrentSocketSilently(),this.connectionReady.value&&this.connectionReady.next(!1);const e=P(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();yn.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const n=`${e}?clientId=${t}`;this.socket=function(e,t={}){let n,i=0,s=1;const r={connected:!1,closeCalled:!1,open(){n=new(Ss?.WebSocket??Ss)(e,t.protocols||[]),n.onmessage=t.onmessage?e=>{e.data&&t.onmessage?t.onmessage(e):console.log("No data received from websockets, please contact support@getsquid.ai with this message.")}:ws,n.onopen=function(e){r.connected=!0,(t.onopen||ws)(e),i=0},n.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return yn.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||ws)(e),void r.reconnect(e);(t.onclose||ws)(e)},n.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||ws)(e)}},reconnect(e){const n=void 0!==t.maxAttempts?t.maxAttempts:1/0;s&&i++<n?s=setTimeout(function(){(t.onreconnect||ws)(e),yn.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||ws)(e)},json(e){n.send(JSON.stringify(e))},send(e){n.send(e)},close(e=4999,t){r.closeCalled=!0;try{r.connected=!1,clearTimeout(s),s=void 0,n.close(e,t)}catch(e){}}};return r.open(),r}(n,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{yn.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{yn.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):yn.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{yn.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):yn.debug(t,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}onConnectionReady(){this.connectionReady.next(!0),this.connectedAtLeastOnce?this.postMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return yn.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=on(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),yn.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new r;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe(A(e=>t.push(e)),u(100)).subscribe(async()=>{const e=[...t.splice(0)];this.postMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await m(R(0)),this.connectionReady.next(!1),await m(R(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function ks(e){var t,n;n="Invalid application ID",me(function(e){return"string"==typeof e}(t=e),()=>ve(n,"Not a string",t));const[i,s,r,o]=e.split("-");return me(!o,`Invalid application ID: ${e}`),{appId:i,environmentId:s??"prod",squidDeveloperId:r}}function Ts(e,t){return`${ks(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function Cs(e,t,n){return`${Ts(e,t)}${n?`-${n}`:""}`}function Os(e){const t=ks(e);return Ts(t.appId,t.environmentId)}class _s{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,n){const i={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:n};await this.rpcManager.post("storage/uploadFile",i,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const n={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",n)}async listDirectoryContents(e){const t={integrationId:this.integrationId,dirPathInBucket:e};return await this.rpcManager.post("storage/listDirectoryContents",t)}async deleteFile(e){await this.deleteFiles([e])}async deleteFiles(e){const t={integrationId:this.integrationId,filePathsInBucket:e};await this.rpcManager.post("storage/deleteFiles",t)}}class Es{constructor(e,t,n,i,s){this.rpcManager=e,this.region=t,this.appId=n,this.apiKey=i,this.consoleRegion=s}async aiSearch(e){return await this.rpcManager.post("web/aiSearch",{query:e})}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e,t){me(this.apiKey,"API key is required to create a short URL");const n=B(this.region,this.consoleRegion,"openapi/sqd/shorten"),i={url:e,appId:this.appId,secondsToLive:t},s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!s.ok)throw console.error("Error making POST request to shorten endpoint",s.statusText),new Error(`${s.statusText}: ${s.text}`);return await s.json()}async createShortUrls(e,t){me(this.apiKey,"API key is required to create a short URL");const n=B(this.region,this.consoleRegion,"openapi/sqd/shortenMany"),i={urls:e,appId:this.appId,secondsToLive:t},s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!s.ok)throw console.error("Error making POST request to shortenMany endpoint",s.statusText),new Error(`${s.statusText}: ${s.text}`);return await s.json()}async deleteShortUrl(e){me(this.apiKey,"API key is required to delete a short URL");const t=B(this.region,this.consoleRegion,"openapi/sqd/delete"),n={id:e,appId:this.appId},i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!i.ok)throw console.error("Error making POST request to delete endpoint",i.statusText),new Error(i.statusText)}async deleteShortUrls(e){me(this.apiKey,"API key is required to delete a short URL");const t=B(this.region,this.consoleRegion,"openapi/sqd/deleteMany"),n={ids:e,appId:this.appId},i=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!i.ok)throw console.error("Error making POST request to delete endpoint",i.statusText),new Error(i.statusText)}}class qs{constructor(e,t,n){this.rpcManager=e,this.region=t,this.appId=n}async executeWebhook(e,t={}){const{headers:n={},queryParams:i={},body:s,files:r=[]}=t,o=await this.rpcManager.getAuthHeaders(),a={...this.rpcManager.getStaticHeaders(),...o,...n};let c=P(this.region,this.appId,`webhooks/${encodeURIComponent(e)}`);if(i&&Object.keys(i).length>0){const e=new URLSearchParams;Object.entries(i).forEach(([t,n])=>{e.append(t,String(n))}),c+=`?${e.toString()}`}const u=new Headers(a);let l;if(u.append(os,cs("c_")),u.append(as,hs),r&&r.length>0){const e=new FormData;for(const t of r)e.append("file",t,t.name);s&&"object"==typeof s&&Object.entries(s).forEach(([t,n])=>{e.append(t,String(n))}),l=e}else u.append("Content-Type","application/json"),l=rn(s||{});const h=await fetch(c,{method:"POST",headers:u,body:l}),d={};if(h.headers.forEach((e,t)=>{d[t]=e}),!h.ok){const e=await h.text();let t;try{t=JSON.parse(e)}catch{t=e}const n="string"==typeof t?t:t?.message||h.statusText;throw new ls(n,h.status,c,d,t)}const p=await h.text();let g;try{g=JSON.parse(p)}catch{g=p}return g}}class Ds{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new Zn,me(e.appId,"APP_ID_MUST_BE_PROVIDED");for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this))){const t=this[e];"function"!=typeof t||"constructor"===e||e.startsWith("_")||(this[e]=t.bind(this))}const t="prod"!==e.environmentId&&e.squidDeveloperId,n=Cs(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new mn(this.destructManager),yn.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new Ut(e.apiKey,e.authProvider),this.socketManager=new Ms(this.clientIdService,e.region,n,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Is(e.region,n,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new ui(this.socketManager,this.rpcManager),this.jobClient=new oi(this.socketManager,this.rpcManager,this.clientIdService),this.backendFunctionManager=new pn(this.rpcManager),this.aiClient=new Bt(this.socketManager,this.rpcManager,this.jobClient,this.backendFunctionManager),this.apiClient=new Lt(this.rpcManager),this.documentStore=new ii,this.lockManager=new ts,this.distributedLockManager=new Xn(this.socketManager,this.destructManager),this.documentIdentityService=new ti(this.documentStore,this.destructManager),this.documentReferenceFactory=new ni(this.documentIdentityService),this.querySender=new _i(this.rpcManager,this.destructManager),this.observabilityClient=new hi(this.rpcManager),this.schedulerClient=new vs(this.rpcManager),this._appId=n,this.querySubscriptionManager=new Zi(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager),this.localQueryManager=new Ci(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new ai(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new En(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new Jn(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new Qn(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.webhookManager=new qs(this.rpcManager,e.region,n),this.nativeQueryManager=new ci(this.rpcManager),this._connectionDetails=new Ln(this.clientIdService,this.socketManager),this.queueManagerFactory=new ns(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new $(this.rpcManager,this.options.region,Os(n),this.options.consoleRegion),this.webClient=new Es(this.rpcManager,this.options.region,Os(n),this.options.apiKey,this.options.consoleRegion)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}static getInstance(e){const t=sn(e);let n=Ds.squidInstancesMap[t];return n||(n=new Ds(e),Ds.squidInstancesMap[t]=n,n)}static getInstances(){return Object.values(Ds.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Ct){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...t){return this._validateNotDestructed(),this.backendFunctionManager.executeFunction(e,...t)}executeFunctionWithHeaders(e,t,...n){return this._validateNotDestructed(),this.backendFunctionManager.executeFunctionWithHeaders(e,t,...n)}executeWebhook(e,t){return this._validateNotDestructed(),this.webhookManager.executeWebhook(e,t)}executeNativeRelationalQuery(e,t,n={}){const i={type:"relational",query:t,params:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativePureQuery(e,t,n={}){const i={type:"pure",query:t,params:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativeMongoQuery(e,t,n){const i={type:"mongo",collectionName:t,aggregationPipeline:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(i)}executeNativeElasticQuery(e,t,n,i="_search",s="GET"){const r={type:"elasticsearch",index:t,endpoint:i,method:s,body:n,integrationId:e};return this.nativeQueryManager.executeNativeQuery(r)}ai(){return this._validateNotDestructed(),this.aiClient}job(){return this._validateNotDestructed(),this.jobClient}api(){return this._validateNotDestructed(),this.apiClient}admin(){return this._validateNotDestructed(),this.adminClient}web(){return this._validateNotDestructed(),this.webClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new _s(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new si(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new ri(this.rpcManager)}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t){const n=await this.acquireLock(e);try{return await t(n)}finally{n.release()}}queue(e,t=Ot){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(Ds.squidInstancesMap).find(([,e])=>e===this);e&&delete Ds.squidInstancesMap[e[0]]})}get isDestructed(){return this.destructManager.isDestructing}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}getNotificationClient(){return this._validateNotDestructed(),this.notificationClient}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}internal(){const{rpcManager:e}=this;return{getApplicationUrl:(e,t,n)=>P(e,t,n),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,n)=>Cs(e,t,n)}}_validateNotDestructed(){me(!this.destructManager.isDestructing,"The client was already destructed.")}}export{It as AI_AGENTS_INTEGRATION_ID,lt as AI_AUDIO_CREATE_SPEECH_MODEL_NAMES,ut as AI_AUDIO_TRANSCRIPTION_MODEL_NAMES,Ge as AI_CHAT_MESSAGE_SOURCE,tt as AI_EMBEDDINGS_MODEL_NAMES,ct as AI_IMAGE_MODEL_NAMES,We as AI_PROVIDER_TYPES,Ft as ALL_OPERATORS,Je as ANTHROPIC_CHAT_MODEL_NAMES,gt as API_INJECTION_FIELD_TYPES,xt as ARRAY_OPERATORS,St as AUTH_INTEGRATION_TYPES,$ as AdminClient,Re as AiAgentClient,De as AiAgentReference,xe as AiAssistantClient,Fe as AiAudioClient,Bt as AiClient,je as AiFilesClient,Pe as AiImageClient,Le as AiKnowledgeBaseClient,Qe as AiKnowledgeBaseReference,Ue as AiMatchMakingClient,Lt as ApiClient,U as ApiKeysSecretClient,Ut as AuthManager,mt as BUILT_IN_AGENT_ID,Ct as BUILT_IN_DB_INTEGRATION_ID,Ot as BUILT_IN_QUEUE_INTEGRATION_ID,_t as BUILT_IN_STORAGE_INTEGRATION_ID,pn as BackendFunctionManager,qn as BaseQueryBuilder,Pt as CLIENT_CONNECTION_STATES,bn as CLIENT_ID_GENERATOR_KEY,In as CLIENT_REQUEST_ID_GENERATOR_KEY,Rn as Changes,mn as ClientIdService,Pn as CollectionReference,Qn as CollectionReferenceFactory,Ln as ConnectionDetails,wt as DATA_INTEGRATION_TYPES,ke as DEFAULT_SHORT_ID_LENGTH,Jn as DataManager,xn as DereferencedJoin,Zn as DestructManager,ei as DistributedLockImpl,Xn as DistributedLockManager,On as DocumentReference,ni as DocumentReferenceFactory,ii as DocumentStore,Ne as EMPTY_CHAT_ID,yt as ENVIRONMENT_IDS,si as ExternalAuthClient,ri as ExtractionClient,Yi as FETCH_BEYOND_LIMIT,at as FLUX_MODEL_NAMES,Ke as GEMINI_CHAT_MODEL_NAMES,Mt as GRAPHQL_INTEGRATION_TYPES,ze as GROK_CHAT_MODEL_NAMES,jn as GroupedJoin,kt as HTTP_INTEGRATION_TYPES,bt as HttpStatus,Tt as INTEGRATION_SCHEMA_TYPES,vt as INTEGRATION_TYPES,Q as IntegrationClient,oi as JobClient,Nn as JoinQueryBuilder,ln as LastUsedValueExecuteFunctionCache,Gi as LimitUnderflowState,Ci as LocalQueryManager,Rt as METRIC_DOMAIN,At as METRIC_FUNCTIONS,Nt as METRIC_INTERVAL_ALIGNMENT,$e as MatchMaker,ai as MutationSender,us as NOOP_FN,ci as NativeQueryManager,ui as NotificationClient,st as OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES,rt as OPENAI_AUDIO_MODEL_NAMES,it as OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES,Ve as OPENAI_CHAT_MODEL_NAMES,Xe as OPENAI_EMBEDDINGS_MODEL_NAMES,nt as OPENAI_IMAGE_MODEL_NAMES,ht as OPEN_AI_CREATE_SPEECH_FORMATS,hi as ObservabilityClient,_n as Pagination,An as QueryBuilder,En as QueryBuilderFactory,_i as QuerySender,Zi as QuerySubscriptionManager,ns as QueueManagerFactory,ss as QueueManagerImpl,pt as RAG_TYPES,He as RERANK_PROVIDERS,rs as RateLimiter,Is as RpcManager,Et as SQUID_BUILT_IN_INTEGRATION_IDS,Dt as SQUID_METRIC_NAMES,jt as SQUID_REGIONS,ot as STABLE_DIFFUSION_MODEL_NAMES,vs as SchedulerClient,L as SecretClient,Ms as SocketManager,Ds as Squid,ls as SquidClientError,_s as StorageClient,Ye as VENDOR_AI_CHAT_MODEL_NAMES,et as VOYAGE_EMBEDDING_MODEL_NAMES,Es as WebClient,qs as WebhookManager,qe as base64ToFile,cn as compareArgsByReference,un as compareArgsBySerializedValue,fi as deserializeQuery,Me as generateId,Ce as generateShortId,Oe as generateShortIds,we as generateUUID,Se as generateUUIDPolyfill,B as getConsoleUrl,gn as getCustomizationFlag,qt as isBuiltInIntegrationId,dt as isIntegrationModelSpec,ft as isPlaceholderParam,Ze as isVendorAiChatModelName,ys as rawSquidHttpDelete,ps as rawSquidHttpGet,fs as rawSquidHttpPatch,ds as rawSquidHttpPost,gs as rawSquidHttpPut,hn as transformFileArgs,bs as tryDeserializing,gi as visitQueryResults};
|