@squidcloud/client 1.0.456 → 1.0.457
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-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 +190 -0
- package/dist/internal-common/src/types/ai-agent.types.d.ts +239 -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/management-api-key.types.d.ts +92 -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 +126 -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 +45 -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/file-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 +86 -0
- package/dist/internal-common/src/utils/serialization.d.ts +18 -0
- package/dist/internal-common/src/utils/squid.constants.d.ts +6 -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 i,Observable as n,ReplaySubject as s,Subject as r,combineLatest as o,combineLatestWith as a,concatMap as c,debounceTime as u,defaultIfEmpty as l,defer as d,delay as h,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 _,switchAll as q,switchMap as C,take as D,takeUntil as O,takeWhile as E,tap as R,timer as A}from"rxjs";var F={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const r=i(642);t.default=r.PromisePool,s(i(273),t),s(i(642),t),s(i(837),t),s(i(426),t),s(i(858),t),s(i(172),t)},837(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class i extends Error{constructor(e,t){super(),this.raw=e,this.item=t,this.name=this.constructor.name,this.message=this.messageFrom(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e,t){return new this(e,t)}messageFrom(e){return e instanceof Error||"object"==typeof e?e.message:"string"==typeof e||"number"==typeof e?e.toString():""}}t.PromisePoolError=i},234(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=i(642),s=i(172),r=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],taskTimeout:0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw 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(n.PromisePool.notRun),this):this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=n.PromisePool.notRun),this.startProcessing(t,e),e+=1,await this.waitForProcessingSlot()}return await this.drained()}async waitForProcessingSlot(){for(;this.hasReachedConcurrencyLimit();)await this.waitForActiveTaskToFinish()}async waitForActiveTaskToFinish(){await Promise.race(this.tasks())}startProcessing(e,t){const i=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(i)}).catch(async n=>{await this.handleErrorFor(n,e,t),this.removeActive(i)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(i),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[i,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise((i,n)=>{t=setTimeout(()=>{n(new 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,i){if(this.shouldUseCorrespondingResults()&&(this.results()[i]=n.PromisePool.failed),!this.isStoppingThePoolError(e)){if(this.isValidationError(e))throw this.markAsStopped(),e;this.hasErrorHandler()?await this.runErrorHandlerFor(e,t):this.saveErrorFor(e,t)}}isStoppingThePoolError(e){return e instanceof o.StopThePromisePoolError}isValidationError(e){return e instanceof 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())}}},642(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(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 n.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=s,s.notRun=Symbol("notRun"),s.failed=Symbol("failed")},426(e,t){Object.defineProperty(t,"__esModule",{value:!0})},858(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i},172(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class i extends Error{constructor(e){super(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e){return new this(e)}}t.ValidationError=i},220(t){t.exports=e}},j={};function N(e){var t=j[e];if(void 0!==t)return t.exports;var i=j[e]={exports:{}};return F[e].call(i.exports,i,i.exports,N),i.exports}N.d=(e,t)=>{for(var i in t)N.o(t,i)&&!N.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},N.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),N.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const x=["api","application","auth","integration","internal-storage","management-secret","mutation","native-query","query","queue","quota","scheduler","secret","storage","ws","internal-extraction","notification"];function P(e,t,i,n,s,r){let o="https",a=`${n||t}.${s||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=x.includes(i.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=i.replace(/^\/+/,"");return l?`${u}/${l}`:u}function B(e,t,i=""){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",i)}class Q{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=B(t,n,`openapi/iac/applications/${i}/integrations`)}async list(e){const t=await this.rpcManager.get(this.iacBaseUrl);return e?t.filter(t=>t.type===e):t}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getIntegrationSchema(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}/schema`)}async 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)}async generateAiDescriptionsForDataSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions`,t)}async generateAiDescriptionsForAssociations(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-associations`,t)}async generateAiDescriptionsForStoredProcedures(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-stored-procedures`,t)}async generateAiDescriptionsForEndpoints(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-endpoints`,t)}async discoverDataConnectionSchema(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-schema`,{})}async testDataConnection(e){return await this.rpcManager.post(`${this.iacBaseUrl}/test-connection`,e)}async discoverGraphQLConnectionSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-graphql-schema`,t)}async discoverOpenApiSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema`,t)}async discoverOpenApiSchemaFromFile(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema-from-file`,{})}}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 i={keys:[e],force:t};return this.rpcManager.post("secret/delete",i)}async deleteMany(e,t=!1){if(0===e.length)return;const i={keys:e,force:t};return this.rpcManager.post("secret/delete",i)}}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,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=n,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 i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},W(e,t)};function K(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}W(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function V(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function z(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o}function J(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s<r;s++)!n&&s in t||(n||(n=Array.prototype.slice.call(t,0,s)),n[s]=t[s]);return e.concat(n||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 i=e.indexOf(t);0<=i&&e.splice(i,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,i,n,s;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=V(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=V(u),d=l.next();!d.done;d=l.next()){var h=d.value;try{te(h)}catch(e){s=null!=s?s:[],e instanceof Z?s=J(J([],z(s)),z(e.errors)):s.push(e)}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(s)throw new Z(s)}},e.prototype.add=function(t){var i;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!==(i=this._finalizers)&&void 0!==i?i:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&X(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&X(i,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 ie={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var s=ie.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,J([e,t],z(i))):setTimeout.apply(void 0,J([e,t],z(i)))},clearTimeout:function(e){var t=ie.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function ne(){}var se=re("C",void 0,void 0);function re(e,t,i){return{kind:e,value:t,error:i}}var oe=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof ee||i&&"closed"in i&&G(i.remove)&&G(i.add)&&G(i.unsubscribe))&&t.add(n)):n.destination=de,n}return K(t,e),t.create=function(e,t,i){return new ce(e,t,i)},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,i,n){var s,r=e.call(this)||this;return s=G(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,r.destination=new ae(s),r}return K(t,e),t}(oe);function ue(e){!function(e){ie.setTimeout(function(){throw e})}(e)}function le(e,t){var i=null;i&&ie.setTimeout(function(){return i(e,t)})}var de={closed:!0,next:ne,error:function(e){throw e},complete:ne};function he(e,t,i,n,s){return new pe(e,t,i,n,s)}var pe=function(e){function t(t,i,n,s,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(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=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return K(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(oe);function ge(e,t){return H(function(i,n){var s=0;i.subscribe(he(n,function(i){n.next(e.call(t,i,s++))}))})}function fe(e){return null!=e}let ye=e=>new Error(e);function me(e,t,...i){e||function(e,...t){const i=Ie(e);if("object"==typeof i)throw i;throw ye(i||"Assertion error",...t)}(t,...i)}function be(e,t,...i){return me(e,t,...i),e}function Ie(e){return void 0===e?"":"string"==typeof e?e:e()}function ve(e,t,i){const n=Ie(e);if("object"==typeof n)throw n;return`${n?`${n}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}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 _e(e=18,t="",i=""){me(t.length<e,"ID prefix is too long"),me(!t||!i||i.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let n="";for(let t=0;t<e;t++)n+=Te();if(t.length>0&&(n=t+n.substring(t.length)),i)for(;n.charAt(t.length)===i[t.length];)n=n.substring(0,t.length)+Te()+n.substring(t.length+1);return n}function qe({count:e,length:t,prefix:i}){me(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(_e(t||18,i||""));return[...n]}const Ce=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function De(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)De(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)De(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(Ce.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${Ce.join(", ")}`);const i=e[t];if("object"!=typeof i&&"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof i}`)}}function Oe(e,t,i){const n=atob(e),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return new File([s],t,{type:i||"application/octet-stream"})}class Ee{constructor(e,t,i,n,s,r,o){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=i,this.rpcManager=n,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 i={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",i)}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})}async listRevisions(){return await this.post("ai/agent/listRevisions",{agentId:this.agentId})}async restoreRevision(e){await this.post("ai/agent/restoreRevision",{agentId:this.agentId,revisionNumber:e})}async deleteRevision(e){await this.post("ai/agent/deleteRevision",{agentId:this.agentId,revisionNumber:e})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),s=await be(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:s.transcribedPrompt}}async ask(e,t,i){const n=await this.askInternal(e,!1,t,i);return this.replaceFileTags(n.responseString,n.annotations)}async askWithAnnotations(e,t,i){const n=await this.askInternal(e,!1,t,i);return{responseString:n.responseString,annotations:n.annotations}}async askAsync(e,t,i){const n={agentId:this.agentId,prompt:e,options:i,jobId:t};await this.post("ai/chatbot/askAsync",n)}observeStatusUpdates(e){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"aiStatus"===e.type&&e.agentId===this.agentId),g(t=>!e||t.jobId===e),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,i){return await this.askInternal(e,!1,t,i)}async transcribeAndAskWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),s=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:Oe(s.base64File,`voice.${s.extension}`,s.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),s=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:Oe(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 addConnectedIntegration(e){await this.post("ai/agent/addConnectedIntegration",{agentId:this.agentId,integrationId:e.integrationId,integrationType:e.integrationType,description:e.description??""})}async addConnectedAgent(e){await this.post("ai/agent/addConnectedAgent",{agentId:this.agentId,connectedAgentId:e.agentId,description:e.description})}async addConnectedKnowledgeBase(e){await this.post("ai/agent/addConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e.knowledgeBaseId,description:e.description})}async addFunction(e){await this.post("ai/agent/addFunction",{agentId:this.agentId,functionId:e})}async removeConnectedAgent(e){await this.post("ai/agent/removeConnectedAgent",{agentId:this.agentId,connectedAgentId:e})}async removeConnectedIntegration(e){await this.post("ai/agent/removeConnectedIntegration",{agentId:this.agentId,integrationId:e})}async removeConnectedKnowledgeBase(e){await this.post("ai/agent/removeConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e})}async removeFunction(e){await this.post("ai/agent/removeFunction",{agentId:this.agentId,functionId:e})}async setAgentDescription(e){await this.post("ai/agent/setAgentDescription",{agentId:this.agentId,description:e})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}async build(e,t){const i={agentId:this.agentId,request:e,memoryId:t};return await this.backendFunctionManager.executeFunction("buildAgent",i)}replaceFileTags(e,t={}){let i=e;for(const[e,n]of Object.entries(t)){let t="";const s=n.aiFileUrl.fileName?n.aiFileUrl.fileName:n.aiFileUrl.url;switch(n.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${s}](${n.aiFileUrl.url})`}const r=`\${id:${e}}`;i=i.replaceAll("`"+r+"`",t).replaceAll(r,t)}return i}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&De(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)De(i.contextMetadataFilterForKnowledgeBase[e]);n=n||we(),i={...Re,...i||{}};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:i,jobId:n},a=s?void 0:[e];return await this.post(r,o,a,"file"),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&De(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)De(t.contextMetadataFilterForKnowledgeBase[e]);const n=we(),s=void 0===(t={...Re,...t||{}}).smoothTyping||t.smoothTyping;let o="";const a=new r,u=new r;this.ongoingChatSequences[n]=u;let l=-1;u.pipe(R(({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:i})=>t?w({value:e,complete:t,annotations:i}):w(e).pipe(s?h(0):R(),ge(e=>({value:e,complete:!1,annotations:void 0})))),E(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:i})=>{o+=e,t&&i&&(o=this.replaceFileTags(o,i)),a.next(o)},error:e=>{console.error(e)},complete:()=>{a.complete()}});const d="string"==typeof e;i=i||we();const p={agentId:this.agentId,jobId:i,prompt:d?e:void 0,options:t,clientRequestId:n},g={responseStream:a.pipe(f(()=>{delete this.ongoingChatSequences[n]}),k())};let y;return y=d?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=y.then(()=>this.jobClient.awaitJob(i)).catch(e=>{a.error(e),a.complete()}),g}async post(e,t,i=[],n="files"){const s={};return this.agentApiKey&&(s["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,i,n,s)}}const Re={smoothTyping:!0,responseFormat:"text"};class Ae{constructor(e,t,i,n){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=n,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 Ee(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:i,complete:n,tokenIndex:s,annotations:r}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===s?void 0:s,annotations:r});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===s?void 0:s,annotations:r})}}const Fe="__squid_empty_chat_id";class je{constructor(e){this.rpcManager=e}async transcribe(e,t={modelName:"whisper-1"}){return this.rpcManager.post("ai/audio/transcribe",t,[e])}async createSpeech(e,t){const i={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",i);return Oe(n.base64File,`audio.${n.extension}`,n.mimeType)}}class Ne{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 xe{constructor(e){this.rpcManager=e}async generate(e,t){const i={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",i)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function Pe(e){for(const t in e){const i=e[t];me("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),me(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class Be{constructor(e,t,i){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async delete(){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:this.knowledgeBaseId})}async listContexts(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:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&Pe(t.metadata);const i=we();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:i},t),await this.jobClient.awaitJob(i)}async search(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return(await this.rpcManager.post("ai/knowledge-base/search",t)).chunks}async 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 Qe{constructor(e,t){this.rpcManager=e,this.jobClient=t}knowledgeBase(e){return new Be(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 Le{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new Ue(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new Ue(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class Ue{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 $e=["user","ai"],Ge=["cohere","none"],He=["anthropic","bedrock","claude-code","cohere","flux","gemini","openai","grok","stability","voyage","mistral","textract","external"],We=["gpt-5-mini","gpt-5-nano","gpt-5.2","gpt-5.2-pro","gpt-5.4"],Ke=["gemini-3-pro","gemini-3-flash"],Ve=["grok-4","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],ze=["claude-haiku-4-5-20251001","claude-opus-4-6","claude-sonnet-4-6"],Je=[...We,...ze,...Ke,...Ve];function Ye(e){return Je.includes(e)}const Ze=["text-embedding-3-small"],Xe=["voyage-3-large"],et=["titan-embed-text-v2"],tt=[...Ze,...Xe,...et];function it(e){return tt.includes(e)}function nt(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const 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],dt=[...rt],ht=[...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","bedrock","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","github","google_calendar","google_docs","google_drive","graphql","hubspot","jira","jira_jsm","jwt_hmac","jwt_rsa","kafka","keycloak","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","oracledb","pinecone","postgres","redis","s3","salesforce","sap_hana","sentry","snowflake","spanner","xata","zendesk","servicenow_csm","freshdesk","mail","slack","mcp","a2a","legend","teams","openai_compatible","openai_compatible_embedding"],Mt=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","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"],_t=["api"],qt=["data","api","graphql"],Ct="built_in_db",Dt="built_in_queue",Ot="built_in_storage",Et=[Ct,Dt,Ot];function Rt(e){return Et.includes(e)}const At=["squid_functionExecution_count","squid_functionExecution_time"],Ft=["sum","max","min","average","median","p95","p99","count"],jt=["user","squid"],Nt=["align-by-start-time","align-by-end-time"],xt=["return-no-result-groups","return-result-group-with-default-values"],Pt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],Bt=[...Pt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],Qt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],Lt=["CONNECTED","DISCONNECTED","REMOVED"];class Ut{constructor(e,t,i,n){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.backendFunctionManager=n}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()}async listFunctions(){const e=await this.rpcManager.post("/application/getBundleMetadata",{});return Object.values(e.aiFunctions||{})}async listChatModels(){return(await this.rpcManager.post("ai/settings/listChatModels",{})).models}image(){return new xe(this.rpcManager)}audio(){return new je(this.rpcManager)}matchMaking(){return new Le(this.rpcManager)}files(e){return new Ne(e,this.rpcManager)}executeAiQuery(e,t,i){const n={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",n)}executeAiApiCall(e,t,i,n){const s={integrationId:e,prompt:t,options:i,sessionContext:n};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 i={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",i)).settings}observeStatusUpdates(e){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"aiStatus"===e.type),g(t=>!e||t.jobId===e),v(e=>({agentId:e.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})))}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Ae(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new Qe(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const $t={headers:{},queryParams:{},pathParams:{}};class Gt{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,n){return this.request(e,t,i,n,"post")}async delete(e,t,i,n){return this.request(e,t,i,n,"delete")}async patch(e,t,i,n){return this.request(e,t,i,n,"patch")}async put(e,t,i,n){return this.request(e,t,i,n,"put")}async request(e,t,i,n,s){const r={integrationId:e,endpointId:t,body:i,options:{...$t,...this.convertOptionsToStrings(n||{})},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 Ht{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 Wt=/[.\[\]]/;function Kt(e,t){if(!e)return;const i=t.split(Wt);let n,s=e;for(;s&&i.length;){const e=i.shift();if(e){if("object"!=typeof s||!(e in s))return;n=s[e],s=n}}return n}function Vt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function zt(e,t,i,n="."){const s=t.split(n);let r=e;for(;s.length;){const e=be(s.shift());if(s.length){const t=r[e],i=Vt(t)?ii(t)??{}:{};r[e]=i,r=i}else r[e]=i}}function Jt(e,t,i="."){const n=t.split(i);let s=e;for(;n.length;){const e=be(n.shift());if(n.length){const t=Vt(s[e])?ii(s[e])??{}:{};s[e]=t,s=t}else delete s[e]}}function Yt(e,t,i){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(i,n)}}function Zt(e){return null==e}function Xt(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const i=typeof e;if(i!==typeof t)return!1;if("object"!==i)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return!1;for(const i of n)if(!s.includes(i)||!Xt(e[i],t[i]))return!1;return!0}function ei(e,t){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=ti(e[n],t);return i}function ti(e,t){const i=t?t(e):void 0;if(void 0!==i)return i;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return ei(e,t);if(e instanceof Map)return new Map(ei(Array.from(e),t));if(e instanceof Set)return new Set(ei(Array.from(e),t));if(ArrayBuffer.isView(e))return(n=e)instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const s={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(s[i]=ti(e[i],t));return s}function ii(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 ni(e,t){if(e===t||Zt(e)&&Zt(t))return 0;if(Zt(e))return-1;if(Zt(t))return 1;const i=typeof e,n=typeof t;return i!==n?i<n?-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 si(e,t){return e.reduce((e,i)=>{const n=t(i);return e[n]?e[n].push(i):e[n]=[i],e},{})}function ri(e){if(Array.isArray(e))return e.map(e=>ri(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),i={};return t.sort().forEach(t=>{i[t]=ri(e[t])}),i}function oi(e){return ai(ri(e))}function ai(e){if(void 0===e)return null;const t=ti(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function ci(e){return ti(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,i=t.$date;return i&&1===Object.keys(t).length?new Date(i):void 0})}function ui(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=ai(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return btoa(i)}}const li=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},di=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(ai(e[i])!==ai(t[i]))return!1;return!0};class hi{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||li,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&i(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function pi(e){const t=[],i=[];let n=0;for(const s of e)if("undefined"!=typeof File)if(s instanceof File){i.push(s);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(gi(s)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:s.map((e,t)=>(i.push(s[t]),n++))};t.push(e)}else t.push(s);else t.push(s);return{argsArray:t,fileArray:i}}function gi(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class fi{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...i){const{argsArray:n,fileArray:s}=pi(i),r="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,a=o?.cache;if(a){const e=a.get(n);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?li:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,n));if(t)return t.promise}const u=this.createExecuteCallPromise(r,n,s,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:n,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,i,n,s={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:ai(t)},a=ci((await this.rpcManager.post(r,o,i.length>0?i:[],"files",s)).payload);if(a?.__isSquidBase64File__){const e=a;return Oe(e.base64,e.filename,e.mimetype)}return n&&n.set(t,a),a}}function yi(e){if("undefined"!=typeof globalThis)return globalThis[e]}function mi(){if("undefined"!=typeof window)return window;if(void 0!==N.g)return N.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}void 0===mi()?.SQUID_LOG_DEBUG_ENABLED&&function(e=!0){mi().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 bi{static debug(...e){(function(){const e=mi();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=mi();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Ii{constructor(e){this.destructManager=e,this.clientTooOldSubject=new t(!1),this.isTenant=!0===mi().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=mi()[wi];return e?e():we()}generateClientId(){const e=mi()[vi];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 vi="SQUID_CLIENT_ID_GENERATOR",wi="SQUID_CLIENT_REQUEST_ID_GENERATOR",Si="__squidId";function Mi(e){return ci(e)}function ki(...e){const[t,i,n]=e,s="object"==typeof t?t:{docId:t,collectionName:i,integrationId:n};return s.integrationId||(s.integrationId=void 0),oi(s)}function Ti(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return Xt(e,t);if("!="===i)return!Xt(e,t);switch(i){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&&_i(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&_i(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&_i(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&_i(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>be(i,"VALUE_CANNOT_BE_NULL").some(t=>Xt(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>be(i,"VALUE_CANNOT_BE_NULL").some(t=>Xt(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!be(i,"VALUE_CANNOT_BE_NULL").some(t=>Xt(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function _i(e,t,i){i||(e=e.toLowerCase(),t=t.toLowerCase());const n=function(e){let t="";for(let i=0;i<e.length;++i)"\\"===e[i]?i+1<e.length&&["%","_"].includes(e[i+1])?(t+=e[i+1],i++):i+1<e.length&&"\\"===e[i+1]?(t+="\\\\",i++):t+="\\":"%"===e[i]?t+="[\\s\\S]*":"_"===e[i]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[i])&&(t+="\\"),t+=e[i]);return t}(t);return new RegExp(`^${n}$`).test(e)}function qi(e,t){return`${e}_${t}`}function Ci(e){return"fieldName"in e}class Di{constructor(e,t,i,n){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.projectFields=n,this.refId=we()}get squidDocId(){return this._squidDocId}get data(){return ti(this.dataRef)}get dataRef(){const e=be(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=Mi(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:i,collectionName:e,integrationId:t},null,2)}`});return this.projectFields?this.applyProjection(e):e}get hasData(){return this.dataManager.hasSufficientData(this.squidDocId,this.projectFields)}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 i={};Object.entries(e).forEach(([e,t])=>{const n=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};i[e]=[n]});const n={type:"update",squidDocIdObj:Mi(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,i){return this.update({[e]:ti(t)},i)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,i){const n={type:"applyNumericFn",fn:"increment",value:t},s={type:"update",squidDocIdObj:Mi(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(s,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async upsert(e,t){const i=Mi(this.squidDocId),n=i.integrationId;let s=ci(i.docId);if(s[Si]&&(s={}),n===Ct&&s.__id)try{const e=ci(s.__id);s={...s,...e}}catch{}const r={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...s}};return this.dataManager.applyOutgoingMutation(r,t)}async insert(e,t){return this.upsert(e,t)}async delete(e){const t={type:"delete",squidDocIdObj:Mi(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)}applyProjection(e){const t={},i=be(this.projectFields,"applyProjection called without projectFields"),{integrationId:n}=Mi(this.squidDocId);"__id"in e&&(t.__id=e.__id),"__docId__"in e&&(t.__docId__=e.__docId__);const s=n===Ct?"__id":"__docId__";if(s in e){const i=e[s];if("string"==typeof i&&i.startsWith("{"))try{const e=ci(i);if("object"==typeof e&&null!==e)for(const[i,n]of Object.entries(e))i in t||(t[i]=n)}catch{}}for(const n of i)if(n.includes(".")){const i=Kt(e,n);void 0!==i&&zt(t,n,i)}else n in e&&(t[n]=e[n]);return t}hasSquidPlaceholderId(){const e=ci(this._squidDocId);if("object"==typeof e&&e.docId){const t=ci(e.docId);if("object"==typeof t&&Object.keys(t).includes(Si))return!0}return!1}}class Oi{constructor(e,i={}){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(q()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...i},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 i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:s}of i){const i=ni(Kt(e,n),Kt(t,n));if(0!==i)return s?i:-i}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 i=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-i-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const i=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,n=Math.max(0,e.length-i-this.paginateOptions.pageSize);i!==e.length?this.internalStateObserver.next({numBefore:i,numAfter:n,data:e,extractedData:t}):this.prevInternal({numBefore:i,numAfter:n,data:e,extractedData:t})}doNewQuery(e,t){if(this.onFirstPage=!1,t){const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder();e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?"<=":">=",value:Kt(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:Kt(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),D(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:n,extractedData:s}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(s[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:n>0,hasPrev:i>0}}prevInternal(e){const{numBefore:t,numAfter:i,extractedData:n}=e;this.firstElement=null,this.lastElement=n[t-1],this.internalStateObserver.next(null),this.doNewQuery(n[n.length-i-1],!0)}}Error;class Ei{constructor(e,t,i,n){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=n}getForDocument(e){const{collectionName:t,integrationId:i,docId:n}=Mi(e),s=ci(n),r=this.get(t,i);for(const[e,t]of Object.entries(s))r.where(e,"==",t);return r}get(e,t){return new Fi(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService)}}class Ri{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,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"like_cs":"like",t)}notLike(e,t,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"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 Ai{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 Ai(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}projectFields(e){const t=this.queryBuilder.projectFields(e);return new Ai(t)}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new Oi(this,e)}}class Fi extends Ri{constructor(e,t,i,n,s,r,o){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=n,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 ui(this.build())}where(e,t,i){if(me(Bt.includes(t),`Invalid operator: ${t}`),this.query.projectFields&&"__docId__"!==e&&!this.query.projectFields.includes(e))throw new Error(`Cannot filter by field '${e}' that is not included in projectFields.`);if("in"===t||"not in"===t){const n=Array.isArray(i)?[...i]:[i];"in"===t&&0===n.length&&(this.containsEmptyInCondition=!0);for(const i of n)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:i});return this}return this.query.conditions.push({fieldName:e,operator:t,value:i}),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 i=this.query.sortOrder.map(e=>e.fieldName);return me(Xt(t.sort(),i.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 i={asc:t,fieldName:e};if(function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var i,n,s,r;me((i=t,n=["fieldName","asc"],!Array.isArray(i)&&[...Object.keys(i)].every(e=>n.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")}(i),me(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.projectFields&&"__docId__"!==e&&!this.query.projectFields.includes(e))throw new Error(`Cannot sort by field '${e}' that is not included in projectFields.`);return this.query.sortOrder.push(i),this}projectFields(e){if(0===e.length&&"built_in_db"!==this.integrationId)throw new Error(`Empty projectFields is only allowed for built_in_db integration. For '${this.integrationId}', you must specify at least one field to project.`);if(this.query.projectFields)for(const t of e)if(!this.query.projectFields.includes(t))throw new Error(`Cannot project field '${t}' that is not in the existing projection. Subsequent projectFields calls must be subsets of the previous projection.`);const t=e;for(const e of this.query.sortOrder)if("__docId__"!==e.fieldName&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including sort field '${e.fieldName}'.`);for(const e of this.query.conditions)if(Ci(e)){if("__docId__"!==e.fieldName&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including filter field '${e.fieldName}'.`)}else for(const i of e.fields)if("__docId__"!==i.fieldName&&!t.includes(i.fieldName))throw new Error(`Cannot set projectFields without including filter field '${i.fieldName}'.`);const i=this.clone();return i.query.projectFields=[...e],i}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 i=this.build(),n=i.projectFields;return this.querySubscriptionManager.processQuery(i,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(ge(e=>e.map(e=>{me(1===Object.keys(e).length);const t=ki(be(e[this.collectionName]).__docId__,this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory,n)})))}changes(){let e,t=new Set;return this.snapshots().pipe(a(this.documentIdentityService.observeChanges().pipe(C(t=>(Object.entries(t).forEach(([t,i])=>{!function(e,t,i){const n=e[t];void 0!==n&&(e[i]=n,delete e[t])}(e||{},t,i)}),i)),_({}))),ge(([i])=>{let n=[];const s=[],r=[];if(e){for(const r of i){const i=r.squidDocId,o=r.dataRef;if(t.has(o))delete e[i],t.delete(o);else if(e[i]){s.push(r);const n=e[i];delete e[i],t.delete(n)}else n.push(r)}for(const e of t)r.push(e)}else n=i;e={},t=new Set;for(const n of i){const i=n.dataRef;e[n.squidDocId]=i,t.add(i)}return new ji(n,s,r)}))}dereference(){return new Ai(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new Fi(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService);return e.query=ti(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){if(!e.length)return this;if(this.query.projectFields)for(const t of e)if("__docId__"!==t.fieldName&&!this.query.projectFields.includes(t.fieldName))throw new Error(`Cannot filter by field '${t.fieldName}' that is not included in projectFields.`);return this.query.conditions.push({fields:e}),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 Oi(this,e)}mergeConditions(){const e=[],t=si(this.query.conditions.filter(Ci)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=si(i,e=>e.operator);for(const[i,n]of Object.entries(t)){if("=="===i||"!="===i){e.push(...n);continue}const t=[...n];t.sort((e,t)=>ni(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!Ci(e)),...e]}}class ji{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class Ni extends Ri{constructor(e,t,i,n,s,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=n,this.queryBuilderFactory=s,this.rootAlias=r,this.latestAlias=o,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,i){return this.queryBuilder.where(e,t,i),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}projectFields(e){throw new Error("projectFields is not yet supported for join queries")}join(e,t,i,n){const s=n?.leftAlias??this.latestAlias,r={...i,leftAlias:s,isInner:n?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[s].push(t),new Ni(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,ti(this.joins),ti(this.joinConditions),e,!1).pipe(ge(e=>e.map(e=>{const t={};for(const[i,n]of Object.entries(e)){const e=i===this.rootAlias?this.collectionName:this.joins[i].collectionName,s=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,r=n?ki(n.__docId__,e,s):void 0;t[i]=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 Bi(this)}dereference(){return new xi(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Ni(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,ti(this.leftToRight),ti(this.joins),ti(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 Oi(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class xi{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 i={},n=Object.keys(e);for(const s of n){const n=e[s];i[s]=t(n)}return i}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new xi(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 Oi(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class Pi{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 Pi(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 Oi(this,e)}dereference(e,t){const i=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(i.length){const n={[t]:e[t].data};for(const t of i)n[t]=e[t].map(e=>this.dereference(e,t));return n}return e.data}}class Bi{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 Pi(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new Bi(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 Oi(this,e)}groupData(e,t){const i=si(e,e=>e[t]?.squidDocId);return Object.values(i).filter(e=>void 0!==e[0][t]).map(e=>{const i=this.joinQueryBuilder.leftToRight[t],n=e[0][t];if(0===i.length)return n;const s={[t]:n};for(const t of i)s[t]=this.groupData(e,t);return s})}}class Qi{constructor(e,t,i,n,s,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=n,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={[Si]:we()};else e=e&&"string"!=typeof e?{__id:oi(e)}:{__id:e||we()};const t=ki(oi(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 i of e)await this.doc(i.id).upsert(i.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)i instanceof Di?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new Ni(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new Li(...e)}}class Li{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 i=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==i.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<i.length;e++)if(t[e].fieldName!==i[e].fieldName||t[e].asc!==i[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 Li(...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 Oi(this,e)}or(e,...t){return o([...t]).pipe(v(t=>{const i=new Set,n=t.flat(),s=[];for(const e of n)i.has(this.extractData(e))||(i.add(this.extractData(e)),s.push(e));return s.sort((t,i)=>{for(const{fieldName:n,asc:s}of e){const e=Kt(this.extractData(t),n),r=Kt(this.extractData(i),n);if(!Ti(e,r,"=="))return Ti(r,e,"<")?s?-1:1:s?1:-1}return 0}).slice(0,this.getLimit())}))}}class Ui{constructor(e,t,i,n){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=i,this.dataManager=n,this.collections=new Map}get(e,t){let i=this.collections.get(t);i||(i=new Map,this.collections.set(t,i));let n=i.get(e);return n||(n=new Qi(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,n)),n}}class $i{constructor(e,t,i){this.clientIdService=e,this.socketManager=t,this.runtimeOptions=i,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 Gi=N(150);function Hi(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?ti(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function Wi(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function Ki(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 i=ti(e);t=ti(t);for(const[e]of Wi(i)){const n=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&n>t.split(".").length)&&delete i.properties[e]}for(const[e,n]of Wi(t))i.properties[e]=Vi([...i.properties[e]||[],...n]);return i}(e,t);const i=ti(e);for(const[e,n]of Wi(t)){const t=n;for(const n of t){const t=Hi(Kt(i.properties,e),n);void 0===t?Jt(i.properties,e):zt(i.properties,e,t)}}return i}function Vi(e){let t=0;for(;t+1<e.length;){const i=zi(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function zi(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 Ji(e){const t={};for(const i of e){const e=`${i.squidDocIdObj.integrationId}/${i.squidDocIdObj.collectionName}/${i.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(i)}const i=[];for(const e in t){const n=t[e].reduce((e,t)=>be(Ki(e,t),"Merge result cannot be null"));i.push(n)}return i}const Yi="dataManager_runInTransaction";var Zi;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Zi||(Zi={}));class Xi{constructor(e,i,n,s,o,a,c,u,l){this.documentStore=e,this.mutationSender=i,this.socketManager=n,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)}hasSufficientData(e,t){return this.documentStore.hasSufficientData(e,t)}isDirty(e){if(this.knownDirtyDocs.has(e))return!0;if(this.pendingOutgoingMutations.get(e)?.length)return!0;const t=this.docIdToServerTimestamp.get(e),i=t&&!t.expireTimestamp?t.timestamp:void 0,n=this.docIdToLocalTimestamp.get(e);return!((!n||i)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&n===i)}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(Yi)?this.lockManager.lockSync(Yi):await this.lockManager.lock(Yi);let i=en;const n=()=>i!==en;return new Promise(async(t,s)=>{try{let r;this.currentTransactionId=we();try{r=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(n()?void 0:{resolve:()=>t(r),reject:s})}}catch(e){i=n()?i:e}finally{try{this.lockManager.release(Yi)}catch(e){i=n()?i:e}}n()&&s(i)})}async applyOutgoingMutation(e,t){const i=ki(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(Yi)||(await this.lockManager.lock(Yi),this.lockManager.release(Yi)),this.knownDirtyDocs.delete(i);const n=this.pendingOutgoingMutations.get(i)?.slice(-1)[0];if(n&&!n.sentToServer)n.mutation=be(Ji([n.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},n=this.pendingOutgoingMutations.get(i)||[];n.push(t),this.pendingOutgoingMutations.set(i,n),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(i),n="delete"===e.type?void 0:"update"===e.type?function(e,t){if(!e)return;const i={...e},n=Wi(t);for(const[e,t]of n){const n=t;for(const t of n){const n=Hi(Kt(i,e),t);void 0===n?Jt(i,e):zt(i,e,n)}}return i}(t,e):{...e.properties};this.updateDocumentFromSnapshot(i,n)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(i,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(i,n).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(Yi);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(Yi)}}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),D(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),D(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t={},i=[];for(const n of e){if(!this.querySubscriptionManager.hasOngoingQuery(n.clientRequestId))continue;const e=this.querySubscriptionManager.getQuery(n.clientRequestId),s=null!==e.projectFields&&void 0!==e.projectFields,r=this.querySubscriptionManager.hasSubscription(n.clientRequestId);s&&r?i.push({squidDocId:n.squidDocId,item:{properties:n.doc,timestamp:n.mutationTimestamp,clientRequestId:n.clientRequestId,projectFields:e.projectFields}}):t[n.squidDocId]={properties:n.doc,timestamp:n.mutationTimestamp}}Object.keys(t).length>0&&this.applyIncomingUpdates(t),i.length>0&&this.runInTransactionSync(()=>{this.applyProjectedUpdates(i)})}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId);if(null!==t.projectFields&&void 0!==t.projectFields){const i=[];for(const n of e.docs){const s=ki(n.__docId__,t.collectionName,t.integrationId);i.push({squidDocId:s,item:{properties:n,timestamp:n.__ts__,clientRequestId:e.clientRequestId,projectFields:t.projectFields}})}this.runInTransactionSync(()=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyProjectedUpdates(i)})}else{const i={};for(const n of e.docs){const e=ki(n.__docId__,t.collectionName,t.integrationId);i[e]={properties:n,timestamp:n.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(i,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)})}}applyIncomingUpdates(e,t){let i=!1;const n=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?i=!0:o&&o.timestamp>r.timestamp?s.add(t):(this.pendingIncomingUpdates.set(t,r),n.add(t))}return this.runInTransactionSync(()=>{for(const e of n)this.maybeApplyIncomingUpdate(e);for(const e of s)this.refreshQueryMapping(e)},t),i}applyProjectedUpdates(e){for(const{squidDocId:t,item:i}of e){const e=be(i.clientRequestId,"clientRequestId required for projected updates"),n=this.pendingOutgoingMutations.get(t);if(n&&n.length)continue;const s=this.docIdToServerTimestamp.get(t);s&&s.timestamp>i.timestamp?(this.querySubscriptionManager.addDocToQuery(t,e),this.batchClientRequestIds.add(e)):(this.acknowledgeDocument(t,i.timestamp,!i.properties),this.docIdToLocalTimestamp.set(t,i.timestamp),i.properties?(this.documentStore.saveProjectedDocument(t,i.properties,i.projectFields),this.querySubscriptionManager.addDocToQuery(t,e)):this.querySubscriptionManager.removeDocFromQuery(t,e),this.batchClientRequestIds.add(e))}}maybeApplyIncomingUpdate(e){const t=this.pendingIncomingUpdates.get(e);if(!t)return;const i=this.pendingOutgoingMutations.get(e);i&&i.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 i=this.documentStore.getDocumentOrUndefined(e);return!(!i&&!t||i===t)&&((!i||!t||oi({...t,__ts__:void 0})!==oi(i))&&(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 Gi.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(),e?.resolve()}catch(t){this.pendingOutgoingMutations.size||(this.outgoingMutationsEmpty.next(!0),await this.resyncFailedUpdates()),e?.reject(t)}}async sendMutationsForIntegration(e,t){try{const{timestamp:i,idResolutionMap:n={},refreshList:s=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(n),s.forEach(e=>{this.refreshDocIdToTimestamp.set(n[e]||e,i)});for(const t of e){let e=this.removeOutgoingMutation(t);n[e]&&(e=n[e]),this.acknowledgeDocument(e,i),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=ki(e.mutation.squidDocIdObj),i=be(this.pendingOutgoingMutations.get(t));return i.splice(i.indexOf(e),1),i.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}=Mi(t);this.setExpiration(t,!0);try{const i=e.includes(Si)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(be(i.length<=1,"Got more than one doc for the same id:"+t),!i.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,i]of this.refreshDocIdToTimestamp.entries()){const n=this.docIdToServerTimestamp.get(t)?.timestamp;n&&n>i||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 i=t[t.length-1];if(i&&!i.sentToServer){const t=i.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(i),i.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,i=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,i)}setExpiration(e,t){const i=this.docIdToServerTimestamp.get(e);i&&(i.expireTimestamp=t?Date.now()+2e4:void 0)}forgetDocument(e,t){this.docIdToLocalTimestamp.delete(e),this.pendingIncomingUpdates.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const i=ki(t.mutation.squidDocIdObj),n=e[i];n&&(t.mutation.squidDocIdObj=Mi(n))})}),Object.entries(e).forEach(([e,t])=>{Yt(this.pendingOutgoingMutations,e,t),Yt(this.docIdToLocalTimestamp,e,t),Yt(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 en=Symbol("undefined");class tn{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 nn{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=>{if(e)return;const t=Object.keys(this.ongoingLocks);t.length>0&&console.warn(`DistributedLockManager: WebSocket disconnected, releasing ${t.length} lock(s): [${t.join(", ")}]`),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 i=t?.acquisitionTimeoutMillis??2e3,n=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),me(await m(M(A(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:i,maxHoldTimeMillis:n,clientRequestId:s}};this.socketManager.postMessage(r);const o=await m(M(A(i+4e3).pipe(D(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 sn(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 sn{constructor(e,t,i,n,s){this.lockId=e,this.resourceId=t,this.clientRequestId=i,this.ongoingLocks=n,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 rn{constructor(e,i){this.documentStore=e,this.destructManager=i,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 on{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t,i){if(i)return new Di(e,be(this.dataManager,"dataManager not found"),t,i);let n=this.documents.get(e);if(n)return n;n=new Di(e,be(this.dataManager,"dataManager not found"),t);const{integrationId:s,collectionName:r}=Mi(e);this.documents.set(e,n);const o=this.getCollectionKey(s,r),a=this.documentsForCollection.get(o)||[];return this.documentsForCollection.set(o,a.concat(n)),n}setDataManager(e){this.dataManager=e}getDocumentsForCollection(e,t){const i=this.getCollectionKey(e,t);return(this.documentsForCollection.get(i)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const i=Mi(e),n=Mi(t);Yt(this.documents,i.docId,n.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class an{constructor(){this.squidDocIdToDoc=new Map,this.squidDocIdToProjectedFields=new Map}saveProjectedDocument(e,t,i){const n=this.squidDocIdToDoc.get(e);if(n){const i=this.mergeDocuments(n,t),s=this.removeInternalProperties(i);this.squidDocIdToDoc.set(e,s)}else{const i=this.removeInternalProperties(t);this.squidDocIdToDoc.set(e,i)}if(i?.length){const t=this.squidDocIdToProjectedFields.get(e);if(void 0!==t)for(const e of i)t.add(e);else n||this.squidDocIdToProjectedFields.set(e,new Set(i))}return this.squidDocIdToDoc.get(e)}mergeDocuments(e,t){const i=ti(e);for(const e of Object.keys(t)){const n=t[e],s=i[e];null===n||"object"!=typeof n||Array.isArray(n)||null===s||"object"!=typeof s||Array.isArray(s)?i[e]=n:i[e]=this.mergeDocuments(s,n)}return i}deleteDocument(e){this.squidDocIdToDoc.delete(e),this.squidDocIdToProjectedFields.delete(e)}saveDocument(e,t){const i=this.squidDocIdToDoc.get(e);if(void 0===i&&!t)return;if(void 0!==i){if(t){const i=ti(t),n=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,n),this.squidDocIdToProjectedFields.delete(e),n}return this.squidDocIdToDoc.delete(e),void this.squidDocIdToProjectedFields.delete(e)}const n=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,n),this.squidDocIdToProjectedFields.delete(e),n}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}hasSufficientData(e,t){if(!this.squidDocIdToDoc.has(e))return!1;const i=this.squidDocIdToProjectedFields.get(e);return void 0===i||!!t?.length&&t.every(e=>i.has(e))}group(e,t){return Object.values(si(e,e=>oi(t.map(t=>Kt(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=Array.from(e).map(e=>this.squidDocIdToDoc.get(e)).filter(fe),{sortOrder:n,limitBy:s}=t,r=i.sort((e,t)=>this.compareSquidDocs(e,t,n)),o=t.limit<0?2e3:t.limit;let a;if(s){const{limit:e,fields:t,reverseSort:i}=s,n=this.group(r,t);let c;c=i?n.map(t=>t.slice(-e)):n.map(t=>t.slice(0,e)),a=c.flat().slice(0,o)}else a=r.slice(0,o);return null!==t.projectFields&&void 0!==t.projectFields&&(a=a.map(e=>this.projectDocument(e,t.projectFields))),a}projectDocument(e,t){const i={};"__id"in e&&(i.__id=e.__id),"__docId__"in e&&(i.__docId__=e.__docId__);for(const n of t)if(n.includes(".")){const t=Kt(e,n);void 0!==t&&zt(i,n,t)}else n in e&&(i[n]=e[n]);return i}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;Yt(this.squidDocIdToDoc,e,t),Yt(this.squidDocIdToProjectedFields,e,t);const n=Mi(t),s=ci(n.docId);this.saveDocument(t,{...i,...s,__docId__:n.docId})}compareSquidDocs(e,t,i){for(const{fieldName:n,asc:s}of i){const i=ni(Kt(e,n),Kt(t,n));if(0!==i)return s?i:-i}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class cn{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const i={authCode:e,externalAuthConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/saveAuthCode",i)}async getAccessToken(e){const t={externalAuthConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/getAccessToken",t)}}class un{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const i={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",i,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const i={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",i)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class ln{constructor(e,t,i,n){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},n.isPassiveMode||this.clientIdService.observeClientId().pipe(p(),T(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))bi.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(t=>{const i=this.listeners[e];i&&(i.error(t),delete this.listeners[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}).catch(i=>{t.error(i),delete this.listeners[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,i=t.id,n=this.listeners[i];n&&("completed"===t.status?n.next(t.result):"failed"===t.status?n.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",i),delete this.listeners[i])}))}}const dn="squid_mgmt_",hn="x-squid-traceid",pn="x-squid-client-version";function gn(e="n_"){return`${e}${_e(10).toLowerCase()}`}const fn=e=>e();class yn extends Error{constructor(e,t,i,n,s){super(e),this.statusCode=t,this.url=i,this.headers=n,this.body=s}}const mn="1.0.456";async function bn(e){const t=await Mn({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage});return t.body=kn(t.body),t}async function In(e){const t=await Mn({...e,method:"GET",files:[],filesFieldName:""});return t.body=kn(t.body),t}async function vn(e){const t=await Mn({...e,method:"PUT"});return t.body=kn(t.body),t}async function wn(e){const t=await Mn({...e,method:"PATCH"});return t.body=kn(t.body),t}async function Sn(e){const t=await Mn({...e,method:"DELETE",files:[],filesFieldName:""});return t.body=kn(t.body),t}async function Mn({headers:e,files:t,filesFieldName:i,message:n,url:s,extractErrorMessage:r,method:o}){const a=new Headers(e);a.append(hn,gn("c_")),a.append(pn,mn);const c={method:o,headers:a,body:void 0};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const n of t)e.append(i||"files",n,n.name);e.append("body",ai(n)),c.body=e}else void 0!==n&&(a.append("Content-Type","application/json"),c.body=ai(n));else"DELETE"===o&&void 0!==n&&(a.append("Content-Type","application/json"),c.body=ai(n));try{const e=await fetch(s,c),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),n=kn(i);if(!r)throw new yn(i,e.status,s,t,n);let o;try{o="string"==typeof n?n:n?.message||i}catch{}throw o||(o=e.statusText),new yn(o,e.status,s,t,n)}const i=await e.text();return bi.debug(`received response from url ${s}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw bi.debug(`Unable to perform fetch request to url: ${s}`,e),e}}function kn(e){if(e){try{return ci(e)}catch{}return e}}class Tn{constructor(e){me(e.apiKey.startsWith(dn),`Invalid management API key format. Key must start with '${dn}'`),this.apiKey=e.apiKey,this.consoleRegion=e.consoleRegion}async createOrganization(e){return this.callApi("POST","organizations",e)}async createApplication(e){return this.callApi("POST","applications",e)}async deleteApplication(e){await this.callApi("DELETE",`applications/${e}`)}async renameOrganization(e){await this.callApi("PATCH",`organizations/${e.organizationId}`,{name:e.name})}async renameApplication(e){await this.callApi("PATCH",`applications/${e.appId}`,{name:e.name})}async callApi(e,t,i){const n=P(this.consoleRegion,"console",`openapi/iac/management/${t}`),s={Authorization:`ManagementKey ${this.apiKey}`};return"POST"===e?(await bn({url:n,headers:s,message:i,files:[],filesFieldName:"",extractErrorMessage:!0})).body:"PATCH"===e?(await wn({url:n,headers:s,message:i,extractErrorMessage:!0})).body:(await Sn({url:n,headers:s,message:i,extractErrorMessage:!0})).body}}class _n{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=Ji(e),n=i.map(e=>`sendMutation_${ki(e.squidDocIdObj)}`);await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:i,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw bi.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...n)}}}class qn{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class Cn{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.notifyWebSocketIsNeeded(),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 Dn={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class On{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!En.test(e)||e.length>=Rn);me(0===i.length,()=>`Tag name is not allowed: ${i.join(",")}`),this.isReporting=!0;const n={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},s=this.rpcManager.post("/observability/metrics",{metrics:[n]}).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={...Dn,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const i=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:i,noDataBehavior:n}=e,s=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-start-time"===n)return e;const s=t-e;let r=t-Math.floor(s/i)*i;return r>e&&(r-=i),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-end-time"===n)return t-i;const s=t-e;let r=e+Math.floor(s/i)*i;return r>=t&&(r-=i),r}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const i=[];for(let t=0;t<e.groupByTags.length;t++){const n=e.groupByTags[t],s=a[n]?.[0]||"";i.push(s)}t.push({tagValues:i,points:[]})}else"return-result-group-with-default-values"===n&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[i,n]of Object.entries(a)){const s=e.groupByTags.indexOf(i);if(!(s<0))for(let e=0;e<t.length;e++){const i=t[e],r=new Set(n);for(let e=0;e<t.length;e++){const n=t[e];i.tagValues.every((e,t)=>t===s||e===n.tagValues[t])&&r.delete(n.tagValues[s])}if(0!==r.size)for(const e of r){const n={tagValues:[...i.tagValues],points:[]};n.tagValues[s]=e,t.push(n)}}}for(const n of t){if(0!==n.points.length){const e=n.points[0][0],t=n.points[n.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+=i){const i=n.points[a];i?i[0]===e?(t.push(i),a++):(me(i[0]>e,()=>`Result point has invalid time: ${i[0]}`),t.push([e,...u])):t.push([e,...u])}n.points=t}}(t,i.resultGroups),i}}const En=/^[a-zA-Z0-9_-]+$/,Rn=1e3;async function An(e,t,i=500){const n=Date.now(),s=e.paginate({pageSize:i,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()-n}}function Fn(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:n}=t,{collectionName:s,integrationId:r}=i;let o=e.collection(s,r).query();return o=jn(o,i),n?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:n,joinConditions:s,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=jn(u,i.query),Object.entries(n).map(([t,i])=>{const{collectionName:n,integrationId:r}=i,{left:o,right:a,leftAlias:c}=s[t];let l=e.collection(n,r).query();l=jn(l,i),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:i}=t,{collectionName:n,integrationId:s}=Nn(i[0]),r=i.map(t=>Fn(e,t));return e.collection(n,s).or(...r)}(e,t)}}function jn(e,t){const{conditions:i,limit:n,sortOrder:s}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:i,operator:n,value:s}=t;e.where(i,n,s)}e.limit(n);for(const{fieldName:t,asc:i}of s)e.sortBy(t,i);return e}function Nn(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:i}=e.query;return{collectionName:t,integrationId:i}}case"join":{const{collectionName:t,integrationId:i}=e.root.query;return{collectionName:t,integrationId:i}}case"merged":return Nn(e.queries[0])}}const xn={"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)=>Pn(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Pn(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Pn(e,t)&&Qn(t),"like_cs:like_cs":(e,t)=>Pn(e,t),"like:not like":(e,t)=>!Bn(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!Bn(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!Bn(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!Bn(e,t),"not like:like":(e,t)=>Un(e,t),"not like_cs:like":(e,t)=>Un(e,t),"not like:like_cs":(e,t)=>Un(e,t),"not like_cs:like_cs":(e,t)=>Un(e,t),"not like:not like":(e,t)=>Pn(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Pn(t,e)&&Qn(e),"not like:not like_cs":(e,t)=>Pn(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Pn(t,e),"in:like":(e,t)=>e.every(e=>Ti(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Ti(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>Ti(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>Ti(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&&Ln(e)||$n(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Ln(e)||$n(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Ln(t)||$n(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Ln(t)||$n(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=>Ti(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Ti(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Ti(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Ti(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 Pn(e,t,i=0,n=0){if(n>=t.length)return i>=e.length;if(i>=e.length)return Ln(t.substring(n));const s=e[i],r=t[n];return"%"===s&&"%"===r?Pn(e,t,i+1,n+1)||Pn(e,t,i+1,n):"%"!==s&&("%"===r?Pn(e,t,i,n+1)||Pn(e,t,i+1,n):(s===r||"_"===r)&&Pn(e,t,i+1,n+1))}function Bn(e,t,i=0,n=0){if(i>=e.length&&n>=t.length)return!0;if(i>=e.length)return Ln(t.substring(n));if(n>=t.length)return Ln(e.substring(i));const s=i<e.length?e[i]:"",r=n<t.length?t[n]:"";return"%"===s&&"%"===r?Bn(e,t,i+1,n+1)||Bn(e,t,i,n+1)||Bn(e,t,i+1,n):"%"===s||"%"===r?Bn(e,t,i,n+1)||Bn(e,t,i+1,n):(s===r||"_"===s||"_"===r)&&Bn(e,t,i+1,n+1)}function Qn(e){return!/[a-zA-Z]/.test(e)}function Ln(e){return e.split("").every(e=>"%"===e)}function Un(e,t){return e.length>0&&Ln(e)||t.length>0&&Ln(t)||$n(e)&&0===t.length}function $n(e){let t=!1,i=!1;for(const n of e)switch(n){case"%":t=!0;break;case"_":if(i)return!1;i=!0;break;default:return!1}return t&&i}class Gn{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Ci))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}get projectFields(){return this.query.projectFields}sortedBy(e){return!e.find((e,t)=>!Xt(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,i){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:i})}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(Ci),i=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),s=-1===e.limit||this.limit>-1&&this.limit<e.limit,r=this.isProjectFieldsSubset(this.query.projectFields,e.projectFields);return i&&n&&s&&r}isProjectFieldsSubset(e,t){if(!t)return!0;if(!e)return!1;const i=new Set(t);return e.every(e=>i.has(e))}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 i=t.fieldName,n=t.operator,s=Kt(e,i);if("in"===n){if(t.value.includes(s))continue;return!1}if("not in"!==n){if(!Ti(t.value,s,n))return!1}else if(t.value.includes(s))return!1}return!0}evaluateSubset(e,t){const{operator:i,value:n}=e,{operator:s,value:r}=this.parseConditions([t])[0],o=xn[`${i}:${s}`];return!!o&&o(n,r)}parseConditions(e){const t=[],i=new Map,n=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":i.set(e.fieldName,(i.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),i.forEach((e,i)=>{t.push({fieldName:i,operator:"in",value:e})}),n.forEach((e,i)=>{t.push({fieldName:i,operator:"not in",value:e})}),t}}class Hn{constructor(e,t,i){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=i}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:i}=e,n=new Gn(e),s=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>n.documentMatchesQuery(e.data)),r={};return s.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[ki(e.__docId__,i,t)])}}function Wn(e,t){return H(function(i,n){var s=0;i.subscribe(he(n,function(i){return e.call(t,i,s++)&&n.next(i)}))})}class Kn{constructor(e,i){this.rpcManager=e,this.destructManager=i,this.safeToSendQueriesToServer=new t(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new t(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new r,i=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(),i):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.safeToSendQueriesToServer.pipe(Wn(Boolean),D(1)).subscribe(()=>{this.processQueryBatch()})},0),i)}async waitForAllQueriesToFinish(){return m(this.inflightQueriesCount.pipe(Wn(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()),i=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const i=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,s=i.errors[e],r=i.results[e];s?n.error(s):n.next(r)}}catch(e){i.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Vn={d:(e,t)=>{for(var i in t)Vn.o(t,i)&&!Vn.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function zn(e,t,...i){e||function(e,...t){const i=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof i)throw i;throw(e=>new Error(e))(i||"Assertion error",...t)}(t,...i)}function Jn(e,t){switch(t.type){case"set":return function(e,t,i){if(void 0===i)return Yn(e,t);if(0===t.length)return zn("object"==typeof i&&null!==i&&!Array.isArray(i),()=>`Root state must be a record. Trying to set '${i}', type: ${typeof i}`),i;function n(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 i=t[e];zn(!Array.isArray(s)||n(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),s=s[i],zn(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 zn(!Array.isArray(s)||n(r),()=>`Invalid array index Path: '${t}`),(null==s?void 0:s[r])===i?e:Zn(e,t,i)}(e,t.path,t.value);case"delete":return Yn(e,t.path);case"batch":return t.actions.reduce((e,t)=>Jn(e,t),e)}}function Yn(e,t){zn(0!==t.length,"Can't delete an empty path");let i=e;for(let n=0;n<t.length-1;n++){const s=t[n];if(i=i[s],void 0===i)return e;zn("object"==typeof i&&null!==i,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,n+1)}', type: ${null===i?"<null>":typeof i}`)}const n=t[t.length-1];return void 0===i[n]?e:Zn(e,t,void 0)}function Zn(e,t,i){function n(e,i){zn(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const s=Object.assign({},e);let r=s;for(let e=0;e<t.length-1;e++){const s=t[e],o=r[s];zn(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===i?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return n(r,s),r;r[s]=a,r=a}const o=t[t.length-1];return void 0===i?n(r,o):r[o]=i,s}function Xn(e,t){const i=[];if("set"===e.type||"delete"===e.type)i.push(e.path);else if("batch"===e.type)for(const t of e.actions)i.push(...Xn(t,"as-is"));return"unique-and-sorted"===t?is(i):i}function es(e,t){if(e.length<t.length)return!1;for(let i=0;i<t.length;i++)if(e[i]!==t[i])return!1;return!0}function ts(e){const t=[...e];return t.sort((e,t)=>{for(let i=0;i<e.length;i++){if(i===t.length)return 1;const n=e[i].localeCompare(t[i]);if(0!==n)return n}return e.length-t.length}),t}function is(e){const t=ts(e),i=t;for(let e=0;e<t.length-1;e++){const n=t[e];for(let s=e+1;s<t.length;s++){const r=t[s];n.length===r.length&&es(n,r)&&(i[s]=void 0,e++)}}return i.filter(e=>void 0!==e)}const ns=(ss={Observable:()=>n,Subject:()=>r},rs={},Vn.d(rs,ss),rs);var ss,rs;const os=(as={filter:()=>Wn,map:()=>ge},cs={},Vn.d(cs,as),cs);var as,cs;class us{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 i=this._buildPath(e);if(void 0!==i.value)return i.value;const n=t(e);return this._setNodeValue(i,n,void 0===n),n}set(e,t){const i=void 0===t?this._findNode(e):this._buildPath(e);i&&this._setNodeValue(i,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 i=(void 0===t.value?0:1)+t.childrenWithValue;i>0&&this._updateChildrenWithValue(t,-i),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const i=this.getNode(e);return void 0===i?0:i.childrenWithValue+("node-and-children"===t&&void 0!==i.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const i=[];let n=this.root,s=t(n.value,i);if(s!==us.StopFillToken){this._setNodeValue(n,s,!1);for(let r=0;r<e.length;r++){const o=e[r];i.push(o);let a=n.children.get(o);if(s=t(null==a?void 0:a.value,i),s===us.StopFillToken)break;a||(a={children:new Map,parent:n,childrenWithValue:0},n.children.set(o,a)),this._setNodeValue(a,s,!1),n=a}this._runGc(n)}}visitDfs(e,t,i=[]){const n=this.getNode(i);void 0!==n&&this._visitDfs(e,n,t,[...i])}_visitDfs(e,t,i,n){if("pre-order"===e&&!1===i(t.value,n))return!1;for(const[s,r]of t.children){if(n.push(s),!this._visitDfs(e,r,i,n))return!1;n.pop()}return"in-order"!==e||!1!==i(t.value,n)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const i of e)if(t=t.children.get(i),!t)return;return t}_findNode(e){let t=this.root;for(let i=0;i<e.length&&t;i++)t=t.children.get(e[i]);return t}_buildPath(e){let t=this.root;for(let i=0;i<e.length;i++){const n=e[i];let s=t.children.get(n);s||(s={children:new Map,parent:t,childrenWithValue:0},t.children.set(n,s)),t=s}return t}_setNodeValue(e,t,i){if(e.value!==t){const i=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,i)}i&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let i=e.parent;i;i=i.parent)if(i.childrenWithValue+=t,i.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))}}us.StopFillToken=Symbol("Trie.StopFillToken");class ls extends ns.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class ds{constructor(e){this.rootState=e,this.observersTrie=new us,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,os.map)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,i){(null==i?void 0:i(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=Jn(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Xn(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),n=is([...t,...i]),s=new us;for(const e of n)s.fillPath(e,()=>!0);s.visitDfs("pre-order",(t,i)=>{const n=this.observersTrie.get(i);if(n){const t=this.get(i),s=n.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;n.next({action:e,value:t,oldValue:s})}})}_observeChanges(e,t=[],i){const n=0===t.length?void 0:new us;for(const e of t)null==n||n.set(e,!0);return new ns.Observable(t=>{const s=this.observersTrie.getOrSet(e,()=>new ls);s.isAllDetailsMode=s.isAllDetailsMode||"all-details"===i;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=s.pipe((0,os.filter)(({action:e})=>void 0===n||Xn(e,"as-is").some(e=>!n.get(e))),(0,os.map)(({action:t,value:i,oldValue:n})=>{let r=this.stubForUnusedPaths;if(s.isAllDetailsMode){const i=Xn(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=ts(e),i=t;for(let e=0;e<i.length-1;e++){const n=t[e];for(let s=e+1;s<t.length;s++)es(t[s],n)&&(i[s]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>es(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:n,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),s.observed||this.observersTrie.delete(e)}})}_get(e,t){let i=e;for(let e=0;e<t.length&&void 0!==i;e++){const n=t[e];i=null==i?void 0:i[n]}return i}selectChildPathsWithObservers(e){const t=[];for(const i of e)this.observersTrie.count(i,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,i)=>{e&&t.push([...i])},i);return t}}function hs(e,t,i=(e,t)=>e>t?1:e<t?-1:0,n=0,s=e.length-1){if(s<n)return-1;const r=Math.trunc((n+s)/2);return 0===i(t,e[r])?r:i(t,e[r])>0?hs(e,t,i,r+1,s):hs(e,t,i,n,r-1)}function ps(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==hs(e,t,i))return;let n;for(n=e.length-1;n>=0&&i(e[n],t)>0;n--)e[n+1]=e[n];e[n+1]=t}function gs(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const n=hs(e,t,i);n>-1&&e.splice(n,1)}const fs=100;class ys{constructor(e,t,i,n,s,o,a,c){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=n,this.documentIdentityService=s,this.querySender=o,this.socketManager=a,this.lockManager=c,this.onOrphanDocuments=new r,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new bs,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:i,integrationId:n}=Mi(t),s=this.queryMappingManager.getMapping(i,n);return s?function(e,t){const i=[...e.unconditional||[]],n=new Map;for(const[i,s]of Object.entries(e.conditional||{})){const e=ci(i);let r;if(Ci(e)){const i=Kt(t,e.fieldName)??null;r=Ti(e.value,i,e.operator)}else r=ms(e,t);if(r)for(const e of s)n.set(e,(n.get(e)||0)+1)}for(const[t,s]of n.entries())s>=e.queriesMetadata[t].condCount&&i.push(t);return i}(s,e):[]}setClientRequestIdsForLocalDoc(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set,n=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([...i,...n]);for(const t of[...i]){if(n.has(t))continue;i.delete(t);const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),i.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...s]}addDocToQuery(e,t){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}removeDocFromQuery(e,t){const i=this.localDocumentToClientRequestIds.get(e);let n=!i;i&&(i.delete(t),i.size||(this.localDocumentToClientRequestIds.delete(e),n=!0));const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),n&&this.documentStore.deleteDocument(e)}errorOutAllQueries(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of i){const i=this.ongoingQueries.get(e);i&&(this.destructManager.isDestructing?i.dataSubject.complete():i.dataSubject.error(t),i.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const i of e){const e=this.ongoingQueries.get(i);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(i)||new Set,s=this.documentStore.sortAndLimitDocs(n,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 Zi.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+100?Zi.ENABLED:Zi.DISABLED;break;case Zi.DISABLED:break;case Zi.ENABLED:if(n.size<e.query.limit+20){e.limitUnderflowState=Zi.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 Gn(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,n,r,a,c){return r&&this.socketManager.notifyWebSocketIsNeeded(),d(()=>{const u=this.createOngoingQueryGraph(e,t,i,n,r,!0,{},c);a&&(u.forceFetchFromServer=!0),this.lockManager.canGetLock(Yi)||console.warn("WARNING: Executing a query inside a transaction is not supported and will cause a transaction deadlock. If you are executing a query while an active transaction is running but outside of its callback, you can disregard this message."),this.sendQueryToServerOrUseParentQuery(u),u.allObservables=new s(1);const l=u.allObservables.pipe(C(e=>o(e).pipe(ge(e=>this.joinResults(e,n,u)))),Wn(()=>this.allOngoingQueriesGotInitialResult(u)),_(void 0),S(),Wn(([e,t])=>!Xt(e,t)),ge(([,e])=>e),r?R():D(1),f(()=>{u.dataSubject.complete(),u.done=!0,this.completeAllSupportedQueries(u),u.allObservables?.complete()})),d=this.collectAllObservables(u);return u.allObservables.next(d),l}).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 Gn(e.query);for(const i of this.ongoingQueries.values()){if(e===i)return;if(this.isValidParent(i)&&t.isSubqueryOfQuery(i.query))return i}}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const i=[];for(const n of t){const t=be(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),i.push(n))}i.length&&this.onOrphanDocuments.next(i)}registerQueryFinalizer(e){const t=e.clientRequestId,i=qi(this.clientIdService.getClientId(),t);e.dataSubject.pipe(f(async()=>{if(e.unsubscribeBlockerCount.value>0&&await m(M(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Wn(e=>0===e)))),this.queryMappingManager.removeQuery(i),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const i={clientRequestId:t};this.rpcManager.post("query/unsubscribe",i).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t)}),Wn(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,i,n,s,r,o,a={},c){if(a[i])return a[i];const u=o&&c?c:this.clientIdService.generateClientRequestId(),l=[],d={clientRequestId:u,activated:o,alias:i,query:e,subscribe:r,dataSubject:new t(null),supportedQueries:l,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?Zi.UNKNOWN:Zi.DISABLED};this.registerQueryFinalizer(d),this.ongoingQueries.set(u,d),a[i]=d;for(const[e,t]of Object.entries(s)){const o=t.leftAlias;if(o!==i&&e!==i)continue;const c=o===i?e:o;if(o===i){const e=this.createOngoingQueryGraph(n[c],c,n,s,r,!1,a);e.joinCondition=t,l.push(e)}else d.supportingOngoingQuery=this.createOngoingQueryGraph(n[c],c,n,s,r,!1,a)}return d}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(Wn(Boolean),ge(e=>({docs:e,alias:i}))));for(const i of e.supportedQueries)this.collectAllObservables(i,t);return t}joinResults(e,t,i){const n=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let s=n[i.alias].map(e=>({[i.alias]:e}));const r=this.getOngoingQueriesBfs(i),o=new Set;for(let e=1;e<r.length;e++){const i=r[e].alias;o.has(i)||(o.add(i),s=this.join(s,i,n[i],t[i]))}return s}join(e,t,i,n){if(!e.length)return e;const s=Object.keys(e[0]);if(!n||!s.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[n.right]);r.has(t)||r.set(t,[]),be(r.get(t)).push(e)}),e.flatMap(e=>{const i=r.get(this.transformKey(e[n.leftAlias]?.[n.left]))||[];return i.length?i.map(i=>({...e,[t]:i})):n.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],i=[e];for(;i.length;){const e=be(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,i){const n=be(i.joinCondition),s=i.query;if(i.activated){if(!i.canExpandForJoin)return!1;const r=be(i.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===i.alias),o=new Set(e.map(e=>e[n.left]??null));for(const e of r)e.query.conditions.filter(Ci).filter(e=>e.fieldName===n.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const a=ti(s);a.conditions=a.conditions.filter(e=>!Ci(e)||e.fieldName!==n.right),[...o].forEach(e=>{a.conditions.push({fieldName:n.right,operator:"==",value:e})});const c={...i,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(i.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(i.activated=!0,s.conditions.filter(Ci).filter(e=>e.fieldName===n.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(i),i.canExpandForJoin=!1,!0;const t=e.map(e=>e[n.left]??null).map(e=>({fieldName:n.right,operator:"==",value:e}));return t.length?(s.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(i)):i.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(Wn(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 i=e.query,n=e.clientRequestId,s=qi(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(i,s),this.ongoingQueries.set(n,e);const r=t?void 0:this.findValidParentOfOngoingQuery(e);r?this.useParentOngoingQuery(e,r):this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const i={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new Gn(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await m(t.queryRegistered.pipe(Wn(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",i).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(i=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,i),e.dataSubject.error(i)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const s=M(e.queryRegistered.pipe(Wn(Boolean),h(2e3),D(1)),this.destructManager.observeIsDestructing().pipe(D(1)));t.dataSubject.pipe(E(()=>!e.done),O(s),Wn(Boolean),R(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),ge(e=>e.filter(e=>n.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc(ki(i.__docId__,e.query.collectionName,e.query.integrationId),i);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,i=t>0&&e.subscribe?t+100:t,n={query:{...e.query,limit:i},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(n).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()):(bi.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 i of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{i.has(t)&&(i.delete(t),i.add(e[t]))});t.forEach(t=>{Yt(this.localDocumentToClientRequestIds,t,e[t])})}}function ms(e,t){for(const i of e.fields){const e=Kt(t,i.fieldName)??null;if(Ti(i.value,e,i.operator))return!0;if(Ti(i.value,e,"!="))return!1}return!1}class bs{constructor(){this.stateService=new ds({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const n=new Set;for(const s of e.conditions){if(Ci(s)&&["=="].includes(s.operator)){const e=ui(s.fieldName);n.has(e)||(i++,n.add(e))}else i++;const r=this.getConditionStatePath(e,s),o=[...this.stateService.get(r)||[]];ps(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];ps(n,t),this.stateService.set(i,n)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],i)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const i of t.conditions){const n=this.getConditionStatePath(t,i),s=[...this.stateService.get(n)||[]];gs(s,e),s.length?this.stateService.set(n,s):this.stateService.delete(n)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];gs(n,e),this.stateService.set(i,n)}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",(i=t,oi(i))];var i}}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)),D(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 i of e)this.locks[i]=new t(!0)}}class vs{constructor(e,t,i){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)}),i.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let i=this.queueManagers.get(e);i||(i=new Map,this.queueManagers.set(e,i));let n=i.get(t);return n||(n=new Ss(e,t,this.rpcManager,this.socketManager),i.set(t,n)),n}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const ws="subscriptionMutex";class Ss{constructor(e,t,i,n){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=n,this.messagesSubject=new r,this.subscriberCount=0,this.lockManager=new Is}async produce(e){await this.lockManager.lock(ws);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(ws)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),d(()=>(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(ws);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(ws)}}async performUnsubscribe(){await this.lockManager.lock(ws);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(ws)}}}class Ms{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}}class ks{constructor(e,i,n,s,r,o){this.region=e,this.appId=i,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")}),n.onDestruct(async()=>{await this.awaitAllSettled()});const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Ms(60*a,5),ai:new Ms(20*a,5),secret:new Ms(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:i}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return i&&(n+=`; IntegrationId ${i}`),{Authorization:n}}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,i=[],n="files",s={}){return(await this.rawPost(e,t,i,n,!0,s)).body}async rawPost(e,t,i=[],n="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};bi.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 bn({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),s={...this.staticHeaders,...n};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,i])=>{e.append(t,String(i))}),r+=`?${e.toString()}`}return bi.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await In({url:r,headers:s,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async put(e,t,i=[],n="files"){return(await this.rawPut(e,t,i,n)).body}async rawPut(e,t,i=[],n="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};bi.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 vn({url:a,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async patch(e,t,i=[],n="files"){return(await this.rawPatch(e,t,i,n)).body}async rawPatch(e,t,i=[],n="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};bi.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 wn({url:a,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),s={...this.staticHeaders,...n};bi.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 Sn({url:r,headers:s,message:t,extractErrorMessage:i})}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")}}function Ts(e){me(!e.isPassiveMode,"This operation is not available in passive mode. Use active mode for real-time features.")}class _s{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 qs(){}const Cs="undefined"!=typeof process&&process.versions?.node?N(220):mi().WebSocket;class Ds{constructor(e,i,n,s=fn,o,a,c){this.clientIdService=e,this.region=i,this.appId=n,this.messageNotificationWrapper=s,this.destructManager=o,this.authManager=a,this.runtimeOptions=c,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),D(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe(T(1),g(e=>!e),C(()=>M(A(this.clientTooOldThreshold),this.connectionReady.pipe(g(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?bi.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(bi.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?bi.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?bi.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(bi.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),bi.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(){Ts(this.runtimeOptions),await m(this.observeConnectionReady().pipe(g(Boolean)))}notifyWebSocketIsNeeded(){Ts(this.runtimeOptions),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&&(bi.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.notifyWebSocketIsNeeded(),this.connectionReady.value||console.warn(`SocketManager.sendMessageImpl: connectionReady=false, waiting... (message type: ${e.type})`),await m(M(this.connectionReady.pipe(g(Boolean)),A(12e4).pipe(R(()=>{throw new Error("WebSocket connection not ready within 2 minutes")}))));const t=await this.authManager.getToken();if(this.connectionReady.value)try{me(this.socket,"Socket is undefined in sendMessageAsync");const i=ai({message:e,authToken:t});bi.debug(this.clientIdService.getClientId(),"Sending message to socket: ",i),this.socket.send(i)}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(ai({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();bi.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,n=0,s=1;const r={connected:!1,closeCalled:!1,open(){i=new(Cs?.WebSocket??Cs)(e,t.protocols||[]),i.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.")}:qs,i.onopen=function(e){r.connected=!0,(t.onopen||qs)(e),n=0},i.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return bi.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||qs)(e),void r.reconnect(e);(t.onclose||qs)(e)},i.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||qs)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;s&&n++<i?s=setTimeout(function(){(t.onreconnect||qs)(e),bi.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||qs)(e)},json(e){i.send(JSON.stringify(e))},send(e){i.send(e)},close(e=4999,t){r.closeCalled=!0;try{r.connected=!1,clearTimeout(s),s=void 0,i.close(e,t)}catch(e){}}};return r.open(),r}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{bi.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{bi.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):bi.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{bi.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):bi.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 bi.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=ci(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),bi.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(R(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(A(0)),this.connectionReady.next(!1),await m(A(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Os(e){var t,i;i="Invalid application ID",me(function(e){return"string"==typeof e}(t=e),()=>ve(i,"Not a string",t));const[n,s,r,o]=e.split("-");return me(!o,`Invalid application ID: ${e}`),{appId:n,environmentId:s??"prod",squidDeveloperId:r}}function Es(e,t){return`${Os(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function Rs(e,t,i){return`${Es(e,t)}${i?`-${i}`:""}`}function As(e){const t=Os(e);return Es(t.appId,t.environmentId)}class Fs{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,i){const n={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:i};await this.rpcManager.post("storage/uploadFile",n,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const i={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",i)}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 js{constructor(e,t,i,n,s){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=n,this.consoleRegion=s}get shortUrlHeaders(){return{"Content-Type":"application/json","x-app-api-key":this.apiKey}}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){me(this.apiKey,"API key is required to create a short URL");const t="string"==typeof e?{url:e}:e,i=B(this.region,this.consoleRegion,"openapi/sqd/shorten"),n={url:t.url,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension},s=await fetch(i,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(n)}),r=await s.text();return me(s.ok,`Failed to create short URL (${s.status}): ${r}`),JSON.parse(r)}async createShortUrls(e){me(this.apiKey,"API key is required to create a short URL");const t=Array.isArray(e)?{urls:e}:e,i=B(this.region,this.consoleRegion,"openapi/sqd/shortenMany"),n={urls:t.urls,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension},s=await fetch(i,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(n)}),r=await s.text();return me(s.ok,`Failed to create short URLs (${s.status}): ${r}`),JSON.parse(r)}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"),i={id:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(i)});me(n.ok,`Failed to delete short URL (${n.status}): ${n.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"),i={ids:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(i)});me(n.ok,`Failed to delete short URLs (${n.status}): ${n.statusText}`)}}class Ns{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i}async executeWebhook(e,t={}){const{headers:i={},queryParams:n={},body:s,files:r=[]}=t,o=await this.rpcManager.getAuthHeaders(),a={...this.rpcManager.getStaticHeaders(),...o,...i};let c=P(this.region,this.appId,`webhooks/${encodeURIComponent(e)}`);if(n&&Object.keys(n).length>0){const e=new URLSearchParams;Object.entries(n).forEach(([t,i])=>{e.append(t,String(i))}),c+=`?${e.toString()}`}const u=new Headers(a);let l;if(u.append(hn,gn("c_")),u.append(pn,mn),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,i])=>{e.append(t,String(i))}),l=e}else u.append("Content-Type","application/json"),l=ai(s||{});const d=await fetch(c,{method:"POST",headers:u,body:l}),h={};if(d.headers.forEach((e,t)=>{h[t]=e}),!d.ok){const e=await d.text();let t;try{t=JSON.parse(e)}catch{t=e}const i="string"==typeof t?t:t?.message||d.statusText;throw new yn(i,d.status,c,h,t)}const p=await d.text();let g;try{g=JSON.parse(p)}catch{g=p}return g}getWebhookUrl(e){return P(this.region,this.appId,e?`webhooks/${encodeURIComponent(e)}`:"webhooks")}}class xs{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new tn,me(e.appId,"APP_ID_MUST_BE_PROVIDED"),this.runtimeOptions={isPassiveMode:e.isPassiveMode??!1};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,i=Rs(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Ii(this.destructManager),bi.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new Ht(e.apiKey,e.authProvider),this.socketManager=new Ds(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager,this.runtimeOptions),this.rpcManager=new ks(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new Cn(this.socketManager,this.rpcManager),this.jobClient=new ln(this.socketManager,this.rpcManager,this.clientIdService,this.runtimeOptions),this.backendFunctionManager=new fi(this.rpcManager),this.aiClient=new Ut(this.socketManager,this.rpcManager,this.jobClient,this.backendFunctionManager),this.apiClient=new Gt(this.rpcManager),this.documentStore=new an,this.lockManager=new Is,this.distributedLockManager=new nn(this.socketManager,this.destructManager),this.documentIdentityService=new rn(this.documentStore,this.destructManager),this.documentReferenceFactory=new on(this.documentIdentityService),this.querySender=new Kn(this.rpcManager,this.destructManager),this.observabilityClient=new On(this.rpcManager),this.schedulerClient=new _s(this.rpcManager),this._appId=i,this.querySubscriptionManager=new ys(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager,this.lockManager),this.localQueryManager=new Hn(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const n=new _n(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Ei(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new Xi(this.documentStore,n,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new Ui(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.webhookManager=new Ns(this.rpcManager,e.region,i),this.nativeQueryManager=new qn(this.rpcManager),this._connectionDetails=new $i(this.clientIdService,this.socketManager,this.runtimeOptions),this.queueManagerFactory=new vs(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new $(this.rpcManager,this.options.region,As(i),this.options.consoleRegion),this.webClient=new js(this.rpcManager,this.options.region,As(i),this.options.apiKey,this.options.consoleRegion)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}get isDestructed(){return this.destructManager.isDestructing}static getInstance(e){const t=oi(e);let i=xs.squidInstancesMap[t];return i||(i=new xs(e),xs.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(xs.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,...i){return this._validateNotDestructed(),this.backendFunctionManager.executeFunctionWithHeaders(e,t,...i)}executeWebhook(e,t){return this._validateNotDestructed(),this.webhookManager.executeWebhook(e,t)}getWebhookUrl(e){return this._validateNotDestructed(),this.webhookManager.getWebhookUrl(e)}executeNativeRelationalQuery(e,t,i={}){const n={type:"relational",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativePureQuery(e,t,i={}){const n={type:"pure",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,i){const n={type:"mongo",collectionName:t,aggregationPipeline:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeElasticQuery(e,t,i,n="_search",s="GET"){const r={type:"elasticsearch",index:t,endpoint:n,method:s,body:i,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 Fs(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new cn(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new un(this.rpcManager)}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t,i){const n=await this.acquireLock(e,i);try{return await t(n)}finally{n.release()}}queue(e,t=Dt){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(xs.squidInstancesMap).find(([,e])=>e===this);e&&delete xs.squidInstancesMap[e[0]]})}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,i)=>P(e,t,i),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,i)=>Rs(e,t,i)}}_validateNotDestructed(){me(!this.destructManager.isDestructing,"The client was already destructed.")}}export{wt as AI_AGENTS_INTEGRATION_ID,ht as AI_AUDIO_CREATE_SPEECH_MODEL_NAMES,dt as AI_AUDIO_TRANSCRIPTION_MODEL_NAMES,$e as AI_CHAT_MESSAGE_SOURCE,tt as AI_EMBEDDINGS_MODEL_NAMES,lt as AI_IMAGE_MODEL_NAMES,He as AI_PROVIDER_TYPES,Bt as ALL_OPERATORS,ze as ANTHROPIC_CHAT_MODEL_NAMES,yt as API_INJECTION_FIELD_TYPES,Pt as ARRAY_OPERATORS,kt as AUTH_INTEGRATION_TYPES,$ as AdminClient,Ae as AiAgentClient,Ee as AiAgentReference,je as AiAudioClient,Ut as AiClient,Ne as AiFilesClient,xe as AiImageClient,Qe as AiKnowledgeBaseClient,Be as AiKnowledgeBaseReference,Le as AiMatchMakingClient,Gt as ApiClient,U as ApiKeysSecretClient,Ht as AuthManager,et as BEDROCK_EMBEDDING_MODEL_NAMES,It as BUILT_IN_AGENT_ID,Ct as BUILT_IN_DB_INTEGRATION_ID,Dt as BUILT_IN_QUEUE_INTEGRATION_ID,Ot as BUILT_IN_STORAGE_INTEGRATION_ID,fi as BackendFunctionManager,Ri as BaseQueryBuilder,Lt as CLIENT_CONNECTION_STATES,vi as CLIENT_ID_GENERATOR_KEY,wi as CLIENT_REQUEST_ID_GENERATOR_KEY,ji as Changes,Ii as ClientIdService,Qi as CollectionReference,Ui as CollectionReferenceFactory,$i as ConnectionDetails,Mt as DATA_INTEGRATION_TYPES,ke as DEFAULT_SHORT_ID_LENGTH,Xi as DataManager,xi as DereferencedJoin,tn as DestructManager,sn as DistributedLockImpl,nn as DistributedLockManager,Di as DocumentReference,on as DocumentReferenceFactory,an as DocumentStore,Fe as EMPTY_CHAT_ID,bt as ENVIRONMENT_IDS,cn as ExternalAuthClient,un as ExtractionClient,fs as FETCH_BEYOND_LIMIT,ut as FLUX_MODEL_NAMES,Ke as GEMINI_CHAT_MODEL_NAMES,Tt as GRAPHQL_INTEGRATION_TYPES,Ve as GROK_CHAT_MODEL_NAMES,Bi as GroupedJoin,_t as HTTP_INTEGRATION_TYPES,vt as HttpStatus,qt as INTEGRATION_SCHEMA_TYPES,St as INTEGRATION_TYPES,Q as IntegrationClient,ln as JobClient,Ni as JoinQueryBuilder,hi as LastUsedValueExecuteFunctionCache,Zi as LimitUnderflowState,Hn as LocalQueryManager,jt as METRIC_DOMAIN,Ft as METRIC_FUNCTIONS,Nt as METRIC_INTERVAL_ALIGNMENT,xt as METRIC_NO_DATA_BEHAVIOR,Tn as ManagementClient,Ue as MatchMaker,_n as MutationSender,fn as NOOP_FN,qn as NativeQueryManager,Cn as NotificationClient,ot as OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES,at as OPENAI_AUDIO_MODEL_NAMES,rt as OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES,We as OPENAI_CHAT_MODEL_NAMES,Ze as OPENAI_EMBEDDINGS_MODEL_NAMES,st as OPENAI_IMAGE_MODEL_NAMES,pt as OPEN_AI_CREATE_SPEECH_FORMATS,On as ObservabilityClient,Oi as Pagination,Fi as QueryBuilder,Ei as QueryBuilderFactory,Kn as QuerySender,ys as QuerySubscriptionManager,vs as QueueManagerFactory,Ss as QueueManagerImpl,ft as RAG_TYPES,Ge as RERANK_PROVIDERS,Yi as RUN_IN_TRANSACTION_MUTEX,Ms as RateLimiter,ks as RpcManager,Et as SQUID_BUILT_IN_INTEGRATION_IDS,At as SQUID_METRIC_NAMES,Qt as SQUID_REGIONS,ct as STABLE_DIFFUSION_MODEL_NAMES,_s as SchedulerClient,L as SecretClient,Ds as SocketManager,xs as Squid,yn as SquidClientError,Fs as StorageClient,Je as VENDOR_AI_CHAT_MODEL_NAMES,Xe as VOYAGE_EMBEDDING_MODEL_NAMES,js as WebClient,Ns as WebhookManager,Ts as assertNotPassiveMode,li as compareArgsByReference,di as compareArgsBySerializedValue,Fn as deserializeQuery,Me as generateId,_e as generateShortId,qe as generateShortIds,we as generateUUID,Se as generateUUIDPolyfill,B as getConsoleUrl,yi as getCustomizationFlag,it as isAiEmbeddingsModelName,Rt as isBuiltInIntegrationId,nt as isIntegrationEmbeddingModelSpec,gt as isIntegrationModelSpec,mt as isPlaceholderParam,Ye as isVendorAiChatModelName,Sn as rawSquidHttpDelete,In as rawSquidHttpGet,wn as rawSquidHttpPatch,bn as rawSquidHttpPost,vn as rawSquidHttpPut,pi as transformFileArgs,kn as tryDeserializing,An as visitQueryResults};
|
|
1
|
+
import*as e from"ws";import{BehaviorSubject as t,NEVER as i,Observable as n,ReplaySubject as s,Subject as r,combineLatest as o,combineLatestWith as a,concatMap as c,debounceTime as u,defaultIfEmpty as l,defer as d,delay as h,distinctUntilChanged as p,filter as g,finalize as f,first as y,firstValueFrom as m,from as b,interval as I,lastValueFrom as v,map as w,of as S,pairwise as M,race as k,share as T,skip as _,startWith as q,switchAll as D,switchMap as C,take as O,takeUntil as E,takeWhile as R,tap as A,timer as F}from"rxjs";var j={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,s)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const r=i(642);t.default=r.PromisePool,s(i(273),t),s(i(642),t),s(i(837),t),s(i(426),t),s(i(858),t),s(i(172),t)},837(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class i extends Error{constructor(e,t){super(),this.raw=e,this.item=t,this.name=this.constructor.name,this.message=this.messageFrom(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e,t){return new this(e,t)}messageFrom(e){return e instanceof Error||"object"==typeof e?e.message:"string"==typeof e||"number"==typeof e?e.toString():""}}t.PromisePoolError=i},234(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=i(642),s=i(172),r=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],taskTimeout:0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw 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(n.PromisePool.notRun),this):this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=n.PromisePool.notRun),this.startProcessing(t,e),e+=1,await this.waitForProcessingSlot()}return await this.drained()}async waitForProcessingSlot(){for(;this.hasReachedConcurrencyLimit();)await this.waitForActiveTaskToFinish()}async waitForActiveTaskToFinish(){await Promise.race(this.tasks())}startProcessing(e,t){const i=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(i)}).catch(async n=>{await this.handleErrorFor(n,e,t),this.removeActive(i)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(i),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[i,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise((i,n)=>{t=setTimeout(()=>{n(new 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,i){if(this.shouldUseCorrespondingResults()&&(this.results()[i]=n.PromisePool.failed),!this.isStoppingThePoolError(e)){if(this.isValidationError(e))throw this.markAsStopped(),e;this.hasErrorHandler()?await this.runErrorHandlerFor(e,t):this.saveErrorFor(e,t)}}isStoppingThePoolError(e){return e instanceof o.StopThePromisePoolError}isValidationError(e){return e instanceof 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())}}},642(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(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 n.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=s,s.notRun=Symbol("notRun"),s.failed=Symbol("failed")},426(e,t){Object.defineProperty(t,"__esModule",{value:!0})},858(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i},172(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class i extends Error{constructor(e){super(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e){return new this(e)}}t.ValidationError=i},220(t){t.exports=e}},N={};function x(e){var t=N[e];if(void 0!==t)return t.exports;var i=N[e]={exports:{}};return j[e].call(i.exports,i,i.exports,x),i.exports}x.d=(e,t)=>{for(var i in t)x.o(t,i)&&!x.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},x.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),x.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const P=["api","application","auth","integration","internal-storage","management-secret","mutation","native-query","query","queue","quota","scheduler","secret","storage","ws","internal-extraction","notification"];function B(e,t,i,n,s,r){let o="https",a=`${n||t}.${s||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=P.includes(i.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=i.replace(/^\/+/,"");return l?`${u}/${l}`:u}function Q(e,t,i=""){return B(function(e,t){return t||(e.includes("sandbox")?"us-east-1.aws.sandbox":e.includes("local")?"local":e.includes("staging")?"us-central1.gcp.staging":"us-east-1.aws")}(e,t),"console",i)}class L{constructor(e,t,i,n){this.rpcManager=e,this.iacBaseUrl=Q(t,n,`openapi/iac/applications/${i}/integrations`)}async list(e){const t=await this.rpcManager.get(this.iacBaseUrl);return e?t.filter(t=>t.type===e):t}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getIntegrationSchema(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}/schema`)}async 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)}async generateAiDescriptionsForDataSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions`,t)}async generateAiDescriptionsForAssociations(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-associations`,t)}async generateAiDescriptionsForStoredProcedures(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-stored-procedures`,t)}async generateAiDescriptionsForEndpoints(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/schema/generate-ai-descriptions-for-endpoints`,t)}async discoverDataConnectionSchema(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-schema`,{})}async testDataConnection(e){return await this.rpcManager.post(`${this.iacBaseUrl}/test-connection`,e)}async discoverGraphQLConnectionSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-graphql-schema`,t)}async discoverOpenApiSchema(e,t){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema`,t)}async discoverOpenApiSchemaFromFile(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-openapi-schema-from-file`,{})}}class U{constructor(e){this.rpcManager=e}get apiKeys(){return new $(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 i={keys:[e],force:t};return this.rpcManager.post("secret/delete",i)}async deleteMany(e,t=!1){if(0===e.length)return;const i={keys:e,force:t};return this.rpcManager.post("secret/delete",i)}}class ${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 G{constructor(e,t,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=n,this.integrationClient=new L(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new U(this.rpcManager)}integrations(){return this.integrationClient}secrets(){return this.secretClient}}function H(e){return"function"==typeof e}function W(e){return function(t){if(function(e){return H(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 K=function(e,t){return K=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},K(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 i(){this.constructor=e}K(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function z(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function J(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,s,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=r.next()).done;)o.push(n.value)}catch(e){s={error:e}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(s)throw s.error}}return o}function Y(e,t,i){if(i||2===arguments.length)for(var n,s=0,r=t.length;s<r;s++)!n&&s in t||(n||(n=Array.prototype.slice.call(t,0,s)),n[s]=t[s]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var Z,X=((Z=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),Z.prototype.constructor=Z,Z);function ee(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var te=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,i,n,s;if(!this.closed){this.closed=!0;var r=this._parentage;if(r)if(this._parentage=null,Array.isArray(r))try{for(var o=z(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(H(c))try{c()}catch(e){s=e instanceof X?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=z(u),d=l.next();!d.done;d=l.next()){var h=d.value;try{ie(h)}catch(e){s=null!=s?s:[],e instanceof X?s=Y(Y([],J(s)),J(e.errors)):s.push(e)}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(s)throw new X(s)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)ie(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ee(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&ee(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function ie(e){H(e)?e():e.unsubscribe()}te.EMPTY;var ne={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var s=ne.delegate;return(null==s?void 0:s.setTimeout)?s.setTimeout.apply(s,Y([e,t],J(i))):setTimeout.apply(void 0,Y([e,t],J(i)))},clearTimeout:function(e){var t=ne.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function se(){}var re=oe("C",void 0,void 0);function oe(e,t,i){return{kind:e,value:t,error:i}}var ae=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof te||i&&"closed"in i&&H(i.remove)&&H(i.add)&&H(i.unsubscribe))&&t.add(n)):n.destination=he,n}return V(t,e),t.create=function(e,t,i){return new ue(e,t,i)},t.prototype.next=function(e){this.isStopped?de(function(e){return oe("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?de(oe("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?de(re,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}(te);Function.prototype.bind;var ce=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){le(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){le(e)}else le(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){le(e)}},e}(),ue=function(e){function t(t,i,n){var s,r=e.call(this)||this;return s=H(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,r.destination=new ce(s),r}return V(t,e),t}(ae);function le(e){!function(e){ne.setTimeout(function(){throw e})}(e)}function de(e,t){var i=null;i&&ne.setTimeout(function(){return i(e,t)})}var he={closed:!0,next:se,error:function(e){throw e},complete:se};function pe(e,t,i,n,s){return new ge(e,t,i,n,s)}var ge=function(e){function t(t,i,n,s,r,o){var a=e.call(this,t)||this;return a.onFinalize=r,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(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=n?function(){try{n()}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 i=this.closed;e.prototype.unsubscribe.call(this),!i&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(ae);function fe(e,t){return W(function(i,n){var s=0;i.subscribe(pe(n,function(i){n.next(e.call(t,i,s++))}))})}function ye(e){return null!=e}let me=e=>new Error(e);function be(e,t,...i){e||function(e,...t){const i=ve(e);if("object"==typeof i)throw i;throw me(i||"Assertion error",...t)}(t,...i)}function Ie(e,t,...i){return be(e,t,...i),e}function ve(e){return void 0===e?"":"string"==typeof e?e:e()}function we(e,t,i){const n=ve(e);if("object"==typeof n)throw n;return`${n?`${n}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}function Se(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():Me()}function Me(){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 ke(){return Se()}const Te=18;function _e(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()))}function qe(e=18,t="",i=""){be(t.length<e,"ID prefix is too long"),be(!t||!i||i.length>t.length,"Invalid 'prefix'/'prefixToAvoid' config");let n="";for(let t=0;t<e;t++)n+=_e();if(t.length>0&&(n=t+n.substring(t.length)),i)for(;n.charAt(t.length)===i[t.length];)n=n.substring(0,t.length)+_e()+n.substring(t.length+1);return n}function De({count:e,length:t,prefix:i}){be(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(qe(t||18,i||""));return[...n]}const Ce=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Oe(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)Oe(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)Oe(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(Ce.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${Ce.join(", ")}`);const i=e[t];if("object"!=typeof i&&"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof i}`)}}function Ee(e,t,i){const n=atob(e),s=new Uint8Array(n.length);for(let e=0;e<n.length;e++)s[e]=n.charCodeAt(e);return new File([s],t,{type:i||"application/octet-stream"})}class Re{constructor(e,t,i,n,s,r,o){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=i,this.rpcManager=n,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();be(t,"Agent not found");const i={...t.options?.guardrails,...e};await this.setAgentOptionInPath("guardrails",i)}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})}async listRevisions(){return await this.post("ai/agent/listRevisions",{agentId:this.agentId})}async restoreRevision(e){await this.post("ai/agent/restoreRevision",{agentId:this.agentId,revisionNumber:e})}async deleteRevision(e){await this.post("ai/agent/deleteRevision",{agentId:this.agentId,revisionNumber:e})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),s=await Ie(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:s.transcribedPrompt}}async ask(e,t,i){const n=await this.askInternal(e,!1,t,i);return this.replaceFileTags(n.responseString,n.annotations)}async askWithAnnotations(e,t,i){const n=await this.askInternal(e,!1,t,i);return{responseString:n.responseString,annotations:n.annotations}}async askAsync(e,t,i){const n={agentId:this.agentId,prompt:e,options:i,jobId:t};await this.post("ai/chatbot/askAsync",n)}observeStatusUpdates(e){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"aiStatus"===e.type&&e.agentId===this.agentId),g(t=>!e||t.jobId===e),fe(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,i){return await this.askInternal(e,!1,t,i)}async transcribeAndAskWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),s=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:Ee(s.base64File,`voice.${s.extension}`,s.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),s=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:Ee(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 addConnectedIntegration(e){await this.post("ai/agent/addConnectedIntegration",{agentId:this.agentId,integrationId:e.integrationId,integrationType:e.integrationType,description:e.description??""})}async addConnectedAgent(e){await this.post("ai/agent/addConnectedAgent",{agentId:this.agentId,connectedAgentId:e.agentId,description:e.description})}async addConnectedKnowledgeBase(e){await this.post("ai/agent/addConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e.knowledgeBaseId,description:e.description})}async addFunction(e){await this.post("ai/agent/addFunction",{agentId:this.agentId,functionId:e})}async removeConnectedAgent(e){await this.post("ai/agent/removeConnectedAgent",{agentId:this.agentId,connectedAgentId:e})}async removeConnectedIntegration(e){await this.post("ai/agent/removeConnectedIntegration",{agentId:this.agentId,integrationId:e})}async removeConnectedKnowledgeBase(e){await this.post("ai/agent/removeConnectedKnowledgeBase",{agentId:this.agentId,knowledgeBaseId:e})}async removeFunction(e){await this.post("ai/agent/removeFunction",{agentId:this.agentId,functionId:e})}async setAgentDescription(e){await this.post("ai/agent/setAgentDescription",{agentId:this.agentId,description:e})}async provideFeedback(e){const t={agentId:this.agentId,feedback:e};return await this.backendFunctionManager.executeFunction("provideAgentFeedback",t)}async build(e,t){const i={agentId:this.agentId,request:e,memoryId:t};return await this.backendFunctionManager.executeFunction("buildAgent",i)}replaceFileTags(e,t={}){let i=e;for(const[e,n]of Object.entries(t)){let t="";const s=n.aiFileUrl.fileName?n.aiFileUrl.fileName:n.aiFileUrl.url;switch(n.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${s}](${n.aiFileUrl.url})`}const r=`\${id:${e}}`;i=i.replaceAll("`"+r+"`",t).replaceAll(r,t)}return i}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&Oe(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)Oe(i.contextMetadataFilterForKnowledgeBase[e]);n=n||Se(),i={...Ae,...i||{}};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:i,jobId:n},a=s?void 0:[e];return await this.post(r,o,a,"file"),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&Oe(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)Oe(t.contextMetadataFilterForKnowledgeBase[e]);const n=Se(),s=void 0===(t={...Ae,...t||{}}).smoothTyping||t.smoothTyping;let o="";const a=new r,u=new r;this.ongoingChatSequences[n]=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:i})=>t?S({value:e,complete:t,annotations:i}):S(e).pipe(s?h(0):A(),fe(e=>({value:e,complete:!1,annotations:void 0})))),R(({complete:e})=>!e,!0)).subscribe({next:({value:e,complete:t,annotations:i})=>{o+=e,t&&i&&(o=this.replaceFileTags(o,i)),a.next(o)},error:e=>{console.error(e)},complete:()=>{a.complete()}});const d="string"==typeof e;i=i||Se();const p={agentId:this.agentId,jobId:i,prompt:d?e:void 0,options:t,clientRequestId:n},g={responseStream:a.pipe(f(()=>{delete this.ongoingChatSequences[n]}),T())};let y;return y=d?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=y.then(()=>this.jobClient.awaitJob(i)).catch(e=>{a.error(e),a.complete()}),g}async post(e,t,i=[],n="files"){const s={};return this.agentApiKey&&(s["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,i,n,s)}}const Ae={smoothTyping:!0,responseFormat:"text"};class Fe{constructor(e,t,i,n){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=n,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe(g(e=>"aiChatbot"===e.type),fe(e=>e)).subscribe(e=>{this.handleChatResponse(e)})}agent(e,t=void 0){return new Re(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:i,complete:n,tokenIndex:s,annotations:r}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===s?void 0:s,annotations:r});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===s?void 0:s,annotations:r})}}const je="__squid_empty_chat_id";class Ne{constructor(e){this.rpcManager=e}async transcribe(e,t={modelName:"whisper-1"}){return this.rpcManager.post("ai/audio/transcribe",t,[e])}async createSpeech(e,t){const i={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",i);return Ee(n.base64File,`audio.${n.extension}`,n.mimeType)}}class xe{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 i={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",i)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function Be(e){for(const t in e){const i=e[t];be("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),be(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class Qe{constructor(e,t,i){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async delete(){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:this.knowledgeBaseId})}async listContexts(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:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&Be(t.metadata);const i=Se();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:i},t),await this.jobClient.awaitJob(i)}async search(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return(await this.rpcManager.post("ai/knowledge-base/search",t)).chunks}async 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","bedrock","claude-code","cohere","flux","gemini","openai","grok","stability","voyage","mistral","textract","external"],Ke=["gpt-5-mini","gpt-5-nano","gpt-5.2","gpt-5.2-pro","gpt-5.4"],Ve=["gemini-3-pro","gemini-3-flash"],ze=["grok-4","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],Je=["claude-haiku-4-5-20251001","claude-opus-4-6","claude-sonnet-4-6"],Ye=[...Ke,...Je,...Ve,...ze];function Ze(e){return Ye.includes(e)}const Xe=["text-embedding-3-small"],et=["voyage-3-large"],tt=["titan-embed-text-v2"],it=[...Xe,...et,...tt];function nt(e){return it.includes(e)}function st(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const rt=["dall-e-3"],ot=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],at=["tts-1","tts-1-hd","gpt-4o-mini-tts"],ct=[...ot,...at],ut=["stable-diffusion-core"],lt=["flux-pro-1.1","flux-kontext-pro"],dt=[...rt,...ut,...lt],ht=[...ot],pt=[...at],gt=["mp3","opus","aac","flac","wav","pcm"];function ft(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const yt=["contextual","basic"],mt=["secret","regular"];function bt(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const It=["dev","prod"],vt="built_in_agent",wt={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,MOVED_TEMPORARILY:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,REQUEST_TOO_LONG:413,REQUEST_URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,REQUESTED_RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,INSUFFICIENT_SPACE_ON_RESOURCE:419,METHOD_FAILURE:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},St="ai_agents",Mt=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","bedrock","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","github","google_calendar","google_docs","google_drive","graphql","hubspot","jira","jira_jsm","jwt_hmac","jwt_rsa","kafka","keycloak","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","oracledb","pinecone","postgres","redis","s3","salesforce","sap_hana","sentry","snowflake","spanner","xata","zendesk","servicenow_csm","freshdesk","mail","slack","mcp","a2a","legend","teams","openai_compatible","openai_compatible_embedding"],kt=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch","legend"],Tt=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth"],_t=["graphql"],qt=["api"],Dt=["data","api","graphql"],Ct="built_in_db",Ot="built_in_queue",Et="built_in_storage",Rt=[Ct,Ot,Et];function At(e){return Rt.includes(e)}const Ft=["squid_functionExecution_count","squid_functionExecution_time"],jt=["sum","max","min","average","median","p95","p99","count"],Nt=["user","squid"],xt=["align-by-start-time","align-by-end-time"],Pt=["return-no-result-groups","return-result-group-with-default-values"],Bt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],Qt=[...Bt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],Lt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],Ut=["CONNECTED","DISCONNECTED","REMOVED"];class $t{constructor(e,t,i,n){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.backendFunctionManager=n}agent(e=vt,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()}async listFunctions(){const e=await this.rpcManager.post("/application/getBundleMetadata",{});return Object.values(e.aiFunctions||{})}async listChatModels(){return(await this.rpcManager.post("ai/settings/listChatModels",{})).models}image(){return new Pe(this.rpcManager)}audio(){return new Ne(this.rpcManager)}matchMaking(){return new Ue(this.rpcManager)}files(e){return new xe(e,this.rpcManager)}executeAiQuery(e,t,i){const n={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",n)}executeAiApiCall(e,t,i,n){const s={integrationId:e,prompt:t,options:i,sessionContext:n};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 i={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",i)).settings}observeStatusUpdates(e){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"aiStatus"===e.type),g(t=>!e||t.jobId===e),w(e=>({agentId:e.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})))}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Fe(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 Gt={headers:{},queryParams:{},pathParams:{}};class Ht{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,n){return this.request(e,t,i,n,"post")}async delete(e,t,i,n){return this.request(e,t,i,n,"delete")}async patch(e,t,i,n){return this.request(e,t,i,n,"patch")}async put(e,t,i,n){return this.request(e,t,i,n,"put")}async request(e,t,i,n,s){const r={integrationId:e,endpointId:t,body:i,options:{...Gt,...this.convertOptionsToStrings(n||{})},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 Wt{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 Kt=/[.\[\]]/;function Vt(e,t){if(!e)return;const i=t.split(Kt);let n,s=e;for(;s&&i.length;){const e=i.shift();if(e){if("object"!=typeof s||!(e in s))return;n=s[e],s=n}}return n}function zt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Jt(e,t,i,n="."){const s=t.split(n);let r=e;for(;s.length;){const e=Ie(s.shift());if(s.length){const t=r[e],i=zt(t)?ni(t)??{}:{};r[e]=i,r=i}else r[e]=i}}function Yt(e,t,i="."){const n=t.split(i);let s=e;for(;n.length;){const e=Ie(n.shift());if(n.length){const t=zt(s[e])?ni(s[e])??{}:{};s[e]=t,s=t}else delete s[e]}}function Zt(e,t,i){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(i,n)}}function Xt(e){return null==e}function ei(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const i=typeof e;if(i!==typeof t)return!1;if("object"!==i)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),s=Object.keys(t);if(n.length!==s.length)return!1;for(const i of n)if(!s.includes(i)||!ei(e[i],t[i]))return!1;return!0}function ti(e,t){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=ii(e[n],t);return i}function ii(e,t){const i=t?t(e):void 0;if(void 0!==i)return i;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return ti(e,t);if(e instanceof Map)return new Map(ti(Array.from(e),t));if(e instanceof Set)return new Set(ti(Array.from(e),t));if(ArrayBuffer.isView(e))return(n=e)instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const s={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(s[i]=ii(e[i],t));return s}function ni(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 si(e,t){if(e===t||Xt(e)&&Xt(t))return 0;if(Xt(e))return-1;if(Xt(t))return 1;const i=typeof e,n=typeof t;return i!==n?i<n?-1:1:"number"==typeof e?(be("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(be("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(be("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(be("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function ri(e,t){return e.reduce((e,i)=>{const n=t(i);return e[n]?e[n].push(i):e[n]=[i],e},{})}function oi(e){if(Array.isArray(e))return e.map(e=>oi(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),i={};return t.sort().forEach(t=>{i[t]=oi(e[t])}),i}function ai(e){return ci(oi(e))}function ci(e){if(void 0===e)return null;const t=ii(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function ui(e){return ii(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,i=t.$date;return i&&1===Object.keys(t).length?new Date(i):void 0})}function li(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=ci(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let i="";for(let t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return btoa(i)}}const di=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},hi=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(ci(e[i])!==ci(t[i]))return!1;return!0};class pi{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||di,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&i(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function gi(e){const t=[],i=[];let n=0;for(const s of e)if("undefined"!=typeof File)if(s instanceof File){i.push(s);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(fi(s)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:s.map((e,t)=>(i.push(s[t]),n++))};t.push(e)}else t.push(s);else t.push(s);return{argsArray:t,fileArray:i}}function fi(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class yi{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...i){const{argsArray:n,fileArray:s}=gi(i),r="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,a=o?.cache;if(a){const e=a.get(n);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?di:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,n));if(t)return t.promise}const u=this.createExecuteCallPromise(r,n,s,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:n,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,i,n,s={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:ci(t)},a=ui((await this.rpcManager.post(r,o,i.length>0?i:[],"files",s)).payload);if(a?.__isSquidBase64File__){const e=a;return Ee(e.base64,e.filename,e.mimetype)}return n&&n.set(t,a),a}}function mi(e){if("undefined"!=typeof globalThis)return globalThis[e]}function bi(){if("undefined"!=typeof window)return window;if(void 0!==x.g)return x.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}void 0===bi()?.SQUID_LOG_DEBUG_ENABLED&&function(e=!0){bi().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 Ii{static debug(...e){(function(){const e=bi();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=bi();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class vi{constructor(e){this.destructManager=e,this.clientTooOldSubject=new t(!1),this.isTenant=!0===bi().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),w(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe(_(1),g(e=>!e),w(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientRequestId(){const e=bi()[Si];return e?e():Se()}generateClientId(){const e=bi()[wi];if(e)return e();let t=`${this.isTenant?"tenant-":""}${Se()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const wi="SQUID_CLIENT_ID_GENERATOR",Si="SQUID_CLIENT_REQUEST_ID_GENERATOR",Mi="__squidId";function ki(e){return ui(e)}function Ti(...e){const[t,i,n]=e,s="object"==typeof t?t:{docId:t,collectionName:i,integrationId:n};return s.integrationId||(s.integrationId=void 0),ai(s)}function _i(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return ei(e,t);if("!="===i)return!ei(e,t);switch(i){case"<":return!Xt(e)&&(!!Xt(t)||t<e);case"<=":return!!Xt(t)||!Xt(e)&&t<=e;case">":return!Xt(t)&&(!!Xt(e)||t>e);case">=":return!!Xt(e)||!Xt(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&qi(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&qi(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&qi(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&qi(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>Ie(i,"VALUE_CANNOT_BE_NULL").some(t=>ei(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>Ie(i,"VALUE_CANNOT_BE_NULL").some(t=>ei(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!Ie(i,"VALUE_CANNOT_BE_NULL").some(t=>ei(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function qi(e,t,i){i||(e=e.toLowerCase(),t=t.toLowerCase());const n=function(e){let t="";for(let i=0;i<e.length;++i)"\\"===e[i]?i+1<e.length&&["%","_"].includes(e[i+1])?(t+=e[i+1],i++):i+1<e.length&&"\\"===e[i+1]?(t+="\\\\",i++):t+="\\":"%"===e[i]?t+="[\\s\\S]*":"_"===e[i]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[i])&&(t+="\\"),t+=e[i]);return t}(t);return new RegExp(`^${n}$`).test(e)}function Di(e,t){return`${e}_${t}`}function Ci(e){return"fieldName"in e}class Oi{constructor(e,t,i,n){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.projectFields=n,this.refId=Se()}setInMemoryData(e){this.inMemoryData=e}get squidDocId(){return this._squidDocId}get data(){return ii(this.dataRef)}get dataRef(){if(void 0!==this.inMemoryData)return this.inMemoryData;const e=Ie(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=ki(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:i,collectionName:e,integrationId:t},null,2)}`});return this.projectFields?this.applyProjection(e):e}get hasData(){return this.dataManager.hasSufficientData(this.squidDocId,this.projectFields)}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 Ie(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(w(e=>(Ie(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 i={};Object.entries(e).forEach(([e,t])=>{const n=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};i[e]=[n]});const n={type:"update",squidDocIdObj:ki(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,i){return this.update({[e]:ii(t)},i)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,i){const n={type:"applyNumericFn",fn:"increment",value:t},s={type:"update",squidDocIdObj:ki(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(s,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async upsert(e,t){const i=ki(this.squidDocId),n=i.integrationId;let s=ui(i.docId);if(s[Mi]&&(s={}),n===Ct&&s.__id)try{const e=ui(s.__id);s={...s,...e}}catch{}const r={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...s}};return this.dataManager.applyOutgoingMutation(r,t)}async insert(e,t){return this.upsert(e,t)}async delete(e){const t={type:"delete",squidDocIdObj:ki(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)}applyProjection(e){const t={},i=Ie(this.projectFields,"applyProjection called without projectFields"),{integrationId:n}=ki(this.squidDocId);"__id"in e&&(t.__id=e.__id),"__docId__"in e&&(t.__docId__=e.__docId__);const s=n===Ct?"__id":"__docId__";if(s in e){const i=e[s];if("string"==typeof i&&i.startsWith("{"))try{const e=ui(i);if("object"==typeof e&&null!==e)for(const[i,n]of Object.entries(e))i in t||(t[i]=n)}catch{}}for(const n of i)if(n.includes(".")){const i=Vt(e,n);void 0!==i&&Jt(t,n,i)}else n in e&&(t[n]=e[n]);return t}hasSquidPlaceholderId(){const e=ui(this._squidDocId);if("object"==typeof e&&e.docId){const t=ui(e.docId);if("object"==typeof t&&Object.keys(t).includes(Mi))return!0}return!1}}class Ei{constructor(e,i={}){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,be(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe(D()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...i},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),w(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(w(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||Xt(e)&&Xt(t))return 0;if(Xt(e))return-1;if(Xt(t))return 1;const i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:s}of i){const i=si(Vt(e,n),Vt(t,n));if(0!==i)return s?i:-i}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 i=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-i-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const i=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,n=Math.max(0,e.length-i-this.paginateOptions.pageSize);i!==e.length?this.internalStateObserver.next({numBefore:i,numAfter:n,data:e,extractedData:t}):this.prevInternal({numBefore:i,numAfter:n,data:e,extractedData:t})}doNewQuery(e,t){if(this.onFirstPage=!1,t){const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder();e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?"<=":">=",value:Vt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe(w(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:Vt(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(k(this.isDestroyed.pipe(g(Boolean),w(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe(g(e=>null!==e),O(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:n,extractedData:s}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(s[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:n>0,hasPrev:i>0}}prevInternal(e){const{numBefore:t,numAfter:i,extractedData:n}=e;this.firstElement=null,this.lastElement=n[t-1],this.internalStateObserver.next(null),this.doNewQuery(n[n.length-i-1],!0)}}Error;class Ri{constructor(e,t,i,n){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=n}getForDocument(e){const{collectionName:t,integrationId:i,docId:n}=ki(e),s=ui(n),r=this.get(t,i);for(const[e,t]of Object.entries(s))r.where(e,"==",t);return r}get(e,t){return new ji(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService)}}class Ai{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,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"like_cs":"like",t)}notLike(e,t,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"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 Fi{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(fe(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Fi(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}projectFields(e){const t=this.queryBuilder.projectFields(e);return new Fi(t)}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new Ei(this,e)}}class ji extends Ai{constructor(e,t,i,n,s,r,o){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=n,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 li(this.build())}where(e,t,i){if(be(Qt.includes(t),`Invalid operator: ${t}`),this.query.projectFields&&"__docId__"!==e&&!this.query.projectFields.includes(e))throw new Error(`Cannot filter by field '${e}' that is not included in projectFields.`);if("in"===t||"not in"===t){const n=Array.isArray(i)?[...i]:[i];"in"===t&&0===n.length&&(this.containsEmptyInCondition=!0);for(const i of n)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:i});return this}return this.query.conditions.push({fieldName:e,operator:t,value:i}),this}limit(e){return function(e){var t;be(function(e){return"number"==typeof e}(t=e),()=>we("Limit needs to be a number","Not a number",t)),-1!==e&&(be(e>0,"query limit has to be greater than 0"),be(Math.floor(e)===e,"query limit has to be an integer"),be(e<=2e4,"Limit can be maximum 20000"))}(e),this.query.limit=e,this}getLimit(){return this.query.limit}limitBy(e,...t){const i=this.query.sortOrder.map(e=>e.fieldName);return be(ei(t.sort(),i.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 i={asc:t,fieldName:e};if(function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var i,n,s,r;be((i=t,n=["fieldName","asc"],!Array.isArray(i)&&[...Object.keys(i)].every(e=>n.includes(e))),"Field sort should only contain a fieldName and asc"),be((s=t.asc,r="boolean",Array.isArray(s)?s.every(e=>typeof e===r):typeof s===r),"Asc needs to be boolean")}(i),be(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.projectFields&&"__docId__"!==e&&!this.query.projectFields.includes(e))throw new Error(`Cannot sort by field '${e}' that is not included in projectFields.`);return this.query.sortOrder.push(i),this}projectFields(e){if(0===e.length&&"built_in_db"!==this.integrationId)throw new Error(`Empty projectFields is only allowed for built_in_db integration. For '${this.integrationId}', you must specify at least one field to project.`);if(this.query.projectFields)for(const t of e)if(!this.query.projectFields.includes(t))throw new Error(`Cannot project field '${t}' that is not in the existing projection. Subsequent projectFields calls must be subsets of the previous projection.`);const t=e;for(const e of this.query.sortOrder)if("__docId__"!==e.fieldName&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including sort field '${e.fieldName}'.`);for(const e of this.query.conditions)if(Ci(e)){if("__docId__"!==e.fieldName&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including filter field '${e.fieldName}'.`)}else for(const i of e.fields)if("__docId__"!==i.fieldName&&!t.includes(i.fieldName))throw new Error(`Cannot set projectFields without including filter field '${i.fieldName}'.`);const i=this.clone();return i.query.projectFields=[...e],i}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 i=this.build(),n=i.projectFields;return this.querySubscriptionManager.processQuery(i,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(fe(e=>e.map(e=>{be(1===Object.keys(e).length);const t=e[this.collectionName],i=Ti(Ie(t).__docId__,this.collectionName,this.integrationId),s=this.documentReferenceFactory.create(i,this.queryBuilderFactory,n);return this.querySubscriptionManager.detachedRecords.delete(e)&&s.setInMemoryData(t),s})))}changes(){let e,t=new Set;return this.snapshots().pipe(a(this.documentIdentityService.observeChanges().pipe(C(t=>(Object.entries(t).forEach(([t,i])=>{!function(e,t,i){const n=e[t];void 0!==n&&(e[i]=n,delete e[t])}(e||{},t,i)}),i)),q({}))),fe(([i])=>{let n=[];const s=[],r=[];if(e){for(const r of i){const i=r.squidDocId,o=r.dataRef;if(t.has(o))delete e[i],t.delete(o);else if(e[i]){s.push(r);const n=e[i];delete e[i],t.delete(n)}else n.push(r)}for(const e of t)r.push(e)}else n=i;e={},t=new Set;for(const n of i){const i=n.dataRef;e[n.squidDocId]=i,t.add(i)}return new Ni(n,s,r)}))}dereference(){return new Fi(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new ji(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService);return e.query=ii(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){if(!e.length)return this;if(this.query.projectFields)for(const t of e)if("__docId__"!==t.fieldName&&!this.query.projectFields.includes(t.fieldName))throw new Error(`Cannot filter by field '${t.fieldName}' that is not included in projectFields.`);return this.query.conditions.push({fields:e}),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 Ei(this,e)}mergeConditions(){const e=[],t=ri(this.query.conditions.filter(Ci)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=ri(i,e=>e.operator);for(const[i,n]of Object.entries(t)){if("=="===i||"!="===i){e.push(...n);continue}const t=[...n];t.sort((e,t)=>si(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!Ci(e)),...e]}}class Ni{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class xi extends Ai{constructor(e,t,i,n,s,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=n,this.queryBuilderFactory=s,this.rootAlias=r,this.latestAlias=o,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,i){return this.queryBuilder.where(e,t,i),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}projectFields(e){throw new Error("projectFields is not yet supported for join queries")}join(e,t,i,n){const s=n?.leftAlias??this.latestAlias,r={...i,leftAlias:s,isInner:n?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[s].push(t),new xi(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,ii(this.joins),ii(this.joinConditions),e,!1).pipe(fe(e=>e.map(e=>{const t={};for(const[i,n]of Object.entries(e)){const e=i===this.rootAlias?this.collectionName:this.joins[i].collectionName,s=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,r=n?Ti(n.__docId__,e,s):void 0;t[i]=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 Qi(this)}dereference(){return new Pi(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new xi(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,ii(this.leftToRight),ii(this.joins),ii(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 Ei(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class Pi{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(fe(e=>e.map(e=>function(e,t){const i={},n=Object.keys(e);for(const s of n){const n=e[s];i[s]=t(n)}return i}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new Pi(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 Ei(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class Bi{constructor(e){this.groupedJoin=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(fe(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 Bi(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 Ei(this,e)}dereference(e,t){const i=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(i.length){const n={[t]:e[t].data};for(const t of i)n[t]=e[t].map(e=>this.dereference(e,t));return n}return e.data}}class Qi{constructor(e){this.joinQueryBuilder=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(fe(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new Bi(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new Qi(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 Ei(this,e)}groupData(e,t){const i=ri(e,e=>e[t]?.squidDocId);return Object.values(i).filter(e=>void 0!==e[0][t]).map(e=>{const i=this.joinQueryBuilder.leftToRight[t],n=e[0][t];if(0===i.length)return n;const s={[t]:n};for(const t of i)s[t]=this.groupData(e,t);return s})}}class Li{constructor(e,t,i,n,s,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=n,this.querySubscriptionManager=s,this.dataManager=r,this.refId=Se()}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={[Mi]:Se()};else e=e&&"string"!=typeof e?{__id:ai(e)}:{__id:e||Se()};const t=Ti(ai(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 i of e)await this.doc(i.id).upsert(i.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)i instanceof Oi?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new xi(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new Ui(...e)}}class Ui{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 i=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==i.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<i.length;e++)if(t[e].fieldName!==i[e].fieldName||t[e].asc!==i[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 Ui(...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 Ei(this,e)}or(e,...t){return o([...t]).pipe(w(t=>{const i=new Set,n=t.flat(),s=[];for(const e of n)i.has(this.extractData(e))||(i.add(this.extractData(e)),s.push(e));return s.sort((t,i)=>{for(const{fieldName:n,asc:s}of e){const e=Vt(this.extractData(t),n),r=Vt(this.extractData(i),n);if(!_i(e,r,"=="))return _i(r,e,"<")?s?-1:1:s?1:-1}return 0}).slice(0,this.getLimit())}))}}class $i{constructor(e,t,i,n){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=i,this.dataManager=n,this.collections=new Map}get(e,t){let i=this.collections.get(t);i||(i=new Map,this.collections.set(t,i));let n=i.get(e);return n||(n=new Li(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,n)),n}}class Gi{constructor(e,t,i){this.clientIdService=e,this.socketManager=t,this.runtimeOptions=i,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 Hi=x(150);const Wi={"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)=>Ki(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Ki(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Ki(e,t)&&zi(t),"like_cs:like_cs":(e,t)=>Ki(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)=>Yi(e,t),"not like_cs:like":(e,t)=>Yi(e,t),"not like:like_cs":(e,t)=>Yi(e,t),"not like_cs:like_cs":(e,t)=>Yi(e,t),"not like:not like":(e,t)=>Ki(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Ki(t,e)&&zi(e),"not like:not like_cs":(e,t)=>Ki(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Ki(t,e),"in:like":(e,t)=>e.every(e=>_i(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>_i(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>_i(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>_i(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&&Ji(e)||Zi(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Ji(e)||Zi(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Ji(t)||Zi(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Ji(t)||Zi(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=>_i(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>_i(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>_i(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>_i(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 Ki(e,t,i=0,n=0){if(n>=t.length)return i>=e.length;if(i>=e.length)return Ji(t.substring(n));const s=e[i],r=t[n];return"%"===s&&"%"===r?Ki(e,t,i+1,n+1)||Ki(e,t,i+1,n):"%"!==s&&("%"===r?Ki(e,t,i,n+1)||Ki(e,t,i+1,n):(s===r||"_"===r)&&Ki(e,t,i+1,n+1))}function Vi(e,t,i=0,n=0){if(i>=e.length&&n>=t.length)return!0;if(i>=e.length)return Ji(t.substring(n));if(n>=t.length)return Ji(e.substring(i));const s=i<e.length?e[i]:"",r=n<t.length?t[n]:"";return"%"===s&&"%"===r?Vi(e,t,i+1,n+1)||Vi(e,t,i,n+1)||Vi(e,t,i+1,n):"%"===s||"%"===r?Vi(e,t,i,n+1)||Vi(e,t,i+1,n):(s===r||"_"===s||"_"===r)&&Vi(e,t,i+1,n+1)}function zi(e){return!/[a-zA-Z]/.test(e)}function Ji(e){return e.split("").every(e=>"%"===e)}function Yi(e,t){return e.length>0&&Ji(e)||t.length>0&&Ji(t)||Zi(e)&&0===t.length}function Zi(e){let t=!1,i=!1;for(const n of e)switch(n){case"%":t=!0;break;case"_":if(i)return!1;i=!0;break;default:return!1}return t&&i}class Xi{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Ci))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}get projectFields(){return this.query.projectFields}sortedBy(e){return!e.find((e,t)=>!ei(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,i){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:i})}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(Ci),i=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),s=-1===e.limit||this.limit>-1&&this.limit<e.limit,r=this.isProjectFieldsSubset(this.query.projectFields,e.projectFields);return i&&n&&s&&r}isProjectFieldsSubset(e,t){if(!t)return!0;if(!e)return!1;const i=new Set(t);return e.every(e=>i.has(e))}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 i=t.fieldName,n=t.operator,s=Vt(e,i);if("in"===n){if(t.value.includes(s))continue;return!1}if("not in"!==n){if(!_i(t.value,s,n))return!1}else if(t.value.includes(s))return!1}return!0}evaluateSubset(e,t){const{operator:i,value:n}=e,{operator:s,value:r}=this.parseConditions([t])[0],o=Wi[`${i}:${s}`];return!!o&&o(n,r)}parseConditions(e){const t=[],i=new Map,n=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":i.set(e.fieldName,(i.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),i.forEach((e,i)=>{t.push({fieldName:i,operator:"in",value:e})}),n.forEach((e,i)=>{t.push({fieldName:i,operator:"not in",value:e})}),t}}function en(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?ii(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function tn(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function nn(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(be("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const i=ii(e);t=ii(t);for(const[e]of tn(i)){const n=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&n>t.split(".").length)&&delete i.properties[e]}for(const[e,n]of tn(t))i.properties[e]=sn([...i.properties[e]||[],...n]);return i}(e,t);const i=ii(e);for(const[e,n]of tn(t)){const t=n;for(const n of t){const t=en(Vt(i.properties,e),n);void 0===t?Yt(i.properties,e):Jt(i.properties,e,t)}}return i}function sn(e){let t=0;for(;t+1<e.length;){const i=rn(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function rn(e,t){return"removeProperty"===t.type||"update"===t.type?t:"applyNumericFn"===t.type?(be("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type?(be("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 on(e,t){if(!e)return;const i={...e},n=tn(t);for(const[e,t]of n){const n=t;for(const t of n){const n=en(Vt(i,e),t);void 0===n?Yt(i,e):Jt(i,e,n)}}return i}function an(e){const t={};for(const i of e){const e=`${i.squidDocIdObj.integrationId}/${i.squidDocIdObj.collectionName}/${i.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(i)}const i=[];for(const e in t){const n=t[e].reduce((e,t)=>Ie(nn(e,t),"Merge result cannot be null"));i.push(n)}return i}const cn="dataManager_runInTransaction";var un;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(un||(un={}));class ln{constructor(e,i,n,s,o,a,c,u,l){this.documentStore=e,this.mutationSender=i,this.socketManager=n,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)}hasSufficientData(e,t){return this.documentStore.hasSufficientData(e,t)}isDirty(e){if(this.knownDirtyDocs.has(e))return!0;if(this.pendingOutgoingMutations.get(e)?.length)return!0;const t=this.docIdToServerTimestamp.get(e),i=t&&!t.expireTimestamp?t.timestamp:void 0,n=this.docIdToLocalTimestamp.get(e);return!((!n||i)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&n===i)}async executeDetachedQuery(e){const t=this.currentTransactionId,i={query:e,clientRequestId:Se(),subscribe:!1},n=await this.querySender.sendQueryDirect(i);return this.currentTransactionId!==t?this.reRunQueryThroughNormalPipeline(e):this.applyPendingMutationsToQueryResult(n.docs,e)}async reRunQueryThroughNormalPipeline(e){await m(this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)));const t={query:e,clientRequestId:Se(),subscribe:!1};return(await this.querySender.sendQueryDirect(t)).docs}applyPendingMutationsToQueryResult(e,t){const i=new Xi(t),n=new Map;for(const i of e){const e=Ti(i.__docId__,t.collectionName,t.integrationId);n.set(e,i)}for(const[e,s]of this.pendingOutgoingMutations){const r=ki(e);if(r.collectionName===t.collectionName&&r.integrationId===t.integrationId)for(const{mutation:t}of s){const s=n.get(e);if("delete"===t.type)n.delete(e);else if("update"===t.type){if(s){const r=on(s,t);r&&i.documentMatchesQuery(r)?n.set(e,r):n.delete(e)}}else if("insert"===t.type){const s={...t.properties,__docId__:r.docId};i.documentMatchesQuery(s)&&n.set(e,s)}}}const s=Array.from(n.values()),{sortOrder:r}=t;s.sort((e,t)=>{for(const{fieldName:i,asc:n}of r){const s=si(Vt(e,i),Vt(t,i));if(0!==s)return n?s:-s}return 0});const o=t.limit<0?2e3:t.limit;return s.slice(0,o)}async runInTransaction(e,t){if(t)return be(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(cn)?this.lockManager.lockSync(cn):await this.lockManager.lock(cn);let i=dn;const n=()=>i!==dn;return new Promise(async(t,s)=>{try{let r;this.currentTransactionId=Se();try{r=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(n()?void 0:{resolve:()=>t(r),reject:s})}}catch(e){i=n()?i:e}finally{try{this.lockManager.release(cn)}catch(e){i=n()?i:e}}n()&&s(i)})}async applyOutgoingMutation(e,t){const i=Ti(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(cn)||(await this.lockManager.lock(cn),this.lockManager.release(cn)),this.knownDirtyDocs.delete(i);const n=this.pendingOutgoingMutations.get(i)?.slice(-1)[0];if(n&&!n.sentToServer)n.mutation=Ie(an([n.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},n=this.pendingOutgoingMutations.get(i)||[];n.push(t),this.pendingOutgoingMutations.set(i,n),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(i),n="delete"===e.type?void 0:"update"===e.type?on(t,e):{...e.properties};this.updateDocumentFromSnapshot(i,n)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(i,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(i,n).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 be(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(cn);try{this.currentTransactionId=Se();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(cn)}}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),fe(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t={},i=[];for(const n of e){if(!this.querySubscriptionManager.hasOngoingQuery(n.clientRequestId))continue;const e=this.querySubscriptionManager.getQuery(n.clientRequestId),s=null!==e.projectFields&&void 0!==e.projectFields,r=this.querySubscriptionManager.hasSubscription(n.clientRequestId);s&&r?i.push({squidDocId:n.squidDocId,item:{properties:n.doc,timestamp:n.mutationTimestamp,clientRequestId:n.clientRequestId,projectFields:e.projectFields}}):t[n.squidDocId]={properties:n.doc,timestamp:n.mutationTimestamp}}Object.keys(t).length>0&&this.applyIncomingUpdates(t),i.length>0&&this.runInTransactionSync(()=>{this.applyProjectedUpdates(i)})}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId);if(null!==t.projectFields&&void 0!==t.projectFields){const i=[];for(const n of e.docs){const s=Ti(n.__docId__,t.collectionName,t.integrationId);i.push({squidDocId:s,item:{properties:n,timestamp:n.__ts__,clientRequestId:e.clientRequestId,projectFields:t.projectFields}})}this.runInTransactionSync(()=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyProjectedUpdates(i)})}else{const i={};for(const n of e.docs){const e=Ti(n.__docId__,t.collectionName,t.integrationId);i[e]={properties:n,timestamp:n.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(i,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)})}}applyIncomingUpdates(e,t){let i=!1;const n=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?i=!0:o&&o.timestamp>r.timestamp?s.add(t):(this.pendingIncomingUpdates.set(t,r),n.add(t))}return this.runInTransactionSync(()=>{for(const e of n)this.maybeApplyIncomingUpdate(e);for(const e of s)this.refreshQueryMapping(e)},t),i}applyProjectedUpdates(e){for(const{squidDocId:t,item:i}of e){const e=Ie(i.clientRequestId,"clientRequestId required for projected updates"),n=this.pendingOutgoingMutations.get(t);if(n&&n.length)continue;const s=this.docIdToServerTimestamp.get(t);s&&s.timestamp>i.timestamp?(this.querySubscriptionManager.addDocToQuery(t,e),this.batchClientRequestIds.add(e)):(this.acknowledgeDocument(t,i.timestamp,!i.properties),this.docIdToLocalTimestamp.set(t,i.timestamp),i.properties?(this.documentStore.saveProjectedDocument(t,i.properties,i.projectFields),this.querySubscriptionManager.addDocToQuery(t,e)):this.querySubscriptionManager.removeDocFromQuery(t,e),this.batchClientRequestIds.add(e))}}maybeApplyIncomingUpdate(e){const t=this.pendingIncomingUpdates.get(e);if(!t)return;const i=this.pendingOutgoingMutations.get(e);i&&i.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 i=this.documentStore.getDocumentOrUndefined(e);return!(!i&&!t||i===t)&&((!i||!t||ai({...t,__ts__:void 0})!==ai(i))&&(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 Hi.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(),e?.resolve()}catch(t){this.pendingOutgoingMutations.size||(this.outgoingMutationsEmpty.next(!0),await this.resyncFailedUpdates()),e?.reject(t)}}async sendMutationsForIntegration(e,t){try{const{timestamp:i,idResolutionMap:n={},refreshList:s=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(n),s.forEach(e=>{this.refreshDocIdToTimestamp.set(n[e]||e,i)});for(const t of e){let e=this.removeOutgoingMutation(t);n[e]&&(e=n[e]),this.acknowledgeDocument(e,i),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=Ti(e.mutation.squidDocIdObj),i=Ie(this.pendingOutgoingMutations.get(t));return i.splice(i.indexOf(e),1),i.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}=ki(t);this.setExpiration(t,!0);try{const i=e.includes(Mi)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(Ie(i.length<=1,"Got more than one doc for the same id:"+t),!i.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,i]of this.refreshDocIdToTimestamp.entries()){const n=this.docIdToServerTimestamp.get(t)?.timestamp;n&&n>i||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 i=t[t.length-1];if(i&&!i.sentToServer){const t=i.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(i),i.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,i=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,i)}setExpiration(e,t){const i=this.docIdToServerTimestamp.get(e);i&&(i.expireTimestamp=t?Date.now()+2e4:void 0)}forgetDocument(e,t){this.docIdToLocalTimestamp.delete(e),this.pendingIncomingUpdates.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const i=Ti(t.mutation.squidDocIdObj),n=e[i];n&&(t.mutation.squidDocIdObj=ki(n))})}),Object.entries(e).forEach(([e,t])=>{Zt(this.pendingOutgoingMutations,e,t),Zt(this.docIdToLocalTimestamp,e,t),Zt(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 dn=Symbol("undefined");class hn{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new t(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe(g(Boolean),fe(()=>{}))}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 pn{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=>{if(e)return;const t=Object.keys(this.ongoingLocks);t.length>0&&console.warn(`DistributedLockManager: WebSocket disconnected, releasing ${t.length} lock(s): [${t.join(", ")}]`),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 i=t?.acquisitionTimeoutMillis??2e3,n=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),be(await m(k(F(this.lockWaitForConnectionThreshold).pipe(fe(()=>!1)),this.socketManager.observeConnectionReady().pipe(g(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const s=Se(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:i,maxHoldTimeMillis:n,clientRequestId:s}};this.socketManager.postMessage(r);const o=await m(k(F(i+4e3).pipe(O(1),fe(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:s}}))),this.acquireLockMessagesFromServer.pipe(g(e=>e.payload.clientRequestId===s)))),a=o.payload.lockId;be(!this.destructManager.isDestructing,"Squid client is in destructuring phase"),be(a,()=>`Failed to acquire lock: ${o.payload.error}`);const c=new gn(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 gn{constructor(e,t,i,n,s){this.lockId=e,this.resourceId=t,this.clientRequestId=i,this.ongoingLocks=n,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 fn{constructor(e,i){this.documentStore=e,this.destructManager=i,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 yn{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t,i){if(i)return new Oi(e,Ie(this.dataManager,"dataManager not found"),t,i);let n=this.documents.get(e);if(n)return n;n=new Oi(e,Ie(this.dataManager,"dataManager not found"),t);const{integrationId:s,collectionName:r}=ki(e);this.documents.set(e,n);const o=this.getCollectionKey(s,r),a=this.documentsForCollection.get(o)||[];return this.documentsForCollection.set(o,a.concat(n)),n}setDataManager(e){this.dataManager=e}getDocumentsForCollection(e,t){const i=this.getCollectionKey(e,t);return(this.documentsForCollection.get(i)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const i=ki(e),n=ki(t);Zt(this.documents,i.docId,n.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class mn{constructor(){this.squidDocIdToDoc=new Map,this.squidDocIdToProjectedFields=new Map}saveProjectedDocument(e,t,i){const n=this.squidDocIdToDoc.get(e);if(n){const i=this.mergeDocuments(n,t),s=this.removeInternalProperties(i);this.squidDocIdToDoc.set(e,s)}else{const i=this.removeInternalProperties(t);this.squidDocIdToDoc.set(e,i)}if(i?.length){const t=this.squidDocIdToProjectedFields.get(e);if(void 0!==t)for(const e of i)t.add(e);else n||this.squidDocIdToProjectedFields.set(e,new Set(i))}return this.squidDocIdToDoc.get(e)}mergeDocuments(e,t){const i=ii(e);for(const e of Object.keys(t)){const n=t[e],s=i[e];null===n||"object"!=typeof n||Array.isArray(n)||null===s||"object"!=typeof s||Array.isArray(s)?i[e]=n:i[e]=this.mergeDocuments(s,n)}return i}deleteDocument(e){this.squidDocIdToDoc.delete(e),this.squidDocIdToProjectedFields.delete(e)}saveDocument(e,t){const i=this.squidDocIdToDoc.get(e);if(void 0===i&&!t)return;if(void 0!==i){if(t){const i=ii(t),n=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,n),this.squidDocIdToProjectedFields.delete(e),n}return this.squidDocIdToDoc.delete(e),void this.squidDocIdToProjectedFields.delete(e)}const n=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,n),this.squidDocIdToProjectedFields.delete(e),n}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}hasSufficientData(e,t){if(!this.squidDocIdToDoc.has(e))return!1;const i=this.squidDocIdToProjectedFields.get(e);return void 0===i||!!t?.length&&t.every(e=>i.has(e))}group(e,t){return Object.values(ri(e,e=>ai(t.map(t=>Vt(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=Array.from(e).map(e=>this.squidDocIdToDoc.get(e)).filter(ye),{sortOrder:n,limitBy:s}=t,r=i.sort((e,t)=>this.compareSquidDocs(e,t,n)),o=t.limit<0?2e3:t.limit;let a;if(s){const{limit:e,fields:t,reverseSort:i}=s,n=this.group(r,t);let c;c=i?n.map(t=>t.slice(-e)):n.map(t=>t.slice(0,e)),a=c.flat().slice(0,o)}else a=r.slice(0,o);return null!==t.projectFields&&void 0!==t.projectFields&&(a=a.map(e=>this.projectDocument(e,t.projectFields))),a}projectDocument(e,t){const i={};"__id"in e&&(i.__id=e.__id),"__docId__"in e&&(i.__docId__=e.__docId__);for(const n of t)if(n.includes(".")){const t=Vt(e,n);void 0!==t&&Jt(i,n,t)}else n in e&&(i[n]=e[n]);return i}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;Zt(this.squidDocIdToDoc,e,t),Zt(this.squidDocIdToProjectedFields,e,t);const n=ki(t),s=ui(n.docId);this.saveDocument(t,{...i,...s,__docId__:n.docId})}compareSquidDocs(e,t,i){for(const{fieldName:n,asc:s}of i){const i=si(Vt(e,n),Vt(t,n));if(0!==i)return s?i:-i}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class bn{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const i={authCode:e,externalAuthConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/saveAuthCode",i)}async getAccessToken(e){const t={externalAuthConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("externalAuth/getAccessToken",t)}}class In{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const i={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",i,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const i={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",i)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class vn{constructor(e,t,i,n){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},n.isPassiveMode||this.clientIdService.observeClientId().pipe(p(),_(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Ii.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e}).catch(t=>{const i=this.listeners[e];i&&(i.error(t),delete this.listeners[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}).catch(i=>{t.error(i),delete this.listeners[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,i=t.id,n=this.listeners[i];n&&("completed"===t.status?n.next(t.result):"failed"===t.status?n.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",i),delete this.listeners[i])}))}}const wn="squid_mgmt_",Sn="x-squid-traceid",Mn="x-squid-client-version";function kn(e="n_"){return`${e}${qe(10).toLowerCase()}`}const Tn=e=>e();class _n extends Error{constructor(e,t,i,n,s){super(e),this.statusCode=t,this.url=i,this.headers=n,this.body=s}}const qn="1.0.457";async function Dn(e){const t=await An({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage});return t.body=Fn(t.body),t}async function Cn(e){const t=await An({...e,method:"GET",files:[],filesFieldName:""});return t.body=Fn(t.body),t}async function On(e){const t=await An({...e,method:"PUT"});return t.body=Fn(t.body),t}async function En(e){const t=await An({...e,method:"PATCH"});return t.body=Fn(t.body),t}async function Rn(e){const t=await An({...e,method:"DELETE",files:[],filesFieldName:""});return t.body=Fn(t.body),t}async function An({headers:e,files:t,filesFieldName:i,message:n,url:s,extractErrorMessage:r,method:o}){const a=new Headers(e);a.append(Sn,kn("c_")),a.append(Mn,qn);const c={method:o,headers:a,body:void 0};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const n of t)e.append(i||"files",n,n.name);e.append("body",ci(n)),c.body=e}else void 0!==n&&(a.append("Content-Type","application/json"),c.body=ci(n));else"DELETE"===o&&void 0!==n&&(a.append("Content-Type","application/json"),c.body=ci(n));try{const e=await fetch(s,c),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),n=Fn(i);if(!r)throw new _n(i,e.status,s,t,n);let o;try{o="string"==typeof n?n:n?.message||i}catch{}throw o||(o=e.statusText),new _n(o,e.status,s,t,n)}const i=await e.text();return Ii.debug(`received response from url ${s}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Ii.debug(`Unable to perform fetch request to url: ${s}`,e),e}}function Fn(e){if(e){try{return ui(e)}catch{}return e}}class jn{constructor(e){be(e.apiKey.startsWith(wn),`Invalid management API key format. Key must start with '${wn}'`),this.apiKey=e.apiKey,this.consoleRegion=e.consoleRegion}async createOrganization(e){return this.callApi("POST","organizations",e)}async createApplication(e){return this.callApi("POST","applications",e)}async deleteApplication(e){await this.callApi("DELETE",`applications/${e}`)}async renameOrganization(e){await this.callApi("PATCH",`organizations/${e.organizationId}`,{name:e.name})}async renameApplication(e){await this.callApi("PATCH",`applications/${e.appId}`,{name:e.name})}async callApi(e,t,i){const n=B(this.consoleRegion,"console",`openapi/iac/management/${t}`),s={Authorization:`ManagementKey ${this.apiKey}`};return"POST"===e?(await Dn({url:n,headers:s,message:i,files:[],filesFieldName:"",extractErrorMessage:!0})).body:"PATCH"===e?(await En({url:n,headers:s,message:i,extractErrorMessage:!0})).body:(await Rn({url:n,headers:s,message:i,extractErrorMessage:!0})).body}}class Nn{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=an(e),n=i.map(e=>`sendMutation_${Ti(e.squidDocIdObj)}`);await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:i,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Ii.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...n)}}}class xn{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class Pn{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe(g(e=>"userNotification"===e.type),w(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 Bn={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class Qn{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!Ln.test(e)||e.length>=Un);be(0===i.length,()=>`Tag name is not allowed: ${i.join(",")}`),this.isReporting=!0;const n={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},s=this.rpcManager.post("/observability/metrics",{metrics:[n]}).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={...Bn,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const i=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:i,noDataBehavior:n}=e,s=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-start-time"===n)return e;const s=t-e;let r=t-Math.floor(s/i)*i;return r>e&&(r-=i),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-end-time"===n)return t-i;const s=t-e;let r=e+Math.floor(s/i)*i;return r>=t&&(r-=i),r}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const i=[];for(let t=0;t<e.groupByTags.length;t++){const n=e.groupByTags[t],s=a[n]?.[0]||"";i.push(s)}t.push({tagValues:i,points:[]})}else"return-result-group-with-default-values"===n&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[i,n]of Object.entries(a)){const s=e.groupByTags.indexOf(i);if(!(s<0))for(let e=0;e<t.length;e++){const i=t[e],r=new Set(n);for(let e=0;e<t.length;e++){const n=t[e];i.tagValues.every((e,t)=>t===s||e===n.tagValues[t])&&r.delete(n.tagValues[s])}if(0!==r.size)for(const e of r){const n={tagValues:[...i.tagValues],points:[]};n.tagValues[s]=e,t.push(n)}}}for(const n of t){if(0!==n.points.length){const e=n.points[0][0],t=n.points[n.points.length-1][0];be(e>=r,()=>`Invalid first point time: ${e}`),be(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+=i){const i=n.points[a];i?i[0]===e?(t.push(i),a++):(be(i[0]>e,()=>`Result point has invalid time: ${i[0]}`),t.push([e,...u])):t.push([e,...u])}n.points=t}}(t,i.resultGroups),i}}const Ln=/^[a-zA-Z0-9_-]+$/,Un=1e3;async function $n(e,t,i=500){const n=Date.now(),s=e.paginate({pageSize:i,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()-n}}function Gn(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:n}=t,{collectionName:s,integrationId:r}=i;let o=e.collection(s,r).query();return o=Hn(o,i),n?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:n,joinConditions:s,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=Hn(u,i.query),Object.entries(n).map(([t,i])=>{const{collectionName:n,integrationId:r}=i,{left:o,right:a,leftAlias:c}=s[t];let l=e.collection(n,r).query();l=Hn(l,i),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:i}=t,{collectionName:n,integrationId:s}=Wn(i[0]),r=i.map(t=>Gn(e,t));return e.collection(n,s).or(...r)}(e,t)}}function Hn(e,t){const{conditions:i,limit:n,sortOrder:s}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:i,operator:n,value:s}=t;e.where(i,n,s)}e.limit(n);for(const{fieldName:t,asc:i}of s)e.sortBy(t,i);return e}function Wn(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:i}=e.query;return{collectionName:t,integrationId:i}}case"join":{const{collectionName:t,integrationId:i}=e.root.query;return{collectionName:t,integrationId:i}}case"merged":return Wn(e.queries[0])}}class Kn{constructor(e,t,i){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=i}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:i}=e,n=new Xi(e),s=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>n.documentMatchesQuery(e.data)),r={};return s.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[Ti(e.__docId__,i,t)])}}function Vn(e,t){return W(function(i,n){var s=0;i.subscribe(pe(n,function(i){return e.call(t,i,s++)&&n.next(i)}))})}class zn{constructor(e,i){this.rpcManager=e,this.destructManager=i,this.safeToSendQueriesToServer=new t(!0),this.pendingQueryRequests=[],this.inflightQueriesCount=new t(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new r,i=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(),i):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.safeToSendQueriesToServer.pipe(Vn(Boolean),O(1)).subscribe(()=>{this.processQueryBatch()})},0),i)}async sendQueryDirect(e){const t=await this.rpcManager.post("query/batchQueries",[e]),i=t.errors[e.clientRequestId];if(i)throw i;return t.results[e.clientRequestId]}async waitForAllQueriesToFinish(){return m(this.inflightQueriesCount.pipe(Vn(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()),i=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const i=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,s=i.errors[e],r=i.results[e];s?n.error(s):n.next(r)}}catch(e){i.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Jn={d:(e,t)=>{for(var i in t)Jn.o(t,i)&&!Jn.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function Yn(e,t,...i){e||function(e,...t){const i=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof i)throw i;throw(e=>new Error(e))(i||"Assertion error",...t)}(t,...i)}function Zn(e,t){switch(t.type){case"set":return function(e,t,i){if(void 0===i)return Xn(e,t);if(0===t.length)return Yn("object"==typeof i&&null!==i&&!Array.isArray(i),()=>`Root state must be a record. Trying to set '${i}', type: ${typeof i}`),i;function n(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 i=t[e];Yn(!Array.isArray(s)||n(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),s=s[i],Yn(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 Yn(!Array.isArray(s)||n(r),()=>`Invalid array index Path: '${t}`),(null==s?void 0:s[r])===i?e:es(e,t,i)}(e,t.path,t.value);case"delete":return Xn(e,t.path);case"batch":return t.actions.reduce((e,t)=>Zn(e,t),e)}}function Xn(e,t){Yn(0!==t.length,"Can't delete an empty path");let i=e;for(let n=0;n<t.length-1;n++){const s=t[n];if(i=i[s],void 0===i)return e;Yn("object"==typeof i&&null!==i,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,n+1)}', type: ${null===i?"<null>":typeof i}`)}const n=t[t.length-1];return void 0===i[n]?e:es(e,t,void 0)}function es(e,t,i){function n(e,i){Yn(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const s=Object.assign({},e);let r=s;for(let e=0;e<t.length-1;e++){const s=t[e],o=r[s];Yn(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===i?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return n(r,s),r;r[s]=a,r=a}const o=t[t.length-1];return void 0===i?n(r,o):r[o]=i,s}function ts(e,t){const i=[];if("set"===e.type||"delete"===e.type)i.push(e.path);else if("batch"===e.type)for(const t of e.actions)i.push(...ts(t,"as-is"));return"unique-and-sorted"===t?ss(i):i}function is(e,t){if(e.length<t.length)return!1;for(let i=0;i<t.length;i++)if(e[i]!==t[i])return!1;return!0}function ns(e){const t=[...e];return t.sort((e,t)=>{for(let i=0;i<e.length;i++){if(i===t.length)return 1;const n=e[i].localeCompare(t[i]);if(0!==n)return n}return e.length-t.length}),t}function ss(e){const t=ns(e),i=t;for(let e=0;e<t.length-1;e++){const n=t[e];for(let s=e+1;s<t.length;s++){const r=t[s];n.length===r.length&&is(n,r)&&(i[s]=void 0,e++)}}return i.filter(e=>void 0!==e)}const rs=(os={Observable:()=>n,Subject:()=>r},as={},Jn.d(as,os),as);var os,as;const cs=(us={filter:()=>Vn,map:()=>fe},ls={},Jn.d(ls,us),ls);var us,ls;class ds{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 i=this._buildPath(e);if(void 0!==i.value)return i.value;const n=t(e);return this._setNodeValue(i,n,void 0===n),n}set(e,t){const i=void 0===t?this._findNode(e):this._buildPath(e);i&&this._setNodeValue(i,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 i=(void 0===t.value?0:1)+t.childrenWithValue;i>0&&this._updateChildrenWithValue(t,-i),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const i=this.getNode(e);return void 0===i?0:i.childrenWithValue+("node-and-children"===t&&void 0!==i.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const i=[];let n=this.root,s=t(n.value,i);if(s!==ds.StopFillToken){this._setNodeValue(n,s,!1);for(let r=0;r<e.length;r++){const o=e[r];i.push(o);let a=n.children.get(o);if(s=t(null==a?void 0:a.value,i),s===ds.StopFillToken)break;a||(a={children:new Map,parent:n,childrenWithValue:0},n.children.set(o,a)),this._setNodeValue(a,s,!1),n=a}this._runGc(n)}}visitDfs(e,t,i=[]){const n=this.getNode(i);void 0!==n&&this._visitDfs(e,n,t,[...i])}_visitDfs(e,t,i,n){if("pre-order"===e&&!1===i(t.value,n))return!1;for(const[s,r]of t.children){if(n.push(s),!this._visitDfs(e,r,i,n))return!1;n.pop()}return"in-order"!==e||!1!==i(t.value,n)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const i of e)if(t=t.children.get(i),!t)return;return t}_findNode(e){let t=this.root;for(let i=0;i<e.length&&t;i++)t=t.children.get(e[i]);return t}_buildPath(e){let t=this.root;for(let i=0;i<e.length;i++){const n=e[i];let s=t.children.get(n);s||(s={children:new Map,parent:t,childrenWithValue:0},t.children.set(n,s)),t=s}return t}_setNodeValue(e,t,i){if(e.value!==t){const i=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,i)}i&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let i=e.parent;i;i=i.parent)if(i.childrenWithValue+=t,i.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))}}ds.StopFillToken=Symbol("Trie.StopFillToken");class hs extends rs.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class ps{constructor(e){this.rootState=e,this.observersTrie=new ds,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,cs.map)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,i){(null==i?void 0:i(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=Zn(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=ts(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),n=ss([...t,...i]),s=new ds;for(const e of n)s.fillPath(e,()=>!0);s.visitDfs("pre-order",(t,i)=>{const n=this.observersTrie.get(i);if(n){const t=this.get(i),s=n.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;n.next({action:e,value:t,oldValue:s})}})}_observeChanges(e,t=[],i){const n=0===t.length?void 0:new ds;for(const e of t)null==n||n.set(e,!0);return new rs.Observable(t=>{const s=this.observersTrie.getOrSet(e,()=>new hs);s.isAllDetailsMode=s.isAllDetailsMode||"all-details"===i;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=s.pipe((0,cs.filter)(({action:e})=>void 0===n||ts(e,"as-is").some(e=>!n.get(e))),(0,cs.map)(({action:t,value:i,oldValue:n})=>{let r=this.stubForUnusedPaths;if(s.isAllDetailsMode){const i=ts(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=ns(e),i=t;for(let e=0;e<i.length-1;e++){const n=t[e];for(let s=e+1;s<t.length;s++)is(t[s],n)&&(i[s]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>is(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:n,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),s.observed||this.observersTrie.delete(e)}})}_get(e,t){let i=e;for(let e=0;e<t.length&&void 0!==i;e++){const n=t[e];i=null==i?void 0:i[n]}return i}selectChildPathsWithObservers(e){const t=[];for(const i of e)this.observersTrie.count(i,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,i)=>{e&&t.push([...i])},i);return t}}function gs(e,t,i=(e,t)=>e>t?1:e<t?-1:0,n=0,s=e.length-1){if(s<n)return-1;const r=Math.trunc((n+s)/2);return 0===i(t,e[r])?r:i(t,e[r])>0?gs(e,t,i,r+1,s):gs(e,t,i,n,r-1)}function fs(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==gs(e,t,i))return;let n;for(n=e.length-1;n>=0&&i(e[n],t)>0;n--)e[n+1]=e[n];e[n+1]=t}function ys(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const n=gs(e,t,i);n>-1&&e.splice(n,1)}const ms=100;class bs{setDetachedQueryExecutor(e){this.detachedQueryExecutor=e}constructor(e,t,i,n,s,o,a,c){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=n,this.documentIdentityService=s,this.querySender=o,this.socketManager=a,this.lockManager=c,this.onOrphanDocuments=new r,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new vs,this.queryResultsSubject=new r,this.detachedRecords=new Set,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 Ie(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:i,integrationId:n}=ki(t),s=this.queryMappingManager.getMapping(i,n);return s?function(e,t){const i=[...e.unconditional||[]],n=new Map;for(const[i,s]of Object.entries(e.conditional||{})){const e=ui(i);let r;if(Ci(e)){const i=Vt(t,e.fieldName)??null;r=_i(e.value,i,e.operator)}else r=Is(e,t);if(r)for(const e of s)n.set(e,(n.get(e)||0)+1)}for(const[t,s]of n.entries())s>=e.queriesMetadata[t].condCount&&i.push(t);return i}(s,e):[]}setClientRequestIdsForLocalDoc(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set,n=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([...i,...n]);for(const t of[...i]){if(n.has(t))continue;i.delete(t);const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),i.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...s]}addDocToQuery(e,t){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}removeDocFromQuery(e,t){const i=this.localDocumentToClientRequestIds.get(e);let n=!i;i&&(i.delete(t),i.size||(this.localDocumentToClientRequestIds.delete(e),n=!0));const s=this.clientRequestIdToLocalDocuments.get(t);s&&(s.delete(e),s.size||this.clientRequestIdToLocalDocuments.delete(t)),n&&this.documentStore.deleteDocument(e)}errorOutAllQueries(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of i){const i=this.ongoingQueries.get(e);i&&(this.destructManager.isDestructing?i.dataSubject.complete():i.dataSubject.error(t),i.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const i of e){const e=this.ongoingQueries.get(i);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(i)||new Set,s=this.documentStore.sortAndLimitDocs(n,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(s,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=Ie(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case un.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+100?un.ENABLED:un.DISABLED;break;case un.DISABLED:break;case un.ENABLED:if(n.size<e.query.limit+20){e.limitUnderflowState=un.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(s)}for(const e of t){const t=this.collectAllObservables(e);Ie(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new Xi(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,n,r,a,c){r&&this.socketManager.notifyWebSocketIsNeeded();const u=Object.keys(i).length>0;return r||u||!this.detachedQueryExecutor||this.lockManager.canGetLock(cn)?d(()=>{const u=this.createOngoingQueryGraph(e,t,i,n,r,!0,{},c);a&&(u.forceFetchFromServer=!0),this.lockManager.canGetLock(cn)||console.warn("WARNING: Executing a query inside a transaction is not supported and will cause a transaction deadlock. If you are executing a query while an active transaction is running but outside of its callback, you can disregard this message."),this.sendQueryToServerOrUseParentQuery(u),u.allObservables=new s(1);const l=u.allObservables.pipe(C(e=>o(e).pipe(fe(e=>this.joinResults(e,n,u)))),Vn(()=>this.allOngoingQueriesGotInitialResult(u)),q(void 0),M(),Vn(([e,t])=>!ei(e,t)),fe(([,e])=>e),r?A():O(1),f(()=>{u.dataSubject.complete(),u.done=!0,this.completeAllSupportedQueries(u),u.allObservables?.complete()})),d=this.collectAllObservables(u);return u.allObservables.next(d),l}).pipe(T()):b(this.detachedQueryExecutor(e)).pipe(fe(e=>e.map(e=>{const i={[t]:e};return this.detachedRecords.add(i),i})))}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 Xi(e.query);for(const i of this.ongoingQueries.values()){if(e===i)return;if(this.isValidParent(i)&&t.isSubqueryOfQuery(i.query))return i}}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const i=[];for(const n of t){const t=Ie(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),i.push(n))}i.length&&this.onOrphanDocuments.next(i)}registerQueryFinalizer(e){const t=e.clientRequestId,i=Di(this.clientIdService.getClientId(),t);e.dataSubject.pipe(f(async()=>{if(e.unsubscribeBlockerCount.value>0&&await m(k(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Vn(e=>0===e)))),this.queryMappingManager.removeQuery(i),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const i={clientRequestId:t};this.rpcManager.post("query/unsubscribe",i).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t)}),Vn(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,i,n,s,r,o,a={},c){if(a[i])return a[i];const u=o&&c?c:this.clientIdService.generateClientRequestId(),l=[],d={clientRequestId:u,activated:o,alias:i,query:e,subscribe:r,dataSubject:new t(null),supportedQueries:l,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?un.UNKNOWN:un.DISABLED};this.registerQueryFinalizer(d),this.ongoingQueries.set(u,d),a[i]=d;for(const[e,t]of Object.entries(s)){const o=t.leftAlias;if(o!==i&&e!==i)continue;const c=o===i?e:o;if(o===i){const e=this.createOngoingQueryGraph(n[c],c,n,s,r,!1,a);e.joinCondition=t,l.push(e)}else d.supportingOngoingQuery=this.createOngoingQueryGraph(n[c],c,n,s,r,!1,a)}return d}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(Vn(Boolean),fe(e=>({docs:e,alias:i}))));for(const i of e.supportedQueries)this.collectAllObservables(i,t);return t}joinResults(e,t,i){const n=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let s=n[i.alias].map(e=>({[i.alias]:e}));const r=this.getOngoingQueriesBfs(i),o=new Set;for(let e=1;e<r.length;e++){const i=r[e].alias;o.has(i)||(o.add(i),s=this.join(s,i,n[i],t[i]))}return s}join(e,t,i,n){if(!e.length)return e;const s=Object.keys(e[0]);if(!n||!s.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[n.right]);r.has(t)||r.set(t,[]),Ie(r.get(t)).push(e)}),e.flatMap(e=>{const i=r.get(this.transformKey(e[n.leftAlias]?.[n.left]))||[];return i.length?i.map(i=>({...e,[t]:i})):n.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],i=[e];for(;i.length;){const e=Ie(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,i){const n=Ie(i.joinCondition),s=i.query;if(i.activated){if(!i.canExpandForJoin)return!1;const r=Ie(i.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===i.alias),o=new Set(e.map(e=>e[n.left]??null));for(const e of r)e.query.conditions.filter(Ci).filter(e=>e.fieldName===n.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const a=ii(s);a.conditions=a.conditions.filter(e=>!Ci(e)||e.fieldName!==n.right),[...o].forEach(e=>{a.conditions.push({fieldName:n.right,operator:"==",value:e})});const c={...i,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),Ie(i.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(i.activated=!0,s.conditions.filter(Ci).filter(e=>e.fieldName===n.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(i),i.canExpandForJoin=!1,!0;const t=e.map(e=>e[n.left]??null).map(e=>({fieldName:n.right,operator:"==",value:e}));return t.length?(s.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(i)):i.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=Ie(t.shift());t.push(...e.supportedQueries||[]),await m(e.unsubscribeBlockerCount.pipe(Vn(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 i=e.query,n=e.clientRequestId,s=Di(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(i,s),this.ongoingQueries.set(n,e);const r=t?void 0:this.findValidParentOfOngoingQuery(e);r?this.useParentOngoingQuery(e,r):this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const i={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new Xi(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await m(t.queryRegistered.pipe(Vn(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",i).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(i=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,i),e.dataSubject.error(i)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const s=k(e.queryRegistered.pipe(Vn(Boolean),h(2e3),O(1)),this.destructManager.observeIsDestructing().pipe(O(1)));t.dataSubject.pipe(R(()=>!e.done),E(s),Vn(Boolean),A(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),fe(e=>e.filter(e=>n.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc(Ti(i.__docId__,e.query.collectionName,e.query.integrationId),i);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,i=t>0&&e.subscribe?t+100:t,n={query:{...e.query,limit:i},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(n).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()):(Ii.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 i of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{i.has(t)&&(i.delete(t),i.add(e[t]))});t.forEach(t=>{Zt(this.localDocumentToClientRequestIds,t,e[t])})}}function Is(e,t){for(const i of e.fields){const e=Vt(t,i.fieldName)??null;if(_i(i.value,e,i.operator))return!0;if(_i(i.value,e,"!="))return!1}return!1}class vs{constructor(){this.stateService=new ps({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const n=new Set;for(const s of e.conditions){if(Ci(s)&&["=="].includes(s.operator)){const e=li(s.fieldName);n.has(e)||(i++,n.add(e))}else i++;const r=this.getConditionStatePath(e,s),o=[...this.stateService.get(r)||[]];fs(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];fs(n,t),this.stateService.set(i,n)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],i)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const i of t.conditions){const n=this.getConditionStatePath(t,i),s=[...this.stateService.get(n)||[]];ys(s,e),s.length?this.stateService.set(n,s):this.stateService.delete(n)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];ys(n,e),this.stateService.set(i,n)}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",(i=t,ai(i))];var i}}class ws{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 v(o(t).pipe(g(e=>!e.includes(!0)),O(1))),await this.lock(...e)}release(...e){for(const t of e){const e=Ie(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){be(this.canGetLock(...e),"Cannot acquire lock sync");for(const i of e)this.locks[i]=new t(!0)}}class Ss{constructor(e,t,i){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)}),i.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let i=this.queueManagers.get(e);i||(i=new Map,this.queueManagers.set(e,i));let n=i.get(t);return n||(n=new ks(e,t,this.rpcManager,this.socketManager),i.set(t,n)),n}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const Ms="subscriptionMutex";class ks{constructor(e,t,i,n){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=n,this.messagesSubject=new r,this.subscriberCount=0,this.lockManager=new ws}async produce(e){await this.lockManager.lock(Ms);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(Ms)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),d(()=>(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(Ms);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(Ms)}}async performUnsubscribe(){await this.lockManager.lock(Ms);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(Ms)}}}class Ts{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(I(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}}class _s{constructor(e,i,n,s,r,o){this.region=e,this.appId=i,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")}),n.onDestruct(async()=>{await this.awaitAllSettled()});const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Ts(60*a,5),ai:new Ts(20*a,5),secret:new Ts(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:i}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return i&&(n+=`; IntegrationId ${i}`),{Authorization:n}}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,i=[],n="files",s={}){return(await this.rawPost(e,t,i,n,!0,s)).body}async rawPost(e,t,i=[],n="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};Ii.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:B(this.region,this.appId,e);return await Dn({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),s={...this.staticHeaders,...n};let r=e.startsWith("http://")||e.startsWith("https://")?e:B(this.region,this.appId,e);if(t&&Object.keys(t).length>0){const e=new URLSearchParams;Object.entries(t).forEach(([t,i])=>{e.append(t,String(i))}),r+=`?${e.toString()}`}return Ii.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await Cn({url:r,headers:s,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async put(e,t,i=[],n="files"){return(await this.rawPut(e,t,i,n)).body}async rawPut(e,t,i=[],n="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};Ii.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:B(this.region,this.appId,e);return await On({url:a,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async patch(e,t,i=[],n="files"){return(await this.rawPatch(e,t,i,n)).body}async rawPatch(e,t,i=[],n="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};Ii.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:B(this.region,this.appId,e);return await En({url:a,headers:o,message:t,files:i,filesFieldName:n,extractErrorMessage:s})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),s={...this.staticHeaders,...n};Ii.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const r=e.startsWith("http://")||e.startsWith("https://")?e:B(this.region,this.appId,e);return await Rn({url:r,headers:s,message:t,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?Ie(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?Ie(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):Ie(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}function qs(e){be(!e.isPassiveMode,"This operation is not available in passive mode. Use active mode for real-time features.")}class Ds{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 Cs(){}const Os="undefined"!=typeof process&&process.versions?.node?x(220):bi().WebSocket;class Es{constructor(e,i,n,s=Tn,o,a,c){this.clientIdService=e,this.region=i,this.appId=n,this.messageNotificationWrapper=s,this.destructManager=o,this.authManager=a,this.runtimeOptions=c,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),O(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe(_(1),g(e=>!e),C(()=>k(F(this.clientTooOldThreshold),this.connectionReady.pipe(g(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Ii.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Ii.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?Ii.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Ii.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Ii.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Ii.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(){qs(this.runtimeOptions),await m(this.observeConnectionReady().pipe(g(Boolean)))}notifyWebSocketIsNeeded(){qs(this.runtimeOptions),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&&(Ii.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.notifyWebSocketIsNeeded(),this.connectionReady.value||console.warn(`SocketManager.sendMessageImpl: connectionReady=false, waiting... (message type: ${e.type})`),await m(k(this.connectionReady.pipe(g(Boolean)),F(12e4).pipe(A(()=>{throw new Error("WebSocket connection not ready within 2 minutes")}))));const t=await this.authManager.getToken();if(this.connectionReady.value)try{be(this.socket,"Socket is undefined in sendMessageAsync");const i=ci({message:e,authToken:t});Ii.debug(this.clientIdService.getClientId(),"Sending message to socket: ",i),this.socket.send(i)}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(ci({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=B(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();Ii.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,n=0,s=1;const r={connected:!1,closeCalled:!1,open(){i=new(Os?.WebSocket??Os)(e,t.protocols||[]),i.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.")}:Cs,i.onopen=function(e){r.connected=!0,(t.onopen||Cs)(e),n=0},i.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return Ii.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Cs)(e),void r.reconnect(e);(t.onclose||Cs)(e)},i.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||Cs)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;s&&n++<i?s=setTimeout(function(){(t.onreconnect||Cs)(e),Ii.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||Cs)(e)},json(e){i.send(JSON.stringify(e))},send(e){i.send(e)},close(e=4999,t){r.closeCalled=!0;try{r.connected=!1,clearTimeout(s),s=void 0,i.close(e,t)}catch(e){}}};return r.open(),r}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Ii.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Ii.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Ii.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Ii.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Ii.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 Ii.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=ui(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Ii.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(F(0)),this.connectionReady.next(!1),await m(F(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Rs(e){var t,i;i="Invalid application ID",be(function(e){return"string"==typeof e}(t=e),()=>we(i,"Not a string",t));const[n,s,r,o]=e.split("-");return be(!o,`Invalid application ID: ${e}`),{appId:n,environmentId:s??"prod",squidDeveloperId:r}}function As(e,t){return`${Rs(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function Fs(e,t,i){return`${As(e,t)}${i?`-${i}`:""}`}function js(e){const t=Rs(e);return As(t.appId,t.environmentId)}class Ns{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,i){const n={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:i};await this.rpcManager.post("storage/uploadFile",n,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const i={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",i)}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 xs{constructor(e,t,i,n,s){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=n,this.consoleRegion=s}get shortUrlHeaders(){return{"Content-Type":"application/json","x-app-api-key":this.apiKey}}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){be(this.apiKey,"API key is required to create a short URL");const t="string"==typeof e?{url:e}:e,i=Q(this.region,this.consoleRegion,"openapi/sqd/shorten"),n={url:t.url,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension},s=await fetch(i,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(n)}),r=await s.text();return be(s.ok,`Failed to create short URL (${s.status}): ${r}`),JSON.parse(r)}async createShortUrls(e){be(this.apiKey,"API key is required to create a short URL");const t=Array.isArray(e)?{urls:e}:e,i=Q(this.region,this.consoleRegion,"openapi/sqd/shortenMany"),n={urls:t.urls,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension},s=await fetch(i,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(n)}),r=await s.text();return be(s.ok,`Failed to create short URLs (${s.status}): ${r}`),JSON.parse(r)}async deleteShortUrl(e){be(this.apiKey,"API key is required to delete a short URL");const t=Q(this.region,this.consoleRegion,"openapi/sqd/delete"),i={id:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(i)});be(n.ok,`Failed to delete short URL (${n.status}): ${n.statusText}`)}async deleteShortUrls(e){be(this.apiKey,"API key is required to delete a short URL");const t=Q(this.region,this.consoleRegion,"openapi/sqd/deleteMany"),i={ids:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(i)});be(n.ok,`Failed to delete short URLs (${n.status}): ${n.statusText}`)}}class Ps{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i}async executeWebhook(e,t={}){const{headers:i={},queryParams:n={},body:s,files:r=[]}=t,o=await this.rpcManager.getAuthHeaders(),a={...this.rpcManager.getStaticHeaders(),...o,...i};let c=B(this.region,this.appId,`webhooks/${encodeURIComponent(e)}`);if(n&&Object.keys(n).length>0){const e=new URLSearchParams;Object.entries(n).forEach(([t,i])=>{e.append(t,String(i))}),c+=`?${e.toString()}`}const u=new Headers(a);let l;if(u.append(Sn,kn("c_")),u.append(Mn,qn),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,i])=>{e.append(t,String(i))}),l=e}else u.append("Content-Type","application/json"),l=ci(s||{});const d=await fetch(c,{method:"POST",headers:u,body:l}),h={};if(d.headers.forEach((e,t)=>{h[t]=e}),!d.ok){const e=await d.text();let t;try{t=JSON.parse(e)}catch{t=e}const i="string"==typeof t?t:t?.message||d.statusText;throw new _n(i,d.status,c,h,t)}const p=await d.text();let g;try{g=JSON.parse(p)}catch{g=p}return g}getWebhookUrl(e){return B(this.region,this.appId,e?`webhooks/${encodeURIComponent(e)}`:"webhooks")}}class Bs{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new hn,be(e.appId,"APP_ID_MUST_BE_PROVIDED"),this.runtimeOptions={isPassiveMode:e.isPassiveMode??!1};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,i=Fs(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new vi(this.destructManager),Ii.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new Wt(e.apiKey,e.authProvider),this.socketManager=new Es(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager,this.runtimeOptions),this.rpcManager=new _s(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new Pn(this.socketManager,this.rpcManager),this.jobClient=new vn(this.socketManager,this.rpcManager,this.clientIdService,this.runtimeOptions),this.backendFunctionManager=new yi(this.rpcManager),this.aiClient=new $t(this.socketManager,this.rpcManager,this.jobClient,this.backendFunctionManager),this.apiClient=new Ht(this.rpcManager),this.documentStore=new mn,this.lockManager=new ws,this.distributedLockManager=new pn(this.socketManager,this.destructManager),this.documentIdentityService=new fn(this.documentStore,this.destructManager),this.documentReferenceFactory=new yn(this.documentIdentityService),this.querySender=new zn(this.rpcManager,this.destructManager),this.observabilityClient=new Qn(this.rpcManager),this.schedulerClient=new Ds(this.rpcManager),this._appId=i,this.querySubscriptionManager=new bs(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager,this.lockManager),this.localQueryManager=new Kn(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const n=new Nn(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Ri(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new ln(this.documentStore,n,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new $i(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.querySubscriptionManager.setDetachedQueryExecutor(e=>this.dataManager.executeDetachedQuery(e)),this.webhookManager=new Ps(this.rpcManager,e.region,i),this.nativeQueryManager=new xn(this.rpcManager),this._connectionDetails=new Gi(this.clientIdService,this.socketManager,this.runtimeOptions),this.queueManagerFactory=new Ss(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new G(this.rpcManager,this.options.region,js(i),this.options.consoleRegion),this.webClient=new xs(this.rpcManager,this.options.region,js(i),this.options.apiKey,this.options.consoleRegion)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}get isDestructed(){return this.destructManager.isDestructing}static getInstance(e){const t=ai(e);let i=Bs.squidInstancesMap[t];return i||(i=new Bs(e),Bs.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(Bs.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,...i){return this._validateNotDestructed(),this.backendFunctionManager.executeFunctionWithHeaders(e,t,...i)}executeWebhook(e,t){return this._validateNotDestructed(),this.webhookManager.executeWebhook(e,t)}getWebhookUrl(e){return this._validateNotDestructed(),this.webhookManager.getWebhookUrl(e)}executeNativeRelationalQuery(e,t,i={}){const n={type:"relational",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativePureQuery(e,t,i={}){const n={type:"pure",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,i){const n={type:"mongo",collectionName:t,aggregationPipeline:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeElasticQuery(e,t,i,n="_search",s="GET"){const r={type:"elasticsearch",index:t,endpoint:n,method:s,body:i,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 Ns(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new bn(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new In(this.rpcManager)}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t,i){const n=await this.acquireLock(e,i);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(Bs.squidInstancesMap).find(([,e])=>e===this);e&&delete Bs.squidInstancesMap[e[0]]})}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,i)=>B(e,t,i),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,i)=>Fs(e,t,i)}}_validateNotDestructed(){be(!this.destructManager.isDestructing,"The client was already destructed.")}}export{St as AI_AGENTS_INTEGRATION_ID,pt 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,dt as AI_IMAGE_MODEL_NAMES,We as AI_PROVIDER_TYPES,Qt as ALL_OPERATORS,Je as ANTHROPIC_CHAT_MODEL_NAMES,mt as API_INJECTION_FIELD_TYPES,Bt as ARRAY_OPERATORS,Tt as AUTH_INTEGRATION_TYPES,G as AdminClient,Fe as AiAgentClient,Re as AiAgentReference,Ne as AiAudioClient,$t as AiClient,xe as AiFilesClient,Pe as AiImageClient,Le as AiKnowledgeBaseClient,Qe as AiKnowledgeBaseReference,Ue as AiMatchMakingClient,Ht as ApiClient,$ as ApiKeysSecretClient,Wt as AuthManager,tt as BEDROCK_EMBEDDING_MODEL_NAMES,vt as BUILT_IN_AGENT_ID,Ct as BUILT_IN_DB_INTEGRATION_ID,Ot as BUILT_IN_QUEUE_INTEGRATION_ID,Et as BUILT_IN_STORAGE_INTEGRATION_ID,yi as BackendFunctionManager,Ai as BaseQueryBuilder,Ut as CLIENT_CONNECTION_STATES,wi as CLIENT_ID_GENERATOR_KEY,Si as CLIENT_REQUEST_ID_GENERATOR_KEY,Ni as Changes,vi as ClientIdService,Li as CollectionReference,$i as CollectionReferenceFactory,Gi as ConnectionDetails,kt as DATA_INTEGRATION_TYPES,Te as DEFAULT_SHORT_ID_LENGTH,ln as DataManager,Pi as DereferencedJoin,hn as DestructManager,gn as DistributedLockImpl,pn as DistributedLockManager,Oi as DocumentReference,yn as DocumentReferenceFactory,mn as DocumentStore,je as EMPTY_CHAT_ID,It as ENVIRONMENT_IDS,bn as ExternalAuthClient,In as ExtractionClient,ms as FETCH_BEYOND_LIMIT,lt as FLUX_MODEL_NAMES,Ve as GEMINI_CHAT_MODEL_NAMES,_t as GRAPHQL_INTEGRATION_TYPES,ze as GROK_CHAT_MODEL_NAMES,Qi as GroupedJoin,qt as HTTP_INTEGRATION_TYPES,wt as HttpStatus,Dt as INTEGRATION_SCHEMA_TYPES,Mt as INTEGRATION_TYPES,L as IntegrationClient,vn as JobClient,xi as JoinQueryBuilder,pi as LastUsedValueExecuteFunctionCache,un as LimitUnderflowState,Kn as LocalQueryManager,Nt as METRIC_DOMAIN,jt as METRIC_FUNCTIONS,xt as METRIC_INTERVAL_ALIGNMENT,Pt as METRIC_NO_DATA_BEHAVIOR,jn as ManagementClient,$e as MatchMaker,Nn as MutationSender,Tn as NOOP_FN,xn as NativeQueryManager,Pn as NotificationClient,at as OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES,ct as OPENAI_AUDIO_MODEL_NAMES,ot as OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES,Ke as OPENAI_CHAT_MODEL_NAMES,Xe as OPENAI_EMBEDDINGS_MODEL_NAMES,rt as OPENAI_IMAGE_MODEL_NAMES,gt as OPEN_AI_CREATE_SPEECH_FORMATS,Qn as ObservabilityClient,Ei as Pagination,ji as QueryBuilder,Ri as QueryBuilderFactory,zn as QuerySender,bs as QuerySubscriptionManager,Ss as QueueManagerFactory,ks as QueueManagerImpl,yt as RAG_TYPES,He as RERANK_PROVIDERS,cn as RUN_IN_TRANSACTION_MUTEX,Ts as RateLimiter,_s as RpcManager,Rt as SQUID_BUILT_IN_INTEGRATION_IDS,Ft as SQUID_METRIC_NAMES,Lt as SQUID_REGIONS,ut as STABLE_DIFFUSION_MODEL_NAMES,Ds as SchedulerClient,U as SecretClient,Es as SocketManager,Bs as Squid,_n as SquidClientError,Ns as StorageClient,Ye as VENDOR_AI_CHAT_MODEL_NAMES,et as VOYAGE_EMBEDDING_MODEL_NAMES,xs as WebClient,Ps as WebhookManager,qs as assertNotPassiveMode,di as compareArgsByReference,hi as compareArgsBySerializedValue,Gn as deserializeQuery,ke as generateId,qe as generateShortId,De as generateShortIds,Se as generateUUID,Me as generateUUIDPolyfill,Q as getConsoleUrl,mi as getCustomizationFlag,nt as isAiEmbeddingsModelName,At as isBuiltInIntegrationId,st as isIntegrationEmbeddingModelSpec,ft as isIntegrationModelSpec,bt as isPlaceholderParam,Ze as isVendorAiChatModelName,Rn as rawSquidHttpDelete,Cn as rawSquidHttpGet,En as rawSquidHttpPatch,Dn as rawSquidHttpPost,On as rawSquidHttpPut,gi as transformFileArgs,Fn as tryDeserializing,$n as visitQueryResults};
|