@squidcloud/client 1.0.488 → 1.0.489
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/public-types/ai-agent-integrations.public-types.d.ts +8 -0
- package/dist/internal-common/src/public-types/ai-agent.public-types.d.ts +71 -1
- package/dist/internal-common/src/public-types/ai-common.public-types.d.ts +17 -5
- package/dist/internal-common/src/public-types/ai-knowledge-base.public-types.d.ts +14 -2
- package/dist/internal-common/src/public-types/extraction.public-types.d.ts +13 -0
- package/dist/internal-common/src/public-types/web.public-types.d.ts +18 -1
- package/dist/typescript-client/src/version.d.ts +1 -1
- package/dist/typescript-client/src/web-client.d.ts +4 -2
- package/package.json +1 -1
- package/dist/internal-common/src/ai/system-openai-compatible.d.ts +0 -35
- package/dist/internal-common/src/metric-name.d.ts +0 -14
- package/dist/internal-common/src/public-types-backend/api-call.public-context.d.ts +0 -30
- package/dist/internal-common/src/public-types-backend/mutation.public-context.d.ts +0 -161
- package/dist/internal-common/src/public-types-backend/native-query.public-context.d.ts +0 -75
- package/dist/internal-common/src/public-types-backend/query.public-context.d.ts +0 -193
- package/dist/internal-common/src/types/ai-agent.types.d.ts +0 -302
- package/dist/internal-common/src/types/ai-knowledge-base.types.d.ts +0 -306
- package/dist/internal-common/src/types/ai-matchmaking.types.d.ts +0 -19
- package/dist/internal-common/src/types/backend-function.types.d.ts +0 -1
- package/dist/internal-common/src/types/communication.types.d.ts +0 -1
- package/dist/internal-common/src/types/document.types.d.ts +0 -1
- package/dist/internal-common/src/types/file.types.d.ts +0 -6
- package/dist/internal-common/src/types/headers.types.d.ts +0 -41
- package/dist/internal-common/src/types/management-api-key.types.d.ts +0 -92
- package/dist/internal-common/src/types/mutation.types.d.ts +0 -1
- package/dist/internal-common/src/types/notification.types.d.ts +0 -19
- package/dist/internal-common/src/types/observability.types.d.ts +0 -168
- package/dist/internal-common/src/types/query.types.d.ts +0 -15
- package/dist/internal-common/src/types/secret.types.d.ts +0 -7
- package/dist/internal-common/src/types/socket.types.d.ts +0 -1
- package/dist/internal-common/src/types/stage.d.ts +0 -9
- package/dist/internal-common/src/types/time-units.d.ts +0 -1
- package/dist/internal-common/src/types/url-shortener.types.d.ts +0 -45
- package/dist/internal-common/src/utils/array.d.ts +0 -7
- package/dist/internal-common/src/utils/e2e-test-utils.d.ts +0 -2
- package/dist/internal-common/src/utils/file-utils.d.ts +0 -2
- package/dist/internal-common/src/utils/global.utils.d.ts +0 -1
- package/dist/internal-common/src/utils/http.d.ts +0 -10
- package/dist/internal-common/src/utils/lock.manager.d.ts +0 -14
- package/dist/internal-common/src/utils/metric-utils.d.ts +0 -4
- package/dist/internal-common/src/utils/metrics.types.d.ts +0 -7
- package/dist/internal-common/src/utils/object.d.ts +0 -86
- package/dist/internal-common/src/utils/serialization.d.ts +0 -24
- package/dist/internal-common/src/utils/squid.constants.d.ts +0 -6
- package/dist/internal-common/src/utils/trace-id-generator.d.ts +0 -1
- package/dist/internal-common/src/utils/validation.d.ts +0 -19
- package/dist/internal-common/src/websocket.impl.d.ts +0 -26
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as e from"ws";import{BehaviorSubject as t,NEVER as i,Observable as s,ReplaySubject as n,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 I,interval as b,lastValueFrom as w,map as v,of as S,pairwise as M,race as k,share as _,skip as T,startWith as E,switchAll as D,switchMap as C,take as O,takeUntil as q,takeWhile as A,tap as R,timer as j}from"rxjs";var N={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const r=i(642);t.default=r.PromisePool,n(i(273),t),n(i(642),t),n(i(837),t),n(i(426),t),n(i(858),t),n(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){t.PromisePoolExecutor=void 0;const s=i(642),n=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:[],processedItemsCounter:0,taskTimeout:0,shouldStoreProcessedItems:!0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw n.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}storeProcessedItems(e=!0){return this.meta.shouldStoreProcessedItems=e,this}shouldStoreProcessedItems(){return this.meta.shouldStoreProcessedItems}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}flushProcessedItems(){this.meta.processedItems=[]}incrementProcessedItemsCounter(){this.meta.processedItemsCounter+=1}processedCount(){return this.meta.processedItemsCounter}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 n.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 n.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 n.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 n.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw n.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw n.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(s.PromisePool.notRun)),this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=s.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 s=>{await this.handleErrorFor(s,e,t),this.removeActive(i)}).finally(()=>{this.shouldStoreProcessedItems()&&this.processedItems().push(e),this.incrementProcessedItemsCounter(),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,s]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(s)}createTaskTimeout(e){let t;return[async()=>new Promise((i,s)=>{t=setTimeout(()=>{s(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]=s.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 n.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 s=i(234);class n{constructor(e){this.shouldStoreProcessedItems=!0,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 n(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}dontStoreProcessedItems(){return this.shouldStoreProcessedItems=!1,this}onTaskFinished(e){return this.onTaskFinishedHandlers.push(e),this}useCorrespondingResults(){return this.shouldResultsCorrespond=!0,this}async process(e){return(new s.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).storeProcessedItems(this.shouldStoreProcessedItems).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=n,n.notRun=Symbol("notRun"),n.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}};const F={};function x(e){const t=F[e];if(void 0!==t)return t.exports;const i=F[e]={exports:{}};return N[e].call(i.exports,i,i.exports,x),i.exports}x.d=(e,t)=>{if(Array.isArray(t))for(var i=0;i<t.length;){var s=t[i++],n=t[i++];x.o(e,s)?0===n&&i++:0===n?Object.defineProperty(e,s,{enumerable:!0,value:t[i++]}):Object.defineProperty(e,s,{enumerable:!0,get:n})}else for(var s in t)x.o(t,s)&&!x.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},x.o=(e,t)=>Object.hasOwn(e,t);const B=["application","auth","mutation","native-query","query"];function P(e,t,i,s,n,r){let o="https",a=`${s||t}.${n||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=r||function(e){const t=e.replace(/^\/+/,"").split("/")[0]||"";return B.includes(t)}(i)?"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 U(e,t,i=""){return P(function(e,t){return t||(e.includes("sandbox")?"squidai.westus3.azure.sandbox":e.includes("local")?"local":e.includes("staging")?"squidai.westus3.azure.staging":"us-east-1.aws")}(e,t),"console",i)}class Q{constructor(e,t,i,s){this.rpcManager=e,this.iacBaseUrl=U(t,s,`openapi/iac/applications/${i}/connectors`)}async list(){return await this.rpcManager.get(this.iacBaseUrl)??[]}async connect(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e}`,{})}async disconnect(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}}class L{constructor(e,t,i,s){this.rpcManager=e,this.iacBaseUrl=U(t,s,`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 discoverSourceRepositories(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-source-repositories`,{})}async discoverSourceRepositoriesFromDraft(e){return await this.rpcManager.post(`${this.iacBaseUrl}/discover-source-repositories`,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 ${constructor(e){this.rpcManager=e}get apiKeys(){return new G(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 G{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 H{constructor(e,t,i,s){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=s,this.integrationClient=new L(this.rpcManager,this.region,this.appId,this.consoleRegion),this.connectorClient=new Q(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new $(this.rpcManager)}integrations(){return this.integrationClient}connectors(){return this.connectorClient}secrets(){return this.secretClient}}function K(e){return"function"==typeof e}function W(e){return function(t){if(function(e){return K(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 V=function(e,t){return V=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])},V(e,t)};function J(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}V(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],s=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Y(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var s,n,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(e){n={error:e}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(n)throw n.error}}return o}function X(e,t,i){if(i||2===arguments.length)for(var s,n=0,r=t.length;n<r;n++)!s&&n in t||(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))}Object.create,Object.create;var Z,ee=((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 te(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var ie=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,s,n;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(K(c))try{c()}catch(e){n=e instanceof ee?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{se(h)}catch(e){n=null!=n?n:[],e instanceof ee?n=X(X([],Y(n)),Y(e.errors)):n.push(e)}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(s=l.return)&&s.call(l)}finally{if(i)throw i.error}}}if(n)throw new ee(n)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)se(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)&&te(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&te(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function se(e){K(e)?e():e.unsubscribe()}ie.EMPTY;var ne={setTimeout:function(e,t){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];var n=ne.delegate;return(null==n?void 0:n.setTimeout)?n.setTimeout.apply(n,X([e,t],Y(i))):setTimeout.apply(void 0,X([e,t],Y(i)))},clearTimeout:function(e){var t=ne.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function re(){}var oe=ae("C",void 0,void 0);function ae(e,t,i){return{kind:e,value:t,error:i}}var ce=function(e){function t(t){var i,s=e.call(this)||this;return s.isStopped=!1,t?(s.destination=t,((i=t)instanceof ie||i&&"closed"in i&&K(i.remove)&&K(i.add)&&K(i.unsubscribe))&&t.add(s)):s.destination=pe,s}return J(t,e),t.create=function(e,t,i){return new le(e,t,i)},t.prototype.next=function(e){this.isStopped?he(function(e){return ae("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?he(ae("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?he(oe,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}(ie);Function.prototype.bind;var ue=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){de(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){de(e)}else de(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){de(e)}},e}(),le=function(e){function t(t,i,s){var n,r=e.call(this)||this;return n=K(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=s?s:void 0}:t,r.destination=new ue(n),r}return J(t,e),t}(ce);function de(e){!function(e){ne.setTimeout(function(){throw e})}(e)}function he(e,t){var i=null;i&&ne.setTimeout(function(){return i(e,t)})}var pe={closed:!0,next:re,error:function(e){throw e},complete:re};function ge(e,t,i,s,n){return new fe(e,t,i,s,n)}var fe=function(e){function t(t,i,s,n,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=n?function(e){try{n(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=s?function(){try{s()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return J(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}(ce);function ye(e,t){return W(function(i,s){var n=0;i.subscribe(ge(s,function(i){s.next(e.call(t,i,n++))}))})}function me(e){return null!=e}let Ie=e=>new Error(e);function be(e,t,...i){e||function(e,...t){const i=ve(e);if("object"==typeof i)throw i;throw Ie(i||"Assertion error",...t)}(t,...i)}function we(e,t,...i){return be(e,t,...i),e}function ve(e){return void 0===e?"":"string"==typeof e?e:e()}function Se(e,t,i){const s=ve(e);if("object"==typeof s)throw s;return`${s?`${s}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}function Me(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():ke()}function ke(){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 _e(){return Me()}function Te(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()))}function Ee(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 s="";for(let t=0;t<e;t++)s+=Te();if(t.length>0&&(s=t+s.substring(t.length)),i)for(;s.charAt(t.length)===i[t.length];)s=s.substring(0,t.length)+Te()+s.substring(t.length+1);return s}function De({count:e,length:t,prefix:i}){be(e>=0,`Invalid IDs count: ${e}`);const s=new Set;for(;s.size<e;)s.add(Ee(t||18,i||""));return[...s]}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 qe(e,t,i){const s=atob(e),n=new Uint8Array(s.length);for(let e=0;e<s.length;e++)n[e]=s.charCodeAt(e);return new File([n],t,{type:i||"application/octet-stream"})}function Ae(e,t){const{agentId:i,jobId:s}=t;return e.notifyWebSocketIsNeeded(),e.observeNotifications().pipe(g(e=>"aiStatus"===e.type&&(void 0===i||e.agentId===i)),g(e=>!s||e.jobId===s),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.payload.statusUpdateId??e.messageId})))}class Re{constructor(e,t,i,s,n,r,o,a=()=>{}){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=i,this.rpcManager=s,this.socketManager=n,this.jobClient=r,this.backendFunctionManager=o,this.getMetricAnnotations=a}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 updatePii(e){const t=await this.get();be(t,"Agent not found");const i={onDetect:"off",...t.options?.pii,...e};await this.setAgentOptionInPath("pii",i)}async updateMcpServer(e){await this.post("ai/agent/setMcpServer",{agentId:this.agentId,mcpServer:e})}async generateMcpDescriptions(){return await this.post("ai/agent/generateMcpDescriptions",{agentId:this.agentId})}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 s=this.chatInternal(e,t,i),n=await we(s.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:s.responseStream,transcribedPrompt:n.transcribedPrompt}}async ask(e,t,i){const s=await this.askInternal(e,!1,t,i);return this.replaceFileTags(s.responseString,s.annotations)}async askWithAnnotations(e,t,i){const s=await this.askInternal(e,!1,t,i);return{responseString:s.responseString,annotations:s.annotations}}async askAsync(e,t,i){const s={agentId:this.agentId,prompt:e,options:this.withMetricAnnotations(i),jobId:t};await this.post("ai/chatbot/askAsync",s)}observeStatusUpdates(e){return Ae(this.socketManager,{agentId:this.agentId,jobId:e})}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 s=await this.askInternal(e,!0,t,i),n=s.voiceResponse;return{responseString:s.responseString,transcribedPrompt:s.transcribedPrompt,voiceResponseFile:qe(n.base64File,`voice.${n.extension}`,n.mimeType)}}async askWithVoiceResponse(e,t,i){const s=await this.askInternal(e,!0,t,i),n=s.voiceResponse;return{responseString:s.responseString,voiceResponseFile:qe(n.base64File,`voice.${n.extension}`,n.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,includeMetadata:e.includeMetadata})}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,i){const s={agentId:this.agentId,request:e,memoryId:t,options:i};return await this.backendFunctionManager.executeFunction("buildAgent",s)}replaceFileTags(e,t={}){let i=e;for(const[e,s]of Object.entries(t)){let t="";const n=s.aiFileUrl.fileName?s.aiFileUrl.fileName:s.aiFileUrl.url;switch(s.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${n}](${s.aiFileUrl.url})`}const r=`\${id:${e}}`;i=i.replaceAll("`"+r+"`",t).replaceAll(r,t)}return i}async askInternal(e,t,i,s){if(i?.contextMetadataFilter&&Oe(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)Oe(i.contextMetadataFilterForKnowledgeBase[e]);s=s||Me(),i=this.withMetricAnnotations({...je,...i||{}});const n="string"==typeof e;let r="ai/chatbot/";r+=n||t?!n&&t?"transcribeAndAskWithVoiceResponse":n&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:n?e:void 0,options:i,jobId:s},a=n?void 0:[e];return await this.post(r,o,a,"file"),await this.jobClient.awaitJob(s)}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 s=Me(),n=void 0===(t=this.withMetricAnnotations({...je,...t||{}})).smoothTyping||t.smoothTyping;let o="";const a=new r,u=new r;this.ongoingChatSequences[s]=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?S({value:e,complete:t,annotations:i}):S(e).pipe((()=>{const e=globalThis.document,t="object"==typeof e&&null!==e&&!0===e.hidden;return n&&!t})()?h(0):R(),ye(e=>({value:e,complete:!1,annotations:void 0})))),A(({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||Me();const p={agentId:this.agentId,jobId:i,prompt:d?e:void 0,options:t,clientRequestId:s},g={responseStream:a.pipe(f(()=>{delete this.ongoingChatSequences[s]}),_())};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}withMetricAnnotations(e){const t=this.getMetricAnnotations();return t?{...e||{},metricAnnotations:{...t,...e?.metricAnnotations}}:e}async post(e,t,i=[],s="files"){const n={};return this.agentApiKey&&(n["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,i,s,n)}}const je={smoothTyping:!0,responseFormat:"text"};class Ne{constructor(e,t,i,s,n=()=>{}){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=s,this.getMetricAnnotations=n,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe(g(e=>"aiChatbot"===e.type),ye(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,this.getMetricAnnotations)}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:s,tokenIndex:n,annotations:r}=e.payload;if(s&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:s,tokenIndex:void 0===n?void 0:n,annotations:r});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:s&&e===i.length-1,tokenIndex:void 0===n?void 0:n,annotations:r})}}const Fe="__squid_empty_chat_id";class xe{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},s=await this.rpcManager.post("ai/audio/createSpeech",i);return qe(s.base64File,`audio.${s.extension}`,s.mimeType)}}class Be{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 Ue(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`)}}const Qe=new Set(["completed","failed","cancelled"]);class Le{constructor(e,t,i,s,n){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i,this.socketManager=s,this.clientIdService=n}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async generateMetadataFieldDescriptions(e){return this.rpcManager.post("ai/knowledge-base/generateMetadataFieldDescriptions",{knowledgeBaseId:this.knowledgeBaseId,fieldNames:e?.fieldNames,overwriteExisting:e?.overwriteExisting})}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 listContextsPage(e){return this.rpcManager.post("ai/knowledge-base/listContextsPage",{id:this.knowledgeBaseId,truncateTextAfter:e?.truncateTextAfter,offset:e?.offset,limit:e?.limit,search:e?.search})}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,contextIds:s,graphIndexingSkippedContextIds:n}=await this.upsertContexts([e],t?[t]:void 0);if(i.length>0)return{failure:i[0]};const r=s?.[0],o=void 0!==r&&(n?.includes(r)??!1);return o?{graphIndexingSkipped:o}:{}}async upsertContexts(e,t,i){for(const t of e)t.metadata&&Ue(t.metadata);const s=Me();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:s},t),i?.onUploaded?.(),await this.jobClient.awaitJob(s)}async bulkUpsertContexts(e,t){return this.rpcManager.post("ai/knowledge-base/bulk/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contexts:e},t)}async createBulkUploadUrls(e){return this.rpcManager.post("ai/knowledge-base/bulk/createUploadUrls",{files:e.map(e=>({fileName:e}))})}async getBulkIngestionJob(e){return this.rpcManager.post("ai/knowledge-base/bulk/getJob",{jobId:e})}async cancelBulkIngestionJob(e){await this.rpcManager.post("ai/knowledge-base/bulk/cancelJob",{jobId:e})}observeBulkIngestionJob(e){return new s(t=>{const i=()=>{this.rpcManager.post("ai/knowledge-base/bulk/subscribeToJob",{jobId:e}).catch(e=>t.error(e))};t.add(this.socketManager.observeNotifications().pipe(g(e=>"bulkIngestionStatus"===e.type),g(t=>t.payload.jobId===e)).subscribe(e=>{t.next(e.payload),Qe.has(e.payload.state)&&t.complete()})),t.add(this.clientIdService.observeClientId().pipe(p(),T(1)).subscribe(()=>i())),this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.awaitConnectionReady().then(i).catch(e=>t.error(e))})}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 searchWithGraphContext(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return this.rpcManager.post("ai/knowledge-base/search",t)}async grep(e,t){return this.rpcManager.post("ai/knowledge-base/grep",{knowledgeBaseId:this.knowledgeBaseId,pattern:e,options:t})}async queryGraph(e){return this.rpcManager.post("ai/knowledge-base/queryGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}async getGraphStatus(){return this.rpcManager.post("ai/knowledge-base/getGraphStatus",{knowledgeBaseId:this.knowledgeBaseId})}async rebuildGraph(e){await this.rpcManager.post("ai/knowledge-base/rebuildGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}async exploreGraph(e){return this.rpcManager.post("ai/knowledge-base/exploreGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}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 $e{constructor(e,t,i,s){this.rpcManager=e,this.jobClient=t,this.socketManager=i,this.clientIdService=s}knowledgeBase(e){return new Le(e,this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)}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 Ge{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new He(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new He(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class He{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 Ke="Agent Response",We="Accessing Knowledge Base",Ve="Calling AI Function",Je="Inspecting Knowledge Base Metadata",ze="Querying Knowledge Base Graph",Ye="Searching Knowledge Base Text",Xe="Querying Spreadsheet",Ze=["user","ai"],et=["email","phoneNumber","creditCard","ssn","iban","passport"],tt="gpt-5.6-luna",it=["cohere","none"],st=["anthropic","bedrock","claude-code","codex","cohere","flux","gemini","openai","openai-compatible","grok","stability","voyage","mistral","textract","azure_document_intelligence","vertex","external"],nt=["gpt-5.4-mini","gpt-5.4-nano","gpt-5.5","gpt-5.5-pro","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"],rt=["gemini-3.1-pro","gemini-3.6-flash","gemini-3.5-flash-lite"],ot=["grok-4.5","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],at=["claude-fable-5","claude-haiku-4-5-20251001","claude-opus-5","claude-sonnet-5"],ct=[...nt,...at,...rt,...ot];function ut(e){return ct.includes(e)}const lt=["text-embedding-3-small"],dt=["voyage-3-large"],ht=["titan-embed-text-v2"],pt=[...lt,...dt,...ht];function gt(e){return pt.includes(e)}function ft(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const yt=["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2","gpt-image-2-2026-04-21","chatgpt-image-latest"],mt=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],It=["tts-1","tts-1-hd","gpt-4o-mini-tts"],bt=[...mt,...It],wt=["stable-diffusion-core"],vt=["flux-pro-1.1","flux-kontext-pro"],St=[...yt,...wt,...vt],Mt=[...mt],kt=[...It],_t=["mp3","opus","aac","flac","wav","pcm"],Tt=["vendor","connector","custom"];function Et(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const Dt=["pod","worker"],Ct=["postgres","mongoAtlas"],Ot="folderPath",qt=104857600,At=["contextual","basic"],Rt=["secret","regular"];function jt(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const Nt=["dev","prod"],Ft="built_in_agent",xt=["bitbucket","confluence","cotomi","essentials","freshdesk","github","google_calendar","google_drive","hubspot","sharepoint","jira","jira_jsm","linear","mail","onedrive","outlook","salesforce","servicenow_csm","slack","teams","ticketmind_companion","zendesk"],Bt={CONTINUE:100,SWITCHING_PROTOCOLS:101,PROCESSING:102,EARLY_HINTS:103,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTI_STATUS:207,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,MOVED_TEMPORARILY:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,PERMANENT_REDIRECT:308,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,REQUEST_TOO_LONG:413,REQUEST_URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,REQUESTED_RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,INSUFFICIENT_SPACE_ON_RESOURCE:419,METHOD_FAILURE:420,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},Pt="ai_agents",Ut=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","bedrock","azure_blob","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","bitbucket","built_in_azure_blob","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","azure-entra-external-id","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","outlook","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","sharepoint","vertex"],Qt=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","mongo","mssql","databricks","mysql","oracledb","postgres","snowflake","elasticsearch","legend"],Lt=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth","azure-entra-external-id"],$t=["auth0"],Gt=["graphql"],Ht=["api"],Kt=["data","api","graphql"],Wt="built_in_db",Vt="built_in_queue",Jt="built_in_storage",zt=[Wt,Vt,Jt];function Yt(e){return zt.includes(e)}const Xt=["squid_functionExecution_count","squid_functionExecution_time"],Zt=["sum","max","min","average","median","p95","p99","count"],ei=["user","squid"],ti=["align-by-start-time","align-by-end-time"],ii=["return-no-result-groups","return-result-group-with-default-values"],si="__docId__",ni=["in","not in","array_includes_some","array_includes_all","array_not_includes"],ri=[...ni,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],oi=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],ai=["CONNECTED","DISCONNECTED","REMOVED"],ci="analyzeCode",ui=["claude-code","codex"],li=["github","bitbucket"],di=["github","bitbucket"];function hi(e){const t=function(e){const t=new Set,i=new Set;for(const s of e){be(Number.isSafeInteger(s.id)&&s.id>0,"GITHUB_REPOSITORY_ID_INVALID"),be(!t.has(s.id),"GITHUB_REPOSITORY_IDS_MUST_BE_UNIQUE"),t.add(s.id),be(gi(s.fullName),"GITHUB_REPOSITORY_NAME_INVALID");const e=s.fullName.toLowerCase();be(!i.has(e),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),i.add(e),be(s.defaultBranch.trim(),"GITHUB_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),fi(s.cloneUrl,s.fullName,!0),fi(s.htmlUrl,s.fullName,!1)}return e}(e.repositories??[]),i=0===t.length?e.repository:void 0,s=t.map(e=>e.fullName);be(t.length>0||i,"GITHUB_REPOSITORIES_REQUIRED"),be(t.length<=20,"GITHUB_REPOSITORY_LIMIT_EXCEEDED");const n=e.defaultRepository??s[0]??i;return be(n,"GITHUB_DEFAULT_REPOSITORY_REQUIRED"),be(s.some(e=>e.toLowerCase()===n.toLowerCase())||i?.toLowerCase()===n.toLowerCase(),"GITHUB_DEFAULT_REPOSITORY_NOT_ALLOWED"),{...i?{legacyRepository:i}:{},repositories:t,defaultRepository:n}}function pi(e){const t=e.workspace;be(t.trim()===t&&/^[A-Za-z0-9_-]+$/.test(t),"BITBUCKET_WORKSPACE_INVALID");const i=e.repositories;be(i.length>0,"BITBUCKET_REPOSITORIES_REQUIRED"),be(i.length<=20,"BITBUCKET_REPOSITORY_LIMIT_EXCEEDED");const s=new Set,n=new Set;for(const e of i){const i=e.uuid.trim();be(i===e.uuid&&i.length>0,"BITBUCKET_REPOSITORY_ID_INVALID");const r=i.toLowerCase();be(!s.has(r),"BITBUCKET_REPOSITORY_IDS_MUST_BE_UNIQUE"),s.add(r);const o=`${t}/`;be(e.fullName.toLowerCase().startsWith(o.toLowerCase())&&e.fullName.length>o.length&&!e.fullName.slice(o.length).includes("/")&&!/\s/.test(e.fullName),"BITBUCKET_REPOSITORY_WORKSPACE_MISMATCH");const a=e.fullName.toLowerCase();be(!n.has(a),"BITBUCKET_REPOSITORIES_MUST_BE_UNIQUE"),n.add(a),be(e.defaultBranch.trim(),"BITBUCKET_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),yi(e.cloneUrl,e.fullName,!0),yi(e.webUrl,e.fullName,!1)}const r=e.defaultRepository;return be(r&&i.some(e=>e.fullName.toLowerCase()===r.toLowerCase()),"BITBUCKET_DEFAULT_REPOSITORY_NOT_ALLOWED"),{repositories:i,defaultRepository:r}}function gi(e){return/^[^/\s]+\/[^/\s]+$/.test(e)}function fi(e,t,i){let s;try{s=new URL(e)}catch{throw new Error("GITHUB_REPOSITORY_URL_INVALID")}const n=`/${t}${i?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?github\.com:\d+(?:\/|$)/i.test(e);be(!("https:"!==s.protocol||"github.com"!==s.hostname||r||s.username||s.password||s.search||s.hash||s.pathname!==n),"GITHUB_REPOSITORY_URL_INVALID")}function yi(e,t,i){let s;try{s=new URL(e)}catch{throw new Error("BITBUCKET_REPOSITORY_URL_INVALID")}const n=`/${t}${i?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?bitbucket\.org:\d+(?:\/|$)/i.test(e);be(!("https:"!==s.protocol||"bitbucket.org"!==s.hostname||r||s.username||s.password||s.search||s.hash||s.pathname!==n),"BITBUCKET_REPOSITORY_URL_INVALID")}class mi{constructor(e,t,i,s,n,r=()=>{}){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.clientIdService=s,this.backendFunctionManager=n,this.getMetricAnnotations=r}agent(e=Ft,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(e){return(await this.rpcManager.post("ai/settings/listChatModels",e??{})).models}image(){return new Pe(this.rpcManager)}audio(){return new xe(this.rpcManager)}matchMaking(){return new Ge(this.rpcManager)}files(e){return new Be(e,this.rpcManager)}executeAiQuery(e,t,i,s){const n={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",n,[],"files",{},s)}executeAiApiCall(e,t,i,s){const n={integrationId:e,prompt:t,options:i,sessionContext:s};return this.rpcManager.post("ai/query/executeApiQuery",n)}executeAiSpreadsheetQuery(e,t,i,s){const n={prompt:e,files:t,options:i,sessionContext:s};return this.rpcManager.post("ai/query/executeSpreadsheetQuery",n)}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 Ae(this.socketManager,{jobId:e})}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Ne(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new $e(this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)),this.aiKnowledgeBaseClient}}const Ii={headers:{},queryParams:{},pathParams:{}};class bi{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,s){return this.request(e,t,i,s,"post")}async delete(e,t,i,s){return this.request(e,t,i,s,"delete")}async patch(e,t,i,s){return this.request(e,t,i,s,"patch")}async put(e,t,i,s){return this.request(e,t,i,s,"put")}async request(e,t,i,s,n){const r={integrationId:e,endpointId:t,body:i,options:{...Ii,...this.convertOptionsToStrings(s||{})},overrideMethod:n};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 wi{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 vi=/[.\[\]]/;function Si(e,t){if(!e)return;const i=t.split(vi);let s,n=e;for(;n&&i.length;){const e=i.shift();if(e){if("object"!=typeof n||!(e in n))return;s=n[e],n=s}}return s}function Mi(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ki(e,t,i,s="."){const n=t.split(s);let r=e;for(;n.length;){const e=we(n.shift());if(n.length){const t=r[e],i=Mi(t)?qi(t)??{}:{};r[e]=i,r=i}else r[e]=i}}function _i(e,t,i="."){const s=t.split(i);let n=e;for(;s.length;){const e=we(s.shift());if(s.length){const t=Mi(n[e])?qi(n[e])??{}:{};n[e]=t,n=t}else delete n[e]}}function Ti(e,t,i){if(e.has(t)){const s=e.get(t);e.delete(t),e.set(i,s)}}function Ei(e){return null==e}function Di(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 s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const i of s)if(!n.includes(i)||!Di(e[i],t[i]))return!1;return!0}function Ci(e,t){const i=new Array(e.length);for(let s=0;s<e.length;s++)i[s]=Oi(e[s],t);return i}function Oi(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 Ci(e,t);if(e instanceof Map)return new Map(Ci(Array.from(e),t));if(e instanceof Set)return new Set(Ci(Array.from(e),t));if(ArrayBuffer.isView(e))return s=e,"undefined"!=typeof Buffer&&s instanceof Buffer?Buffer.from(s):new s.constructor(s.buffer.slice(),s.byteOffset,s.length);var s;const n={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(n[i]=Oi(e[i],t));return n}function qi(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 Ai(e,t){if(e===t||Ei(e)&&Ei(t))return 0;if(Ei(e))return-1;if(Ei(t))return 1;const i=typeof e,s=typeof t;return i!==s?i<s?-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 s=t(i);return e[s]?e[s].push(i):e[s]=[i],e},{})}function ji(e){if(Array.isArray(e))return e.map(e=>ji(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]=ji(e[t])}),i}function Ni(e){return Fi(ji(e))}function Fi(e){if(void 0===e)return null;const t=Oi(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function xi(e){return Oi(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 Bi(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=Fi(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 Pi=(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},Ui=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(Fi(e[i])!==Fi(t[i]))return!1;return!0};class Qi{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||Pi,s=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+s&&i(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}function Li(e){const t=[],i=[];let s=0;for(const n of e)if("undefined"!=typeof File)if(n instanceof File){i.push(n);const e={type:"file",__squid_placeholder__:!0,fileIndex:s++};t.push(e)}else if($i(n)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:n.map((e,t)=>(i.push(n[t]),s++))};t.push(e)}else t.push(n);else t.push(n);return{argsArray:t,fileArray:i}}function $i(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class Gi{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...i){const{argsArray:s,fileArray:n}=Li(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(s);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?Pi:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,s));if(t)return t.promise}const u=this.createExecuteCallPromise(r,s,n,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:s,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,i,s,n={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:Fi(t)},a=xi((await this.rpcManager.post(r,o,i.length>0?i:[],"files",n)).payload);if(a?.__isSquidBase64File__){const e=a;return qe(e.base64,e.filename,e.mimetype)}return s&&s.set(t,a),a}}function Hi(e){if("undefined"!=typeof globalThis)return globalThis[e]}function Ki(){if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}void 0===Ki()?.SQUID_LOG_DEBUG_ENABLED&&function(e=!0){Ki().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 Wi{static debug(...e){(function(){const e=Ki();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=Ki();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===Ki().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=Ki()[zi];return e?e():Me()}generateClientId(){const e=Ki()[Ji];if(e)return e();let t=`${this.isTenant?"tenant-":""}${Me()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const Ji="SQUID_CLIENT_ID_GENERATOR",zi="SQUID_CLIENT_REQUEST_ID_GENERATOR",Yi="__squidId";function Xi(e){return xi(e)}function Zi(...e){const[t,i,s]=e,n="object"==typeof t?t:{docId:t,collectionName:i,integrationId:s};return n.integrationId||(n.integrationId=void 0),Ni(n)}function es(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return Di(e,t);if("!="===i)return!Di(e,t);switch(i){case"<":return!Ei(e)&&(!!Ei(t)||t<e);case"<=":return!!Ei(t)||!Ei(e)&&t<=e;case">":return!Ei(t)&&(!!Ei(e)||t>e);case">=":return!!Ei(e)||!Ei(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&ts(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&ts(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&ts(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&ts(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>we(i,"VALUE_CANNOT_BE_NULL").some(t=>Di(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>we(i,"VALUE_CANNOT_BE_NULL").some(t=>Di(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!we(i,"VALUE_CANNOT_BE_NULL").some(t=>Di(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function ts(e,t,i){i||(e=e.toLowerCase(),t=t.toLowerCase());const s=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(`^${s}$`).test(e)}function is(e,t){return`${e}_${t}`}function ss(e){return"fieldName"in e}function ns(e){return"docIds"in e}function rs(e,t,i){const s=e.docIds.some(e=>Object.entries(e).every(([e,s])=>es(s,i(t,e)??null,"==")));switch(e.operator){case"==":case"in":return s;case"!=":case"not in":return!s}}function os(e,t,i,s){const n=e,r=s(t,si);if("string"!=typeof r)return es(n,r??null,i);let o;try{o=xi(r)}catch{return es(n,r,i)}if(!o||"object"!=typeof o||Array.isArray(o))return es(n,r,i);const a=Object.keys(o);if(1===a.length&&"__id"===a[0]){const e=o.__id,t=function(e){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const t=Object.keys(e);return 1===t.length&&"__id"===t[0]?e.__id:Ni(e)}if("string"==typeof e)try{const t=xi(e);if(t&&"object"==typeof t&&!Array.isArray(t)){const e=Object.keys(t);if(1===e.length&&"__id"===e[0])return t.__id}}catch{}return e}(n);return es(t,e,i)}if(1===a.length){const e=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const i=Object.keys(e);if(1===i.length&&i[0]===t)return e[t]}if("string"==typeof e)try{const i=xi(e);if(i&&"object"==typeof i&&!Array.isArray(i)){const e=Object.keys(i);if(1===e.length&&e[0]===t)return i[t]}}catch{}return e}(n,a[0]);return es(e,o[a[0]],i)}return"object"!=typeof n||null===n||Array.isArray(n)?es(n,r,i):es(Ni(n),r,i)}class as{constructor(e,t,i,s){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.projectFields=s,this.refId=Me()}setInMemoryData(e){this.inMemoryData=e}get squidDocId(){return this._squidDocId}get data(){return Oi(this.dataRef)}get dataRef(){if(void 0!==this.inMemoryData)return this.inMemoryData;const e=we(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=Xi(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 we(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=>(we(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 s=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};i[e]=[s]});const s={type:"update",squidDocIdObj:Xi(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(s,t)}async setInPath(e,t,i){return this.update({[e]:Oi(t)},i)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,i){const s={type:"applyNumericFn",fn:"increment",value:t},n={type:"update",squidDocIdObj:Xi(this.squidDocId),properties:{[e]:[s]}};return this.dataManager.applyOutgoingMutation(n,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async upsert(e,t){const i=Xi(this.squidDocId),s=i.integrationId;let n=xi(i.docId);if(n[Yi]&&(n={}),s===Wt&&n.__id)try{const e=xi(n.__id);n={...n,...e}}catch{}const r={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...n}};return this.dataManager.applyOutgoingMutation(r,t)}async insert(e,t){return this.upsert(e,t)}async delete(e){const t={type:"delete",squidDocIdObj:Xi(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=we(this.projectFields,"applyProjection called without projectFields"),{integrationId:s}=Xi(this.squidDocId);"__id"in e&&(t.__id=e.__id),"__docId__"in e&&(t.__docId__=e.__docId__);const n=s===Wt?"__id":"__docId__";if(n in e){const i=e[n];if("string"==typeof i&&i.startsWith("{"))try{const e=xi(i);if("object"==typeof e&&null!==e)for(const[i,s]of Object.entries(e))i in t||(t[i]=s)}catch{}}for(const s of i)if(s.includes(".")){const i=Si(e,s);void 0!==i&&ki(t,s,i)}else s in e&&(t[s]=e[s]);return t}hasSquidPlaceholderId(){const e=xi(this._squidDocId);if("object"==typeof e&&e.docId){const t=xi(e.docId);if("object"==typeof t&&Object.keys(t).includes(Yi))return!0}return!1}}class cs{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),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||Ei(e)&&Ei(t))return 0;if(Ei(e))return-1;if(Ei(t))return 1;const i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:s,asc:n}of i){const i=Ai(Si(e,s),Si(t,s));if(0!==i)return n?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,s=Math.max(0,e.length-i-this.paginateOptions.pageSize);i!==e.length?this.internalStateObserver.next({numBefore:i,numAfter:s,data:e,extractedData:t}):this.prevInternal({numBefore:i,numAfter:s,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:Si(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:Si(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),v(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe(g(e=>null!==e),O(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:s,extractedData:n}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(n[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:s>0,hasPrev:i>0}}prevInternal(e){const{numBefore:t,numAfter:i,extractedData:s}=e;this.firstElement=null,this.lastElement=s[t-1],this.internalStateObserver.next(null),this.doNewQuery(s[s.length-i-1],!0)}}Error;class us{constructor(e,t,i,s,n){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=s,this.mutationSender=n}getForDocument(e){const{collectionName:t,integrationId:i,docId:s}=Xi(e),n=xi(s),r=this.get(t,i);for(const[e,t]of Object.entries(n))r.where(e,"==",t);return r}get(e,t){return new hs(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService,this.mutationSender)}}class ls{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)}docId(e){return this.eq(si,e)}docIds(e){return this.in(si,e)}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 ds{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(ye(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new ds(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 ds(t)}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new cs(this,e)}}class hs extends ls{constructor(e,t,i,s,n,r,o,a){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=s,this.documentReferenceFactory=n,this.queryBuilderFactory=r,this.documentIdentityService=o,this.mutationSender=a,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}get hash(){return Bi(this.build())}where(e,t,i){if(be(ri.includes(t),`Invalid operator: ${t}`),this.query.projectFields&&e!==si&&!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 s=Array.isArray(i)?[...i]:[i];"in"===t&&0===s.length&&(this.containsEmptyInCondition=!0);for(const i of s)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),()=>Se("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(Di(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,s,n,r;be((i=t,s=["fieldName","asc"],!Array.isArray(i)&&[...Object.keys(i)].every(e=>s.includes(e))),"Field sort should only contain a fieldName and asc"),be((n=t.asc,r="boolean",Array.isArray(n)?n.every(e=>typeof e===r):typeof n===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&&e!==si&&!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(e.fieldName!==si&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including sort field '${e.fieldName}'.`);for(const e of this.query.conditions)if(ss(e)){if(e.fieldName!==si&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including filter field '${e.fieldName}'.`)}else if(ns(e));else for(const i of e.fields)if(i.fieldName!==si&&!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(),s=i.projectFields;return this.querySubscriptionManager.processQuery(i,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(ye(e=>e.map(e=>{be(1===Object.keys(e).length);const t=e[this.collectionName],i=Zi(we(t).__docId__,this.collectionName,this.integrationId),n=this.documentReferenceFactory.create(i,this.queryBuilderFactory,s);return this.querySubscriptionManager.detachedRecords.delete(e)&&n.setInMemoryData(t),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 s=e[t];void 0!==s&&(e[i]=s,delete e[t])}(e||{},t,i)}),i)),E({}))),ye(([i])=>{let s=[];const n=[],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]){n.push(r);const s=e[i];delete e[i],t.delete(s)}else s.push(r)}for(const e of t)r.push(e)}else s=i;e={},t=new Set;for(const s of i){const i=s.dataRef;e[s.squidDocId]=i,t.add(i)}return new ps(s,n,r)}))}async delete(){return this.validateQueryDeleteModifiers(),this.containsEmptyInCondition?{deletedCount:0}:(be(this.mutationSender,"Query delete is not available on this query builder."),this.mutationSender.deleteQuery(this.build()))}dereference(){return new ds(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new hs(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService,this.mutationSender);return e.query=Oi(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){if(!e.length)return this;if(this.query.projectFields)for(const t of e)if(t.fieldName!==si&&!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 cs(this,e)}validateQueryDeleteModifiers(){be(0===this.query.sortOrder.length&&-1===this.query.limit&&!this.query.limitBy,"query.delete() does not currently support sortBy, limit, or limitBy.")}mergeConditions(){const e=[],t=Ri(this.query.conditions.filter(ss)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=Ri(i,e=>e.operator);for(const[i,s]of Object.entries(t)){if("=="===i||"!="===i){e.push(...s);continue}const t=[...s];t.sort((e,t)=>Ai(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!ss(e)),...e]}}class ps{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class gs extends ls{constructor(e,t,i,s,n,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=s,this.queryBuilderFactory=n,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,s){const n=s?.leftAlias??this.latestAlias,r={...i,leftAlias:n,isInner:s?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[n].push(t),new gs(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,Oi(this.joins),Oi(this.joinConditions),e,!1).pipe(ye(e=>e.map(e=>{const t={};for(const[i,s]of Object.entries(e)){const e=i===this.rootAlias?this.collectionName:this.joins[i].collectionName,n=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,r=s?Zi(s.__docId__,e,n):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 ms(this)}dereference(){return new fs(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new gs(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,Oi(this.leftToRight),Oi(this.joins),Oi(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 cs(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class fs{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(ye(e=>e.map(e=>function(e,t){const i={},s=Object.keys(e);for(const n of s){const s=e[n];i[n]=t(s)}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 fs(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 cs(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class ys{constructor(e){this.groupedJoin=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(ye(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 ys(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 cs(this,e)}dereference(e,t){const i=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(i.length){const s={[t]:e[t].data};for(const t of i)s[t]=e[t].map(e=>this.dereference(e,t));return s}return e.data}}class ms{constructor(e){this.joinQueryBuilder=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(ye(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new ys(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new ms(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 cs(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],s=e[0][t];if(0===i.length)return s;const n={[t]:s};for(const t of i)n[t]=this.groupData(e,t);return n})}}class Is{constructor(e,t,i,s,n,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=s,this.querySubscriptionManager=n,this.dataManager=r,this.refId=Me()}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!==Wt)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={[Yi]:Me()};else e=e&&"string"!=typeof e?{__id:Ni(e)}:{__id:e||Me()};const t=Zi(Ni(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 as?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new gs(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new bs(...e)}}class bs{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 bs(...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 cs(this,e)}or(e,...t){return o([...t]).pipe(v(t=>{const i=new Set,s=t.flat(),n=[];for(const e of s)i.has(this.extractData(e))||(i.add(this.extractData(e)),n.push(e));return n.sort((t,i)=>{for(const{fieldName:s,asc:n}of e){const e=Si(this.extractData(t),s),r=Si(this.extractData(i),s);if(!es(e,r,"=="))return es(r,e,"<")?n?-1:1:n?1:-1}return 0}).slice(0,this.getLimit())}))}}class ws{constructor(e,t,i,s){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=i,this.dataManager=s,this.collections=new Map}get(e,t){let i=this.collections.get(t);i||(i=new Map,this.collections.set(t,i));let s=i.get(e);return s||(s=new Is(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,s)),s}}class vs{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 Ss=x(150);const Ms={"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)=>ks(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>ks(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>ks(e,t)&&Ts(t),"like_cs:like_cs":(e,t)=>ks(e,t),"like:not like":(e,t)=>!_s(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!_s(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!_s(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!_s(e,t),"not like:like":(e,t)=>Ds(e,t),"not like_cs:like":(e,t)=>Ds(e,t),"not like:like_cs":(e,t)=>Ds(e,t),"not like_cs:like_cs":(e,t)=>Ds(e,t),"not like:not like":(e,t)=>ks(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>ks(t,e)&&Ts(e),"not like:not like_cs":(e,t)=>ks(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>ks(t,e),"in:like":(e,t)=>e.every(e=>es(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>es(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>es(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>es(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&&Es(e)||Cs(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Es(e)||Cs(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Es(t)||Cs(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Es(t)||Cs(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=>es(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>es(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>es(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>es(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 ks(e,t,i=0,s=0){if(s>=t.length)return i>=e.length;if(i>=e.length)return Es(t.substring(s));const n=e[i],r=t[s];return"%"===n&&"%"===r?ks(e,t,i+1,s+1)||ks(e,t,i+1,s):"%"!==n&&("%"===r?ks(e,t,i,s+1)||ks(e,t,i+1,s):(n===r||"_"===r)&&ks(e,t,i+1,s+1))}function _s(e,t,i=0,s=0){if(i>=e.length&&s>=t.length)return!0;if(i>=e.length)return Es(t.substring(s));if(s>=t.length)return Es(e.substring(i));const n=i<e.length?e[i]:"",r=s<t.length?t[s]:"";return"%"===n&&"%"===r?_s(e,t,i+1,s+1)||_s(e,t,i,s+1)||_s(e,t,i+1,s):"%"===n||"%"===r?_s(e,t,i,s+1)||_s(e,t,i+1,s):(n===r||"_"===n||"_"===r)&&_s(e,t,i+1,s+1)}function Ts(e){return!/[a-zA-Z]/.test(e)}function Es(e){return e.split("").every(e=>"%"===e)}function Ds(e,t){return e.length>0&&Es(e)||t.length>0&&Es(t)||Cs(e)&&0===t.length}function Cs(e){let t=!1,i=!1;for(const s of e)switch(s){case"%":t=!0;break;case"_":if(i)return!1;i=!0;break;default:return!1}return t&&i}function Os(e,t){const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(const s of i){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Di(e[s],t[s]))return!1}return!0}function qs(e,t){return t.every(t=>{const i=Object.keys(t).sort();if(i.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(i[t]!==e[t])return!1;return!0})}class As{constructor(e){this.query=e,this.query=e;const t=this.query.conditions.filter(ss),i=this.query.conditions.filter(ns),s=i.flatMap(e=>function(e){if("=="!==e.operator&&"in"!==e.operator)return[];if(0===e.docIds.length)return[];const t=[],i=e.docIds[0];for(const s of Object.keys(i)){const n=i[s];e.docIds.every(e=>Object.prototype.hasOwnProperty.call(e,s)&&Di(e[s],n))&&t.push({fieldName:s,operator:"==",value:n})}return t}(e));this.exactSimpleConditions=this.parseConditions(t),this.exactDocIdConditions=i,this.subqueryConditions=this.parseConditions([...t,...s])}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)=>!Di(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.subqueryConditions.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;for(const t of e.conditions.filter(ns))if(!this.childImpliesParentDocIdCondition(t))return!1;const t=e.conditions.filter(ss),i=this.isSubqueryOfConditions(t),s=this.sortedBy(e.sortOrder),n=-1===e.limit||this.limit>-1&&this.limit<e.limit,r=this.isProjectFieldsSubset(this.query.projectFields,e.projectFields);return i&&s&&n&&r}childImpliesParentDocIdCondition(e){const t=e.docIds;if(0===t.length)return!1;const i="=="===e.operator||"in"===e.operator,s=Object.keys(t[0]).sort(),n=[];for(const e of this.query.conditions)ns(e)&&n.push(...e.docIds);if(!qs(s,t)||!qs(s,n))return!1;const r=this.buildChildEffectiveTupleSet();return i?void 0!==r.allowed&&r.allowed.every(e=>t.some(t=>Os(e,t))):void 0!==r.allowed?r.allowed.every(e=>!t.some(t=>Os(e,t))):t.every(e=>r.excluded.some(t=>Os(e,t)))}buildChildEffectiveTupleSet(){let e;const t=[];for(const i of this.query.conditions)if(ns(i))if("=="===i.operator||"in"===i.operator)e=void 0===e?[...i.docIds]:e.filter(e=>i.docIds.some(t=>Os(e,t)));else for(const e of i.docIds)t.some(t=>Os(t,e))||t.push(e);return void 0!==e&&t.length>0&&(e=e.filter(e=>!t.some(t=>Os(e,t)))),{allowed:e,excluded:t}}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.subqueryConditions.filter(t=>e.includes(t.fieldName))}getConditionsForField(e){return this.subqueryConditions.filter(t=>t.fieldName===e)}documentMatchesQuery(e){for(const t of this.exactSimpleConditions){const i=t.fieldName,s=t.operator;if(i===si){const i=t.value;if("in"===s||"not in"===s){const t=(Array.isArray(i)?i:[i]).some(t=>os(t,e,"==",Si));if(!("in"===s?t:!t))return!1;continue}if(!os(i,e,s,Si))return!1;continue}const n=Si(e,i);if("in"===s){if(t.value.includes(n))continue;return!1}if("not in"!==s){if(!es(t.value,n,s))return!1}else if(t.value.includes(n))return!1}for(const t of this.exactDocIdConditions)if(!rs(t,e,Si))return!1;return!0}evaluateSubset(e,t){const{operator:i,value:s}=e,{operator:n,value:r}=this.parseConditions([t])[0],o=Ms[`${i}:${n}`];return!!o&&o(s,r)}parseConditions(e){const t=[],i=new Map,s=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":s.set(e.fieldName,(s.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),i.forEach((e,i)=>{t.push({fieldName:i,operator:"in",value:e})}),s.forEach((e,i)=>{t.push({fieldName:i,operator:"not in",value:e})}),t}}function Rs(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?Oi(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function js(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function Ns(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=Oi(e);t=Oi(t);for(const[e]of js(i)){const s=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&s>t.split(".").length)&&delete i.properties[e]}for(const[e,s]of js(t))i.properties[e]=Fs([...i.properties[e]||[],...s]);return i}(e,t);const i=Oi(e);for(const[e,s]of js(t)){const t=s;for(const s of t){const t=Rs(Si(i.properties,e),s);void 0===t?_i(i.properties,e):ki(i.properties,e,t)}}return i}function Fs(e){let t=0;for(;t+1<e.length;){const i=xs(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function xs(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 Bs(e,t){if(!e)return;const i={...e},s=js(t);for(const[e,t]of s){const s=t;for(const t of s){const s=Rs(Si(i,e),t);void 0===s?_i(i,e):ki(i,e,s)}}return i}function Ps(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 s=t[e].reduce((e,t)=>we(Ns(e,t),"Merge result cannot be null"));i.push(s)}return i}const Us="dataManager_runInTransaction";var Qs;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(Qs||(Qs={}));class Ls{constructor(e,i,s,n,o,a,c,u,l){this.documentStore=e,this.mutationSender=i,this.socketManager=s,this.querySubscriptionManager=n,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,s=this.docIdToLocalTimestamp.get(e);return!((!s||i)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&s===i)}async executeDetachedQuery(e){const t=this.currentTransactionId,i={query:e,clientRequestId:Me(),subscribe:!1},s=await this.querySender.sendQueryDirect(i);return this.currentTransactionId!==t?this.reRunQueryThroughNormalPipeline(e):this.applyPendingMutationsToQueryResult(s.docs,e)}async reRunQueryThroughNormalPipeline(e){await m(this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)));const t={query:e,clientRequestId:Me(),subscribe:!1};return(await this.querySender.sendQueryDirect(t)).docs}applyPendingMutationsToQueryResult(e,t){const i=new As(t),s=new Map;for(const i of e){const e=Zi(i.__docId__,t.collectionName,t.integrationId);s.set(e,i)}for(const[e,n]of this.pendingOutgoingMutations){const r=Xi(e);if(r.collectionName===t.collectionName&&r.integrationId===t.integrationId)for(const{mutation:t}of n){const n=s.get(e);if("delete"===t.type)s.delete(e);else if("update"===t.type){if(n){const r=Bs(n,t);r&&i.documentMatchesQuery(r)?s.set(e,r):s.delete(e)}}else if("insert"===t.type){const n={...t.properties,__docId__:r.docId};i.documentMatchesQuery(n)&&s.set(e,n)}}}const n=Array.from(s.values()),{sortOrder:r}=t;n.sort((e,t)=>{for(const{fieldName:i,asc:s}of r){const n=Ai(Si(e,i),Si(t,i));if(0!==n)return s?n:-n}return 0});const o=t.limit<0?2e3:t.limit;return n.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(Us)?this.lockManager.lockSync(Us):await this.lockManager.lock(Us);let i=$s;const s=()=>i!==$s;return new Promise(async(t,n)=>{try{let r;this.currentTransactionId=Me();try{r=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(s()?void 0:{resolve:()=>t(r),reject:n})}}catch(e){i=s()?i:e}finally{try{this.lockManager.release(Us)}catch(e){i=s()?i:e}}s()&&n(i)})}async applyOutgoingMutation(e,t){const i=Zi(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(Us)||(await this.lockManager.lock(Us),this.lockManager.release(Us)),this.knownDirtyDocs.delete(i);const s=this.pendingOutgoingMutations.get(i)?.slice(-1)[0];if(s&&!s.sentToServer)s.mutation=we(Ps([s.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},s=this.pendingOutgoingMutations.get(i)||[];s.push(t),this.pendingOutgoingMutations.set(i,s),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(i),s="delete"===e.type?void 0:"update"===e.type?Bs(t,e):{...e.properties};this.updateDocumentFromSnapshot(i,s)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(i,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(i,s).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(Us);try{this.currentTransactionId=Me();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(Us)}}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),ye(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 s of e){if(!this.querySubscriptionManager.hasOngoingQuery(s.clientRequestId))continue;const e=this.querySubscriptionManager.getQuery(s.clientRequestId),n=null!==e.projectFields&&void 0!==e.projectFields,r=this.querySubscriptionManager.hasSubscription(s.clientRequestId);n&&r?i.push({squidDocId:s.squidDocId,item:{properties:s.doc,timestamp:s.mutationTimestamp,clientRequestId:s.clientRequestId,projectFields:e.projectFields}}):t[s.squidDocId]={properties:s.doc,timestamp:s.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 s of e.docs){const n=Zi(s.__docId__,t.collectionName,t.integrationId);i.push({squidDocId:n,item:{properties:s,timestamp:s.__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 s of e.docs){const e=Zi(s.__docId__,t.collectionName,t.integrationId);i[e]={properties:s,timestamp:s.__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 s=new Set,n=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?(r.properties&&this.documentStore.adoptMissingFields(t,r.properties),n.add(t)):(this.pendingIncomingUpdates.set(t,r),s.add(t))}return this.runInTransactionSync(()=>{for(const e of s)this.maybeApplyIncomingUpdate(e);for(const e of n)this.refreshQueryMapping(e)},t),i}applyProjectedUpdates(e){for(const{squidDocId:t,item:i}of e){const e=we(i.clientRequestId,"clientRequestId required for projected updates"),s=this.pendingOutgoingMutations.get(t);if(s&&s.length)continue;const n=this.docIdToServerTimestamp.get(t);n&&n.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||Ni({...t,__ts__:void 0})!==Ni(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 Ss.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:s={},refreshList:n=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(s),n.forEach(e=>{this.refreshDocIdToTimestamp.set(s[e]||e,i)});for(const t of e){let e=this.removeOutgoingMutation(t);s[e]&&(e=s[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=Zi(e.mutation.squidDocIdObj),i=we(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}=Xi(t);this.setExpiration(t,!0);try{const i=e.includes(Yi)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(we(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 s=this.docIdToServerTimestamp.get(t)?.timestamp;s&&s>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=Zi(t.mutation.squidDocIdObj),s=e[i];s&&(t.mutation.squidDocIdObj=Xi(s))})}),Object.entries(e).forEach(([e,t])=>{Ti(this.pendingOutgoingMutations,e,t),Ti(this.docIdToLocalTimestamp,e,t),Ti(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 $s=Symbol("undefined");class Gs{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new t(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe(g(Boolean),ye(()=>{}))}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 Hs{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)`),Wi.debug(`DistributedLockManager: released 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,s=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),be(await m(k(j(this.lockWaitForConnectionThreshold).pipe(ye(()=>!1)),this.socketManager.observeConnectionReady().pipe(g(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const n=Me(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:i,maxHoldTimeMillis:s,clientRequestId:n}};this.socketManager.postMessage(r);const o=await m(k(j(i+4e3).pipe(O(1),ye(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:n}}))),this.acquireLockMessagesFromServer.pipe(g(e=>e.payload.clientRequestId===n)))),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 Ks(a,e,n,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 Ks{constructor(e,t,i,s,r){this.lockId=e,this.resourceId=t,this.clientRequestId=i,this.ongoingLocks=s,this.socketManager=r,this.released=!1,this.onReleaseSubject=new n(1)}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}},t=this.socketManager.sendMessage(e),i=await m(k(I(t.then(Ws,Ws)),this.socketManager.observeConnectionReady().pipe(g(e=>!e),ye(()=>!1))));if(this.onReleaseSubject.next(),!i)return t.catch(()=>{}),void this.onReleaseSubject.complete();try{await t}finally{this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}function Ws(){return!0}class Vs{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 Js{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 as(e,we(this.dataManager,"dataManager not found"),t,i);let s=this.documents.get(e);if(s)return s;s=new as(e,we(this.dataManager,"dataManager not found"),t);const{integrationId:n,collectionName:r}=Xi(e);this.documents.set(e,s);const o=this.getCollectionKey(n,r),a=this.documentsForCollection.get(o)||[];return this.documentsForCollection.set(o,a.concat(s)),s}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=Xi(e),s=Xi(t);Ti(this.documents,i.docId,s.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class zs{constructor(){this.squidDocIdToDoc=new Map,this.squidDocIdToProjectedFields=new Map}saveProjectedDocument(e,t,i){const s=this.squidDocIdToDoc.get(e);if(s){const i=this.mergeDocuments(s,t),n=this.removeInternalProperties(i);this.squidDocIdToDoc.set(e,n)}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 s||this.squidDocIdToProjectedFields.set(e,new Set(i))}return this.squidDocIdToDoc.get(e)}mergeDocuments(e,t){const i=Oi(e);for(const e of Object.keys(t)){const s=t[e],n=i[e];null===s||"object"!=typeof s||Array.isArray(s)||null===n||"object"!=typeof n||Array.isArray(n)?i[e]=s:i[e]=this.mergeDocuments(n,s)}return i}adoptMissingFields(e,t){const i=this.squidDocIdToDoc.get(e);if(!i)return;const s=Object.keys(t).filter(e=>"__ts__"!==e&&!(e in i));if(!s.length)return;const n=Oi(i);for(const e of s)n[e]=t[e];this.squidDocIdToDoc.set(e,n);const r=this.squidDocIdToProjectedFields.get(e);if(r)for(const e of s)r.add(e)}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=Oi(t),s=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,s),this.squidDocIdToProjectedFields.delete(e),s}return this.squidDocIdToDoc.delete(e),void this.squidDocIdToProjectedFields.delete(e)}const s=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,s),this.squidDocIdToProjectedFields.delete(e),s}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=>Ni(t.map(t=>Si(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=Array.from(e).map(e=>this.squidDocIdToDoc.get(e)).filter(me),{sortOrder:s,limitBy:n}=t,r=i.sort((e,t)=>this.compareSquidDocs(e,t,s)),o=t.limit<0?2e3:t.limit;let a;if(n){const{limit:e,fields:t,reverseSort:i}=n,s=this.group(r,t);let c;c=i?s.map(t=>t.slice(-e)):s.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 s of t)if(s.includes(".")){const t=Si(e,s);void 0!==t&&ki(i,s,t)}else s in e&&(i[s]=e[s]);return i}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;Ti(this.squidDocIdToDoc,e,t),Ti(this.squidDocIdToProjectedFields,e,t);const s=Xi(t),n=xi(s.docId);this.saveDocument(t,{...i,...n,__docId__:s.docId})}compareSquidDocs(e,t,i){for(const{fieldName:s,asc:n}of i){const i=Ai(Si(e,s),Si(t,s));if(0!==i)return n?i:-i}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class Ys{constructor(e){this.rpcManager=e}async emit(e){const t={event:e};await this.rpcManager.post("events/emit",t)}}class Xs{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 Zs{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 en{constructor(e,t,i,s,n){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},this.ownedJobs=new Set,s.onDestruct(async()=>{this.stopKeepAlive();const e=[...this.ownedJobs];this.ownedJobs.clear(),await Promise.all(e.map(e=>this.resolveJob(e,"failed",void 0,"Client shut down").catch(()=>{})))}),n.isPassiveMode||this.clientIdService.observeClientId().pipe(p(),T(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Wi.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 startJob(e){await this.rpcManager.post("job/startJob",{jobId:e}),this.ownedJobs.add(e),this.ensureKeepAlive()}async completeJob(e,t){await this.resolveJob(e,"completed",t)}async failJob(e,t){await this.resolveJob(e,"failed",void 0,t)}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 n(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,s=this.listeners[i];s&&("completed"===t.status?s.next(t.result):"failed"===t.status?s.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",i),delete this.listeners[i])}))}async resolveJob(e,t,i,s){try{await this.rpcManager.post("job/resolveJob",{jobId:e,status:t,result:i,error:s})}finally{this.ownedJobs.delete(e),this.ownedJobs.size||this.stopKeepAlive()}}ensureKeepAlive(){void 0===this.keepAliveHandle&&(this.keepAliveHandle=setInterval(()=>{if(!this.ownedJobs.size)return void this.stopKeepAlive();const e={jobIds:[...this.ownedJobs]};this.rpcManager.post("job/keepAlive",e).catch(e=>Wi.debug("Job keep-alive failed:",e))},15e3))}stopKeepAlive(){void 0!==this.keepAliveHandle&&(clearInterval(this.keepAliveHandle),this.keepAliveHandle=void 0)}}class tn{constructor(e,t,i){this.graphId=e,this.rpcManager=t,this.jobClient=i}async invoke(e={}){const t=Me();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,jobId:t}),await this.jobClient.awaitJob(t)}async invokeAsync(e={}){const t=Me();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,jobId:t}),t}async resume(e,t){const i=Me();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,jobId:i}),await this.jobClient.awaitJob(i)}async resumeAsync(e,t){const i=Me();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,jobId:i}),i}async getState(e){return this.rpcManager.post("langgraph/getState",{graphId:this.graphId,threadId:e})}async deleteThread(e){await this.rpcManager.post("langgraph/deleteThread",{graphId:this.graphId,threadId:e})}}class sn{constructor(e,t){this.rpcManager=e,this.jobClient=t}graph(e){return new tn(e,this.rpcManager,this.jobClient)}}const nn="squid_mgmt_",rn="x-squid-traceid",on="x-squid-client-version";function an(e="n_"){return`${e}${Ee(10).toLowerCase()}`}const cn=e=>e();class un extends Error{constructor(e,t,i,s,n){super(e),this.statusCode=t,this.url=i,this.headers=s,this.body=n}}const ln="1.0.488";async function dn(e){return yn({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage,abortSignal:e.abortSignal})}async function hn(e){return yn({...e,method:"GET",files:[],filesFieldName:""})}async function pn(e){return yn({...e,method:"PUT"})}async function gn(e){return yn({...e,method:"PATCH"})}async function fn(e){return yn({...e,method:"DELETE",files:[],filesFieldName:""})}async function yn(e){const t=await async function({headers:e,files:t,filesFieldName:i,message:s,url:n,extractErrorMessage:r,method:o,abortSignal:a}){const c=new Headers(e);c.append(rn,an("c_")),c.append(on,ln);const u={method:o,headers:c,body:void 0,signal:a};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const s of t)e.append(i||"files",s,s.name);e.append("body",Fi(s)),u.body=e}else void 0!==s&&(c.append("Content-Type","application/json"),u.body=Fi(s));else"DELETE"===o&&void 0!==s&&(c.append("Content-Type","application/json"),u.body=Fi(s));try{const e=await fetch(n,u),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),s=mn(i);if(!r)throw new un(i,e.status,n,t,s);let o;try{o="string"==typeof s?s:s?.message||i}catch{}throw o||(o=e.statusText),new un(o,e.status,n,t,s)}const i=await e.text();return Wi.debug(`received response from url ${n}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Wi.debug(`Unable to perform fetch request to url: ${n}`,e),e}}(e);return t.body=mn(t.body),t}function mn(e){if(e){try{return xi(e)}catch{}return e}}class In{constructor(e){be(e.apiKey.startsWith(nn),`Invalid management API key format. Key must start with '${nn}'`),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 s=P(this.consoleRegion,"console",`openapi/iac/management/${t}`),n={Authorization:`ManagementKey ${this.apiKey}`};return"POST"===e?(await dn({url:s,headers:n,message:i,files:[],filesFieldName:"",extractErrorMessage:!0})).body:"PATCH"===e?(await gn({url:s,headers:n,message:i,extractErrorMessage:!0})).body:(await fn({url:s,headers:n,message:i,extractErrorMessage:!0})).body}}class bn{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=Ps(e),s=i.map(e=>`sendMutation_${Zi(e.squidDocIdObj)}`);await this.lockManager.lock(...s),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:i,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Wi.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...s)}}async deleteQuery(e){const t=`deleteQuery_${e.integrationId}_${e.collectionName}`;await this.lockManager.lock(t),await this.querySender.waitForAllQueriesToFinish();try{const t={query:e};return await this.rpcManager.post("mutation/deleteQuery",t)}catch(t){throw Wi.debug("Error while deleting query results",{error:t,query:JSON.stringify(e,null,2)}),t}finally{this.lockManager.release(t)}}}class wn{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class vn{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 Sn={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class Mn{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!kn.test(e)||e.length>=_n);be(0===i.length,()=>`Tag name is not allowed: ${i.join(",")}`),this.isReporting=!0;const s={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},n=this.rpcManager.post("/observability/metrics",{metrics:[s]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==n),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(n)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...Sn,...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:s}=e,n=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:s}){if("align-by-start-time"===s)return e;const n=t-e;let r=t-Math.floor(n/i)*i;return r>e&&(r-=i),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:s}){if("align-by-end-time"===s)return t-i;const n=t-e;let r=e+Math.floor(n/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 s=e.groupByTags[t],n=a[s]?.[0]||"";i.push(n)}t.push({tagValues:i,points:[]})}else"return-result-group-with-default-values"===s&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[i,s]of Object.entries(a)){const n=e.groupByTags.indexOf(i);if(!(n<0))for(let e=0;e<t.length;e++){const i=t[e],r=new Set(s);for(let e=0;e<t.length;e++){const s=t[e];i.tagValues.every((e,t)=>t===n||e===s.tagValues[t])&&r.delete(s.tagValues[n])}if(0!==r.size)for(const e of r){const s={tagValues:[...i.tagValues],points:[]};s.tagValues[n]=e,t.push(s)}}}for(const s of t){if(0!==s.points.length){const e=s.points[0][0],t=s.points[s.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:n,u=Array.isArray(e.fn)?e.fn.map(c):[n];for(let e=r;e<=o;e+=i){const i=s.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])}s.points=t}}(t,i.resultGroups),i}}const kn=/^[a-zA-Z0-9_-]+$/,_n=1e3;async function Tn(e,t,i=500){const s=Date.now(),n=e.paginate({pageSize:i,subscribe:!1});let r=0,o=await n.waitForData();for(;;){for(const e of o.data)r++,await t(e.data);if(!o.hasNext)break;o=await n.next()}return{count:r,time:Date.now()-s}}async function En(e,t=500){const i=[],s=e.paginate({pageSize:t,subscribe:!1});let n=await s.waitForData();for(;;){for(const e of n.data){const t=Xi(e.squidDocId),s=xi(t.docId),n=t.integrationId===Wt?s.__id:s;i.push(n)}if(!n.hasNext)break;n=await s.next()}return i}function Dn(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:s}=t,{collectionName:n,integrationId:r}=i;let o=e.collection(n,r).query();return o=Cn(o,i),s?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:s,joinConditions:n,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=Cn(u,i.query),Object.entries(s).map(([t,i])=>{const{collectionName:s,integrationId:r}=i,{left:o,right:a,leftAlias:c}=n[t];let l=e.collection(s,r).query();l=Cn(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:s,integrationId:n}=On(i[0]),r=i.map(t=>Dn(e,t));return e.collection(s,n).or(...r)}(e,t)}}function Cn(e,t){const{conditions:i,limit:s,sortOrder:n}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");if("docIds"in t)throw new Error("DocId conditions are not supported in query serialization.");const{fieldName:i,operator:s,value:n}=t;e.where(i,s,n)}e.limit(s);for(const{fieldName:t,asc:i}of n)e.sortBy(t,i);return e}function On(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 On(e.queries[0])}}class qn{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,s=new As(e),n=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>s.documentMatchesQuery(e.data)),r={};return n.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[Zi(e.__docId__,i,t)])}}function An(e,t){return W(function(i,s){var n=0;i.subscribe(ge(s,function(i){return e.call(t,i,n++)&&s.next(i)}))})}class Rn{constructor(e,i,s){this.rpcManager=e,this.destructManager=i,this.webSocketConnectionReady$=s,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.gateForCurrentBatch().subscribe(()=>{this.processQueryBatch()})},0),i)}gateForCurrentBatch(){return this.pendingQueryRequests.some(({queryRequest:e})=>e.subscribe)&&this.webSocketConnectionReady$?o([this.safeToSendQueriesToServer,this.webSocketConnectionReady$]).pipe(An(([e,t])=>e&&t),O(1),ye(()=>!0)):this.safeToSendQueriesToServer.pipe(An(Boolean),O(1))}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(An(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:s}of e){const e=t.clientRequestId,n=i.errors[e],r=i.results[e];n?s.error(n):s.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 Nn(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 Fn(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 Nn("object"==typeof i&&null!==i&&!Array.isArray(i),()=>`Root state must be a record. Trying to set '${i}', type: ${typeof i}`),i;function s(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let n=e;for(let e=0;e<t.length-1&&void 0!==n;e++){const i=t[e];Nn(!Array.isArray(n)||s(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),n=n[i],Nn(void 0===n||"object"==typeof n&&null!==n,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===n?"<null>":typeof n}'`)}const r=t[t.length-1];return Nn(!Array.isArray(n)||s(r),()=>`Invalid array index Path: '${t}`),(null==n?void 0:n[r])===i?e:Bn(e,t,i)}(e,t.path,t.value);case"delete":return xn(e,t.path);case"batch":return t.actions.reduce((e,t)=>Fn(e,t),e)}}function xn(e,t){Nn(0!==t.length,"Can't delete an empty path");let i=e;for(let s=0;s<t.length-1;s++){const n=t[s];if(i=i[n],void 0===i)return e;Nn("object"==typeof i&&null!==i,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,s+1)}', type: ${null===i?"<null>":typeof i}`)}const s=t[t.length-1];return void 0===i[s]?e:Bn(e,t,void 0)}function Bn(e,t,i){function s(e,i){Nn(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const n=Object.assign({},e);let r=n;for(let e=0;e<t.length-1;e++){const n=t[e],o=r[n];Nn(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 s(r,n),r;r[n]=a,r=a}const o=t[t.length-1];return void 0===i?s(r,o):r[o]=i,n}function Pn(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(...Pn(t,"as-is"));return"unique-and-sorted"===t?Ln(i):i}function Un(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 Qn(e){const t=[...e];return t.sort((e,t)=>{for(let i=0;i<e.length;i++){if(i===t.length)return 1;const s=e[i].localeCompare(t[i]);if(0!==s)return s}return e.length-t.length}),t}function Ln(e){const t=Qn(e),i=t;for(let e=0;e<t.length-1;e++){const s=t[e];for(let n=e+1;n<t.length;n++){const r=t[n];s.length===r.length&&Un(s,r)&&(i[n]=void 0,e++)}}return i.filter(e=>void 0!==e)}const $n=(Gn={Observable:()=>s,Subject:()=>r},Hn={},jn.d(Hn,Gn),Hn);var Gn,Hn;const Kn=(Wn={filter:()=>An,map:()=>ye},Vn={},jn.d(Vn,Wn),Vn);var Wn,Vn;class Jn{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 s=t(e);return this._setNodeValue(i,s,void 0===s),s}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 s=this.root,n=t(s.value,i);if(n!==Jn.StopFillToken){this._setNodeValue(s,n,!1);for(let r=0;r<e.length;r++){const o=e[r];i.push(o);let a=s.children.get(o);if(n=t(null==a?void 0:a.value,i),n===Jn.StopFillToken)break;a||(a={children:new Map,parent:s,childrenWithValue:0},s.children.set(o,a)),this._setNodeValue(a,n,!1),s=a}this._runGc(s)}}visitDfs(e,t,i=[]){const s=this.getNode(i);void 0!==s&&this._visitDfs(e,s,t,[...i])}_visitDfs(e,t,i,s){if("pre-order"===e&&!1===i(t.value,s))return!1;for(const[n,r]of t.children){if(s.push(n),!this._visitDfs(e,r,i,s))return!1;s.pop()}return"in-order"!==e||!1!==i(t.value,s)}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 s=e[i];let n=t.children.get(s);n||(n={children:new Map,parent:t,childrenWithValue:0},t.children.set(s,n)),t=n}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))}}Jn.StopFillToken=Symbol("Trie.StopFillToken");class zn extends $n.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class Yn{constructor(e){this.rootState=e,this.observersTrie=new Jn,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,Kn.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=Fn(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Pn(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),s=Ln([...t,...i]),n=new Jn;for(const e of s)n.fillPath(e,()=>!0);n.visitDfs("pre-order",(t,i)=>{const s=this.observersTrie.get(i);if(s){const t=this.get(i),n=s.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;s.next({action:e,value:t,oldValue:n})}})}_observeChanges(e,t=[],i){const s=0===t.length?void 0:new Jn;for(const e of t)null==s||s.set(e,!0);return new $n.Observable(t=>{const n=this.observersTrie.getOrSet(e,()=>new zn);n.isAllDetailsMode=n.isAllDetailsMode||"all-details"===i;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=n.pipe((0,Kn.filter)(({action:e})=>void 0===s||Pn(e,"as-is").some(e=>!s.get(e))),(0,Kn.map)(({action:t,value:i,oldValue:s})=>{let r=this.stubForUnusedPaths;if(n.isAllDetailsMode){const i=Pn(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=Qn(e),i=t;for(let e=0;e<i.length-1;e++){const s=t[e];for(let n=e+1;n<t.length;n++)Un(t[n],s)&&(i[n]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>Un(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:s,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),n.observed||this.observersTrie.delete(e)}})}_get(e,t){let i=e;for(let e=0;e<t.length&&void 0!==i;e++){const s=t[e];i=null==i?void 0:i[s]}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 Xn(e,t,i=(e,t)=>e>t?1:e<t?-1:0,s=0,n=e.length-1){if(n<s)return-1;const r=Math.trunc((s+n)/2);return 0===i(t,e[r])?r:i(t,e[r])>0?Xn(e,t,i,r+1,n):Xn(e,t,i,s,r-1)}function Zn(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==Xn(e,t,i))return;let s;for(s=e.length-1;s>=0&&i(e[s],t)>0;s--)e[s+1]=e[s];e[s+1]=t}function er(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const s=Xn(e,t,i);s>-1&&e.splice(s,1)}class tr{setDetachedQueryExecutor(e){this.detachedQueryExecutor=e}constructor(e,t,i,s,n,o,a,c){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=s,this.documentIdentityService=n,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 sr,this.queryResultsSubject=new r,this.detachedRecords=new Set,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientTooOld().subscribe(()=>{this.invalidateOngoingQueryRegistrations()}),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 we(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:s}=Xi(t),n=this.queryMappingManager.getMapping(i,s);return n?function(e,t){const i=[...e.unconditional||[]],s=new Map;for(const[i,n]of Object.entries(e.conditional||{})){const e=xi(i);let r;if(ss(e))if(e.fieldName===si)r=os(e.value,t,e.operator,Si);else{const i=Si(t,e.fieldName)??null;r=es(e.value,i,e.operator)}else r=ns(e)?rs(e,t,Si):ir(e,t);if(r)for(const e of n)s.set(e,(s.get(e)||0)+1)}for(const[t,n]of s.entries())n>=e.queriesMetadata[t].condCount&&i.push(t);return i}(n,e):[]}setClientRequestIdsForLocalDoc(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set,s=new Set(t?this.findQueriesForDocument(t,e).map(e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId):[]),n=new Set([...i,...s]);for(const t of[...i]){if(s.has(t))continue;i.delete(t);const n=this.clientRequestIdToLocalDocuments.get(t);n&&(n.delete(e),n.size||this.clientRequestIdToLocalDocuments.delete(t)),i.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of s){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let s=this.clientRequestIdToLocalDocuments.get(t);s||(s=new Set,this.clientRequestIdToLocalDocuments.set(t,s)),s.add(e)}return[...n]}addDocToQuery(e,t){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let s=this.clientRequestIdToLocalDocuments.get(t);s||(s=new Set,this.clientRequestIdToLocalDocuments.set(t,s)),s.add(e)}removeDocFromQuery(e,t){const i=this.localDocumentToClientRequestIds.get(e);let s=!i;i&&(i.delete(t),i.size||(this.localDocumentToClientRequestIds.delete(e),s=!0));const n=this.clientRequestIdToLocalDocuments.get(t);n&&(n.delete(e),n.size||this.clientRequestIdToLocalDocuments.delete(t)),s&&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 s=this.clientRequestIdToLocalDocuments.get(i)||new Set,n=this.documentStore.sortAndLimitDocs(s,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(n,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=we(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case Qs.UNKNOWN:e.limitUnderflowState=s.size===e.query.limit+100?Qs.ENABLED:Qs.DISABLED;break;case Qs.DISABLED:break;case Qs.ENABLED:if(s.size<e.query.limit+20){e.limitUnderflowState=Qs.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(n)}for(const e of t){const t=this.collectAllObservables(e);we(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new As(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,s,r,a,c){r&&this.socketManager.notifyWebSocketIsNeeded();const u=Object.keys(i).length>0;return r||u||!this.detachedQueryExecutor||this.lockManager.canGetLock(Us)?d(()=>{const u=this.createOngoingQueryGraph(e,t,i,s,r,!0,{},c);a&&(u.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(u),u.allObservables=new n(1);const l=u.allObservables.pipe(C(e=>o(e).pipe(ye(e=>this.joinResults(e,s,u)))),An(()=>this.allOngoingQueriesGotInitialResult(u)),E(void 0),M(),An(([e,t])=>!Di(e,t)),ye(([,e])=>e),r?R():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(_()):I(this.detachedQueryExecutor(e)).pipe(ye(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 As(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 s of t){const t=we(this.localDocumentToClientRequestIds.get(s));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(s),i.push(s))}i.length&&this.onOrphanDocuments.next(i)}registerQueryFinalizer(e){const t=e.clientRequestId,i=is(this.clientIdService.getClientId(),t);e.dataSubject.pipe(f(async()=>{if(e.unsubscribeBlockerCount.value>0&&await m(k(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(An(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)}),An(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,i,s,n,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?Qs.UNKNOWN:Qs.DISABLED};this.registerQueryFinalizer(d),this.ongoingQueries.set(u,d),a[i]=d;for(const[e,t]of Object.entries(n)){const o=t.leftAlias;if(o!==i&&e!==i)continue;const c=o===i?e:o;if(o===i){const e=this.createOngoingQueryGraph(s[c],c,s,n,r,!1,a);e.joinCondition=t,l.push(e)}else d.supportingOngoingQuery=this.createOngoingQueryGraph(s[c],c,s,n,r,!1,a)}return d}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(An(Boolean),ye(e=>({docs:e,alias:i}))));for(const i of e.supportedQueries)this.collectAllObservables(i,t);return t}joinResults(e,t,i){const s=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let n=s[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),n=this.join(n,i,s[i],t[i]))}return n}join(e,t,i,s){if(!e.length)return e;const n=Object.keys(e[0]);if(!s||!n.includes(s.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[s.right]);r.has(t)||r.set(t,[]),we(r.get(t)).push(e)}),e.flatMap(e=>{const i=r.get(this.transformKey(e[s.leftAlias]?.[s.left]))||[];return i.length?i.map(i=>({...e,[t]:i})):s.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],i=[e];for(;i.length;){const e=we(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,i){const s=we(i.joinCondition),n=i.query;if(i.activated){if(!i.canExpandForJoin)return!1;const r=we(i.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===i.alias),o=new Set(e.map(e=>e[s.left]??null));for(const e of r)e.query.conditions.filter(ss).filter(e=>e.fieldName===s.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const a=Oi(n);a.conditions=a.conditions.filter(e=>!ss(e)||e.fieldName!==s.right),[...o].forEach(e=>{a.conditions.push({fieldName:s.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),we(i.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(i.activated=!0,n.conditions.filter(ss).filter(e=>e.fieldName===s.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(i),i.canExpandForJoin=!1,!0;const t=e.map(e=>e[s.left]??null).map(e=>({fieldName:s.right,operator:"==",value:e}));return t.length?(n.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=we(t.shift());t.push(...e.supportedQueries||[]),await m(e.unsubscribeBlockerCount.pipe(An(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,s=e.clientRequestId,n=is(this.clientIdService.getClientId(),s);this.queryMappingManager.addQuery(i,n),this.ongoingQueries.set(s,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},s=new As(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await m(t.queryRegistered.pipe(An(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 n=k(e.queryRegistered.pipe(An(Boolean),h(2e3),O(1)),this.destructManager.observeIsDestructing().pipe(O(1)));t.dataSubject.pipe(A(()=>!e.done),q(n),An(Boolean),R(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),ye(e=>e.filter(e=>s.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc(Zi(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,s={query:{...e.query,limit:i},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(s).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()):(Wi.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0})}invalidateOngoingQueryRegistrations(){for(const e of this.ongoingQueries.values())e.queryRegistered.next(!1)}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=>{Ti(this.localDocumentToClientRequestIds,t,e[t])})}}function ir(e,t){for(const i of e.fields){const e=Si(t,i.fieldName)??null;if(es(i.value,e,i.operator))return!0;if(es(i.value,e,"!="))return!1}return!1}class sr{constructor(){this.stateService=new Yn({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const s=new Set;for(const n of e.conditions){if(ss(n)&&["=="].includes(n.operator)){const e=Bi(n.fieldName);s.has(e)||(i++,s.add(e))}else i++;const r=this.getConditionStatePath(e,n),o=[...this.stateService.get(r)||[]];Zn(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],s=[...this.stateService.get(i)||[]];Zn(s,t),this.stateService.set(i,s)}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 s=this.getConditionStatePath(t,i),n=[...this.stateService.get(s)||[]];er(n,e),n.length?this.stateService.set(s,n):this.stateService.delete(s)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],s=[...this.stateService.get(i)||[]];er(s,e),this.stateService.set(i,s)}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,Ni(i))];var i}}class nr{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 w(o(t).pipe(g(e=>!e.includes(!0)),O(1))),await this.lock(...e)}release(...e){for(const t of e){const e=we(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 rr{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 s=i.get(t);return s||(s=new ar(e,t,this.rpcManager,this.socketManager),i.set(t,s)),s}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const or="subscriptionMutex";class ar{constructor(e,t,i,s){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=s,this.messagesSubject=new r,this.subscriberCount=0,this.lockManager=new nr}async produce(e){await this.lockManager.lock(or);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(or)}}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(or);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(or)}}async performUnsubscribe(){await this.lockManager.lock(or);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(or)}}}class cr{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 ur{constructor(e,i,s,n,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(n))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe(e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")}),s.onDestruct(async()=>{await this.awaitAllSettled()});const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new cr(60*a,5),ai:new cr(20*a,5),secret:new cr(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 s=`Bearer ${t}`;return i&&(s+=`; IntegrationId ${i}`),{Authorization:s}}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=[],s="files",n={},r){return(await this.rawPost(e,t,i,s,!0,n,r)).body}async rawPost(e,t,i=[],s="files",n=!0,r={},o){return this.runRawRequest(e,r,async r=>{Wi.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await dn({url:a,headers:r,message:t,files:i,filesFieldName:s,extractErrorMessage:n,abortSignal:o})})}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){return this.runRawRequest(e,{},async s=>{let n=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))}),n+=`?${e.toString()}`}return Wi.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await hn({url:n,headers:s,extractErrorMessage:i})})}async put(e,t,i=[],s="files"){return(await this.rawPut(e,t,i,s)).body}async rawPut(e,t,i=[],s="files",n=!0){return this.runRawRequest(e,{},async r=>{Wi.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const o=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await pn({url:o,headers:r,message:t,files:i,filesFieldName:s,extractErrorMessage:n})})}async patch(e,t,i=[],s="files"){return(await this.rawPatch(e,t,i,s)).body}async rawPatch(e,t,i=[],s="files",n=!0){return this.runRawRequest(e,{},async r=>{Wi.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const o=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await gn({url:o,headers:r,message:t,files:i,filesFieldName:s,extractErrorMessage:n})})}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){return this.runRawRequest(e,{},async s=>{Wi.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const n=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await fn({url:n,headers:s,message:t,extractErrorMessage:i})})}async runRawRequest(e,t,i){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const s=await this.getAuthHeaders(),n={...this.staticHeaders,...s,...t};return await i(n)}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?we(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?we(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):we(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}function lr(e){be(!e.isPassiveMode,"This operation is not available in passive mode. Use active mode for real-time features.")}class dr{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 hr(){}const pr="undefined"!=typeof process&&process.versions?.node?x(220):Ki().WebSocket;class gr{constructor(e,i,s,n=cn,o,a,c){this.clientIdService=e,this.region=i,this.appId=s,this.messageNotificationWrapper=n,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(T(1),g(e=>!e),C(()=>k(j(this.clientTooOldThreshold),this.connectionReady.pipe(g(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Wi.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Wi.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?Wi.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Wi.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Wi.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Wi.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(){lr(this.runtimeOptions),await m(this.observeConnectionReady().pipe(g(Boolean)))}notifyWebSocketIsNeeded(){lr(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&&(Wi.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.notifyWebSocketIsNeeded();try{await m(k(this.connectionReady.pipe(g(Boolean)),j(12e4).pipe(R(()=>{throw new Error("WebSocket connection not ready within 2 minutes")}))).pipe(q(this.destructSubject)))}catch(e){if(this.destructManager.isDestructing)return;throw e}const t=await this.authManager.getToken();if(this.connectionReady.value)try{be(this.socket,"Socket is undefined in sendMessageAsync");const i=Fi({message:e,authToken:t});Wi.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(Fi({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();Wi.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,s=0,n=1;const r={connected:!1,closeCalled:!1,open(){i=new(pr?.WebSocket??pr)(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.")}:hr,i.onopen=function(e){r.connected=!0,(t.onopen||hr)(e),s=0},i.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return Wi.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||hr)(e),void r.reconnect(e);(t.onclose||hr)(e)},i.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||hr)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;n&&s++<i?n=setTimeout(function(){(t.onreconnect||hr)(e),Wi.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||hr)(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(n),n=void 0,i.close(e,t)}catch(e){}}};return r.open(),r}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Wi.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Wi.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Wi.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Wi.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Wi.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 Wi.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=xi(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Wi.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(j(0)),this.connectionReady.next(!1),await m(j(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function fr(e){var t,i;i="Invalid application ID",be(function(e){return"string"==typeof e}(t=e),()=>Se(i,"Not a string",t));const s=e.split("-");be(s.length<4,`Invalid application ID: ${e}`);const[n,r,o]=s;return{appId:n,environmentId:r??"prod",squidDeveloperId:o}}function yr(e,t){return`${fr(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function mr(e,t,i){return`${yr(e,t)}${i?`-${i}`:""}`}function Ir(e){const t=fr(e);return yr(t.appId,t.environmentId)}class br{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,i){const s={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:i};await this.rpcManager.post("storage/uploadFile",s,[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 wr{constructor(e,t,i,s,n){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=s,this.consoleRegion=n}get shortUrlHeaders(){return{"Content-Type":"application/json","x-app-api-key":this.apiKey}}async aiSearch(e,t,i){return await this.rpcManager.post("web/aiSearch",{query:e,allowedDomains:i},[],"files",{},t)}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={url:t.url,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shorten",i,"create short URL","json")}async createShortUrls(e){be(this.apiKey,"API key is required to create a short URL");const t=Array.isArray(e)?{urls:e}:e,i={urls:t.urls,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shortenMany",i,"create short URLs","json")}async deleteShortUrl(e){be(this.apiKey,"API key is required to delete a short URL");const t={id:e,appId:this.appId};await this.postShortUrlApi("delete",t,"delete short URL","ignore")}async deleteShortUrls(e){be(this.apiKey,"API key is required to delete a short URL");const t={ids:e,appId:this.appId};await this.postShortUrlApi("deleteMany",t,"delete short URLs","ignore")}async postShortUrlApi(e,t,i,s){const n=U(this.region,this.consoleRegion,`openapi/sqd/${e}`),r=await fetch(n,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(t)});if("ignore"===s)return void be(r.ok,`Failed to ${i} (${r.status}): ${r.statusText}`);const o=await r.text();return be(r.ok,`Failed to ${i} (${r.status}): ${o}`),JSON.parse(o)}}class vr{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i}async executeWebhook(e,t={}){const{headers:i={},queryParams:s={},body:n,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(s&&Object.keys(s).length>0){const e=new URLSearchParams;Object.entries(s).forEach(([t,i])=>{e.append(t,String(i))}),c+=`?${e.toString()}`}const u=new Headers(a);let l;if(u.append(rn,an("c_")),u.append(on,ln),r&&r.length>0){const e=new FormData;for(const t of r)e.append("file",t,t.name);n&&"object"==typeof n&&Object.entries(n).forEach(([t,i])=>{e.append(t,String(i))}),l=e}else u.append("Content-Type","application/json"),l=Fi(n||{});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 un(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 Sr{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new Gs,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=mr(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Vi(this.destructManager),Wi.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new wi(e.apiKey,e.authProvider),this.socketManager=new gr(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager,this.runtimeOptions),this.rpcManager=new ur(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new vn(this.socketManager,this.rpcManager),this.jobClient=new en(this.socketManager,this.rpcManager,this.clientIdService,this.destructManager,this.runtimeOptions),this.langGraphClient=new sn(this.rpcManager,this.jobClient),this.backendFunctionManager=new Gi(this.rpcManager),this.aiClient=new mi(this.socketManager,this.rpcManager,this.jobClient,this.clientIdService,this.backendFunctionManager,()=>this.metricAnnotations),this.apiClient=new bi(this.rpcManager),this.eventsClient=new Ys(this.rpcManager),this.documentStore=new zs,this.lockManager=new nr,this.distributedLockManager=new Hs(this.socketManager,this.destructManager),this.documentIdentityService=new Vs(this.documentStore,this.destructManager),this.documentReferenceFactory=new Js(this.documentIdentityService),this.querySender=new Rn(this.rpcManager,this.destructManager,this.socketManager.observeConnectionReady()),this.observabilityClient=new Mn(this.rpcManager),this.schedulerClient=new dr(this.rpcManager),this._appId=i,this.querySubscriptionManager=new tr(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager,this.lockManager),this.localQueryManager=new qn(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const s=new bn(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new us(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService,s),this.dataManager=new Ls(this.documentStore,s,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new ws(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.querySubscriptionManager.setDetachedQueryExecutor(e=>this.dataManager.executeDetachedQuery(e)),this.webhookManager=new vr(this.rpcManager,e.region,i),this.nativeQueryManager=new wn(this.rpcManager),this._connectionDetails=new vs(this.clientIdService,this.socketManager,this.runtimeOptions),this.queueManagerFactory=new rr(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new H(this.rpcManager,this.options.region,Ir(i),this.options.consoleRegion),this.webClient=new wr(this.rpcManager,this.options.region,Ir(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=Ni(e);let i=Sr.squidInstancesMap[t];return i||(i=new Sr(e),Sr.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(Sr.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Wt){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 s={type:"relational",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativePureQuery(e,t,i={}){const s={type:"pure",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativeMongoQuery(e,t,i){const s={type:"mongo",collectionName:t,aggregationPipeline:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativeElasticQuery(e,t,i,s="_search",n="GET"){const r={type:"elasticsearch",index:t,endpoint:s,method:n,body:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(r)}ai(){return this._validateNotDestructed(),this.aiClient}setMetricAnnotations(e){this.metricAnnotations=e?{...e}:void 0}job(){return this._validateNotDestructed(),this.jobClient}langGraph(e){return this._validateNotDestructed(),this.langGraphClient.graph(e)}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 br(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new Xs(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new Zs(this.rpcManager)}events(){return this._validateNotDestructed(),this.eventsClient}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t,i){const s=await this.acquireLock(e,i);try{return await t(s)}finally{s.release()}}queue(e,t=Vt){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(Sr.squidInstancesMap).find(([,e])=>e===this);e&&delete Sr.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)=>mr(e,t,i)}}_validateNotDestructed(){be(!this.destructManager.isDestructing,"The client was already destructed.")}}const Mr=18,kr=100,_r=50,Tr=200,Er=500,Dr=500,Cr=20,Or=2e4;export{We as AGENT_STATUS_TITLE_ACCESSING_KB,Ke as AGENT_STATUS_TITLE_AGENT_RESPONSE,Ve as AGENT_STATUS_TITLE_CALLING_AI_FUNCTION,Ye as AGENT_STATUS_TITLE_GREPPING_KB,Je as AGENT_STATUS_TITLE_INSPECTING_KB_METADATA,ze as AGENT_STATUS_TITLE_QUERYING_KB_GRAPH,Xe as AGENT_STATUS_TITLE_QUERYING_SPREADSHEET,Pt as AI_AGENTS_INTEGRATION_ID,kt as AI_AUDIO_CREATE_SPEECH_MODEL_NAMES,Mt as AI_AUDIO_TRANSCRIPTION_MODEL_NAMES,Ze as AI_CHAT_MESSAGE_SOURCE,pt as AI_EMBEDDINGS_MODEL_NAMES,St as AI_IMAGE_MODEL_NAMES,Tt as AI_MODEL_SOURCES,st as AI_PROVIDER_TYPES,ri as ALL_OPERATORS,at as ANTHROPIC_CHAT_MODEL_NAMES,Rt as API_INJECTION_FIELD_TYPES,ni as ARRAY_OPERATORS,Lt as AUTH_INTEGRATION_TYPES,H as AdminClient,Ne as AiAgentClient,Re as AiAgentReference,xe as AiAudioClient,mi as AiClient,Be as AiFilesClient,Pe as AiImageClient,$e as AiKnowledgeBaseClient,Le as AiKnowledgeBaseReference,Ge as AiMatchMakingClient,bi as ApiClient,G as ApiKeysSecretClient,wi as AuthManager,ht as BEDROCK_EMBEDDING_MODEL_NAMES,Ft as BUILT_IN_AGENT_ID,Wt as BUILT_IN_DB_INTEGRATION_ID,Vt as BUILT_IN_QUEUE_INTEGRATION_ID,Jt as BUILT_IN_STORAGE_INTEGRATION_ID,qt as BULK_INGESTION_MAX_MULTIPART_FILE_BYTES,Gi as BackendFunctionManager,ls as BaseQueryBuilder,ai as CLIENT_CONNECTION_STATES,Ji as CLIENT_ID_GENERATOR_KEY,zi as CLIENT_REQUEST_ID_GENERATOR_KEY,xt as CONNECTOR_IDS,ps as Changes,Vi as ClientIdService,Is as CollectionReference,ws as CollectionReferenceFactory,vs as ConnectionDetails,Q as ConnectorClient,Qt as DATA_INTEGRATION_TYPES,tt as DEFAULT_PII_CLASSIFIER_MODEL,et as DEFAULT_PII_ENTITY_TYPES,Mr as DEFAULT_SHORT_ID_LENGTH,si as DOC_ID_FIELD,Ls as DataManager,fs as DereferencedJoin,Gs as DestructManager,Ks as DistributedLockImpl,Hs as DistributedLockManager,as as DocumentReference,Js as DocumentReferenceFactory,zs as DocumentStore,Fe as EMPTY_CHAT_ID,Nt as ENVIRONMENT_IDS,Ys as EventsClient,Xs as ExternalAuthClient,Zs as ExtractionClient,kr as FETCH_BEYOND_LIMIT,vt as FLUX_MODEL_NAMES,Ot as FOLDER_PATH_METADATA_FIELD_NAME,Dt as FUNCTION_AFFINITY_SCOPES,rt as GEMINI_CHAT_MODEL_NAMES,Gt as GRAPHQL_INTEGRATION_TYPES,_r as GREP_KNOWLEDGE_BASE_DEFAULT_MAX_MATCHES,Tr as GREP_KNOWLEDGE_BASE_MAX_MATCHES,Er as GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS,Dr as GREP_KNOWLEDGE_BASE_MAX_PATTERN_CHARS,ot as GROK_CHAT_MODEL_NAMES,ms as GroupedJoin,Ht as HTTP_INTEGRATION_TYPES,Bt as HttpStatus,Kt as INTEGRATION_SCHEMA_TYPES,Ut as INTEGRATION_TYPES,L as IntegrationClient,en as JobClient,gs as JoinQueryBuilder,sn as LangGraphClient,tn as LangGraphReference,Qi as LastUsedValueExecuteFunctionCache,Qs as LimitUnderflowState,qn as LocalQueryManager,$t as MCP_OAUTH_INTEGRATION_TYPES,ei as METRIC_DOMAIN,Zt as METRIC_FUNCTIONS,ti as METRIC_INTERVAL_ALIGNMENT,ii as METRIC_NO_DATA_BEHAVIOR,In as ManagementClient,He as MatchMaker,bn as MutationSender,cn as NOOP_FN,wn as NativeQueryManager,vn as NotificationClient,It as OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES,bt as OPENAI_AUDIO_MODEL_NAMES,mt as OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES,nt as OPENAI_CHAT_MODEL_NAMES,lt as OPENAI_EMBEDDINGS_MODEL_NAMES,yt as OPENAI_IMAGE_MODEL_NAMES,_t as OPEN_AI_CREATE_SPEECH_FORMATS,Mn as ObservabilityClient,cs as Pagination,hs as QueryBuilder,us as QueryBuilderFactory,Rn as QuerySender,tr as QuerySubscriptionManager,rr as QueueManagerFactory,ar as QueueManagerImpl,At as RAG_TYPES,it as RERANK_PROVIDERS,Us as RUN_IN_TRANSACTION_MUTEX,cr as RateLimiter,ur as RpcManager,ui as SOURCE_CODE_ANALYZER_MODELS,ci as SOURCE_CODE_ANALYZE_FUNCTION_ID,di as SOURCE_CODE_INTEGRATION_TYPES,Cr as SOURCE_CODE_MAX_REPOSITORIES,Or as SOURCE_CODE_MAX_SUPPLEMENTAL_INSTRUCTIONS_LENGTH,li as SOURCE_CONTROL_PROVIDERS,zt as SQUID_BUILT_IN_INTEGRATION_IDS,Xt as SQUID_METRIC_NAMES,oi as SQUID_REGIONS,wt as STABLE_DIFFUSION_MODEL_NAMES,dr as SchedulerClient,$ as SecretClient,gr as SocketManager,Sr as Squid,un as SquidClientError,br as StorageClient,Ct as VECTOR_DB_TYPES,ct as VENDOR_AI_CHAT_MODEL_NAMES,dt as VOYAGE_EMBEDDING_MODEL_NAMES,wr as WebClient,vr as WebhookManager,lr as assertNotPassiveMode,Pi as compareArgsByReference,Ui as compareArgsBySerializedValue,Dn as deserializeQuery,_e as generateId,Ee as generateShortId,De as generateShortIds,Me as generateUUID,ke as generateUUIDPolyfill,U as getConsoleUrl,Hi as getCustomizationFlag,gt as isAiEmbeddingsModelName,Yt as isBuiltInIntegrationId,ft as isIntegrationEmbeddingModelSpec,Et as isIntegrationModelSpec,jt as isPlaceholderParam,ut as isVendorAiChatModelName,En as loadQueryResultDocIds,pi as normalizeBitbucketRepositorySelection,hi as normalizeGitHubRepositorySelection,Ae as observeAiStatusUpdates,fn as rawSquidHttpDelete,hn as rawSquidHttpGet,gn as rawSquidHttpPatch,dn as rawSquidHttpPost,pn as rawSquidHttpPut,Li as transformFileArgs,mn as tryDeserializing,Tn as visitQueryResults};
|
|
1
|
+
import*as e from"ws";import{BehaviorSubject as t,NEVER as i,Observable as s,ReplaySubject as n,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 I,interval as b,lastValueFrom as w,map as v,of as S,pairwise as M,race as k,share as _,skip as T,startWith as E,switchAll as D,switchMap as C,take as O,takeUntil as q,takeWhile as A,tap as R,timer as j}from"rxjs";var N={273(e,t){Object.defineProperty(t,"__esModule",{value:!0})},150(e,t,i){var s=this&&this.__createBinding||(Object.create?function(e,t,i,s){void 0===s&&(s=i);var n=Object.getOwnPropertyDescriptor(t,i);n&&!("get"in n?!t.__esModule:n.writable||n.configurable)||(n={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,s,n)}:function(e,t,i,s){void 0===s&&(s=i),e[s]=t[i]}),n=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||s(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const r=i(642);t.default=r.PromisePool,n(i(273),t),n(i(642),t),n(i(837),t),n(i(426),t),n(i(858),t),n(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){t.PromisePoolExecutor=void 0;const s=i(642),n=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:[],processedItemsCounter:0,taskTimeout:0,shouldStoreProcessedItems:!0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw n.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}storeProcessedItems(e=!0){return this.meta.shouldStoreProcessedItems=e,this}shouldStoreProcessedItems(){return this.meta.shouldStoreProcessedItems}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}flushProcessedItems(){this.meta.processedItems=[]}incrementProcessedItemsCounter(){this.meta.processedItemsCounter+=1}processedCount(){return this.meta.processedItemsCounter}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 n.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 n.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 n.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 n.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw n.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw n.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(s.PromisePool.notRun)),this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=s.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 s=>{await this.handleErrorFor(s,e,t),this.removeActive(i)}).finally(()=>{this.shouldStoreProcessedItems()&&this.processedItems().push(e),this.incrementProcessedItemsCounter(),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,s]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(s)}createTaskTimeout(e){let t;return[async()=>new Promise((i,s)=>{t=setTimeout(()=>{s(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]=s.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 n.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 s=i(234);class n{constructor(e){this.shouldStoreProcessedItems=!0,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 n(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}dontStoreProcessedItems(){return this.shouldStoreProcessedItems=!1,this}onTaskFinished(e){return this.onTaskFinishedHandlers.push(e),this}useCorrespondingResults(){return this.shouldResultsCorrespond=!0,this}async process(e){return(new s.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).storeProcessedItems(this.shouldStoreProcessedItems).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=n,n.notRun=Symbol("notRun"),n.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}};const F={};function x(e){const t=F[e];if(void 0!==t)return t.exports;const i=F[e]={exports:{}};return N[e].call(i.exports,i,i.exports,x),i.exports}x.d=(e,t)=>{if(Array.isArray(t))for(var i=0;i<t.length;){var s=t[i++],n=t[i++];x.o(e,s)?0===n&&i++:0===n?Object.defineProperty(e,s,{enumerable:!0,value:t[i++]}):Object.defineProperty(e,s,{enumerable:!0,get:n})}else for(var s in t)x.o(t,s)&&!x.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},x.o=(e,t)=>Object.hasOwn(e,t);const B=["application","auth","mutation","native-query","query"];function P(e,t,i,s,n,r){let o="https",a=`${s||t}.${n||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=r||function(e){const t=e.replace(/^\/+/,"").split("/")[0]||"";return B.includes(t)}(i)?"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 U(e,t,i=""){return P(function(e,t){return t||(e.includes("sandbox")?"squidai.westus3.azure.sandbox":e.includes("local")?"local":e.includes("staging")?"squidai.westus3.azure.staging":"us-east-1.aws")}(e,t),"console",i)}class Q{constructor(e,t,i,s){this.rpcManager=e,this.iacBaseUrl=U(t,s,`openapi/iac/applications/${i}/connectors`)}async list(){return await this.rpcManager.get(this.iacBaseUrl)??[]}async connect(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e}`,{})}async disconnect(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}}class L{constructor(e,t,i,s){this.rpcManager=e,this.iacBaseUrl=U(t,s,`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 discoverSourceRepositories(e){return await this.rpcManager.post(`${this.iacBaseUrl}/${e}/discover-source-repositories`,{})}async discoverSourceRepositoriesFromDraft(e){return await this.rpcManager.post(`${this.iacBaseUrl}/discover-source-repositories`,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 ${constructor(e){this.rpcManager=e}get apiKeys(){return new G(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 G{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 H{constructor(e,t,i,s){this.rpcManager=e,this.region=t,this.appId=i,this.consoleRegion=s,this.integrationClient=new L(this.rpcManager,this.region,this.appId,this.consoleRegion),this.connectorClient=new Q(this.rpcManager,this.region,this.appId,this.consoleRegion),this.secretClient=new $(this.rpcManager)}integrations(){return this.integrationClient}connectors(){return this.connectorClient}secrets(){return this.secretClient}}function K(e){return"function"==typeof e}function W(e){return function(t){if(function(e){return K(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 V=function(e,t){return V=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])},V(e,t)};function J(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}V(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],s=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Y(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var s,n,r=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(s=r.next()).done;)o.push(s.value)}catch(e){n={error:e}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(n)throw n.error}}return o}function X(e,t,i){if(i||2===arguments.length)for(var s,n=0,r=t.length;n<r;n++)!s&&n in t||(s||(s=Array.prototype.slice.call(t,0,n)),s[n]=t[n]);return e.concat(s||Array.prototype.slice.call(t))}Object.create,Object.create;var Z,ee=((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 te(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var ie=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,s,n;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(K(c))try{c()}catch(e){n=e instanceof ee?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{se(h)}catch(e){n=null!=n?n:[],e instanceof ee?n=X(X([],Y(n)),Y(e.errors)):n.push(e)}}}catch(e){i={error:e}}finally{try{d&&!d.done&&(s=l.return)&&s.call(l)}finally{if(i)throw i.error}}}if(n)throw new ee(n)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)se(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)&&te(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&te(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function se(e){K(e)?e():e.unsubscribe()}ie.EMPTY;var ne={setTimeout:function(e,t){for(var i=[],s=2;s<arguments.length;s++)i[s-2]=arguments[s];var n=ne.delegate;return(null==n?void 0:n.setTimeout)?n.setTimeout.apply(n,X([e,t],Y(i))):setTimeout.apply(void 0,X([e,t],Y(i)))},clearTimeout:function(e){var t=ne.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function re(){}var oe=ae("C",void 0,void 0);function ae(e,t,i){return{kind:e,value:t,error:i}}var ce=function(e){function t(t){var i,s=e.call(this)||this;return s.isStopped=!1,t?(s.destination=t,((i=t)instanceof ie||i&&"closed"in i&&K(i.remove)&&K(i.add)&&K(i.unsubscribe))&&t.add(s)):s.destination=pe,s}return J(t,e),t.create=function(e,t,i){return new le(e,t,i)},t.prototype.next=function(e){this.isStopped?he(function(e){return ae("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?he(ae("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?he(oe,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}(ie);Function.prototype.bind;var ue=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){de(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){de(e)}else de(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){de(e)}},e}(),le=function(e){function t(t,i,s){var n,r=e.call(this)||this;return n=K(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=s?s:void 0}:t,r.destination=new ue(n),r}return J(t,e),t}(ce);function de(e){!function(e){ne.setTimeout(function(){throw e})}(e)}function he(e,t){var i=null;i&&ne.setTimeout(function(){return i(e,t)})}var pe={closed:!0,next:re,error:function(e){throw e},complete:re};function ge(e,t,i,s,n){return new fe(e,t,i,s,n)}var fe=function(e){function t(t,i,s,n,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=n?function(e){try{n(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=s?function(){try{s()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return J(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}(ce);function ye(e,t){return W(function(i,s){var n=0;i.subscribe(ge(s,function(i){s.next(e.call(t,i,n++))}))})}function me(e){return null!=e}let Ie=e=>new Error(e);function be(e,t,...i){e||function(e,...t){const i=ve(e);if("object"==typeof i)throw i;throw Ie(i||"Assertion error",...t)}(t,...i)}function we(e,t,...i){return be(e,t,...i),e}function ve(e){return void 0===e?"":"string"==typeof e?e:e()}function Se(e,t,i){const s=ve(e);if("object"==typeof s)throw s;return`${s?`${s}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}function Me(){return"function"==typeof globalThis.crypto?.randomUUID?globalThis.crypto.randomUUID():ke()}function ke(){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 _e(){return Me()}function Te(){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".charAt(Math.floor(62*Math.random()))}function Ee(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 s="";for(let t=0;t<e;t++)s+=Te();if(t.length>0&&(s=t+s.substring(t.length)),i)for(;s.charAt(t.length)===i[t.length];)s=s.substring(0,t.length)+Te()+s.substring(t.length+1);return s}function De({count:e,length:t,prefix:i}){be(e>=0,`Invalid IDs count: ${e}`);const s=new Set;for(;s.size<e;)s.add(Ee(t||18,i||""));return[...s]}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 qe(e,t,i){const s=atob(e),n=new Uint8Array(s.length);for(let e=0;e<s.length;e++)n[e]=s.charCodeAt(e);return new File([n],t,{type:i||"application/octet-stream"})}function Ae(e,t){const{agentId:i,jobId:s}=t;return e.notifyWebSocketIsNeeded(),e.observeNotifications().pipe(g(e=>"aiStatus"===e.type&&(void 0===i||e.agentId===i)),g(e=>!s||e.jobId===s),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.payload.statusUpdateId??e.messageId})))}class Re{constructor(e,t,i,s,n,r,o,a=()=>{}){this.agentId=e,this.agentApiKey=t,this.ongoingChatSequences=i,this.rpcManager=s,this.socketManager=n,this.jobClient=r,this.backendFunctionManager=o,this.getMetricAnnotations=a}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 updatePii(e){const t=await this.get();be(t,"Agent not found");const i={onDetect:"off",...t.options?.pii,...e};await this.setAgentOptionInPath("pii",i)}async updateMcpServer(e){await this.post("ai/agent/setMcpServer",{agentId:this.agentId,mcpServer:e})}async generateMcpDescriptions(){return await this.post("ai/agent/generateMcpDescriptions",{agentId:this.agentId})}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 s=this.chatInternal(e,t,i),n=await we(s.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:s.responseStream,transcribedPrompt:n.transcribedPrompt}}async ask(e,t,i){const s=await this.askInternal(e,!1,t,i);return this.replaceFileTags(s.responseString,s.annotations)}async askWithAnnotations(e,t,i){const s=await this.askInternal(e,!1,t,i);return{responseString:s.responseString,annotations:s.annotations}}async askAsync(e,t,i){const s={agentId:this.agentId,prompt:e,options:this.withMetricAnnotations(i),jobId:t};await this.post("ai/chatbot/askAsync",s)}observeStatusUpdates(e){return Ae(this.socketManager,{agentId:this.agentId,jobId:e})}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 s=await this.askInternal(e,!0,t,i),n=s.voiceResponse;return{responseString:s.responseString,transcribedPrompt:s.transcribedPrompt,voiceResponseFile:qe(n.base64File,`voice.${n.extension}`,n.mimeType)}}async askWithVoiceResponse(e,t,i){const s=await this.askInternal(e,!0,t,i),n=s.voiceResponse;return{responseString:s.responseString,voiceResponseFile:qe(n.base64File,`voice.${n.extension}`,n.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,includeMetadata:e.includeMetadata})}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,i){const s={agentId:this.agentId,request:e,memoryId:t,options:i};return await this.backendFunctionManager.executeFunction("buildAgent",s)}replaceFileTags(e,t={}){let i=e;for(const[e,s]of Object.entries(t)){let t="";const n=s.aiFileUrl.fileName?s.aiFileUrl.fileName:s.aiFileUrl.url;switch(s.aiFileUrl.type){case"image":t=``;break;case"document":t=`[${n}](${s.aiFileUrl.url})`}const r=`\${id:${e}}`;i=i.replaceAll("`"+r+"`",t).replaceAll(r,t)}return i}async askInternal(e,t,i,s){if(i?.contextMetadataFilter&&Oe(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)Oe(i.contextMetadataFilterForKnowledgeBase[e]);s=s||Me(),i=this.withMetricAnnotations({...je,...i||{}});const n="string"==typeof e;let r="ai/chatbot/";r+=n||t?!n&&t?"transcribeAndAskWithVoiceResponse":n&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:n?e:void 0,options:i,jobId:s},a=n?void 0:[e];return await this.post(r,o,a,"file"),await this.jobClient.awaitJob(s)}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 s=Me(),n=void 0===(t=this.withMetricAnnotations({...je,...t||{}})).smoothTyping||t.smoothTyping;let o="";const a=new r,u=new r;this.ongoingChatSequences[s]=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?S({value:e,complete:t,annotations:i}):S(e).pipe((()=>{const e=globalThis.document,t="object"==typeof e&&null!==e&&!0===e.hidden;return n&&!t})()?h(0):R(),ye(e=>({value:e,complete:!1,annotations:void 0})))),A(({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||Me();const p={agentId:this.agentId,jobId:i,prompt:d?e:void 0,options:t,clientRequestId:s},g={responseStream:a.pipe(f(()=>{delete this.ongoingChatSequences[s]}),_())};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}withMetricAnnotations(e){const t=this.getMetricAnnotations();return t?{...e||{},metricAnnotations:{...t,...e?.metricAnnotations}}:e}async post(e,t,i=[],s="files"){const n={};return this.agentApiKey&&(n["x-squid-agent-api-key"]=`Bearer ${this.agentApiKey}`),this.rpcManager.post(e,t,i,s,n)}}const je={smoothTyping:!0,responseFormat:"text"};class Ne{constructor(e,t,i,s,n=()=>{}){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.backendFunctionManager=s,this.getMetricAnnotations=n,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe(g(e=>"aiChatbot"===e.type),ye(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,this.getMetricAnnotations)}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:s,tokenIndex:n,annotations:r}=e.payload;if(s&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0,annotations:r});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:s,tokenIndex:void 0===n?void 0:n,annotations:r});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:s&&e===i.length-1,tokenIndex:void 0===n?void 0:n,annotations:r})}}const Fe="__squid_empty_chat_id";class xe{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},s=await this.rpcManager.post("ai/audio/createSpeech",i);return qe(s.base64File,`audio.${s.extension}`,s.mimeType)}}class Be{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 Ue(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`)}}const Qe=new Set(["completed","failed","cancelled"]);class Le{constructor(e,t,i,s,n){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i,this.socketManager=s,this.clientIdService=n}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{knowledgeBaseId:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async generateMetadataFieldDescriptions(e){return this.rpcManager.post("ai/knowledge-base/generateMetadataFieldDescriptions",{knowledgeBaseId:this.knowledgeBaseId,fieldNames:e?.fieldNames,overwriteExisting:e?.overwriteExisting})}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 listContextsPage(e){return this.rpcManager.post("ai/knowledge-base/listContextsPage",{id:this.knowledgeBaseId,truncateTextAfter:e?.truncateTextAfter,offset:e?.offset,limit:e?.limit,search:e?.search})}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,contextIds:s,graphIndexingSkippedContextIds:n}=await this.upsertContexts([e],t?[t]:void 0);if(i.length>0)return{failure:i[0]};const r=s?.[0],o=void 0!==r&&(n?.includes(r)??!1);return o?{graphIndexingSkipped:o}:{}}async upsertContexts(e,t,i){for(const t of e)t.metadata&&Ue(t.metadata);const s=Me();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:s},t),i?.onUploaded?.(),await this.jobClient.awaitJob(s)}async bulkUpsertContexts(e,t){return this.rpcManager.post("ai/knowledge-base/bulk/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contexts:e},t)}async createBulkUploadUrls(e){return this.rpcManager.post("ai/knowledge-base/bulk/createUploadUrls",{files:e.map(e=>({fileName:e}))})}async getBulkIngestionJob(e){return this.rpcManager.post("ai/knowledge-base/bulk/getJob",{jobId:e})}async cancelBulkIngestionJob(e){await this.rpcManager.post("ai/knowledge-base/bulk/cancelJob",{jobId:e})}observeBulkIngestionJob(e){return new s(t=>{const i=()=>{this.rpcManager.post("ai/knowledge-base/bulk/subscribeToJob",{jobId:e}).catch(e=>t.error(e))};t.add(this.socketManager.observeNotifications().pipe(g(e=>"bulkIngestionStatus"===e.type),g(t=>t.payload.jobId===e)).subscribe(e=>{t.next(e.payload),Qe.has(e.payload.state)&&t.complete()})),t.add(this.clientIdService.observeClientId().pipe(p(),T(1)).subscribe(()=>i())),this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.awaitConnectionReady().then(i).catch(e=>t.error(e))})}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 searchWithGraphContext(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return this.rpcManager.post("ai/knowledge-base/search",t)}async grep(e,t){return this.rpcManager.post("ai/knowledge-base/grep",{knowledgeBaseId:this.knowledgeBaseId,pattern:e,options:t})}async queryGraph(e){return this.rpcManager.post("ai/knowledge-base/queryGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}async getGraphStatus(){return this.rpcManager.post("ai/knowledge-base/getGraphStatus",{knowledgeBaseId:this.knowledgeBaseId})}async rebuildGraph(e){await this.rpcManager.post("ai/knowledge-base/rebuildGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}async exploreGraph(e){return this.rpcManager.post("ai/knowledge-base/exploreGraph",{...e,knowledgeBaseId:this.knowledgeBaseId})}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 $e{constructor(e,t,i,s){this.rpcManager=e,this.jobClient=t,this.socketManager=i,this.clientIdService=s}knowledgeBase(e){return new Le(e,this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)}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 Ge{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new He(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new He(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class He{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 Ke="Agent Response",We="Accessing Knowledge Base",Ve="Calling AI Function",Je="Inspecting Knowledge Base Metadata",ze="Querying Knowledge Base Graph",Ye="Searching Knowledge Base Text",Xe="Querying Spreadsheet",Ze=["user","ai"],et=["email","phoneNumber","creditCard","ssn","iban","passport"],tt="gpt-5.6-luna",it=["cohere","none"],st=["anthropic","bedrock","claude-code","codex","cohere","flux","gemini","openai","openai-compatible","grok","stability","voyage","mistral","textract","azure_document_intelligence","vertex","external"],nt=["openai","gemini","anthropic","grok"];function rt(e){return nt.includes(e)}const ot=["gpt-5.5-pro","gpt-5.6-sol","gpt-5.6-terra","gpt-5.6-luna"],at=["gemini-3.1-pro","gemini-3.7-flash","gemini-3.5-flash-lite"],ct=["grok-4.6","grok-4-1-fast-reasoning","grok-4-1-fast-non-reasoning"],ut=["claude-fable-5","claude-haiku-4-5-20251001","claude-opus-5","claude-sonnet-5"],lt=[...ot,...ut,...at,...ct];function dt(e){return lt.includes(e)}const ht=["text-embedding-3-small"],pt=["voyage-3-large"],gt=["titan-embed-text-v2"],ft=[...ht,...pt,...gt];function yt(e){return ft.includes(e)}function mt(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e&&"dimensions"in e}const It=["gpt-image-1","gpt-image-1-mini","gpt-image-1.5","gpt-image-2","gpt-image-2-2026-04-21","chatgpt-image-latest"],bt=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],wt=["tts-1","tts-1-hd","gpt-4o-mini-tts"],vt=[...bt,...wt],St=["stable-diffusion-core"],Mt=["flux-pro-1.1","flux-kontext-pro"],kt=[...It,...St,...Mt],_t=[...bt],Tt=[...wt],Et=["mp3","opus","aac","flac","wav","pcm"],Dt=["vendor","connector","custom"];function Ct(e){return"object"==typeof e&&null!==e&&"integrationId"in e&&"model"in e}const Ot=["pod","worker"],qt=["postgres","mongoAtlas"],At="folderPath",Rt=104857600,jt=["contextual","basic"],Nt=["secret","regular"];function Ft(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const xt=["dev","prod"],Bt="built_in_agent",Pt=["bitbucket","confluence","cotomi","essentials","freshdesk","github","google_calendar","google_drive","hubspot","sharepoint","jira","jira_jsm","linear","mail","onedrive","outlook","salesforce","servicenow_csm","slack","teams","ticketmind_companion","zendesk"],Ut={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},Qt="ai_agents",Lt=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","bedrock","azure_blob","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","bitbucket","built_in_azure_blob","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","azure-entra-external-id","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","outlook","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","sharepoint","vertex"],$t=["bigquery","built_in_db","clickhouse","cockroach","dynamodb","mongo","mssql","databricks","mysql","oracledb","postgres","snowflake","elasticsearch","legend"],Gt=["auth0","jwt_rsa","jwt_hmac","cognito","okta","keycloak","descope","firebase_auth","azure-entra-external-id"],Ht=["auth0"],Kt=["graphql"],Wt=["api"],Vt=["data","api","graphql"],Jt="built_in_db",zt="built_in_queue",Yt="built_in_storage",Xt=[Jt,zt,Yt];function Zt(e){return Xt.includes(e)}const ei=["squid_functionExecution_count","squid_functionExecution_time"],ti=["sum","max","min","average","median","p95","p99","count"],ii=["user","squid"],si=["align-by-start-time","align-by-end-time"],ni=["return-no-result-groups","return-result-group-with-default-values"],ri="__docId__",oi=["in","not in","array_includes_some","array_includes_all","array_not_includes"],ai=[...oi,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],ci=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],ui=["CONNECTED","DISCONNECTED","REMOVED"],li="analyzeCode",di=["claude-code","codex"],hi=["github","bitbucket"],pi=["github","bitbucket"];function gi(e){const t=function(e){const t=new Set,i=new Set;for(const s of e){be(Number.isSafeInteger(s.id)&&s.id>0,"GITHUB_REPOSITORY_ID_INVALID"),be(!t.has(s.id),"GITHUB_REPOSITORY_IDS_MUST_BE_UNIQUE"),t.add(s.id),be(yi(s.fullName),"GITHUB_REPOSITORY_NAME_INVALID");const e=s.fullName.toLowerCase();be(!i.has(e),"GITHUB_REPOSITORIES_MUST_BE_UNIQUE"),i.add(e),be(s.defaultBranch.trim(),"GITHUB_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),mi(s.cloneUrl,s.fullName,!0),mi(s.htmlUrl,s.fullName,!1)}return e}(e.repositories??[]),i=0===t.length?e.repository:void 0,s=t.map(e=>e.fullName);be(t.length>0||i,"GITHUB_REPOSITORIES_REQUIRED"),be(t.length<=20,"GITHUB_REPOSITORY_LIMIT_EXCEEDED");const n=e.defaultRepository??s[0]??i;return be(n,"GITHUB_DEFAULT_REPOSITORY_REQUIRED"),be(s.some(e=>e.toLowerCase()===n.toLowerCase())||i?.toLowerCase()===n.toLowerCase(),"GITHUB_DEFAULT_REPOSITORY_NOT_ALLOWED"),{...i?{legacyRepository:i}:{},repositories:t,defaultRepository:n}}function fi(e){const t=e.workspace;be(t.trim()===t&&/^[A-Za-z0-9_-]+$/.test(t),"BITBUCKET_WORKSPACE_INVALID");const i=e.repositories;be(i.length>0,"BITBUCKET_REPOSITORIES_REQUIRED"),be(i.length<=20,"BITBUCKET_REPOSITORY_LIMIT_EXCEEDED");const s=new Set,n=new Set;for(const e of i){const i=e.uuid.trim();be(i===e.uuid&&i.length>0,"BITBUCKET_REPOSITORY_ID_INVALID");const r=i.toLowerCase();be(!s.has(r),"BITBUCKET_REPOSITORY_IDS_MUST_BE_UNIQUE"),s.add(r);const o=`${t}/`;be(e.fullName.toLowerCase().startsWith(o.toLowerCase())&&e.fullName.length>o.length&&!e.fullName.slice(o.length).includes("/")&&!/\s/.test(e.fullName),"BITBUCKET_REPOSITORY_WORKSPACE_MISMATCH");const a=e.fullName.toLowerCase();be(!n.has(a),"BITBUCKET_REPOSITORIES_MUST_BE_UNIQUE"),n.add(a),be(e.defaultBranch.trim(),"BITBUCKET_REPOSITORY_DEFAULT_BRANCH_REQUIRED"),Ii(e.cloneUrl,e.fullName,!0),Ii(e.webUrl,e.fullName,!1)}const r=e.defaultRepository;return be(r&&i.some(e=>e.fullName.toLowerCase()===r.toLowerCase()),"BITBUCKET_DEFAULT_REPOSITORY_NOT_ALLOWED"),{repositories:i,defaultRepository:r}}function yi(e){return/^[^/\s]+\/[^/\s]+$/.test(e)}function mi(e,t,i){let s;try{s=new URL(e)}catch{throw new Error("GITHUB_REPOSITORY_URL_INVALID")}const n=`/${t}${i?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?github\.com:\d+(?:\/|$)/i.test(e);be(!("https:"!==s.protocol||"github.com"!==s.hostname||r||s.username||s.password||s.search||s.hash||s.pathname!==n),"GITHUB_REPOSITORY_URL_INVALID")}function Ii(e,t,i){let s;try{s=new URL(e)}catch{throw new Error("BITBUCKET_REPOSITORY_URL_INVALID")}const n=`/${t}${i?".git":""}`,r=/^https:\/\/(?:[^/@]+@)?bitbucket\.org:\d+(?:\/|$)/i.test(e);be(!("https:"!==s.protocol||"bitbucket.org"!==s.hostname||r||s.username||s.password||s.search||s.hash||s.pathname!==n),"BITBUCKET_REPOSITORY_URL_INVALID")}class bi{constructor(e,t,i,s,n,r=()=>{}){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.clientIdService=s,this.backendFunctionManager=n,this.getMetricAnnotations=r}agent(e=Bt,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(e){return(await this.rpcManager.post("ai/settings/listChatModels",e??{})).models}image(){return new Pe(this.rpcManager)}audio(){return new xe(this.rpcManager)}matchMaking(){return new Ge(this.rpcManager)}files(e){return new Be(e,this.rpcManager)}executeAiQuery(e,t,i,s){const n={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",n,[],"files",{},s)}executeAiApiCall(e,t,i,s){const n={integrationId:e,prompt:t,options:i,sessionContext:s};return this.rpcManager.post("ai/query/executeApiQuery",n)}executeAiSpreadsheetQuery(e,t,i,s){const n={prompt:e,files:t,options:i,sessionContext:s};return this.rpcManager.post("ai/query/executeSpreadsheetQuery",n)}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 Ae(this.socketManager,{jobId:e})}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new Ne(this.rpcManager,this.socketManager,this.jobClient,this.backendFunctionManager,this.getMetricAnnotations)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new $e(this.rpcManager,this.jobClient,this.socketManager,this.clientIdService)),this.aiKnowledgeBaseClient}}const wi={headers:{},queryParams:{},pathParams:{}};class vi{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,s){return this.request(e,t,i,s,"post")}async delete(e,t,i,s){return this.request(e,t,i,s,"delete")}async patch(e,t,i,s){return this.request(e,t,i,s,"patch")}async put(e,t,i,s){return this.request(e,t,i,s,"put")}async request(e,t,i,s,n){const r={integrationId:e,endpointId:t,body:i,options:{...wi,...this.convertOptionsToStrings(s||{})},overrideMethod:n};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 Si{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 Mi=/[.\[\]]/;function ki(e,t){if(!e)return;const i=t.split(Mi);let s,n=e;for(;n&&i.length;){const e=i.shift();if(e){if("object"!=typeof n||!(e in n))return;s=n[e],n=s}}return s}function _i(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function Ti(e,t,i,s="."){const n=t.split(s);let r=e;for(;n.length;){const e=we(n.shift());if(n.length){const t=r[e],i=_i(t)?Ri(t)??{}:{};r[e]=i,r=i}else r[e]=i}}function Ei(e,t,i="."){const s=t.split(i);let n=e;for(;s.length;){const e=we(s.shift());if(s.length){const t=_i(n[e])?Ri(n[e])??{}:{};n[e]=t,n=t}else delete n[e]}}function Di(e,t,i){if(e.has(t)){const s=e.get(t);e.delete(t),e.set(i,s)}}function Ci(e){return null==e}function Oi(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 s=Object.keys(e),n=Object.keys(t);if(s.length!==n.length)return!1;for(const i of s)if(!n.includes(i)||!Oi(e[i],t[i]))return!1;return!0}function qi(e,t){const i=new Array(e.length);for(let s=0;s<e.length;s++)i[s]=Ai(e[s],t);return i}function Ai(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 qi(e,t);if(e instanceof Map)return new Map(qi(Array.from(e),t));if(e instanceof Set)return new Set(qi(Array.from(e),t));if(ArrayBuffer.isView(e))return s=e,"undefined"!=typeof Buffer&&s instanceof Buffer?Buffer.from(s):new s.constructor(s.buffer.slice(),s.byteOffset,s.length);var s;const n={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(n[i]=Ai(e[i],t));return n}function Ri(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 ji(e,t){if(e===t||Ci(e)&&Ci(t))return 0;if(Ci(e))return-1;if(Ci(t))return 1;const i=typeof e,s=typeof t;return i!==s?i<s?-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 Ni(e,t){return e.reduce((e,i)=>{const s=t(i);return e[s]?e[s].push(i):e[s]=[i],e},{})}function Fi(e){if(Array.isArray(e))return e.map(e=>Fi(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]=Fi(e[t])}),i}function xi(e){return Bi(Fi(e))}function Bi(e){if(void 0===e)return null;const t=Ai(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function Pi(e){return Ai(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=Bi(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 Qi=(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},Li=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(Bi(e[i])!==Bi(t[i]))return!1;return!0};class $i{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||Qi,s=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+s&&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 s=0;for(const n of e)if("undefined"!=typeof File)if(n instanceof File){i.push(n);const e={type:"file",__squid_placeholder__:!0,fileIndex:s++};t.push(e)}else if(Hi(n)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:n.map((e,t)=>(i.push(n[t]),s++))};t.push(e)}else t.push(n);else t.push(n);return{argsArray:t,fileArray:i}}function Hi(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}class Ki{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){return this.executeFunctionWithHeaders(e,{},...t)}executeFunctionWithHeaders(e,t,...i){const{argsArray:s,fileArray:n}=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(s);if(e.found)return Promise.resolve(e.value)}const c="string"==typeof e?void 0:e.deduplication;if(c){const e="boolean"==typeof c?Qi:c.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,s));if(t)return t.promise}const u=this.createExecuteCallPromise(r,s,n,a,t);return c&&(this.inFlightDedupCalls.push({functionName:r,args:s,promise:u}),u.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==u)})),u}async createExecuteCallPromise(e,t,i,s,n={}){const r=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:Bi(t)},a=Pi((await this.rpcManager.post(r,o,i.length>0?i:[],"files",n)).payload);if(a?.__isSquidBase64File__){const e=a;return qe(e.base64,e.filename,e.mimetype)}return s&&s.set(t,a),a}}function Wi(e){if("undefined"!=typeof globalThis)return globalThis[e]}function Vi(){if("undefined"!=typeof window)return window;if("undefined"!=typeof global)return global;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}void 0===Vi()?.SQUID_LOG_DEBUG_ENABLED&&function(e=!0){Vi().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 Ji{static debug(...e){(function(){const e=Vi();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=Vi();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class zi{constructor(e){this.destructManager=e,this.clientTooOldSubject=new t(!1),this.isTenant=!0===Vi().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=Vi()[Xi];return e?e():Me()}generateClientId(){const e=Vi()[Yi];if(e)return e();let t=`${this.isTenant?"tenant-":""}${Me()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}}const Yi="SQUID_CLIENT_ID_GENERATOR",Xi="SQUID_CLIENT_REQUEST_ID_GENERATOR",Zi="__squidId";function es(e){return Pi(e)}function ts(...e){const[t,i,s]=e,n="object"==typeof t?t:{docId:t,collectionName:i,integrationId:s};return n.integrationId||(n.integrationId=void 0),xi(n)}function is(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return Oi(e,t);if("!="===i)return!Oi(e,t);switch(i){case"<":return!Ci(e)&&(!!Ci(t)||t<e);case"<=":return!!Ci(t)||!Ci(e)&&t<=e;case">":return!Ci(t)&&(!!Ci(e)||t>e);case">=":return!!Ci(e)||!Ci(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&ss(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&ss(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&ss(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&ss(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>we(i,"VALUE_CANNOT_BE_NULL").some(t=>Oi(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>we(i,"VALUE_CANNOT_BE_NULL").some(t=>Oi(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!we(i,"VALUE_CANNOT_BE_NULL").some(t=>Oi(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function ss(e,t,i){i||(e=e.toLowerCase(),t=t.toLowerCase());const s=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(`^${s}$`).test(e)}function ns(e,t){return`${e}_${t}`}function rs(e){return"fieldName"in e}function os(e){return"docIds"in e}function as(e,t,i){const s=e.docIds.some(e=>Object.entries(e).every(([e,s])=>is(s,i(t,e)??null,"==")));switch(e.operator){case"==":case"in":return s;case"!=":case"not in":return!s}}function cs(e,t,i,s){const n=e,r=s(t,ri);if("string"!=typeof r)return is(n,r??null,i);let o;try{o=Pi(r)}catch{return is(n,r,i)}if(!o||"object"!=typeof o||Array.isArray(o))return is(n,r,i);const a=Object.keys(o);if(1===a.length&&"__id"===a[0]){const e=o.__id,t=function(e){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const t=Object.keys(e);return 1===t.length&&"__id"===t[0]?e.__id:xi(e)}if("string"==typeof e)try{const t=Pi(e);if(t&&"object"==typeof t&&!Array.isArray(t)){const e=Object.keys(t);if(1===e.length&&"__id"===e[0])return t.__id}}catch{}return e}(n);return is(t,e,i)}if(1===a.length){const e=function(e,t){if("object"==typeof e&&null!==e&&!Array.isArray(e)){const i=Object.keys(e);if(1===i.length&&i[0]===t)return e[t]}if("string"==typeof e)try{const i=Pi(e);if(i&&"object"==typeof i&&!Array.isArray(i)){const e=Object.keys(i);if(1===e.length&&e[0]===t)return i[t]}}catch{}return e}(n,a[0]);return is(e,o[a[0]],i)}return"object"!=typeof n||null===n||Array.isArray(n)?is(n,r,i):is(xi(n),r,i)}class us{constructor(e,t,i,s){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.projectFields=s,this.refId=Me()}setInMemoryData(e){this.inMemoryData=e}get squidDocId(){return this._squidDocId}get data(){return Ai(this.dataRef)}get dataRef(){if(void 0!==this.inMemoryData)return this.inMemoryData;const e=we(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=es(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 we(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=>(we(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 s=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};i[e]=[s]});const s={type:"update",squidDocIdObj:es(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(s,t)}async setInPath(e,t,i){return this.update({[e]:Ai(t)},i)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,i){const s={type:"applyNumericFn",fn:"increment",value:t},n={type:"update",squidDocIdObj:es(this.squidDocId),properties:{[e]:[s]}};return this.dataManager.applyOutgoingMutation(n,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async upsert(e,t){const i=es(this.squidDocId),s=i.integrationId;let n=Pi(i.docId);if(n[Zi]&&(n={}),s===Jt&&n.__id)try{const e=Pi(n.__id);n={...n,...e}}catch{}const r={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...n}};return this.dataManager.applyOutgoingMutation(r,t)}async insert(e,t){return this.upsert(e,t)}async delete(e){const t={type:"delete",squidDocIdObj:es(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=we(this.projectFields,"applyProjection called without projectFields"),{integrationId:s}=es(this.squidDocId);"__id"in e&&(t.__id=e.__id),"__docId__"in e&&(t.__docId__=e.__docId__);const n=s===Jt?"__id":"__docId__";if(n in e){const i=e[n];if("string"==typeof i&&i.startsWith("{"))try{const e=Pi(i);if("object"==typeof e&&null!==e)for(const[i,s]of Object.entries(e))i in t||(t[i]=s)}catch{}}for(const s of i)if(s.includes(".")){const i=ki(e,s);void 0!==i&&Ti(t,s,i)}else s in e&&(t[s]=e[s]);return t}hasSquidPlaceholderId(){const e=Pi(this._squidDocId);if("object"==typeof e&&e.docId){const t=Pi(e.docId);if("object"==typeof t&&Object.keys(t).includes(Zi))return!0}return!1}}class ls{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),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||Ci(e)&&Ci(t))return 0;if(Ci(e))return-1;if(Ci(t))return 1;const i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:s,asc:n}of i){const i=ji(ki(e,s),ki(t,s));if(0!==i)return n?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,s=Math.max(0,e.length-i-this.paginateOptions.pageSize);i!==e.length?this.internalStateObserver.next({numBefore:i,numAfter:s,data:e,extractedData:t}):this.prevInternal({numBefore:i,numAfter:s,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:ki(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:ki(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),v(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe(g(e=>null!==e),O(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:s,extractedData:n}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(n[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:s>0,hasPrev:i>0}}prevInternal(e){const{numBefore:t,numAfter:i,extractedData:s}=e;this.firstElement=null,this.lastElement=s[t-1],this.internalStateObserver.next(null),this.doNewQuery(s[s.length-i-1],!0)}}Error;class ds{constructor(e,t,i,s,n){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=s,this.mutationSender=n}getForDocument(e){const{collectionName:t,integrationId:i,docId:s}=es(e),n=Pi(s),r=this.get(t,i);for(const[e,t]of Object.entries(n))r.where(e,"==",t);return r}get(e,t){return new gs(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService,this.mutationSender)}}class hs{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)}docId(e){return this.eq(ri,e)}docIds(e){return this.in(ri,e)}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 ps{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(ye(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new ps(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 ps(t)}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new ls(this,e)}}class gs extends hs{constructor(e,t,i,s,n,r,o,a){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=s,this.documentReferenceFactory=n,this.queryBuilderFactory=r,this.documentIdentityService=o,this.mutationSender=a,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}get hash(){return Ui(this.build())}where(e,t,i){if(be(ai.includes(t),`Invalid operator: ${t}`),this.query.projectFields&&e!==ri&&!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 s=Array.isArray(i)?[...i]:[i];"in"===t&&0===s.length&&(this.containsEmptyInCondition=!0);for(const i of s)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),()=>Se("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(Oi(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,s,n,r;be((i=t,s=["fieldName","asc"],!Array.isArray(i)&&[...Object.keys(i)].every(e=>s.includes(e))),"Field sort should only contain a fieldName and asc"),be((n=t.asc,r="boolean",Array.isArray(n)?n.every(e=>typeof e===r):typeof n===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&&e!==ri&&!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(e.fieldName!==ri&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including sort field '${e.fieldName}'.`);for(const e of this.query.conditions)if(rs(e)){if(e.fieldName!==ri&&!t.includes(e.fieldName))throw new Error(`Cannot set projectFields without including filter field '${e.fieldName}'.`)}else if(os(e));else for(const i of e.fields)if(i.fieldName!==ri&&!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(),s=i.projectFields;return this.querySubscriptionManager.processQuery(i,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(ye(e=>e.map(e=>{be(1===Object.keys(e).length);const t=e[this.collectionName],i=ts(we(t).__docId__,this.collectionName,this.integrationId),n=this.documentReferenceFactory.create(i,this.queryBuilderFactory,s);return this.querySubscriptionManager.detachedRecords.delete(e)&&n.setInMemoryData(t),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 s=e[t];void 0!==s&&(e[i]=s,delete e[t])}(e||{},t,i)}),i)),E({}))),ye(([i])=>{let s=[];const n=[],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]){n.push(r);const s=e[i];delete e[i],t.delete(s)}else s.push(r)}for(const e of t)r.push(e)}else s=i;e={},t=new Set;for(const s of i){const i=s.dataRef;e[s.squidDocId]=i,t.add(i)}return new fs(s,n,r)}))}async delete(){return this.validateQueryDeleteModifiers(),this.containsEmptyInCondition?{deletedCount:0}:(be(this.mutationSender,"Query delete is not available on this query builder."),this.mutationSender.deleteQuery(this.build()))}dereference(){return new ps(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new gs(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService,this.mutationSender);return e.query=Ai(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){if(!e.length)return this;if(this.query.projectFields)for(const t of e)if(t.fieldName!==ri&&!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 ls(this,e)}validateQueryDeleteModifiers(){be(0===this.query.sortOrder.length&&-1===this.query.limit&&!this.query.limitBy,"query.delete() does not currently support sortBy, limit, or limitBy.")}mergeConditions(){const e=[],t=Ni(this.query.conditions.filter(rs)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=Ni(i,e=>e.operator);for(const[i,s]of Object.entries(t)){if("=="===i||"!="===i){e.push(...s);continue}const t=[...s];t.sort((e,t)=>ji(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!rs(e)),...e]}}class fs{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class ys extends hs{constructor(e,t,i,s,n,r,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=s,this.queryBuilderFactory=n,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,s){const n=s?.leftAlias??this.latestAlias,r={...i,leftAlias:n,isInner:s?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[n].push(t),new ys(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,Ai(this.joins),Ai(this.joinConditions),e,!1).pipe(ye(e=>e.map(e=>{const t={};for(const[i,s]of Object.entries(e)){const e=i===this.rootAlias?this.collectionName:this.joins[i].collectionName,n=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,r=s?ts(s.__docId__,e,n):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 bs(this)}dereference(){return new ms(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new ys(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,Ai(this.leftToRight),Ai(this.joins),Ai(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 ls(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class ms{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(ye(e=>e.map(e=>function(e,t){const i={},s=Object.keys(e);for(const n of s){const s=e[n];i[n]=t(s)}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 ms(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 ls(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class Is{constructor(e){this.groupedJoin=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(ye(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 Is(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 ls(this,e)}dereference(e,t){const i=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(i.length){const s={[t]:e[t].data};for(const t of i)s[t]=e[t].map(e=>this.dereference(e,t));return s}return e.data}}class bs{constructor(e){this.joinQueryBuilder=e}snapshot(){return m(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(ye(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new Is(this)}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new bs(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 ls(this,e)}groupData(e,t){const i=Ni(e,e=>e[t]?.squidDocId);return Object.values(i).filter(e=>void 0!==e[0][t]).map(e=>{const i=this.joinQueryBuilder.leftToRight[t],s=e[0][t];if(0===i.length)return s;const n={[t]:s};for(const t of i)n[t]=this.groupData(e,t);return n})}}class ws{constructor(e,t,i,s,n,r){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=s,this.querySubscriptionManager=n,this.dataManager=r,this.refId=Me()}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!==Jt)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={[Zi]:Me()};else e=e&&"string"!=typeof e?{__id:xi(e)}:{__id:e||Me()};const t=ts(xi(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 us?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new ys(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new vs(...e)}}class vs{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 vs(...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 ls(this,e)}or(e,...t){return o([...t]).pipe(v(t=>{const i=new Set,s=t.flat(),n=[];for(const e of s)i.has(this.extractData(e))||(i.add(this.extractData(e)),n.push(e));return n.sort((t,i)=>{for(const{fieldName:s,asc:n}of e){const e=ki(this.extractData(t),s),r=ki(this.extractData(i),s);if(!is(e,r,"=="))return is(r,e,"<")?n?-1:1:n?1:-1}return 0}).slice(0,this.getLimit())}))}}class Ss{constructor(e,t,i,s){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=i,this.dataManager=s,this.collections=new Map}get(e,t){let i=this.collections.get(t);i||(i=new Map,this.collections.set(t,i));let s=i.get(e);return s||(s=new ws(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,s)),s}}class Ms{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 ks=x(150);const _s={"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)=>Ts(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Ts(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Ts(e,t)&&Ds(t),"like_cs:like_cs":(e,t)=>Ts(e,t),"like:not like":(e,t)=>!Es(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!Es(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!Es(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!Es(e,t),"not like:like":(e,t)=>Os(e,t),"not like_cs:like":(e,t)=>Os(e,t),"not like:like_cs":(e,t)=>Os(e,t),"not like_cs:like_cs":(e,t)=>Os(e,t),"not like:not like":(e,t)=>Ts(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Ts(t,e)&&Ds(e),"not like:not like_cs":(e,t)=>Ts(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Ts(t,e),"in:like":(e,t)=>e.every(e=>is(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>is(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>is(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>is(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&&Cs(e)||qs(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Cs(e)||qs(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Cs(t)||qs(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Cs(t)||qs(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=>is(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>is(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>is(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>is(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 Ts(e,t,i=0,s=0){if(s>=t.length)return i>=e.length;if(i>=e.length)return Cs(t.substring(s));const n=e[i],r=t[s];return"%"===n&&"%"===r?Ts(e,t,i+1,s+1)||Ts(e,t,i+1,s):"%"!==n&&("%"===r?Ts(e,t,i,s+1)||Ts(e,t,i+1,s):(n===r||"_"===r)&&Ts(e,t,i+1,s+1))}function Es(e,t,i=0,s=0){if(i>=e.length&&s>=t.length)return!0;if(i>=e.length)return Cs(t.substring(s));if(s>=t.length)return Cs(e.substring(i));const n=i<e.length?e[i]:"",r=s<t.length?t[s]:"";return"%"===n&&"%"===r?Es(e,t,i+1,s+1)||Es(e,t,i,s+1)||Es(e,t,i+1,s):"%"===n||"%"===r?Es(e,t,i,s+1)||Es(e,t,i+1,s):(n===r||"_"===n||"_"===r)&&Es(e,t,i+1,s+1)}function Ds(e){return!/[a-zA-Z]/.test(e)}function Cs(e){return e.split("").every(e=>"%"===e)}function Os(e,t){return e.length>0&&Cs(e)||t.length>0&&Cs(t)||qs(e)&&0===t.length}function qs(e){let t=!1,i=!1;for(const s of e)switch(s){case"%":t=!0;break;case"_":if(i)return!1;i=!0;break;default:return!1}return t&&i}function As(e,t){const i=Object.keys(e),s=Object.keys(t);if(i.length!==s.length)return!1;for(const s of i){if(!Object.prototype.hasOwnProperty.call(t,s))return!1;if(!Oi(e[s],t[s]))return!1}return!0}function Rs(e,t){return t.every(t=>{const i=Object.keys(t).sort();if(i.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(i[t]!==e[t])return!1;return!0})}class js{constructor(e){this.query=e,this.query=e;const t=this.query.conditions.filter(rs),i=this.query.conditions.filter(os),s=i.flatMap(e=>function(e){if("=="!==e.operator&&"in"!==e.operator)return[];if(0===e.docIds.length)return[];const t=[],i=e.docIds[0];for(const s of Object.keys(i)){const n=i[s];e.docIds.every(e=>Object.prototype.hasOwnProperty.call(e,s)&&Oi(e[s],n))&&t.push({fieldName:s,operator:"==",value:n})}return t}(e));this.exactSimpleConditions=this.parseConditions(t),this.exactDocIdConditions=i,this.subqueryConditions=this.parseConditions([...t,...s])}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)=>!Oi(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.subqueryConditions.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;for(const t of e.conditions.filter(os))if(!this.childImpliesParentDocIdCondition(t))return!1;const t=e.conditions.filter(rs),i=this.isSubqueryOfConditions(t),s=this.sortedBy(e.sortOrder),n=-1===e.limit||this.limit>-1&&this.limit<e.limit,r=this.isProjectFieldsSubset(this.query.projectFields,e.projectFields);return i&&s&&n&&r}childImpliesParentDocIdCondition(e){const t=e.docIds;if(0===t.length)return!1;const i="=="===e.operator||"in"===e.operator,s=Object.keys(t[0]).sort(),n=[];for(const e of this.query.conditions)os(e)&&n.push(...e.docIds);if(!Rs(s,t)||!Rs(s,n))return!1;const r=this.buildChildEffectiveTupleSet();return i?void 0!==r.allowed&&r.allowed.every(e=>t.some(t=>As(e,t))):void 0!==r.allowed?r.allowed.every(e=>!t.some(t=>As(e,t))):t.every(e=>r.excluded.some(t=>As(e,t)))}buildChildEffectiveTupleSet(){let e;const t=[];for(const i of this.query.conditions)if(os(i))if("=="===i.operator||"in"===i.operator)e=void 0===e?[...i.docIds]:e.filter(e=>i.docIds.some(t=>As(e,t)));else for(const e of i.docIds)t.some(t=>As(t,e))||t.push(e);return void 0!==e&&t.length>0&&(e=e.filter(e=>!t.some(t=>As(e,t)))),{allowed:e,excluded:t}}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.subqueryConditions.filter(t=>e.includes(t.fieldName))}getConditionsForField(e){return this.subqueryConditions.filter(t=>t.fieldName===e)}documentMatchesQuery(e){for(const t of this.exactSimpleConditions){const i=t.fieldName,s=t.operator;if(i===ri){const i=t.value;if("in"===s||"not in"===s){const t=(Array.isArray(i)?i:[i]).some(t=>cs(t,e,"==",ki));if(!("in"===s?t:!t))return!1;continue}if(!cs(i,e,s,ki))return!1;continue}const n=ki(e,i);if("in"===s){if(t.value.includes(n))continue;return!1}if("not in"!==s){if(!is(t.value,n,s))return!1}else if(t.value.includes(n))return!1}for(const t of this.exactDocIdConditions)if(!as(t,e,ki))return!1;return!0}evaluateSubset(e,t){const{operator:i,value:s}=e,{operator:n,value:r}=this.parseConditions([t])[0],o=_s[`${i}:${n}`];return!!o&&o(s,r)}parseConditions(e){const t=[],i=new Map,s=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":s.set(e.fieldName,(s.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),i.forEach((e,i)=>{t.push({fieldName:i,operator:"in",value:e})}),s.forEach((e,i)=>{t.push({fieldName:i,operator:"not in",value:e})}),t}}function Ns(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?Ai(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function Fs(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function xs(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=Ai(e);t=Ai(t);for(const[e]of Fs(i)){const s=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&s>t.split(".").length)&&delete i.properties[e]}for(const[e,s]of Fs(t))i.properties[e]=Bs([...i.properties[e]||[],...s]);return i}(e,t);const i=Ai(e);for(const[e,s]of Fs(t)){const t=s;for(const s of t){const t=Ns(ki(i.properties,e),s);void 0===t?Ei(i.properties,e):Ti(i.properties,e,t)}}return i}function Bs(e){let t=0;for(;t+1<e.length;){const i=Ps(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function Ps(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 Us(e,t){if(!e)return;const i={...e},s=Fs(t);for(const[e,t]of s){const s=t;for(const t of s){const s=Ns(ki(i,e),t);void 0===s?Ei(i,e):Ti(i,e,s)}}return i}function Qs(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 s=t[e].reduce((e,t)=>we(xs(e,t),"Merge result cannot be null"));i.push(s)}return i}const Ls="dataManager_runInTransaction";var $s;!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}($s||($s={}));class Gs{constructor(e,i,s,n,o,a,c,u,l){this.documentStore=e,this.mutationSender=i,this.socketManager=s,this.querySubscriptionManager=n,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,s=this.docIdToLocalTimestamp.get(e);return!((!s||i)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&s===i)}async executeDetachedQuery(e){const t=this.currentTransactionId,i={query:e,clientRequestId:Me(),subscribe:!1},s=await this.querySender.sendQueryDirect(i);return this.currentTransactionId!==t?this.reRunQueryThroughNormalPipeline(e):this.applyPendingMutationsToQueryResult(s.docs,e)}async reRunQueryThroughNormalPipeline(e){await m(this.outgoingMutationsEmpty.pipe(g(Boolean),O(1)));const t={query:e,clientRequestId:Me(),subscribe:!1};return(await this.querySender.sendQueryDirect(t)).docs}applyPendingMutationsToQueryResult(e,t){const i=new js(t),s=new Map;for(const i of e){const e=ts(i.__docId__,t.collectionName,t.integrationId);s.set(e,i)}for(const[e,n]of this.pendingOutgoingMutations){const r=es(e);if(r.collectionName===t.collectionName&&r.integrationId===t.integrationId)for(const{mutation:t}of n){const n=s.get(e);if("delete"===t.type)s.delete(e);else if("update"===t.type){if(n){const r=Us(n,t);r&&i.documentMatchesQuery(r)?s.set(e,r):s.delete(e)}}else if("insert"===t.type){const n={...t.properties,__docId__:r.docId};i.documentMatchesQuery(n)&&s.set(e,n)}}}const n=Array.from(s.values()),{sortOrder:r}=t;n.sort((e,t)=>{for(const{fieldName:i,asc:s}of r){const n=ji(ki(e,i),ki(t,i));if(0!==n)return s?n:-n}return 0});const o=t.limit<0?2e3:t.limit;return n.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(Ls)?this.lockManager.lockSync(Ls):await this.lockManager.lock(Ls);let i=Hs;const s=()=>i!==Hs;return new Promise(async(t,n)=>{try{let r;this.currentTransactionId=Me();try{r=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(s()?void 0:{resolve:()=>t(r),reject:n})}}catch(e){i=s()?i:e}finally{try{this.lockManager.release(Ls)}catch(e){i=s()?i:e}}s()&&n(i)})}async applyOutgoingMutation(e,t){const i=ts(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(Ls)||(await this.lockManager.lock(Ls),this.lockManager.release(Ls)),this.knownDirtyDocs.delete(i);const s=this.pendingOutgoingMutations.get(i)?.slice(-1)[0];if(s&&!s.sentToServer)s.mutation=we(Qs([s.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},s=this.pendingOutgoingMutations.get(i)||[];s.push(t),this.pendingOutgoingMutations.set(i,s),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(i),s="delete"===e.type?void 0:"update"===e.type?Us(t,e):{...e.properties};this.updateDocumentFromSnapshot(i,s)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(i,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(i,s).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(Ls);try{this.currentTransactionId=Me();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(Ls)}}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),ye(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 s of e){if(!this.querySubscriptionManager.hasOngoingQuery(s.clientRequestId))continue;const e=this.querySubscriptionManager.getQuery(s.clientRequestId),n=null!==e.projectFields&&void 0!==e.projectFields,r=this.querySubscriptionManager.hasSubscription(s.clientRequestId);n&&r?i.push({squidDocId:s.squidDocId,item:{properties:s.doc,timestamp:s.mutationTimestamp,clientRequestId:s.clientRequestId,projectFields:e.projectFields}}):t[s.squidDocId]={properties:s.doc,timestamp:s.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 s of e.docs){const n=ts(s.__docId__,t.collectionName,t.integrationId);i.push({squidDocId:n,item:{properties:s,timestamp:s.__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 s of e.docs){const e=ts(s.__docId__,t.collectionName,t.integrationId);i[e]={properties:s,timestamp:s.__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 s=new Set,n=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?(r.properties&&this.documentStore.adoptMissingFields(t,r.properties),n.add(t)):(this.pendingIncomingUpdates.set(t,r),s.add(t))}return this.runInTransactionSync(()=>{for(const e of s)this.maybeApplyIncomingUpdate(e);for(const e of n)this.refreshQueryMapping(e)},t),i}applyProjectedUpdates(e){for(const{squidDocId:t,item:i}of e){const e=we(i.clientRequestId,"clientRequestId required for projected updates"),s=this.pendingOutgoingMutations.get(t);if(s&&s.length)continue;const n=this.docIdToServerTimestamp.get(t);n&&n.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||xi({...t,__ts__:void 0})!==xi(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 ks.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:s={},refreshList:n=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(s),n.forEach(e=>{this.refreshDocIdToTimestamp.set(s[e]||e,i)});for(const t of e){let e=this.removeOutgoingMutation(t);s[e]&&(e=s[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=ts(e.mutation.squidDocIdObj),i=we(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}=es(t);this.setExpiration(t,!0);try{const i=e.includes(Zi)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(we(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 s=this.docIdToServerTimestamp.get(t)?.timestamp;s&&s>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=ts(t.mutation.squidDocIdObj),s=e[i];s&&(t.mutation.squidDocIdObj=es(s))})}),Object.entries(e).forEach(([e,t])=>{Di(this.pendingOutgoingMutations,e,t),Di(this.docIdToLocalTimestamp,e,t),Di(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 Hs=Symbol("undefined");class Ks{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new t(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe(g(Boolean),ye(()=>{}))}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 Ws{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)`),Ji.debug(`DistributedLockManager: released 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,s=t?.maxHoldTimeMillis;this.socketManager.notifyWebSocketIsNeeded(),be(await m(k(j(this.lockWaitForConnectionThreshold).pipe(ye(()=>!1)),this.socketManager.observeConnectionReady().pipe(g(Boolean)),this.destructManager.observeIsDestructing())),"CLIENT_NOT_CONNECTED");const n=Me(),r={type:"acquireLock",payload:{mutex:e,acquisitionTimeoutMillis:i,maxHoldTimeMillis:s,clientRequestId:n}};this.socketManager.postMessage(r);const o=await m(k(j(i+4e3).pipe(O(1),ye(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0,clientRequestId:n}}))),this.acquireLockMessagesFromServer.pipe(g(e=>e.payload.clientRequestId===n)))),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 Vs(a,e,n,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 Vs{constructor(e,t,i,s,r){this.lockId=e,this.resourceId=t,this.clientRequestId=i,this.ongoingLocks=s,this.socketManager=r,this.released=!1,this.onReleaseSubject=new n(1)}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}},t=this.socketManager.sendMessage(e),i=await m(k(I(t.then(Js,Js)),this.socketManager.observeConnectionReady().pipe(g(e=>!e),ye(()=>!1))));if(this.onReleaseSubject.next(),!i)return t.catch(()=>{}),void this.onReleaseSubject.complete();try{await t}finally{this.onReleaseSubject.complete()}}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}function Js(){return!0}class zs{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 Ys{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 us(e,we(this.dataManager,"dataManager not found"),t,i);let s=this.documents.get(e);if(s)return s;s=new us(e,we(this.dataManager,"dataManager not found"),t);const{integrationId:n,collectionName:r}=es(e);this.documents.set(e,s);const o=this.getCollectionKey(n,r),a=this.documentsForCollection.get(o)||[];return this.documentsForCollection.set(o,a.concat(s)),s}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=es(e),s=es(t);Di(this.documents,i.docId,s.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class Xs{constructor(){this.squidDocIdToDoc=new Map,this.squidDocIdToProjectedFields=new Map}saveProjectedDocument(e,t,i){const s=this.squidDocIdToDoc.get(e);if(s){const i=this.mergeDocuments(s,t),n=this.removeInternalProperties(i);this.squidDocIdToDoc.set(e,n)}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 s||this.squidDocIdToProjectedFields.set(e,new Set(i))}return this.squidDocIdToDoc.get(e)}mergeDocuments(e,t){const i=Ai(e);for(const e of Object.keys(t)){const s=t[e],n=i[e];null===s||"object"!=typeof s||Array.isArray(s)||null===n||"object"!=typeof n||Array.isArray(n)?i[e]=s:i[e]=this.mergeDocuments(n,s)}return i}adoptMissingFields(e,t){const i=this.squidDocIdToDoc.get(e);if(!i)return;const s=Object.keys(t).filter(e=>"__ts__"!==e&&!(e in i));if(!s.length)return;const n=Ai(i);for(const e of s)n[e]=t[e];this.squidDocIdToDoc.set(e,n);const r=this.squidDocIdToProjectedFields.get(e);if(r)for(const e of s)r.add(e)}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=Ai(t),s=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,s),this.squidDocIdToProjectedFields.delete(e),s}return this.squidDocIdToDoc.delete(e),void this.squidDocIdToProjectedFields.delete(e)}const s=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,s),this.squidDocIdToProjectedFields.delete(e),s}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(Ni(e,e=>xi(t.map(t=>ki(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=Array.from(e).map(e=>this.squidDocIdToDoc.get(e)).filter(me),{sortOrder:s,limitBy:n}=t,r=i.sort((e,t)=>this.compareSquidDocs(e,t,s)),o=t.limit<0?2e3:t.limit;let a;if(n){const{limit:e,fields:t,reverseSort:i}=n,s=this.group(r,t);let c;c=i?s.map(t=>t.slice(-e)):s.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 s of t)if(s.includes(".")){const t=ki(e,s);void 0!==t&&Ti(i,s,t)}else s in e&&(i[s]=e[s]);return i}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;Di(this.squidDocIdToDoc,e,t),Di(this.squidDocIdToProjectedFields,e,t);const s=es(t),n=Pi(s.docId);this.saveDocument(t,{...i,...n,__docId__:s.docId})}compareSquidDocs(e,t,i){for(const{fieldName:s,asc:n}of i){const i=ji(ki(e,s),ki(t,s));if(0!==i)return n?i:-i}return 0}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}}class Zs{constructor(e){this.rpcManager=e}async emit(e){const t={event:e};await this.rpcManager.post("events/emit",t)}}class en{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 tn{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 sn{constructor(e,t,i,s,n){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},this.ownedJobs=new Set,s.onDestruct(async()=>{this.stopKeepAlive();const e=[...this.ownedJobs];this.ownedJobs.clear(),await Promise.all(e.map(e=>this.resolveJob(e,"failed",void 0,"Client shut down").catch(()=>{})))}),n.isPassiveMode||this.clientIdService.observeClientId().pipe(p(),T(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Ji.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 startJob(e){await this.rpcManager.post("job/startJob",{jobId:e}),this.ownedJobs.add(e),this.ensureKeepAlive()}async completeJob(e,t){await this.resolveJob(e,"completed",t)}async failJob(e,t){await this.resolveJob(e,"failed",void 0,t)}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 n(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,s=this.listeners[i];s&&("completed"===t.status?s.next(t.result):"failed"===t.status?s.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",i),delete this.listeners[i])}))}async resolveJob(e,t,i,s){try{await this.rpcManager.post("job/resolveJob",{jobId:e,status:t,result:i,error:s})}finally{this.ownedJobs.delete(e),this.ownedJobs.size||this.stopKeepAlive()}}ensureKeepAlive(){void 0===this.keepAliveHandle&&(this.keepAliveHandle=setInterval(()=>{if(!this.ownedJobs.size)return void this.stopKeepAlive();const e={jobIds:[...this.ownedJobs]};this.rpcManager.post("job/keepAlive",e).catch(e=>Ji.debug("Job keep-alive failed:",e))},15e3))}stopKeepAlive(){void 0!==this.keepAliveHandle&&(clearInterval(this.keepAliveHandle),this.keepAliveHandle=void 0)}}class nn{constructor(e,t,i){this.graphId=e,this.rpcManager=t,this.jobClient=i}async invoke(e={}){const t=Me();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,jobId:t}),await this.jobClient.awaitJob(t)}async invokeAsync(e={}){const t=Me();return await this.rpcManager.post("langgraph/invoke",{graphId:this.graphId,threadId:e.threadId,input:e.input,jobId:t}),t}async resume(e,t){const i=Me();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,jobId:i}),await this.jobClient.awaitJob(i)}async resumeAsync(e,t){const i=Me();return await this.rpcManager.post("langgraph/resume",{graphId:this.graphId,threadId:e,resumePayload:t,jobId:i}),i}async getState(e){return this.rpcManager.post("langgraph/getState",{graphId:this.graphId,threadId:e})}async deleteThread(e){await this.rpcManager.post("langgraph/deleteThread",{graphId:this.graphId,threadId:e})}}class rn{constructor(e,t){this.rpcManager=e,this.jobClient=t}graph(e){return new nn(e,this.rpcManager,this.jobClient)}}const on="squid_mgmt_",an="x-squid-traceid",cn="x-squid-client-version";function un(e="n_"){return`${e}${Ee(10).toLowerCase()}`}const ln=e=>e();class dn extends Error{constructor(e,t,i,s,n){super(e),this.statusCode=t,this.url=i,this.headers=s,this.body=n}}const hn="1.0.489";async function pn(e){return In({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage,abortSignal:e.abortSignal})}async function gn(e){return In({...e,method:"GET",files:[],filesFieldName:""})}async function fn(e){return In({...e,method:"PUT"})}async function yn(e){return In({...e,method:"PATCH"})}async function mn(e){return In({...e,method:"DELETE",files:[],filesFieldName:""})}async function In(e){const t=await async function({headers:e,files:t,filesFieldName:i,message:s,url:n,extractErrorMessage:r,method:o,abortSignal:a}){const c=new Headers(e);c.append(an,un("c_")),c.append(cn,hn);const u={method:o,headers:c,body:void 0,signal:a};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const s of t)e.append(i||"files",s,s.name);e.append("body",Bi(s)),u.body=e}else void 0!==s&&(c.append("Content-Type","application/json"),u.body=Bi(s));else"DELETE"===o&&void 0!==s&&(c.append("Content-Type","application/json"),u.body=Bi(s));try{const e=await fetch(n,u),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),s=bn(i);if(!r)throw new dn(i,e.status,n,t,s);let o;try{o="string"==typeof s?s:s?.message||i}catch{}throw o||(o=e.statusText),new dn(o,e.status,n,t,s)}const i=await e.text();return Ji.debug(`received response from url ${n}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Ji.debug(`Unable to perform fetch request to url: ${n}`,e),e}}(e);return t.body=bn(t.body),t}function bn(e){if(e){try{return Pi(e)}catch{}return e}}class wn{constructor(e){be(e.apiKey.startsWith(on),`Invalid management API key format. Key must start with '${on}'`),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 s=P(this.consoleRegion,"console",`openapi/iac/management/${t}`),n={Authorization:`ManagementKey ${this.apiKey}`};return"POST"===e?(await pn({url:s,headers:n,message:i,files:[],filesFieldName:"",extractErrorMessage:!0})).body:"PATCH"===e?(await yn({url:s,headers:n,message:i,extractErrorMessage:!0})).body:(await mn({url:s,headers:n,message:i,extractErrorMessage:!0})).body}}class vn{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=Qs(e),s=i.map(e=>`sendMutation_${ts(e.squidDocIdObj)}`);await this.lockManager.lock(...s),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:i,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Ji.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...s)}}async deleteQuery(e){const t=`deleteQuery_${e.integrationId}_${e.collectionName}`;await this.lockManager.lock(t),await this.querySender.waitForAllQueriesToFinish();try{const t={query:e};return await this.rpcManager.post("mutation/deleteQuery",t)}catch(t){throw Ji.debug("Error while deleting query results",{error:t,query:JSON.stringify(e,null,2)}),t}finally{this.lockManager.release(t)}}}class Sn{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class Mn{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 kn={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class _n{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!Tn.test(e)||e.length>=En);be(0===i.length,()=>`Tag name is not allowed: ${i.join(",")}`),this.isReporting=!0;const s={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},n=this.rpcManager.post("/observability/metrics",{metrics:[s]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==n),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(n)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...kn,...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:s}=e,n=void 0===e.fillValue?null:e.fillValue,r=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:s}){if("align-by-start-time"===s)return e;const n=t-e;let r=t-Math.floor(n/i)*i;return r>e&&(r-=i),r}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:s}){if("align-by-end-time"===s)return t-i;const n=t-e;let r=e+Math.floor(n/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 s=e.groupByTags[t],n=a[s]?.[0]||"";i.push(n)}t.push({tagValues:i,points:[]})}else"return-result-group-with-default-values"===s&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[i,s]of Object.entries(a)){const n=e.groupByTags.indexOf(i);if(!(n<0))for(let e=0;e<t.length;e++){const i=t[e],r=new Set(s);for(let e=0;e<t.length;e++){const s=t[e];i.tagValues.every((e,t)=>t===n||e===s.tagValues[t])&&r.delete(s.tagValues[n])}if(0!==r.size)for(const e of r){const s={tagValues:[...i.tagValues],points:[]};s.tagValues[n]=e,t.push(s)}}}for(const s of t){if(0!==s.points.length){const e=s.points[0][0],t=s.points[s.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:n,u=Array.isArray(e.fn)?e.fn.map(c):[n];for(let e=r;e<=o;e+=i){const i=s.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])}s.points=t}}(t,i.resultGroups),i}}const Tn=/^[a-zA-Z0-9_-]+$/,En=1e3;async function Dn(e,t,i=500){const s=Date.now(),n=e.paginate({pageSize:i,subscribe:!1});let r=0,o=await n.waitForData();for(;;){for(const e of o.data)r++,await t(e.data);if(!o.hasNext)break;o=await n.next()}return{count:r,time:Date.now()-s}}async function Cn(e,t=500){const i=[],s=e.paginate({pageSize:t,subscribe:!1});let n=await s.waitForData();for(;;){for(const e of n.data){const t=es(e.squidDocId),s=Pi(t.docId),n=t.integrationId===Jt?s.__id:s;i.push(n)}if(!n.hasNext)break;n=await s.next()}return i}function On(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:s}=t,{collectionName:n,integrationId:r}=i;let o=e.collection(n,r).query();return o=qn(o,i),s?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:s,joinConditions:n,dereference:r,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=qn(u,i.query),Object.entries(s).map(([t,i])=>{const{collectionName:s,integrationId:r}=i,{left:o,right:a,leftAlias:c}=n[t];let l=e.collection(s,r).query();l=qn(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:s,integrationId:n}=An(i[0]),r=i.map(t=>On(e,t));return e.collection(s,n).or(...r)}(e,t)}}function qn(e,t){const{conditions:i,limit:s,sortOrder:n}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");if("docIds"in t)throw new Error("DocId conditions are not supported in query serialization.");const{fieldName:i,operator:s,value:n}=t;e.where(i,s,n)}e.limit(s);for(const{fieldName:t,asc:i}of n)e.sortBy(t,i);return e}function An(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 An(e.queries[0])}}class Rn{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,s=new js(e),n=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>s.documentMatchesQuery(e.data)),r={};return n.forEach(e=>{r[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(r)),e).map(e=>r[ts(e.__docId__,i,t)])}}function jn(e,t){return W(function(i,s){var n=0;i.subscribe(ge(s,function(i){return e.call(t,i,n++)&&s.next(i)}))})}class Nn{constructor(e,i,s){this.rpcManager=e,this.destructManager=i,this.webSocketConnectionReady$=s,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.gateForCurrentBatch().subscribe(()=>{this.processQueryBatch()})},0),i)}gateForCurrentBatch(){return this.pendingQueryRequests.some(({queryRequest:e})=>e.subscribe)&&this.webSocketConnectionReady$?o([this.safeToSendQueriesToServer,this.webSocketConnectionReady$]).pipe(jn(([e,t])=>e&&t),O(1),ye(()=>!0)):this.safeToSendQueriesToServer.pipe(jn(Boolean),O(1))}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(jn(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:s}of e){const e=t.clientRequestId,n=i.errors[e],r=i.results[e];n?s.error(n):s.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 Fn={d:(e,t)=>{for(var i in t)Fn.o(t,i)&&!Fn.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function xn(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 Bn(e,t){switch(t.type){case"set":return function(e,t,i){if(void 0===i)return Pn(e,t);if(0===t.length)return xn("object"==typeof i&&null!==i&&!Array.isArray(i),()=>`Root state must be a record. Trying to set '${i}', type: ${typeof i}`),i;function s(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let n=e;for(let e=0;e<t.length-1&&void 0!==n;e++){const i=t[e];xn(!Array.isArray(n)||s(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),n=n[i],xn(void 0===n||"object"==typeof n&&null!==n,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===n?"<null>":typeof n}'`)}const r=t[t.length-1];return xn(!Array.isArray(n)||s(r),()=>`Invalid array index Path: '${t}`),(null==n?void 0:n[r])===i?e:Un(e,t,i)}(e,t.path,t.value);case"delete":return Pn(e,t.path);case"batch":return t.actions.reduce((e,t)=>Bn(e,t),e)}}function Pn(e,t){xn(0!==t.length,"Can't delete an empty path");let i=e;for(let s=0;s<t.length-1;s++){const n=t[s];if(i=i[n],void 0===i)return e;xn("object"==typeof i&&null!==i,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,s+1)}', type: ${null===i?"<null>":typeof i}`)}const s=t[t.length-1];return void 0===i[s]?e:Un(e,t,void 0)}function Un(e,t,i){function s(e,i){xn(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const n=Object.assign({},e);let r=n;for(let e=0;e<t.length-1;e++){const n=t[e],o=r[n];xn(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 s(r,n),r;r[n]=a,r=a}const o=t[t.length-1];return void 0===i?s(r,o):r[o]=i,n}function Qn(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(...Qn(t,"as-is"));return"unique-and-sorted"===t?Gn(i):i}function Ln(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 $n(e){const t=[...e];return t.sort((e,t)=>{for(let i=0;i<e.length;i++){if(i===t.length)return 1;const s=e[i].localeCompare(t[i]);if(0!==s)return s}return e.length-t.length}),t}function Gn(e){const t=$n(e),i=t;for(let e=0;e<t.length-1;e++){const s=t[e];for(let n=e+1;n<t.length;n++){const r=t[n];s.length===r.length&&Ln(s,r)&&(i[n]=void 0,e++)}}return i.filter(e=>void 0!==e)}const Hn=(Kn={Observable:()=>s,Subject:()=>r},Wn={},Fn.d(Wn,Kn),Wn);var Kn,Wn;const Vn=(Jn={filter:()=>jn,map:()=>ye},zn={},Fn.d(zn,Jn),zn);var Jn,zn;class Yn{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 s=t(e);return this._setNodeValue(i,s,void 0===s),s}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 s=this.root,n=t(s.value,i);if(n!==Yn.StopFillToken){this._setNodeValue(s,n,!1);for(let r=0;r<e.length;r++){const o=e[r];i.push(o);let a=s.children.get(o);if(n=t(null==a?void 0:a.value,i),n===Yn.StopFillToken)break;a||(a={children:new Map,parent:s,childrenWithValue:0},s.children.set(o,a)),this._setNodeValue(a,n,!1),s=a}this._runGc(s)}}visitDfs(e,t,i=[]){const s=this.getNode(i);void 0!==s&&this._visitDfs(e,s,t,[...i])}_visitDfs(e,t,i,s){if("pre-order"===e&&!1===i(t.value,s))return!1;for(const[n,r]of t.children){if(s.push(n),!this._visitDfs(e,r,i,s))return!1;s.pop()}return"in-order"!==e||!1!==i(t.value,s)}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 s=e[i];let n=t.children.get(s);n||(n={children:new Map,parent:t,childrenWithValue:0},t.children.set(s,n)),t=n}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))}}Yn.StopFillToken=Symbol("Trie.StopFillToken");class Xn extends Hn.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class Zn{constructor(e){this.rootState=e,this.observersTrie=new Yn,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,Vn.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=Bn(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Qn(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),s=Gn([...t,...i]),n=new Yn;for(const e of s)n.fillPath(e,()=>!0);n.visitDfs("pre-order",(t,i)=>{const s=this.observersTrie.get(i);if(s){const t=this.get(i),n=s.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;s.next({action:e,value:t,oldValue:n})}})}_observeChanges(e,t=[],i){const s=0===t.length?void 0:new Yn;for(const e of t)null==s||s.set(e,!0);return new Hn.Observable(t=>{const n=this.observersTrie.getOrSet(e,()=>new Xn);n.isAllDetailsMode=n.isAllDetailsMode||"all-details"===i;const r={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(r);const o=n.pipe((0,Vn.filter)(({action:e})=>void 0===s||Qn(e,"as-is").some(e=>!s.get(e))),(0,Vn.map)(({action:t,value:i,oldValue:s})=>{let r=this.stubForUnusedPaths;if(n.isAllDetailsMode){const i=Qn(t,"as-is");r=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=$n(e),i=t;for(let e=0;e<i.length-1;e++){const s=t[e];for(let n=e+1;n<t.length;n++)Ln(t[n],s)&&(i[n]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>Ln(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:s,paths:r}})).subscribe(t);return()=>{o.unsubscribe(),n.observed||this.observersTrie.delete(e)}})}_get(e,t){let i=e;for(let e=0;e<t.length&&void 0!==i;e++){const s=t[e];i=null==i?void 0:i[s]}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 er(e,t,i=(e,t)=>e>t?1:e<t?-1:0,s=0,n=e.length-1){if(n<s)return-1;const r=Math.trunc((s+n)/2);return 0===i(t,e[r])?r:i(t,e[r])>0?er(e,t,i,r+1,n):er(e,t,i,s,r-1)}function tr(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==er(e,t,i))return;let s;for(s=e.length-1;s>=0&&i(e[s],t)>0;s--)e[s+1]=e[s];e[s+1]=t}function ir(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const s=er(e,t,i);s>-1&&e.splice(s,1)}class sr{setDetachedQueryExecutor(e){this.detachedQueryExecutor=e}constructor(e,t,i,s,n,o,a,c){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=s,this.documentIdentityService=n,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 rr,this.queryResultsSubject=new r,this.detachedRecords=new Set,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientTooOld().subscribe(()=>{this.invalidateOngoingQueryRegistrations()}),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 we(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:s}=es(t),n=this.queryMappingManager.getMapping(i,s);return n?function(e,t){const i=[...e.unconditional||[]],s=new Map;for(const[i,n]of Object.entries(e.conditional||{})){const e=Pi(i);let r;if(rs(e))if(e.fieldName===ri)r=cs(e.value,t,e.operator,ki);else{const i=ki(t,e.fieldName)??null;r=is(e.value,i,e.operator)}else r=os(e)?as(e,t,ki):nr(e,t);if(r)for(const e of n)s.set(e,(s.get(e)||0)+1)}for(const[t,n]of s.entries())n>=e.queriesMetadata[t].condCount&&i.push(t);return i}(n,e):[]}setClientRequestIdsForLocalDoc(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set,s=new Set(t?this.findQueriesForDocument(t,e).map(e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId):[]),n=new Set([...i,...s]);for(const t of[...i]){if(s.has(t))continue;i.delete(t);const n=this.clientRequestIdToLocalDocuments.get(t);n&&(n.delete(e),n.size||this.clientRequestIdToLocalDocuments.delete(t)),i.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of s){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let s=this.clientRequestIdToLocalDocuments.get(t);s||(s=new Set,this.clientRequestIdToLocalDocuments.set(t,s)),s.add(e)}return[...n]}addDocToQuery(e,t){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let s=this.clientRequestIdToLocalDocuments.get(t);s||(s=new Set,this.clientRequestIdToLocalDocuments.set(t,s)),s.add(e)}removeDocFromQuery(e,t){const i=this.localDocumentToClientRequestIds.get(e);let s=!i;i&&(i.delete(t),i.size||(this.localDocumentToClientRequestIds.delete(e),s=!0));const n=this.clientRequestIdToLocalDocuments.get(t);n&&(n.delete(e),n.size||this.clientRequestIdToLocalDocuments.delete(t)),s&&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 s=this.clientRequestIdToLocalDocuments.get(i)||new Set,n=this.documentStore.sortAndLimitDocs(s,e.query),r=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(n,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=we(o?.supportingOngoingQuery);if(r&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case $s.UNKNOWN:e.limitUnderflowState=s.size===e.query.limit+100?$s.ENABLED:$s.DISABLED;break;case $s.DISABLED:break;case $s.ENABLED:if(s.size<e.query.limit+20){e.limitUnderflowState=$s.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(n)}for(const e of t){const t=this.collectAllObservables(e);we(e.allObservables).next(t)}}findValidParentOfQuery(e){const t=new js(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,s,r,a,c){r&&this.socketManager.notifyWebSocketIsNeeded();const u=Object.keys(i).length>0;return r||u||!this.detachedQueryExecutor||this.lockManager.canGetLock(Ls)?d(()=>{const u=this.createOngoingQueryGraph(e,t,i,s,r,!0,{},c);a&&(u.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(u),u.allObservables=new n(1);const l=u.allObservables.pipe(C(e=>o(e).pipe(ye(e=>this.joinResults(e,s,u)))),jn(()=>this.allOngoingQueriesGotInitialResult(u)),E(void 0),M(),jn(([e,t])=>!Oi(e,t)),ye(([,e])=>e),r?R():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(_()):I(this.detachedQueryExecutor(e)).pipe(ye(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 js(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 s of t){const t=we(this.localDocumentToClientRequestIds.get(s));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(s),i.push(s))}i.length&&this.onOrphanDocuments.next(i)}registerQueryFinalizer(e){const t=e.clientRequestId,i=ns(this.clientIdService.getClientId(),t);e.dataSubject.pipe(f(async()=>{if(e.unsubscribeBlockerCount.value>0&&await m(k(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(jn(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)}),jn(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,i,s,n,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?$s.UNKNOWN:$s.DISABLED};this.registerQueryFinalizer(d),this.ongoingQueries.set(u,d),a[i]=d;for(const[e,t]of Object.entries(n)){const o=t.leftAlias;if(o!==i&&e!==i)continue;const c=o===i?e:o;if(o===i){const e=this.createOngoingQueryGraph(s[c],c,s,n,r,!1,a);e.joinCondition=t,l.push(e)}else d.supportingOngoingQuery=this.createOngoingQueryGraph(s[c],c,s,n,r,!1,a)}return d}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(jn(Boolean),ye(e=>({docs:e,alias:i}))));for(const i of e.supportedQueries)this.collectAllObservables(i,t);return t}joinResults(e,t,i){const s=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let n=s[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),n=this.join(n,i,s[i],t[i]))}return n}join(e,t,i,s){if(!e.length)return e;const n=Object.keys(e[0]);if(!s||!n.includes(s.leftAlias))throw new Error("No join condition found for alias "+t);const r=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[s.right]);r.has(t)||r.set(t,[]),we(r.get(t)).push(e)}),e.flatMap(e=>{const i=r.get(this.transformKey(e[s.leftAlias]?.[s.left]))||[];return i.length?i.map(i=>({...e,[t]:i})):s.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],i=[e];for(;i.length;){const e=we(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,i){const s=we(i.joinCondition),n=i.query;if(i.activated){if(!i.canExpandForJoin)return!1;const r=we(i.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===i.alias),o=new Set(e.map(e=>e[s.left]??null));for(const e of r)e.query.conditions.filter(rs).filter(e=>e.fieldName===s.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const a=Ai(n);a.conditions=a.conditions.filter(e=>!rs(e)||e.fieldName!==s.right),[...o].forEach(e=>{a.conditions.push({fieldName:s.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),we(i.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(i.activated=!0,n.conditions.filter(rs).filter(e=>e.fieldName===s.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(i),i.canExpandForJoin=!1,!0;const t=e.map(e=>e[s.left]??null).map(e=>({fieldName:s.right,operator:"==",value:e}));return t.length?(n.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=we(t.shift());t.push(...e.supportedQueries||[]),await m(e.unsubscribeBlockerCount.pipe(jn(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,s=e.clientRequestId,n=ns(this.clientIdService.getClientId(),s);this.queryMappingManager.addQuery(i,n),this.ongoingQueries.set(s,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},s=new js(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await m(t.queryRegistered.pipe(jn(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 n=k(e.queryRegistered.pipe(jn(Boolean),h(2e3),O(1)),this.destructManager.observeIsDestructing().pipe(O(1)));t.dataSubject.pipe(A(()=>!e.done),q(n),jn(Boolean),R(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),ye(e=>e.filter(e=>s.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc(ts(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,s={query:{...e.query,limit:i},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(s).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()):(Ji.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0})}invalidateOngoingQueryRegistrations(){for(const e of this.ongoingQueries.values())e.queryRegistered.next(!1)}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=>{Di(this.localDocumentToClientRequestIds,t,e[t])})}}function nr(e,t){for(const i of e.fields){const e=ki(t,i.fieldName)??null;if(is(i.value,e,i.operator))return!0;if(is(i.value,e,"!="))return!1}return!1}class rr{constructor(){this.stateService=new Zn({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const s=new Set;for(const n of e.conditions){if(rs(n)&&["=="].includes(n.operator)){const e=Ui(n.fieldName);s.has(e)||(i++,s.add(e))}else i++;const r=this.getConditionStatePath(e,n),o=[...this.stateService.get(r)||[]];tr(o,t),this.stateService.set(r,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],s=[...this.stateService.get(i)||[]];tr(s,t),this.stateService.set(i,s)}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 s=this.getConditionStatePath(t,i),n=[...this.stateService.get(s)||[]];ir(n,e),n.length?this.stateService.set(s,n):this.stateService.delete(s)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],s=[...this.stateService.get(i)||[]];ir(s,e),this.stateService.set(i,s)}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,xi(i))];var i}}class or{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 w(o(t).pipe(g(e=>!e.includes(!0)),O(1))),await this.lock(...e)}release(...e){for(const t of e){const e=we(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 ar{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 s=i.get(t);return s||(s=new ur(e,t,this.rpcManager,this.socketManager),i.set(t,s)),s}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const cr="subscriptionMutex";class ur{constructor(e,t,i,s){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=s,this.messagesSubject=new r,this.subscriberCount=0,this.lockManager=new or}async produce(e){await this.lockManager.lock(cr);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(cr)}}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(cr);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(cr)}}async performUnsubscribe(){await this.lockManager.lock(cr);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(cr)}}}class lr{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 dr{constructor(e,i,s,n,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(n))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe(e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")}),s.onDestruct(async()=>{await this.awaitAllSettled()});const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new lr(60*a,5),ai:new lr(20*a,5),secret:new lr(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 s=`Bearer ${t}`;return i&&(s+=`; IntegrationId ${i}`),{Authorization:s}}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=[],s="files",n={},r){return(await this.rawPost(e,t,i,s,!0,n,r)).body}async rawPost(e,t,i=[],s="files",n=!0,r={},o){return this.runRawRequest(e,r,async r=>{Ji.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const a=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await pn({url:a,headers:r,message:t,files:i,filesFieldName:s,extractErrorMessage:n,abortSignal:o})})}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){return this.runRawRequest(e,{},async s=>{let n=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))}),n+=`?${e.toString()}`}return Ji.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await gn({url:n,headers:s,extractErrorMessage:i})})}async put(e,t,i=[],s="files"){return(await this.rawPut(e,t,i,s)).body}async rawPut(e,t,i=[],s="files",n=!0){return this.runRawRequest(e,{},async r=>{Ji.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const o=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await fn({url:o,headers:r,message:t,files:i,filesFieldName:s,extractErrorMessage:n})})}async patch(e,t,i=[],s="files"){return(await this.rawPatch(e,t,i,s)).body}async rawPatch(e,t,i=[],s="files",n=!0){return this.runRawRequest(e,{},async r=>{Ji.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const o=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await yn({url:o,headers:r,message:t,files:i,filesFieldName:s,extractErrorMessage:n})})}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){return this.runRawRequest(e,{},async s=>{Ji.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const n=e.startsWith("http://")||e.startsWith("https://")?e:P(this.region,this.appId,e);return await mn({url:n,headers:s,message:t,extractErrorMessage:i})})}async runRawRequest(e,t,i){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const s=await this.getAuthHeaders(),n={...this.staticHeaders,...s,...t};return await i(n)}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?we(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?we(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):we(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}function hr(e){be(!e.isPassiveMode,"This operation is not available in passive mode. Use active mode for real-time features.")}class pr{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 gr(){}const fr="undefined"!=typeof process&&process.versions?.node?x(220):Vi().WebSocket;class yr{constructor(e,i,s,n=ln,o,a,c){this.clientIdService=e,this.region=i,this.appId=s,this.messageNotificationWrapper=n,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(T(1),g(e=>!e),C(()=>k(j(this.clientTooOldThreshold),this.connectionReady.pipe(g(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Ji.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Ji.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?Ji.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Ji.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Ji.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Ji.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(){hr(this.runtimeOptions),await m(this.observeConnectionReady().pipe(g(Boolean)))}notifyWebSocketIsNeeded(){hr(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&&(Ji.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}async sendMessageImpl(e){this.notifyWebSocketIsNeeded();try{await m(k(this.connectionReady.pipe(g(Boolean)),j(12e4).pipe(R(()=>{throw new Error("WebSocket connection not ready within 2 minutes")}))).pipe(q(this.destructSubject)))}catch(e){if(this.destructManager.isDestructing)return;throw e}const t=await this.authManager.getToken();if(this.connectionReady.value)try{be(this.socket,"Socket is undefined in sendMessageAsync");const i=Bi({message:e,authToken:t});Ji.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(Bi({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();Ji.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,s=0,n=1;const r={connected:!1,closeCalled:!1,open(){i=new(fr?.WebSocket??fr)(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.")}:gr,i.onopen=function(e){r.connected=!0,(t.onopen||gr)(e),s=0},i.onclose=function(e){if(r.connected=!1,4999!==e.code&&4001!==e.code)return Ji.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||gr)(e),void r.reconnect(e);(t.onclose||gr)(e)},i.onerror=function(e){r.connected=!1,e&&"ECONNREFUSED"===e.code?r.reconnect(e):r.closeCalled||(t.onerror||gr)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;n&&s++<i?n=setTimeout(function(){(t.onreconnect||gr)(e),Ji.debug("WebSocket trying to reconnect..."),r.open()},t.timeoutMillis||1e3):(t.onmaximum||gr)(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(n),n=void 0,i.close(e,t)}catch(e){}}};return r.open(),r}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Ji.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Ji.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Ji.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Ji.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Ji.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 Ji.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=Pi(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Ji.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(j(0)),this.connectionReady.next(!1),await m(j(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function mr(e){var t,i;i="Invalid application ID",be(function(e){return"string"==typeof e}(t=e),()=>Se(i,"Not a string",t));const s=e.split("-");be(s.length<4,`Invalid application ID: ${e}`);const[n,r,o]=s;return{appId:n,environmentId:r??"prod",squidDeveloperId:o}}function Ir(e,t){return`${mr(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function br(e,t,i){return`${Ir(e,t)}${i?`-${i}`:""}`}function wr(e){const t=mr(e);return Ir(t.appId,t.environmentId)}class vr{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,i){const s={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:i};await this.rpcManager.post("storage/uploadFile",s,[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 Sr{constructor(e,t,i,s,n){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=s,this.consoleRegion=n}get shortUrlHeaders(){return{"Content-Type":"application/json","x-app-api-key":this.apiKey}}async aiSearch(e,t,i){return await this.rpcManager.post("web/aiSearch",{query:e,allowedDomains:i},[],"files",{},t)}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={url:t.url,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shorten",i,"create short URL","json")}async createShortUrls(e){be(this.apiKey,"API key is required to create a short URL");const t=Array.isArray(e)?{urls:e}:e,i={urls:t.urls,appId:this.appId,secondsToLive:t.secondsToLive,fileExtension:t.fileExtension};return await this.postShortUrlApi("shortenMany",i,"create short URLs","json")}async deleteShortUrl(e){be(this.apiKey,"API key is required to delete a short URL");const t={id:e,appId:this.appId};await this.postShortUrlApi("delete",t,"delete short URL","ignore")}async deleteShortUrls(e){be(this.apiKey,"API key is required to delete a short URL");const t={ids:e,appId:this.appId};await this.postShortUrlApi("deleteMany",t,"delete short URLs","ignore")}async postShortUrlApi(e,t,i,s){const n=U(this.region,this.consoleRegion,`openapi/sqd/${e}`),r=await fetch(n,{method:"POST",headers:this.shortUrlHeaders,body:JSON.stringify(t)});if("ignore"===s)return void be(r.ok,`Failed to ${i} (${r.status}): ${r.statusText}`);const o=await r.text();return be(r.ok,`Failed to ${i} (${r.status}): ${o}`),JSON.parse(o)}}class Mr{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i}async executeWebhook(e,t={}){const{headers:i={},queryParams:s={},body:n,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(s&&Object.keys(s).length>0){const e=new URLSearchParams;Object.entries(s).forEach(([t,i])=>{e.append(t,String(i))}),c+=`?${e.toString()}`}const u=new Headers(a);let l;if(u.append(an,un("c_")),u.append(cn,hn),r&&r.length>0){const e=new FormData;for(const t of r)e.append("file",t,t.name);n&&"object"==typeof n&&Object.entries(n).forEach(([t,i])=>{e.append(t,String(i))}),l=e}else u.append("Content-Type","application/json"),l=Bi(n||{});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 dn(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 kr{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new Ks,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=br(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new zi(this.destructManager),Ji.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new Si(e.apiKey,e.authProvider),this.socketManager=new yr(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager,this.runtimeOptions),this.rpcManager=new dr(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new Mn(this.socketManager,this.rpcManager),this.jobClient=new sn(this.socketManager,this.rpcManager,this.clientIdService,this.destructManager,this.runtimeOptions),this.langGraphClient=new rn(this.rpcManager,this.jobClient),this.backendFunctionManager=new Ki(this.rpcManager),this.aiClient=new bi(this.socketManager,this.rpcManager,this.jobClient,this.clientIdService,this.backendFunctionManager,()=>this.metricAnnotations),this.apiClient=new vi(this.rpcManager),this.eventsClient=new Zs(this.rpcManager),this.documentStore=new Xs,this.lockManager=new or,this.distributedLockManager=new Ws(this.socketManager,this.destructManager),this.documentIdentityService=new zs(this.documentStore,this.destructManager),this.documentReferenceFactory=new Ys(this.documentIdentityService),this.querySender=new Nn(this.rpcManager,this.destructManager,this.socketManager.observeConnectionReady()),this.observabilityClient=new _n(this.rpcManager),this.schedulerClient=new pr(this.rpcManager),this._appId=i,this.querySubscriptionManager=new sr(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager,this.lockManager),this.localQueryManager=new Rn(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const s=new vn(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new ds(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService,s),this.dataManager=new Gs(this.documentStore,s,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new Ss(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.querySubscriptionManager.setDetachedQueryExecutor(e=>this.dataManager.executeDetachedQuery(e)),this.webhookManager=new Mr(this.rpcManager,e.region,i),this.nativeQueryManager=new Sn(this.rpcManager),this._connectionDetails=new Ms(this.clientIdService,this.socketManager,this.runtimeOptions),this.queueManagerFactory=new ar(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new H(this.rpcManager,this.options.region,wr(i),this.options.consoleRegion),this.webClient=new Sr(this.rpcManager,this.options.region,wr(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=xi(e);let i=kr.squidInstancesMap[t];return i||(i=new kr(e),kr.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(kr.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Jt){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 s={type:"relational",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativePureQuery(e,t,i={}){const s={type:"pure",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativeMongoQuery(e,t,i){const s={type:"mongo",collectionName:t,aggregationPipeline:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}executeNativeElasticQuery(e,t,i,s="_search",n="GET"){const r={type:"elasticsearch",index:t,endpoint:s,method:n,body:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(r)}ai(){return this._validateNotDestructed(),this.aiClient}setMetricAnnotations(e){this.metricAnnotations=e?{...e}:void 0}job(){return this._validateNotDestructed(),this.jobClient}langGraph(e){return this._validateNotDestructed(),this.langGraphClient.graph(e)}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 vr(e,this.rpcManager)}externalAuth(e){return this._validateNotDestructed(),new en(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new tn(this.rpcManager)}events(){return this._validateNotDestructed(),this.eventsClient}acquireLock(e,t){return this._validateNotDestructed(),this.distributedLockManager.lock(e,t)}async withLock(e,t,i){const s=await this.acquireLock(e,i);try{return await t(s)}finally{s.release()}}queue(e,t=zt){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(kr.squidInstancesMap).find(([,e])=>e===this);e&&delete kr.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)=>br(e,t,i)}}_validateNotDestructed(){be(!this.destructManager.isDestructing,"The client was already destructed.")}}const _r=18,Tr=100,Er=50,Dr=200,Cr=500,Or=500,qr=20,Ar=2e4;export{We as AGENT_STATUS_TITLE_ACCESSING_KB,Ke as AGENT_STATUS_TITLE_AGENT_RESPONSE,Ve as AGENT_STATUS_TITLE_CALLING_AI_FUNCTION,Ye as AGENT_STATUS_TITLE_GREPPING_KB,Je as AGENT_STATUS_TITLE_INSPECTING_KB_METADATA,ze as AGENT_STATUS_TITLE_QUERYING_KB_GRAPH,Xe as AGENT_STATUS_TITLE_QUERYING_SPREADSHEET,Qt as AI_AGENTS_INTEGRATION_ID,Tt as AI_AUDIO_CREATE_SPEECH_MODEL_NAMES,_t as AI_AUDIO_TRANSCRIPTION_MODEL_NAMES,Ze as AI_CHAT_MESSAGE_SOURCE,ft as AI_EMBEDDINGS_MODEL_NAMES,nt as AI_FILE_PROVIDER_TYPES,kt as AI_IMAGE_MODEL_NAMES,Dt as AI_MODEL_SOURCES,st as AI_PROVIDER_TYPES,ai as ALL_OPERATORS,ut as ANTHROPIC_CHAT_MODEL_NAMES,Nt as API_INJECTION_FIELD_TYPES,oi as ARRAY_OPERATORS,Gt as AUTH_INTEGRATION_TYPES,H as AdminClient,Ne as AiAgentClient,Re as AiAgentReference,xe as AiAudioClient,bi as AiClient,Be as AiFilesClient,Pe as AiImageClient,$e as AiKnowledgeBaseClient,Le as AiKnowledgeBaseReference,Ge as AiMatchMakingClient,vi as ApiClient,G as ApiKeysSecretClient,Si as AuthManager,gt as BEDROCK_EMBEDDING_MODEL_NAMES,Bt as BUILT_IN_AGENT_ID,Jt as BUILT_IN_DB_INTEGRATION_ID,zt as BUILT_IN_QUEUE_INTEGRATION_ID,Yt as BUILT_IN_STORAGE_INTEGRATION_ID,Rt as BULK_INGESTION_MAX_MULTIPART_FILE_BYTES,Ki as BackendFunctionManager,hs as BaseQueryBuilder,ui as CLIENT_CONNECTION_STATES,Yi as CLIENT_ID_GENERATOR_KEY,Xi as CLIENT_REQUEST_ID_GENERATOR_KEY,Pt as CONNECTOR_IDS,fs as Changes,zi as ClientIdService,ws as CollectionReference,Ss as CollectionReferenceFactory,Ms as ConnectionDetails,Q as ConnectorClient,$t as DATA_INTEGRATION_TYPES,tt as DEFAULT_PII_CLASSIFIER_MODEL,et as DEFAULT_PII_ENTITY_TYPES,_r as DEFAULT_SHORT_ID_LENGTH,ri as DOC_ID_FIELD,Gs as DataManager,ms as DereferencedJoin,Ks as DestructManager,Vs as DistributedLockImpl,Ws as DistributedLockManager,us as DocumentReference,Ys as DocumentReferenceFactory,Xs as DocumentStore,Fe as EMPTY_CHAT_ID,xt as ENVIRONMENT_IDS,Zs as EventsClient,en as ExternalAuthClient,tn as ExtractionClient,Tr as FETCH_BEYOND_LIMIT,Mt as FLUX_MODEL_NAMES,At as FOLDER_PATH_METADATA_FIELD_NAME,Ot as FUNCTION_AFFINITY_SCOPES,at as GEMINI_CHAT_MODEL_NAMES,Kt as GRAPHQL_INTEGRATION_TYPES,Er as GREP_KNOWLEDGE_BASE_DEFAULT_MAX_MATCHES,Dr as GREP_KNOWLEDGE_BASE_MAX_MATCHES,Cr as GREP_KNOWLEDGE_BASE_MAX_MATCH_LINE_CHARS,Or as GREP_KNOWLEDGE_BASE_MAX_PATTERN_CHARS,ct as GROK_CHAT_MODEL_NAMES,bs as GroupedJoin,Wt as HTTP_INTEGRATION_TYPES,Ut as HttpStatus,Vt as INTEGRATION_SCHEMA_TYPES,Lt as INTEGRATION_TYPES,L as IntegrationClient,sn as JobClient,ys as JoinQueryBuilder,rn as LangGraphClient,nn as LangGraphReference,$i as LastUsedValueExecuteFunctionCache,$s as LimitUnderflowState,Rn as LocalQueryManager,Ht as MCP_OAUTH_INTEGRATION_TYPES,ii as METRIC_DOMAIN,ti as METRIC_FUNCTIONS,si as METRIC_INTERVAL_ALIGNMENT,ni as METRIC_NO_DATA_BEHAVIOR,wn as ManagementClient,He as MatchMaker,vn as MutationSender,ln as NOOP_FN,Sn as NativeQueryManager,Mn as NotificationClient,wt as OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES,vt as OPENAI_AUDIO_MODEL_NAMES,bt as OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES,ot as OPENAI_CHAT_MODEL_NAMES,ht as OPENAI_EMBEDDINGS_MODEL_NAMES,It as OPENAI_IMAGE_MODEL_NAMES,Et as OPEN_AI_CREATE_SPEECH_FORMATS,_n as ObservabilityClient,ls as Pagination,gs as QueryBuilder,ds as QueryBuilderFactory,Nn as QuerySender,sr as QuerySubscriptionManager,ar as QueueManagerFactory,ur as QueueManagerImpl,jt as RAG_TYPES,it as RERANK_PROVIDERS,Ls as RUN_IN_TRANSACTION_MUTEX,lr as RateLimiter,dr as RpcManager,di as SOURCE_CODE_ANALYZER_MODELS,li as SOURCE_CODE_ANALYZE_FUNCTION_ID,pi as SOURCE_CODE_INTEGRATION_TYPES,qr as SOURCE_CODE_MAX_REPOSITORIES,Ar as SOURCE_CODE_MAX_SUPPLEMENTAL_INSTRUCTIONS_LENGTH,hi as SOURCE_CONTROL_PROVIDERS,Xt as SQUID_BUILT_IN_INTEGRATION_IDS,ei as SQUID_METRIC_NAMES,ci as SQUID_REGIONS,St as STABLE_DIFFUSION_MODEL_NAMES,pr as SchedulerClient,$ as SecretClient,yr as SocketManager,kr as Squid,dn as SquidClientError,vr as StorageClient,qt as VECTOR_DB_TYPES,lt as VENDOR_AI_CHAT_MODEL_NAMES,pt as VOYAGE_EMBEDDING_MODEL_NAMES,Sr as WebClient,Mr as WebhookManager,hr as assertNotPassiveMode,Qi as compareArgsByReference,Li as compareArgsBySerializedValue,On as deserializeQuery,_e as generateId,Ee as generateShortId,De as generateShortIds,Me as generateUUID,ke as generateUUIDPolyfill,U as getConsoleUrl,Wi as getCustomizationFlag,yt as isAiEmbeddingsModelName,Zt as isBuiltInIntegrationId,rt as isFileCapableProviderType,mt as isIntegrationEmbeddingModelSpec,Ct as isIntegrationModelSpec,Ft as isPlaceholderParam,dt as isVendorAiChatModelName,Cn as loadQueryResultDocIds,fi as normalizeBitbucketRepositorySelection,gi as normalizeGitHubRepositorySelection,Ae as observeAiStatusUpdates,mn as rawSquidHttpDelete,gn as rawSquidHttpGet,yn as rawSquidHttpPatch,pn as rawSquidHttpPost,fn as rawSquidHttpPut,Gi as transformFileArgs,bn as tryDeserializing,Dn as visitQueryResults};
|