@squidcloud/client 1.0.393 → 1.0.395
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/integration.public-types.d.ts +1 -1
- package/dist/internal-common/src/public-utils/id-utils.d.ts +9 -1
- package/dist/typescript-client/src/version.d.ts +1 -1
- package/package.json +2 -2
- package/dist/internal-common/src/metric-name.d.ts +0 -9
- 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 -148
- package/dist/internal-common/src/public-types-backend/native-query.public-context.d.ts +0 -60
- package/dist/internal-common/src/public-types-backend/query.public-context.d.ts +0 -166
- package/dist/internal-common/src/types/ai-agent.types.d.ts +0 -159
- package/dist/internal-common/src/types/ai-assistant.types.d.ts +0 -1
- package/dist/internal-common/src/types/ai-knowledge-base.types.d.ts +0 -130
- package/dist/internal-common/src/types/ai-matchmaking.types.d.ts +0 -59
- 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 -17
- package/dist/internal-common/src/types/mutation.types.d.ts +0 -1
- package/dist/internal-common/src/types/notification.types.d.ts +0 -5
- package/dist/internal-common/src/types/observability.types.d.ts +0 -78
- package/dist/internal-common/src/types/query.types.d.ts +0 -13
- package/dist/internal-common/src/types/secret.types.d.ts +0 -2
- 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 -41
- 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/global.utils.d.ts +0 -1
- package/dist/internal-common/src/utils/http.d.ts +0 -5
- 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 -58
- package/dist/internal-common/src/utils/serialization.d.ts +0 -11
- package/dist/internal-common/src/utils/squid.constants.d.ts +0 -1
- 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/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{"use strict";var e={86:e=>{e.exports=require("ws")},150:function(e,t,r){var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0});const o=r(642);t.default=o.PromisePool,i(r(273),t),i(r(642),t),i(r(837),t),i(r(426),t),i(r(858),t),i(r(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class r extends Error{constructor(e){super(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e){return new this(e)}}t.ValidationError=r},234:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=r(642),i=r(172),o=r(837),s=r(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],taskTimeout:0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw i.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}isValidConcurrency(e){return"number"==typeof e&&e>=1}withTaskTimeout(e){return this.meta.taskTimeout=e,this}concurrency(){return this.meta.concurrency}useCorrespondingResults(e){return this.meta.shouldResultsCorrespond=e,this}shouldUseCorrespondingResults(){return this.meta.shouldResultsCorrespond}taskTimeout(){return this.meta.taskTimeout}for(e){return this.meta.items=e,this}items(){return this.meta.items}itemsCount(){const e=this.items();return Array.isArray(e)?e.length:NaN}tasks(){return this.meta.tasks}activeTaskCount(){return this.activeTasksCount()}activeTasksCount(){return this.tasks().length}processedItems(){return this.meta.processedItems}processedCount(){return this.processedItems().length}processedPercentage(){return this.processedCount()/this.itemsCount()*100}results(){return this.meta.results}errors(){return this.meta.errors}withHandler(e){return this.handler=e,this}hasErrorHandler(){return!!this.errorHandler}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers=e,this}onTaskFinished(e){return this.onTaskFinishedHandlers=e,this}hasReachedConcurrencyLimit(){return this.activeTasksCount()>=this.concurrency()}stop(){throw this.markAsStopped(),new s.StopThePromisePoolError}markAsStopped(){return this.meta.stopped=!0,this}isStopped(){return this.meta.stopped}async start(){return await this.validateInputs().prepareResultsArray().process()}validateInputs(){if("function"!=typeof this.handler)throw i.ValidationError.createFrom("The first parameter for the .process(fn) method must be a function");const e=this.taskTimeout();if(!(null==e||"number"==typeof e&&e>=0))throw i.ValidationError.createFrom(`"timeout" must be undefined or a number. A number must be 0 or up. Received "${String(e)}" (${typeof e})`);if(!this.areItemsValid())throw i.ValidationError.createFrom(`"items" must be an array, an iterable or an async iterable. Received "${typeof this.items()}"`);if(this.errorHandler&&"function"!=typeof this.errorHandler)throw i.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw i.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw i.ValidationError.createFrom(`The error handler must be a function. Received "${typeof e}"`)}),this}areItemsValid(){const e=this.items();return!!Array.isArray(e)||"function"==typeof e[Symbol.iterator]||"function"==typeof e[Symbol.asyncIterator]}prepareResultsArray(){const e=this.items();return Array.isArray(e)&&this.shouldUseCorrespondingResults()?(this.meta.results=Array(e.length).fill(n.PromisePool.notRun),this):this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=n.PromisePool.notRun),this.startProcessing(t,e),e+=1,await this.waitForProcessingSlot()}return await this.drained()}async waitForProcessingSlot(){for(;this.hasReachedConcurrencyLimit();)await this.waitForActiveTaskToFinish()}async waitForActiveTaskToFinish(){await Promise.race(this.tasks())}startProcessing(e,t){const r=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(r)}).catch(async n=>{await this.handleErrorFor(n,e,t),this.removeActive(r)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(r),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[r,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),r()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise((r,n)=>{t=setTimeout(()=>{n(new o.PromisePoolError(`Task in promise pool timed out after ${this.taskTimeout()}ms`,e))},this.taskTimeout())}),()=>clearTimeout(t)]}save(e,t){return this.shouldUseCorrespondingResults()?this.results()[t]=e:this.results().push(e),this}removeActive(e){return this.tasks().splice(this.tasks().indexOf(e),1),this}async handleErrorFor(e,t,r){if(this.shouldUseCorrespondingResults()&&(this.results()[r]=n.PromisePool.failed),!this.isStoppingThePoolError(e)){if(this.isValidationError(e))throw this.markAsStopped(),e;this.hasErrorHandler()?await this.runErrorHandlerFor(e,t):this.saveErrorFor(e,t)}}isStoppingThePoolError(e){return e instanceof s.StopThePromisePoolError}isValidationError(e){return e instanceof i.ValidationError}async runErrorHandlerFor(e,t){try{await(this.errorHandler?.(e,t,this))}catch(e){this.rethrowIfNotStoppingThePool(e)}}runOnTaskStartedHandlers(e){this.onTaskStartedHandlers.forEach(t=>{t(e,this)})}runOnTaskFinishedHandlers(e){this.onTaskFinishedHandlers.forEach(t=>{t(e,this)})}rethrowIfNotStoppingThePool(e){if(!this.isStoppingThePoolError(e))throw e}saveErrorFor(e,t){this.errors().push(o.PromisePoolError.createFrom(e,t))}async drained(){return await this.drainActiveTasks(),{errors:this.errors(),results:this.results()}}async drainActiveTasks(){await Promise.all(this.tasks())}}},273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},426:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},642:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=r(234);class i{constructor(e){this.timeout=void 0,this.concurrency=10,this.items=e??[],this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[],this.shouldResultsCorrespond=!1}withConcurrency(e){return this.concurrency=e,this}static withConcurrency(e){return(new this).withConcurrency(e)}withTaskTimeout(e){return this.timeout=e,this}static withTaskTimeout(e){return(new this).withTaskTimeout(e)}for(e){const t=new i(e).withConcurrency(this.concurrency);return"function"==typeof this.errorHandler&&t.handleError(this.errorHandler),"number"==typeof this.timeout?t.withTaskTimeout(this.timeout):t}static for(e){return(new this).for(e)}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers.push(e),this}onTaskFinished(e){return this.onTaskFinishedHandlers.push(e),this}useCorrespondingResults(){return this.shouldResultsCorrespond=!0,this}async process(e){return(new n.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=i,i.notRun=Symbol("notRun"),i.failed=Symbol("failed")},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class r extends Error{constructor(e,t){super(),this.raw=e,this.item=t,this.name=this.constructor.name,this.message=this.messageFrom(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e,t){return new this(e,t)}messageFrom(e){return e instanceof Error||"object"==typeof e?e.message:"string"==typeof e||"number"==typeof e?e.toString():""}}t.PromisePoolError=r},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class r extends Error{}t.StopThePromisePoolError=r}},t={};function r(n){var i=t[n];if(void 0!==i)return i.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,r),o.exports}r.d=(e,t)=>{for(var n in t)r.o(t,n)&&!r.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},r.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};r.r(n),r.d(n,{AI_AGENTS_INTEGRATION_ID:()=>Be,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Pe,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>xe,AI_EMBEDDINGS_MODEL_NAMES:()=>Oe,AI_IMAGE_MODEL_NAMES:()=>Ce,AI_PROVIDER_TYPES:()=>ye,AI_STATUS_MESSAGE_PARENT_MESSAGE_ID_TAG:()=>he,AI_STATUS_MESSAGE_RESULT_TAG:()=>pe,ALL_OPERATORS:()=>rt,ANTHROPIC_CHAT_MODEL_NAMES:()=>me,API_INJECTION_FIELD_TYPES:()=>Re,ARRAY_OPERATORS:()=>tt,AUTH_INTEGRATION_TYPES:()=>Ue,AdminClient:()=>l,AiAgentClient:()=>re,AiAgentReference:()=>ee,AiAssistantClient:()=>ie,AiAudioClient:()=>oe,AiClient:()=>ot,AiImageClient:()=>se,AiKnowledgeBaseClient:()=>ue,AiKnowledgeBaseReference:()=>ce,AiMatchMakingClient:()=>le,ApiClient:()=>at,ApiKeysSecretClient:()=>u,AuthManager:()=>ct,BUILT_IN_AGENT_ID:()=>G,BUILT_IN_DB_INTEGRATION_ID:()=>We,BUILT_IN_QUEUE_INTEGRATION_ID:()=>He,BUILT_IN_STORAGE_INTEGRATION_ID:()=>ze,BackendFunctionManager:()=>jt,BaseQueryBuilder:()=>Ht,CLIENT_CONNECTION_STATES:()=>it,CLIENT_ID_GENERATOR_KEY:()=>Nt,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>Rt,Changes:()=>Jt,ClientIdService:()=>Dt,CollectionReference:()=>tr,CollectionReferenceFactory:()=>nr,ConnectionDetails:()=>ir,DATA_INTEGRATION_TYPES:()=>Qe,DEFAULT_SHORT_ID_LENGTH:()=>W,DataManager:()=>pr,DereferencedJoin:()=>Zt,DestructManager:()=>yr,DistributedLockImpl:()=>vr,DistributedLockManager:()=>gr,DocumentReference:()=>Gt,DocumentReferenceFactory:()=>mr,DocumentStore:()=>_r,EMPTY_CHAT_ID:()=>ne,ENVIRONMENT_IDS:()=>$,ExtractionClient:()=>Sr,FETCH_BEYOND_LIMIT:()=>yn,FLUX_MODEL_NAMES:()=>je,GEMINI_CHAT_MODEL_NAMES:()=>ve,GRAPHQL_INTEGRATION_TYPES:()=>$e,GROK_CHAT_MODEL_NAMES:()=>be,GroupedJoin:()=>er,HTTP_INTEGRATION_TYPES:()=>Ge,HttpStatus:()=>Fe,INTEGRATION_SCHEMA_TYPES:()=>Ve,INTEGRATION_TYPES:()=>Le,IntegrationClient:()=>a,JobClient:()=>wr,JoinQueryBuilder:()=>Yt,LastUsedValueExecuteFunctionCache:()=>At,LimitUnderflowState:()=>an,LocalQueryManager:()=>$r,METRIC_DOMAIN:()=>Xe,METRIC_FUNCTIONS:()=>Ze,METRIC_INTERVAL_ALIGNMENT:()=>et,MatchMaker:()=>de,MutationSender:()=>Ir,NOOP_FN:()=>Mn,NativeQueryManager:()=>Or,NotificationClient:()=>Mr,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Te,OPENAI_AUDIO_MODEL_NAMES:()=>ke,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Ee,OPENAI_CHAT_MODEL_NAMES:()=>ge,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>we,OPENAI_IMAGE_MODEL_NAMES:()=>Me,OPEN_AI_CREATE_SPEECH_FORMATS:()=>De,ObservabilityClient:()=>Tr,Pagination:()=>Vt,PersonalStorageClient:()=>jr,QueryBuilder:()=>Kt,QueryBuilderFactory:()=>Wt,QuerySender:()=>Vr,QuerySubscriptionManager:()=>gn,QueueManagerFactory:()=>_n,QueueManagerImpl:()=>wn,RAG_TYPES:()=>Ne,RERANK_PROVIDERS:()=>fe,RateLimiter:()=>In,RpcManager:()=>Nn,SQUID_BUILT_IN_INTEGRATION_IDS:()=>Ke,SQUID_METRIC_NAMES:()=>Ye,SQUID_REGIONS:()=>nt,STABLE_DIFFUSION_MODEL_NAMES:()=>Ae,SchedulerClient:()=>Rn,SecretClient:()=>c,SocketManager:()=>Bn,Squid:()=>Wn,SquidClientError:()=>En,StorageClient:()=>Gn,VENDOR_AI_CHAT_MODEL_NAMES:()=>_e,VOYAGE_EMBEDDING_MODEL_NAMES:()=>Ie,WebClient:()=>Vn,base64ToFile:()=>X,compareArgsByReference:()=>Tt,compareArgsBySerializedValue:()=>kt,deserializeQuery:()=>xr,generateId:()=>V,generateShortId:()=>z,generateShortIds:()=>K,getConsoleUrl:()=>s,getCustomizationFlag:()=>Ct,isBuiltInIntegrationId:()=>Je,isPlaceholderParam:()=>qe,isVendorAiChatModelName:()=>Se,rawSquidHttpDelete:()=>xn,rawSquidHttpGet:()=>An,rawSquidHttpPatch:()=>Cn,rawSquidHttpPost:()=>kn,rawSquidHttpPut:()=>jn,tryDeserializing:()=>Dn,visitQueryResults:()=>Cr});const i=["aiData","api","application","application-kotlin","auth","backend-function","connector","integration","internal-storage","internalCodeExecutor","mutation","named-query","native-query","observability","openapi","query","queue","quota","scheduler","secret","storage","webhooks","ws","personalStorage","internal-extraction","notification"];function o(e,t,r,n,o){let s="https",a=`${n||t}.${o||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(s="http",c=i.includes(r.replace(/^\//,"").split("/")[0]||"")?"8001":"8000",/android$/.test(e)?a="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(a="localhost"));const u=s+"://"+a+(c?`:${c}`:""),l=r.replace(/^\/+/,"");return l?`${u}/${l}`:u}function s(e,t=""){return o(function(e){return e.includes("sandbox")?"us-east-1.aws.sandbox":e.includes("local")?"local":e.includes("staging")?"us-central1.gcp.staging":"us-east-1.aws"}(e),"console",t)}class a{constructor(e,t,r){this.rpcManager=e,this.iacBaseUrl=s(t,`openapi/iac/applications/${r}/integrations`)}async list(e){const t=await this.rpcManager.get(this.iacBaseUrl);return e?t.filter(t=>t.type===e):t}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getIntegrationSchema(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}/schema`)}async delete(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}async deleteMany(e){await Promise.all(e.map(e=>this.delete(e)))}async upsertIntegration(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e.id}`,e)}}class c{constructor(e){this.rpcManager=e}async get(e){const t={key:e};return await this.rpcManager.post("secret/get",t)||void 0}getAll(){return this.rpcManager.post("secret/getAll",{})}async upsert(e,t){return this.upsertMany([{key:e,value:t}]).then(e=>e[0])}async upsertMany(e){if(0===e.length)return[];const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e,t=!1){const r={keys:[e],force:t};return this.rpcManager.post("secret/delete",r)}async deleteMany(e,t=!1){if(0===e.length)return;const r={keys:e,force:t};return this.rpcManager.post("secret/delete",r)}get apiKeys(){return new u(this.rpcManager)}}class u{constructor(e){this.rpcManager=e}get(e){const t={key:e};return this.rpcManager.post("secret/api-key/get",t)}getAll(){return this.rpcManager.post("secret/api-key/getAll",{})}upsert(e){const t={key:e};return this.rpcManager.post("secret/api-key/upsert",t)}delete(e){const t={key:e};return this.rpcManager.post("secret/api-key/delete",t)}}class l{constructor(e,t,r){this.rpcManager=e,this.region=t,this.appId=r,this.integrationClient=new a(this.rpcManager,this.region,this.appId),this.secretClient=new c(this.rpcManager)}integrations(){return this.integrationClient}secrets(){return this.secretClient}}const d=require("rxjs");function h(e){return"function"==typeof e}function p(e){return function(t){if(function(e){return h(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}var f=function(e,t){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},f(e,t)};function y(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}f(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function g(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function v(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s}function b(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var m,_=((m=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),m.prototype.constructor=m,m);function S(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}var w=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,n,i;if(!this.closed){this.closed=!0;var o=this._parentage;if(o)if(this._parentage=null,Array.isArray(o))try{for(var s=g(o),a=s.next();!a.done;a=s.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else o.remove(this);var c=this.initialTeardown;if(h(c))try{c()}catch(e){i=e instanceof _?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=g(u),d=l.next();!d.done;d=l.next()){var p=d.value;try{I(p)}catch(e){i=null!=i?i:[],e instanceof _?i=b(b([],v(i)),v(e.errors)):i.push(e)}}}catch(e){r={error:e}}finally{try{d&&!d.done&&(n=l.return)&&n.call(l)}finally{if(r)throw r.error}}}if(i)throw new _(i)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)I(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&S(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&S(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function I(e){h(e)?e():e.unsubscribe()}w.EMPTY;var O={setTimeout:function(e,t){for(var r=[],n=2;n<arguments.length;n++)r[n-2]=arguments[n];var i=O.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,b([e,t],v(r))):setTimeout.apply(void 0,b([e,t],v(r)))},clearTimeout:function(e){var t=O.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function M(){}var E=T("C",void 0,void 0);function T(e,t,r){return{kind:e,value:t,error:r}}var k=function(e){function t(t){var r,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((r=t)instanceof w||r&&"closed"in r&&h(r.remove)&&h(r.add)&&h(r.unsubscribe))&&t.add(n)):n.destination=P,n}return y(t,e),t.create=function(e,t,r){return new j(e,t,r)},t.prototype.next=function(e){this.isStopped?x(function(e){return T("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?x(T("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?x(E,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(w);Function.prototype.bind;var A=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){C(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){C(e)}else C(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){C(e)}},e}(),j=function(e){function t(t,r,n){var i,o=e.call(this)||this;return i=h(t)||!t?{next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:t,o.destination=new A(i),o}return y(t,e),t}(k);function C(e){!function(e){O.setTimeout(function(){throw e})}(e)}function x(e,t){var r=null;r&&O.setTimeout(function(){return r(e,t)})}var P={closed:!0,next:M,error:function(e){throw e},complete:M};function D(e,t,r,n,i){return new N(e,t,r,n,i)}var N=function(e){function t(t,r,n,i,o,s){var a=e.call(this,t)||this;return a.onFinalize=o,a.shouldUnsubscribe=s,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return y(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(k);function R(e,t){return p(function(r,n){var i=0;r.subscribe(D(n,function(r){n.next(e.call(t,r,i++))}))})}function q(e){return null!=e}let F=e=>new Error(e);function B(e,t,...r){e||function(e,...t){const r=Q(e);if("object"==typeof r)throw r;throw F(r||"Assertion error",...t)}(t,...r)}function L(e,t,...r){return B(e,t,...r),e}function Q(e){return void 0===e?"":"string"==typeof e?e:e()}function U(e,t,r){const n=Q(e);if("object"==typeof n)throw n;return`${n?`${n}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(r)}`}const $=["dev","prod"],G="built_in_agent";function V(){let e=(new Date).getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(t){const r=(e+16*Math.random())%16|0;return e=Math.floor(e/16),("x"===t?r:3&r|8).toString(16)})}const W=18,H="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function z(e=W,t=""){B(t.length<e,"ID prefix is too long");let r="";for(let t=0;t<e;t++)r+=H.charAt(Math.floor(Math.random()*H.length));return t.length>0&&(r=t+r.substring(t.length)),r}function K({count:e,length:t,prefix:r}){B(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(z(t||W,r||""));return[...n]}const J=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Y(e){for(const t in e){const r=e[t];if("string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r&&void 0!==r)throw new Error(`Invalid metadata value for key ${t} - cannot be of type ${typeof r}`);if(J.includes(t))throw new Error(`Invalid metadata key ${t} - cannot be an internal key. Internal keys: ${J.join(", ")}`);if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}function Z(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)Z(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)Z(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(J.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${J.join(", ")}`);const r=e[t];if("object"!=typeof r&&"string"!=typeof r&&"number"!=typeof r&&"boolean"!=typeof r)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof r}`)}}function X(e,t,r){const n=atob(e),i=new Uint8Array(n.length);for(let e=0;e<n.length;e++)i[e]=n.charCodeAt(e);const o=r||"application/octet-stream",s=new Blob([i],{type:o});return new File([s],t,{type:o})}class ee{constructor(e,t,r,n,i){this.agentId=e,this.ongoingChatSequences=t,this.rpcManager=r,this.socketManager=n,this.jobClient=i}async get(){const e=await this.rpcManager.post("ai/agent/getAgent",{agentId:this.agentId});return e?.agent}async upsert(e){await this.rpcManager.post("ai/agent/upsertAgent",{...e,id:this.agentId})}async delete(){await this.rpcManager.post("ai/agent/deleteAgent",{agentId:this.agentId})}async updateInstructions(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,instructions:e}})}async updateModel(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,model:e}})}async updateConnectedAgents(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,connectedAgents:e}})}async getContext(e){return await this.rpcManager.post("ai/agent/getContext",{agentId:this.agentId,contextId:e})}async listContexts(){return(await this.rpcManager.post("ai/agent/listContexts",{agentId:this.agentId})).contexts||[]}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/agent/deleteContexts",{agentId:this.agentId,contextIds:e})}async upsertContext(e,t){const{failures:r}=await this.upsertContexts([e],t?[t]:void 0);return r.length>0?{failure:r[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&Y(t.metadata);return await this.rpcManager.post("ai/agent/upsertContexts",{agentId:this.agentId,contextRequests:e},t)}async provideFeedback(e){await this.rpcManager.post("ai/agent/provideFeedback",{agentId:this.agentId,feedback:e})}async resetFeedback(){await this.rpcManager.post("ai/agent/resetFeedback",{agentId:this.agentId})}async updateGuardrails(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,guardrails:{...t.options?.guardrails,...e}}})}async updateCustomGuardrails(e){await this.rpcManager.post("ai/agent/upsertCustomGuardrails",{agentId:this.agentId,customGuardrail:e})}async deleteCustomGuardrail(){await this.rpcManager.post("ai/agent/deleteCustomGuardrails",{agentId:this.agentId})}chat(e,t,r){return this.chatInternal(e,t,r).responseStream}async transcribeAndChat(e,t,r){const n=this.chatInternal(e,t,r),i=await L(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:i.transcribedPrompt}}async search(e){B(this.agentId!==G,"Cannot search the built-in agent");const t={options:e,agentId:this.agentId};return(await this.rpcManager.post("ai/chatbot/search",t)).chunks}async ask(e,t,r){const n=await this.askInternal(e,!1,t,r);let i=n.responseString;for(const[e,t]of Object.entries(n.annotations||{})){let r="";switch(t.aiFileUrl.type){case"image":r=``;break;case"document":r=`[${t.aiFileUrl.fileName}](${t.aiFileUrl.url})`}i=i.replace(`\${id:${e}}`,r)}return i}async askWithAnnotations(e,t,r){const n=await this.askInternal(e,!1,t,r);return{responseString:n.responseString,annotations:n.annotations}}async askAsync(e,t,r){const n={agentId:this.agentId,prompt:e,options:r,jobId:t};await this.rpcManager.post("ai/chatbot/askAsync",n)}observeStatusUpdates(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,d.filter)(e=>"aiStatus"===e.type&&e.agentId===this.agentId),R(e=>({agentId:this.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,messageId:e.messageId})))}async transcribeAndAsk(e,t,r){return await this.askInternal(e,!1,t,r)}async transcribeAndAskWithVoiceResponse(e,t,r){const n=await this.askInternal(e,!0,t,r),i=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:X(i.base64File,`voice.${i.extension}`,i.mimeType)}}async askWithVoiceResponse(e,t,r){const n=await this.askInternal(e,!0,t,r),i=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:X(i.base64File,`voice.${i.extension}`,i.mimeType)}}async askInternal(e,t,r,n){if(r?.contextMetadataFilter&&Z(r.contextMetadataFilter),r?.contextMetadataFilterForKnowledgeBase)for(const e in r.contextMetadataFilterForKnowledgeBase)Z(r.contextMetadataFilterForKnowledgeBase[e]);n=n||V(),r={...te,...r||{}};const i="string"==typeof e;let o="ai/chatbot/";o+=i||t?!i&&t?"transcribeAndAskWithVoiceResponse":i&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const s={agentId:this.agentId,prompt:i?e:void 0,options:r,jobId:n},a=i?void 0:[e];return await this.rpcManager.post(o,s,a,"file"),await this.jobClient.awaitJob(n)}chatInternal(e,t,r){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&Z(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)Z(t.contextMetadataFilterForKnowledgeBase[e]);const n=V(),i=void 0===(t={...te,...t||{}}).smoothTyping||t.smoothTyping;let o="";const s=new d.Subject,a=new d.Subject;this.ongoingChatSequences[n]=a;let c=-1;a.pipe((0,d.tap)(({tokenIndex:e})=>{void 0!==e&&e<c&&console.warn("Received token index out of order",e,c),void 0!==e&&(c=e)}),(0,d.concatMap)(({value:e,complete:t})=>t?(0,d.of)({value:e,complete:t}):(0,d.of)(e).pipe(i?(0,d.delay)(0):(0,d.tap)(),R(e=>({value:e,complete:!1})))),(0,d.takeWhile)(({complete:e})=>!e,!0)).subscribe({next:({value:e})=>{o+=e,s.next(o)},error:e=>{console.error(e)},complete:()=>{s.complete()}});const u="string"==typeof e;r=r||V();const l={agentId:this.agentId,jobId:r,prompt:u?e:void 0,options:t,clientRequestId:n},h={responseStream:s.pipe((0,d.finalize)(()=>{delete this.ongoingChatSequences[n]}),(0,d.share)())};return u?this.rpcManager.post("ai/chatbot/chat",l).catch(e=>{s.error(e),s.complete()}):this.rpcManager.post("ai/chatbot/transcribeAndChat",l,[e],"file").catch(e=>{throw s.error(e),s.complete(),e}),h.serverResponse=this.jobClient.awaitJob(r).catch(e=>{s.error(e),s.complete()}),h}}const te={smoothTyping:!0,responseFormat:"text"};class re{constructor(e,t,r){this.rpcManager=e,this.socketManager=t,this.jobClient=r,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe((0,d.filter)(e=>"aiChatbot"===e.type),R(e=>e)).subscribe(e=>{this.handleChatResponse(e).then()})}agent(e){return new ee(e,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient)}async listAgents(){return(await this.rpcManager.post("ai/agent/listAgents",{})).agents}async handleChatResponse(e){const t=this.ongoingChatSequences[e.clientRequestId];if(!t)return;const{token:r,complete:n,tokenIndex:i}=e.payload;if(n&&!r.length)t.next({value:"",complete:!0,tokenIndex:void 0});else if(r.match(/\[.*?]\((.*?)\)/g))t.next({value:r,complete:n,tokenIndex:void 0===i?void 0:i});else for(let e=0;e<r.length;e++)t.next({value:r[e],complete:n&&e===r.length-1,tokenIndex:void 0===i?void 0:i})}}const ne="__squid_empty_chat_id";class ie{constructor(e){this.rpcManager=e}async createAssistant(e,t,r,n){const i={name:e,instructions:t,functions:r,toolTypes:n};return(await this.rpcManager.post("ai/assistant/createAssistant",i)).assistantId}async deleteAssistant(e){const t={assistantId:e};await this.rpcManager.post("ai/assistant/deleteAssistant",t)}async createThread(e){const t={assistantId:e};return(await this.rpcManager.post("ai/assistant/createThread",t)).threadId}async deleteThread(e){const t={threadId:e};await this.rpcManager.post("ai/assistant/deleteThread",t)}async queryAssistant(e,t,r,n,i){const o={assistantId:e,threadId:t,prompt:r,fileIds:n,options:i};return(await this.rpcManager.post("ai/assistant/queryAssistant",o)).answer}async addFileToAssistant(e,t){const r={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",r,[t],"file")).fileId}async removeFileFromAssistant(e,t){const r={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",r)}async addFileToThread(e,t){const r={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",r,[t],"file")).fileId}}class oe{constructor(e){this.rpcManager=e}async transcribe(e,t={modelName:"whisper-1"}){return this.rpcManager.post("ai/audio/transcribe",t,[e])}async createSpeech(e,t){const r={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",r);return X(n.base64File,`audio.${n.extension}`,n.mimeType)}}class se{constructor(e){this.rpcManager=e}async generate(e,t){const r={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",r)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function ae(e){for(const t in e){const r=e[t];B("string"==typeof r||"number"==typeof r||"boolean"==typeof r||void 0===r,`Invalid metadata value for key ${t} - cannot be of type ${typeof r}`),B(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class ce{constructor(e,t,r){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=r}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{id:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async delete(){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:this.knowledgeBaseId})}async listContexts(){return(await this.rpcManager.post("ai/knowledge-base/listContexts",{id:this.knowledgeBaseId})).contexts||[]}async getContext(e){return(await this.rpcManager.post("ai/knowledge-base/getContext",{knowledgeBaseId:this.knowledgeBaseId,contextId:e})).context}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/knowledge-base/deleteContexts",{knowledgeBaseId:this.knowledgeBaseId,contextIds:e})}async upsertContext(e,t){const{failures:r}=await this.upsertContexts([e],t?[t]:void 0);return r.length>0?{failure:r[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&ae(t.metadata);const r=V();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:r},t),await this.jobClient.awaitJob(r)}async search(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return(await this.rpcManager.post("ai/knowledge-base/search",t)).chunks}}class ue{constructor(e,t){this.rpcManager=e,this.jobClient=t}knowledgeBase(e){return new ce(e,this.rpcManager,this.jobClient)}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async delete(e){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:e})}}class le{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new de(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new de(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class de{constructor(e,t){this.matchMaker=e,this.rpcManager=t,this.id=e.id}async insertEntity(e){await this.rpcManager.post("matchMaking/insertEntity",{matchMakerId:this.id,entity:e})}async insertManyEntities(e){await this.rpcManager.post("matchMaking/insertEntities",{matchMakerId:this.id,entities:e})}async delete(){await this.rpcManager.post("matchMaking/deleteMatchMaker",{matchMakerId:this.id})}async deleteEntity(e){await this.rpcManager.post("matchMaking/deleteEntity",{entityId:e,matchMakerId:this.id})}async findMatches(e,t={}){return(await this.rpcManager.post("matchMaking/findMatches",{matchMakerId:this.id,entityId:e,options:t})).matches}async findMatchesForEntity(e,t={}){return(await this.rpcManager.post("matchMaking/findMatchesForEntity",{matchMakerId:this.id,entity:e,options:t})).matches}async listEntities(e,t={}){return await this.rpcManager.post("matchMaking/listEntities",{categoryId:e,options:t,matchMakerId:this.id})}async getEntity(e){return(await this.rpcManager.post("matchMaking/getEntity",{matchMakerId:this.id,entityId:e})).entity}getMatchMakerDetails(){return this.matchMaker}}const he="parent",pe="result",fe=["cohere","none"],ye=["anthropic","flux","gemini","openai","grok","stability","voyage","external"],ge=["o1","o3","o3-mini","o4-mini","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"],ve=["gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"],be=["grok-3","grok-3-fast","grok-3-mini","grok-3-mini-fast","grok-4"],me=["claude-3-7-sonnet-latest","claude-opus-4-20250514","claude-opus-4-1-20250805","claude-sonnet-4-20250514"],_e=[...ge,...me,...ve,...be];function Se(e){return _e.includes(e)}const we=["text-embedding-3-small"],Ie=["voyage-3-large"],Oe=[...we,...Ie],Me=["dall-e-3"],Ee=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],Te=["tts-1","tts-1-hd","gpt-4o-mini-tts"],ke=[...Ee,...Te],Ae=["stable-diffusion-core"],je=["flux-pro-1.1","flux-kontext-pro"],Ce=[...Me,...Ae,...je],xe=[...Ee],Pe=[...Te],De=["mp3","opus","aac","flac","wav","pcm"],Ne=["contextual","basic"],Re=["secret","regular"];function qe(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const Fe={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},Be="ai_agents",Le=["active_directory","ai_agents","ai_knowledgebases","ai_chatbot","algolia","alloydb","api","auth0","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","built_in_db","built_in_gcs","built_in_queue","built_in_s3","cassandra","clickhouse","cloudsql","cockroach","cognito","confluence","confluent","datadog","db2","descope","documentdb","dynamodb","elasticsearch","firebase_auth","firestore","gcs","google_docs","google_drive","graphql","hubspot","jira","jwt_hmac","jwt_rsa","kafka","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","oracledb","pinecone","postgres","redis","s3","salesforce_crm","sap_hana","sentry","servicenow","snowflake","spanner","xata","zendesk","mail","slack","mcp","a2a"],Qe=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch"],Ue=["auth0","jwt_rsa","jwt_hmac","cognito","okta","descope","firebase_auth"],$e=["graphql","linear"],Ge=["api","confluence"],Ve=["data","api","graphql"],We="built_in_db",He="built_in_queue",ze="built_in_storage",Ke=[We,He,ze];function Je(e){return Ke.includes(e)}const Ye=["squid_functionExecution_count","squid_functionExecution_time"],Ze=["sum","max","min","average","median","p95","p99","count"],Xe=["user","squid"],et=["align-by-start-time","align-by-end-time"],tt=["in","not in","array_includes_some","array_includes_all","array_not_includes"],rt=[...tt,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],nt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],it=["CONNECTED","DISCONNECTED","REMOVED"];class ot{constructor(e,t,r){this.socketManager=e,this.rpcManager=t,this.jobClient=r,this.aiAssistantClient=new ie(this.rpcManager)}agent(e=G){return this.getAiAgentClient().agent(e)}knowledgeBase(e){return this.getAiKnowledgeBaseClient().knowledgeBase(e)}async listAgents(){return this.getAiAgentClient().listAgents()}async listKnowledgeBases(){return this.getAiKnowledgeBaseClient().listKnowledgeBases()}assistant(){return this.aiAssistantClient}image(){return new se(this.rpcManager)}audio(){return new oe(this.rpcManager)}matchMaking(){return new le(this.rpcManager)}executeAiQuery(e,t,r){const n={integrationId:e,prompt:t,options:r};return this.rpcManager.post("ai/query/executeDataQuery",n)}executeAiApiCall(e,t,r,n){const i={integrationId:e,prompt:t,allowedEndpoints:r,provideExplanation:n};return this.rpcManager.post("ai/query/executeApiQuery",i)}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 r={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",r)).settings}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new re(this.rpcManager,this.socketManager,this.jobClient)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new ue(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const st={headers:{},queryParams:{},pathParams:{}};class at{constructor(e){this.rpcManager=e}async get(e,t,r){return this.request(e,t,void 0,r,"get")}async post(e,t,r,n){return this.request(e,t,r,n,"post")}async delete(e,t,r,n){return this.request(e,t,r,n,"delete")}async patch(e,t,r,n){return this.request(e,t,r,n,"patch")}async put(e,t,r,n){return this.request(e,t,r,n,"put")}async request(e,t,r,n,i){const o={integrationId:e,endpointId:t,body:r,options:{...st,...this.convertOptionsToStrings(n||{})},overrideMethod:i};return await this.rpcManager.rawPost("api/callApi",o,void 0,void 0,!1)}convertOptionsToStrings(e){return{headers:this.convertToStrings(e.headers),queryParams:this.convertToStrings(e.queryParams),pathParams:this.convertToStrings(e.pathParams)}}convertToStrings(e){if(!e)return{};const t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,String(t)]);return Object.fromEntries(t)}}class ct{constructor(e,t){this.apiKey=e,this.authProvider=t}setAuthProvider(e){this.authProvider=e}async getAuthData(){return{token:await this.getTokenFromAuthProvider(),integrationId:this.authProvider?.integrationId}}async getTokenFromAuthProvider(){const e=this.authProvider?.getToken();return"object"==typeof e?await e:e}getApiKey(){return this.apiKey}async getToken(){if(this.apiKey)return{type:"ApiKey",token:this.apiKey};const e=await this.getTokenFromAuthProvider();return e?{type:"Bearer",token:e,integrationId:this.authProvider?.integrationId}:void 0}}const ut=/[.\[\]]/;function lt(e,t){if(!e)return;const r=t.split(ut);let n,i=e;for(;i&&r.length;){const e=r.shift();if(e){if("object"!=typeof i||!(e in i))return;n=i[e],i=n}}return n}function dt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function ht(e,t,r,n="."){const i=t.split(n);let o=e;for(;i.length;){const e=L(i.shift());if(i.length){const t=o[e],r=dt(t)?mt(t)??{}:{};o[e]=r,o=r}else o[e]=r}}function pt(e,t,r="."){const n=t.split(r);let i=e;for(;n.length;){const e=L(n.shift());if(n.length){const t=dt(i[e])?mt(i[e])??{}:{};i[e]=t,i=t}else delete i[e]}}function ft(e,t,r){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(r,n)}}function yt(e){return null==e}function gt(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const r=typeof e;if(r!==typeof t)return!1;if("object"!==r)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),i=Object.keys(t);if(n.length!==i.length)return!1;for(const r of n)if(!i.includes(r)||!gt(e[r],t[r]))return!1;return!0}function vt(e,t){const r=new Array(e.length);for(let n=0;n<e.length;n++)r[n]=bt(e[n],t);return r}function bt(e,t){const r=t?t(e):void 0;if(void 0!==r)return r;if("object"!=typeof e||null===e)return e;if(e instanceof Date)return new Date(e);if(Array.isArray(e))return vt(e,t);if(e instanceof Map)return new Map(vt(Array.from(e),t));if(e instanceof Set)return new Set(vt(Array.from(e),t));if(ArrayBuffer.isView(e))return(n=e)instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const i={};for(const r in e)Object.hasOwnProperty.call(e,r)&&(i[r]=bt(e[r],t));return i}function mt(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 _t(e,t){if(e===t||yt(e)&&yt(t))return 0;if(yt(e))return-1;if(yt(t))return 1;const r=typeof e,n=typeof t;return r!==n?r<n?-1:1:"number"==typeof e?(B("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(B("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(B("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(B("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function St(e,t){return e.reduce((e,r)=>{const n=t(r);return e[n]?e[n].push(r):e[n]=[r],e},{})}function wt(e){if(Array.isArray(e))return e.map(e=>wt(e));if("object"!=typeof e||null===e||e instanceof Date)return e;const t=Object.keys(e),r={};return t.sort().forEach(t=>{r[t]=wt(e[t])}),r}function It(e){return Ot(wt(e))}function Ot(e){if(void 0===e)return null;const t=bt(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function Mt(e){return bt(JSON.parse(e),e=>{if(null===e||"object"!=typeof e)return;const t=e,r=t.$date;return r&&1===Object.keys(t).length?new Date(r):void 0})}function Et(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=Ot(e);if("undefined"!=typeof Buffer)return Buffer.from(t,"utf8").toString("base64");{const e=(new TextEncoder).encode(t);let r="";for(let t=0;t<e.length;t++)r+=String.fromCharCode(e[t]);return btoa(r)}}const Tt=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},kt=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(Ot(e[r])!==Ot(t[r]))return!1;return!0};class At{constructor(e){this.options=e}get(e){const t=this.cachedEntry,r=this.options.argsComparator||Tt,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&r(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}class jt{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){const{argsArray:r,fileArray:n}=this.transformFileArgs(t),i="string"==typeof e?e:e.functionName,o="string"==typeof e?void 0:e.caching,s=o?.cache;if(s){const e=s.get(r);if(e.found)return Promise.resolve(e.value)}const a="string"==typeof e?void 0:e.deduplication;if(a){const e="boolean"==typeof a?Tt:a.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===i&&e(t.args,r));if(t)return t.promise}const c=this.createExecuteCallPromise(i,r,n,s);return a&&(this.inFlightDedupCalls.push({functionName:i,args:r,promise:c}),c.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==c)})),c}createExecuteCallPromise(e,t,r,n){const i=`backend-function/execute?${encodeURIComponent(e)}`,o={functionName:e,paramsArrayStr:Ot(t)};return(0,d.firstValueFrom)((0,d.race)((0,d.from)(this.rpcManager.post(i,o,r.length>0?r:[])).pipe(R(e=>{if(!e.success)throw new Error(e.payload);const r=Mt(e.payload);if(r?.__isSquidBase64File__){const e=r;return new File([Buffer.from(e.base64,"base64")],e.filename,{type:e.mimetype})}return n&&n.set(t,r),r}))))}transformFileArgs(e){const t=[],r=[];let n=0;for(const i of e)if("undefined"!=typeof File)if(i instanceof File){r.push(i);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(this.isArrayOfFiles(i)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:i.map((e,t)=>(r.push(i[t]),n++))};t.push(e)}else t.push(i);else t.push(i);return{argsArray:t,fileArray:r}}isArrayOfFiles(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}}function Ct(e){if("undefined"!=typeof globalThis)return globalThis[e]}function xt(){if("undefined"!=typeof window)return window;if(void 0!==r.g)return r.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}!function(e=!0){xt().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 Pt{static debug(...e){(function(){const e=xt();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=xt();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Dt{constructor(e){this.destructManager=e,this.clientTooOldSubject=new d.BehaviorSubject(!1),this.isTenant=!0===xt().squidTenant,this.clientIdSubject=new d.BehaviorSubject(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe((0,d.filter)(e=>e),(0,d.map)(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe((0,d.skip)(1),(0,d.filter)(e=>!e),(0,d.map)(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientId(){const e=xt()[Nt];if(e)return e();let t=`${this.isTenant?"tenant-":""}${V()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}generateClientRequestId(){const e=xt()[Rt];return e?e():V()}}const Nt="SQUID_CLIENT_ID_GENERATOR",Rt="SQUID_CLIENT_REQUEST_ID_GENERATOR",qt="__squidId";function Ft(e){return Mt(e)}function Bt(...e){const[t,r,n]=e,i="object"==typeof t?t:{docId:t,collectionName:r,integrationId:n};return i.integrationId||(i.integrationId=void 0),It(i)}function Lt(e,t,r){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===r)return gt(e,t);if("!="===r)return!gt(e,t);switch(r){case"<":return!yt(e)&&(!!yt(t)||t<e);case"<=":return!!yt(t)||!yt(e)&&t<=e;case">":return!yt(t)&&(!!yt(e)||t>e);case">=":return!!yt(e)||!yt(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Qt(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Qt(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Qt(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Qt(t,e,!0));case"array_includes_some":{const r=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>L(r,"VALUE_CANNOT_BE_NULL").some(t=>gt(t,e)))}case"array_includes_all":{const r=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>L(r,"VALUE_CANNOT_BE_NULL").some(t=>gt(t,e)))}case"array_not_includes":{const r=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!L(r,"VALUE_CANNOT_BE_NULL").some(t=>gt(t,e)))}default:throw new Error(`Unsupported operator comparison: ${r}`)}}function Qt(e,t,r){r||(e=e.toLowerCase(),t=t.toLowerCase());const n=function(e){let t="";for(let r=0;r<e.length;++r)"\\"===e[r]?r+1<e.length&&["%","_"].includes(e[r+1])?(t+=e[r+1],r++):r+1<e.length&&"\\"===e[r+1]?(t+="\\\\",r++):t+="\\":"%"===e[r]?t+="[\\s\\S]*":"_"===e[r]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[r])&&(t+="\\"),t+=e[r]);return t}(t);return new RegExp(`^${n}$`).test(e)}function Ut(e,t){return`${e}_${t}`}function $t(e){return"fieldName"in e}class Gt{constructor(e,t,r){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=r,this.refId=V()}get squidDocId(){return this._squidDocId}get data(){return bt(this.dataRef)}get dataRef(){return L(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:r}=Ft(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:r,collectionName:e,integrationId:t},null,2)}`})}get hasData(){return!!this.dataManager.getProperties(this.squidDocId)}async snapshot(){if(this.hasSquidPlaceholderId())throw new Error("Cannot invoke snapshot of a document that was created locally without storing it on the server.");if(this.isTracked()&&this.hasData)return this.data;const e=await this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshot();return L(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0}snapshots(){return this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshots().pipe((0,d.map)(e=>(L(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0)))}peek(){return this.isTracked()&&this.hasData?this.data:void 0}isDirty(){return this.dataManager.isDirty(this.squidDocId)}isTracked(){return this.dataManager.isTracked(this.squidDocId)}async update(e,t){const r={};Object.entries(e).forEach(([e,t])=>{const n=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};r[e]=[n]});const n={type:"update",squidDocIdObj:Ft(this.squidDocId),properties:r};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,r){return this.update({[e]:bt(t)},r)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,r){const n={type:"applyNumericFn",fn:"increment",value:t},i={type:"update",squidDocIdObj:Ft(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(i,r)}decrementInPath(e,t,r){return this.incrementInPath(e,-t,r)}async insert(e,t){const r=Ft(this.squidDocId),n=r.integrationId;let i=Mt(r.docId);if(i[qt]&&(i={}),n===We&&i.__id)try{const e=Mt(i.__id);i={...i,...e}}catch{}const o={type:"insert",squidDocIdObj:r,properties:{...e,__docId__:r.docId,...i}};return this.dataManager.applyOutgoingMutation(o,t)}async delete(e){const t={type:"delete",squidDocIdObj:Ft(this.squidDocId)};return this.dataManager.applyOutgoingMutation(t,e)}migrateDocIds(e){const t=e[this.squidDocId];t&&(this._squidDocId=t)}hasSquidPlaceholderId(){const e=Mt(this._squidDocId);if("object"==typeof e&&e.docId){const t=Mt(e.docId);if("object"==typeof t&&Object.keys(t).includes(qt))return!0}return!1}}class Vt{constructor(e,t={}){this.internalStateObserver=new d.BehaviorSubject(null),this.firstElement=null,this.isDestroyed=new d.BehaviorSubject(!1),this.snapshotSubject=new d.Subject,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,B(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe((0,d.switchAll)()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...t},this.goToFirstPage()}goToFirstPage(){this.onFirstPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).snapshots(this.paginateOptions.subscribe);this.snapshotSubject.next(e)}compareObjects(e,t){if(e===t||yt(e)&&yt(t))return 0;if(yt(e))return-1;if(yt(t))return 1;const r=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:i}of r){const r=_t(lt(e,n),lt(t,n));if(0!==r)return i?r:-r}return 0}async dataReceived(e){const t=e.map(e=>this.templateSnapshotEmitter.extractData(e));if(0===e.length)return void(this.onFirstPage?this.internalStateObserver.next({numBefore:0,numAfter:0,data:e,extractedData:t}):this.goToFirstPage());if(null===this.firstElement)if(null!==this.lastElement){const r=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-r-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const r=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,n=Math.max(0,e.length-r-this.paginateOptions.pageSize);r!==e.length?this.internalStateObserver.next({numBefore:r,numAfter:n,data:e,extractedData:t}):this.prevInternal({numBefore:r,numAfter:n,data:e,extractedData:t})}doNewQuery(e,t){if(this.onFirstPage=!1,t){const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder();e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?"<=":">=",value:lt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe((0,d.map)(e=>e.reverse())))}else{const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize);e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?">=":"<=",value:lt(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await(0,d.firstValueFrom)((0,d.race)(this.isDestroyed.pipe((0,d.filter)(Boolean),(0,d.map)(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe((0,d.filter)(e=>null!==e),(0,d.take)(1))))}internalStateToState(e){const{data:t,numBefore:r,numAfter:n,extractedData:i}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(i[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:n>0,hasPrev:r>0}}unsubscribe(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.internalStateObserver.complete(),this.snapshotSubject.complete()}prevInternal(e){const{numBefore:t,numAfter:r,extractedData:n}=e;this.firstElement=null,this.lastElement=n[t-1],this.internalStateObserver.next(null),this.doNewQuery(n[n.length-r-1],!0)}async prev(){return this.prevInternal(await this.waitForInternalState()),await this.waitForData()}async next(){const{numBefore:e,extractedData:t}=await this.waitForInternalState();return e+this.paginateOptions.pageSize<t.length&&(this.firstElement=t[e+this.paginateOptions.pageSize]),this.internalStateObserver.next(null),this.doNewQuery(t[e],!1),await this.waitForData()}async waitForData(){return this.internalStateToState(await this.waitForInternalState())}observeState(){return this.internalStateObserver.pipe((0,d.filter)(e=>null!==e),(0,d.map)(e=>this.internalStateToState(e)))}async first(){return await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.goToFirstPage(),await this.waitForData()}async refreshPage(){const{extractedData:e}=await this.waitForInternalState();return this.internalStateObserver.next(null),this.onFirstPage?this.goToFirstPage():this.doNewQuery(e[0],!1),await this.waitForData()}async last(){await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.navigatingToLastPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder().snapshots(this.paginateOptions.subscribe).pipe((0,d.map)(e=>e.reverse()));return this.snapshotSubject.next(e),await this.waitForData()}}Error;class Wt{constructor(e,t,r,n){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=r,this.documentIdentityService=n}getForDocument(e){const{collectionName:t,integrationId:r,docId:n}=Ft(e),i=Mt(n),o=this.get(t,r);for(const[e,t]of Object.entries(i))o.where(e,"==",t);return o}get(e,t){return new Kt(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService)}}class Ht{constructor(){this.containsEmptyInCondition=!1}eq(e,t){return this.where(e,"==",t)}neq(e,t){return this.where(e,"!=",t)}in(e,t){return this.where(e,"in",t)}nin(e,t){return this.where(e,"not in",t)}gt(e,t){return this.where(e,">",t)}gte(e,t){return this.where(e,">=",t)}lt(e,t){return this.where(e,"<",t)}lte(e,t){return this.where(e,"<=",t)}like(e,t,r){return this.throwIfInvalidLikePattern(t),this.where(e,r?"like_cs":"like",t)}notLike(e,t,r){return this.throwIfInvalidLikePattern(t),this.where(e,r?"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 zt{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return(0,d.firstValueFrom)(this.snapshots(!1).pipe((0,d.defaultIfEmpty)([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(R(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new zt(this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new Vt(this,e)}}class Kt extends Ht{constructor(e,t,r,n,i,o,s){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=r,this.localQueryManager=n,this.documentReferenceFactory=i,this.queryBuilderFactory=o,this.documentIdentityService=s,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}where(e,t,r){if(B(rt.includes(t),`Invalid operator: ${t}`),"in"===t||"not in"===t){const n=Array.isArray(r)?[...r]:[r];"in"===t&&0===n.length&&(this.containsEmptyInCondition=!0);for(const r of n)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:r});return this}return this.query.conditions.push({fieldName:e,operator:t,value:r}),this}limit(e){return function(e){var t;B(function(e){return"number"==typeof e}(t=e),()=>U("Limit needs to be a number","Not a number",t)),-1!==e&&(B(e>0,"query limit has to be greater than 0"),B(Math.floor(e)===e,"query limit has to be an integer"),B(e<=2e4,"Limit can be maximum 20000"))}(e),this.query.limit=e,this}getLimit(){return this.query.limit}limitBy(e,...t){const r=this.query.sortOrder.map(e=>e.fieldName);return B(gt(t.sort(),r.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 r={asc:t,fieldName:e};return function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var r,n,i,o;B((r=t,n=["fieldName","asc"],!Array.isArray(r)&&[...Object.keys(r)].every(e=>n.includes(e))),"Field sort should only contain a fieldName and asc"),B((i=t.asc,o="boolean",Array.isArray(i)?i.every(e=>typeof e===o):typeof i===o),"Asc needs to be boolean")}(r),B(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.sortOrder.push(r),this}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}mergeConditions(){const e=[],t=St(this.query.conditions.filter($t)||[],e=>e.fieldName);for(const r of Object.values(t)){const t=St(r,e=>e.operator);for(const[r,n]of Object.entries(t)){if("=="===r||"!="===r){e.push(...n);continue}const t=[...n];t.sort((e,t)=>_t(e.value,t.value)),">"===r||">="===r?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!$t(e)),...e]}getSortOrder(){return this.query.sortOrder}snapshot(){return(0,d.firstValueFrom)(this.snapshots(!1).pipe((0,d.defaultIfEmpty)([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new d.BehaviorSubject([]);const t=this.build();return this.querySubscriptionManager.processQuery(t,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(R(e=>e.map(e=>{B(1===Object.keys(e).length);const t=Bt(L(e[this.collectionName]).__docId__,this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)})))}changes(){let e,t=new Set;return this.snapshots().pipe((0,d.combineLatestWith)(this.documentIdentityService.observeChanges().pipe((0,d.switchMap)(t=>(Object.entries(t).forEach(([t,r])=>{!function(e,t,r){const n=e[t];void 0!==n&&(e[r]=n,delete e[t])}(e||{},t,r)}),d.NEVER)),(0,d.startWith)({}))),R(([r])=>{let n=[];const i=[],o=[];if(e){for(const o of r){const r=o.squidDocId,s=o.dataRef;if(t.has(s))delete e[r],t.delete(s);else if(e[r]){i.push(o);const n=e[r];delete e[r],t.delete(n)}else n.push(o)}for(const e of t)o.push(e)}else n=r;e={},t=new Set;for(const n of r){const r=n.dataRef;e[n.squidDocId]=r,t.add(r)}return new Jt(n,i,o)}))}get hash(){return Et(this.build())}dereference(){return new zt(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new Kt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService);return e.query=bt(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){return e.length?(this.query.conditions.push({fields:e}),this):this}flipSortOrder(){return this.query.sortOrder=this.query.sortOrder.map(e=>({...e,asc:!e.asc})),this.query.limitBy&&(this.query.limitBy.reverseSort=!this.query.limitBy.reverseSort),this}serialize(){return{type:"simple",dereference:!1,query:this.build()}}extractData(e){return e.dataRef}paginate(e){return new Vt(this,e)}}class Jt{constructor(e,t,r){this.inserts=e,this.updates=t,this.deletes=r}}class Yt extends Ht{constructor(e,t,r,n,i,o,s,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=r,this.documentReferenceFactory=n,this.queryBuilderFactory=i,this.rootAlias=o,this.latestAlias=s,this.leftToRight=a,this.joins=c,this.joinConditions=u,this.queryBuilder=l}where(e,t,r){return this.queryBuilder.where(e,t,r),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}sortBy(e,t=!0){return this.queryBuilder.sortBy(e,t),this}join(e,t,r,n){const i=n?.leftAlias??this.latestAlias,o={...r,leftAlias:i,isInner:n?.isInner??!1},s={...this.leftToRight,[t]:[]};return s[i].push(t),new Yt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,t,s,{...this.joins,[t]:e.build()},{...this.joinConditions,[t]:o},this.queryBuilder)}snapshot(){return(0,d.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new d.BehaviorSubject([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,bt(this.joins),bt(this.joinConditions),e,!1).pipe(R(e=>e.map(e=>{const t={};for(const[r,n]of Object.entries(e)){const e=r===this.rootAlias?this.collectionName:this.joins[r].collectionName,i=r===this.rootAlias?this.integrationId:this.joins[r].integrationId,o=n?Bt(n.__docId__,e,i):void 0;t[r]=o?this.documentReferenceFactory.create(o,this.queryBuilderFactory):void 0}return t})))}peek(){throw new Error("peek is not currently supported for join queries")}grouped(){return new er(this)}dereference(){return new Zt(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Yt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,bt(this.leftToRight),bt(this.joins),bt(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 Vt(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class Zt{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return(0,d.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(R(e=>e.map(e=>function(e,t){const r={},n=Object.keys(e);for(const i of n){const n=e[i];r[i]=t(n)}return r}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new Zt(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 Vt(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class Xt{constructor(e){this.groupedJoin=e}snapshot(){return(0,d.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(R(e=>e.map(e=>this.dereference(e,this.groupedJoin.joinQueryBuilder.rootAlias))))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(e,t){const r=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(r.length){const n={[t]:e[t].data};for(const t of r)n[t]=e[t].map(e=>this.dereference(e,t));return n}return e.data}getSortOrders(){return this.groupedJoin.getSortOrders()}clone(){return new Xt(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 Vt(this,e)}}class er{constructor(e){this.joinQueryBuilder=e}snapshot(){return(0,d.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(R(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new Xt(this)}groupData(e,t){const r=St(e,e=>e[t]?.squidDocId);return Object.values(r).filter(e=>void 0!==e[0][t]).map(e=>{const r=this.joinQueryBuilder.leftToRight[t],n=e[0][t];if(0===r.length)return n;const i={[t]:n};for(const t of r)i[t]=this.groupData(e,t);return i})}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new er(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 Vt(this,e)}}class tr{constructor(e,t,r,n,i,o){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=r,this.queryBuilderFactory=n,this.querySubscriptionManager=i,this.dataManager=o,this.refId=V()}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!==We)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={[qt]:V()};else e=e&&"string"!=typeof e?{__id:It(e)}:{__id:e||V()};const t=Bt(It(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 r of e)await this.doc(r.id).insert(r.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const r of e)r instanceof Gt?await r.delete(t):await this.doc(r).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new Yt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new rr(...e)}}class rr{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 r=this.snapshotEmitters[0].getSortOrders();for(const e of this.snapshotEmitters){const t=e.getSortOrders();if(t.length!==r.length)throw new Error("All the queries must have the same sort order");for(let e=0;e<r.length;e++)if(t[e].fieldName!==r[e].fieldName||t[e].asc!==r[e].asc)throw new Error("All the queries must have the same sort order")}}snapshot(){return(0,d.firstValueFrom)(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")}or(e,...t){return(0,d.combineLatest)([...t]).pipe((0,d.map)(t=>{const r=new Set,n=t.flat(),i=[];for(const e of n)r.has(this.extractData(e))||(r.add(this.extractData(e)),i.push(e));return i.sort((t,r)=>{for(const{fieldName:n,asc:i}of e){const e=lt(this.extractData(t),n),o=lt(this.extractData(r),n);if(!Lt(e,o,"=="))return Lt(o,e,"<")?i?-1:1:i?1:-1}return 0}).slice(0,this.getLimit())}))}clone(){return new rr(...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 Vt(this,e)}}class nr{constructor(e,t,r,n){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=r,this.dataManager=n,this.collections=new Map}get(e,t){let r=this.collections.get(t);r||(r=new Map,this.collections.set(t,r));let n=r.get(e);return n||(n=new tr(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),r.set(e,n)),n}}class ir{constructor(e,t){this.clientIdService=e,this.socketManager=t,this.isConnected=!1,this.socketManager.observeConnectionReady().subscribe(e=>{this.isConnected=e})}get connected(){return this.isConnected}get clientId(){return this.clientIdService.getClientId()}observeConnected(){return this.socketManager.observeConnectionReady()}}var or=r(150);function sr(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?bt(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function ar(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function cr(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(B("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const r=bt(e);t=bt(t);for(const[e]of ar(r)){const n=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&n>t.split(".").length)&&delete r.properties[e]}for(const[e,n]of ar(t))r.properties[e]=ur([...r.properties[e]||[],...n]);return r}(e,t);const r=bt(e);for(const[e,n]of ar(t)){const t=n;for(const n of t){const t=sr(lt(r.properties,e),n);void 0===t?pt(r.properties,e):ht(r.properties,e,t)}}return r}function ur(e){let t=0;for(;t+1<e.length;){const r=lr(e[t],e[t+1]);r?e.splice(t,2,r):++t}return e}function lr(e,t){return"removeProperty"===t.type||"update"===t.type?t:"applyNumericFn"===t.type?(B("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type?(B("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 dr(e){const t={};for(const r of e){const e=`${r.squidDocIdObj.integrationId}/${r.squidDocIdObj.collectionName}/${r.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(r)}const r=[];for(const e in t){const n=t[e].reduce((e,t)=>L(cr(e,t),"Merge result cannot be null"));r.push(n)}return r}const hr="dataManager_runInTransaction";class pr{constructor(e,t,r,n,i,o,s,a,c){this.documentStore=e,this.mutationSender=t,this.socketManager=r,this.querySubscriptionManager=n,this.queryBuilderFactory=i,this.lockManager=o,this.destructManager=s,this.documentIdentityService=a,this.querySender=c,this.docIdToLocalTimestamp=new Map,this.batchClientRequestIds=new Set,this.docIdToServerTimestamp=new Map,this.pendingIncomingUpdates=new Map,this.pendingOutgoingMutations=new Map,this.pendingOutgoingMutationsChanged=new d.Subject,this.outgoingMutationsEmpty=new d.BehaviorSubject(!0),this.knownDirtyDocs=new Set,this.failedDocsToResync=[],this.refreshDocIdToTimestamp=new Map,this.handleIncomingMessagesForTests=!0,this.destructManager.onDestruct(()=>{this.destruct()}),this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.handleNotifications(),this.startDeleteExpiredTimestampsJob(),this.handleOrphanDocs(),this.outgoingMutationsEmpty.subscribe(e=>{this.querySender.safeToSendQueriesToServer.next(e)})}getProperties(e){return this.documentStore.getDocumentOrUndefined(e)}isDirty(e){if(this.knownDirtyDocs.has(e))return!0;if(this.pendingOutgoingMutations.get(e)?.length)return!0;const t=this.docIdToServerTimestamp.get(e),r=t&&!t.expireTimestamp?t.timestamp:void 0,n=this.docIdToLocalTimestamp.get(e);return!((!n||r)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&n===r)}async runInTransaction(e,t){if(t)return B(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(hr)?this.lockManager.lockSync(hr):await this.lockManager.lock(hr);let r=fr;const n=()=>r!==fr;return new Promise(async(t,i)=>{try{let o;this.currentTransactionId=V();try{o=await e(this.currentTransactionId)}catch(e){r=e}finally{this.finishTransaction(n()?void 0:{resolve:()=>t(o),reject:i})}}catch(e){r=n()?r:e}finally{try{this.lockManager.release(hr)}catch(e){r=n()?r:e}}n()&&i(r)})}async applyOutgoingMutation(e,t){const r=Bt(e.squidDocIdObj);this.knownDirtyDocs.add(r),t||this.lockManager.canGetLock(hr)||(await this.lockManager.lock(hr),this.lockManager.release(hr)),this.knownDirtyDocs.delete(r);const n=this.pendingOutgoingMutations.get(r)?.slice(-1)[0];if(n&&!n.sentToServer)n.mutation=L(dr([n.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},n=this.pendingOutgoingMutations.get(r)||[];n.push(t),this.pendingOutgoingMutations.set(r,n),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(r),n="delete"===e.type?void 0:"update"===e.type?function(e,t){if(!e)return;const r={...e},n=ar(t);for(const[e,t]of n){const n=t;for(const t of n){const n=sr(lt(r,e),t);void 0===n?pt(r,e):ht(r,e,n)}}return r}(t,e):{...e.properties};this.updateDocumentFromSnapshot(r,n)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(r,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(r,n).forEach(e=>this.batchClientRequestIds.add(e)))},t)}async runInTransactionSync(e,t){if(t)return B(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(hr);try{this.currentTransactionId=V();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(hr)}}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((0,d.filter)(e=>"mutations"===e.type),R(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,d.filter)(Boolean),(0,d.take)(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,d.filter)(Boolean),(0,d.take)(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t=e.reduce((e,t)=>this.querySubscriptionManager.hasOngoingQuery(t.clientRequestId)?(e[t.squidDocId]={properties:t.doc,timestamp:t.mutationTimestamp},e):e,{});this.applyIncomingUpdates(t)}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId),r={};for(const n of e.docs){const e=Bt(n.__docId__,t.collectionName,t.integrationId);r[e]={properties:n,timestamp:n.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(r,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)}).then()}applyIncomingUpdates(e,t){let r=!1;const n=new Set,i=new Set;for(const[t,o]of Object.entries(e)){const e=this.pendingIncomingUpdates.get(t),s=this.docIdToServerTimestamp.get(t);e&&e.timestamp>o.timestamp?r=!0:s&&s.timestamp>o.timestamp?i.add(t):(this.pendingIncomingUpdates.set(t,o),n.add(t))}return this.runInTransactionSync(()=>{for(const e of n)this.maybeApplyIncomingUpdate(e);for(const e of i)this.refreshQueryMapping(e)},t).then(),r}maybeApplyIncomingUpdate(e){const t=this.pendingIncomingUpdates.get(e);if(!t)return;const r=this.pendingOutgoingMutations.get(e);r&&r.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)}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)}updateDocumentFromSnapshot(e,t){const r=this.documentStore.getDocumentOrUndefined(e);return!(!r&&!t||r===t)&&((!r||!t||It({...t,__ts__:void 0})!==It(r))&&(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).then()}async sendAllUnsentOutgoingMutations(e){const t=this.groupOutgoingMutationsByIntegrationId();try{await or.PromisePool.for(t).withConcurrency(t.length||1).useCorrespondingResults().handleError(e=>{throw e}).process(async([e,t])=>{await this.sendMutationsForIntegration([...t],e)}),this.pendingOutgoingMutations.size||this.outgoingMutationsEmpty.next(!0),await this.refreshUpdatedDocuments(),this.hasPendingSentMutations()?(await(0,d.firstValueFrom)(this.pendingOutgoingMutationsChanged.pipe((0,d.filter)(()=>!this.hasPendingSentMutations()))),e?.resolve()):e?.resolve()}catch(t){this.pendingOutgoingMutations.size||(this.outgoingMutationsEmpty.next(!0),await this.resyncFailedUpdates()),e?.reject(t)}}async sendMutationsForIntegration(e,t){try{const{timestamp:r,idResolutionMap:n={},refreshList:i=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(n),i.forEach(e=>{this.refreshDocIdToTimestamp.set(n[e]||e,r)});for(const t of e){let e=this.removeOutgoingMutation(t);n[e]&&(e=n[e]),this.acknowledgeDocument(e,r),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=Bt(e.mutation.squidDocIdObj),r=L(this.pendingOutgoingMutations.get(t));return r.splice(r.indexOf(e),1),r.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}=Ft(t);this.setExpiration(t,!0);try{const r=e.includes(qt)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(L(r.length<=1,"Got more than one doc for the same id:"+t),!r.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,r]of this.refreshDocIdToTimestamp.entries()){const n=this.docIdToServerTimestamp.get(t)?.timestamp;n&&n>r||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 r=t[t.length-1];if(r&&!r.sentToServer){const t=r.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(r),r.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,r=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,r)}setExpiration(e,t){const r=this.docIdToServerTimestamp.get(e);r&&(r.expireTimestamp=t?Date.now()+2e4:void 0)}forgetDocument(e,t){this.docIdToLocalTimestamp.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const r=Bt(t.mutation.squidDocIdObj),n=e[r];n&&(t.mutation.squidDocIdObj=Ft(n))})}),Object.entries(e).forEach(([e,t])=>{ft(this.pendingOutgoingMutations,e,t),ft(this.docIdToLocalTimestamp,e,t),ft(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 fr=Symbol("undefined");class yr{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new d.BehaviorSubject(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe((0,d.filter)(Boolean),R(()=>{}))}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 gr{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,d.filter)(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,d.filter)(e=>"lockReleased"===e.type)),this.lockWaitForConnectionThreshold=2e3,t.onPreDestruct(()=>{this.releaseAllLocks()}),this.socketManager.observeConnectionReady().subscribe(e=>{e||this.releaseAllLocks()}),this.releaseLockMessagesFromServer.subscribe(e=>{const t=this.ongoingLocks[e.payload.clientRequestId];void 0!==t&&t.release()})}async lock(e,t=2e3){if(this.socketManager.notifyWebSocketIsNeeded(),!await(0,d.firstValueFrom)((0,d.race)((0,d.timer)(this.lockWaitForConnectionThreshold).pipe(R(()=>!1)),this.socketManager.observeConnectionReady().pipe((0,d.filter)(Boolean)),this.destructManager.observeIsDestructing())))return Promise.reject("CLIENT_NOT_CONNECTED");const r=V(),n={type:"acquireLock",payload:{mutex:e,timeoutMillis:t,clientRequestId:r}};this.socketManager.sendMessage(n);const i=await(0,d.firstValueFrom)((0,d.race)((0,d.timer)(t+4e3).pipe((0,d.take)(1),R(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0}}))),this.acquireLockMessagesFromServer.pipe((0,d.filter)(e=>e.payload.clientRequestId===r))));if(this.destructManager.isDestructing)throw new Error("Destructing");if(!i.payload.lockId)throw new Error(`Failed to acquire lock: ${i.payload.error}`);const o=i.payload.lockId,s=new vr(o,r,this.ongoingLocks,this.socketManager);return this.ongoingLocks[o]=s,s}releaseAllLocks(){for(const[e,t]of Object.entries(this.ongoingLocks))t.release(),delete this.ongoingLocks[e]}}class vr{constructor(e,t,r,n){this.lockId=e,this.clientRequestId=t,this.ongoingLocks=r,this.socketManager=n,this.released=!1,this.onReleaseSubject=new d.Subject}release(){if(this.released)return;this.released=!0,delete this.ongoingLocks[this.lockId];const e={type:"releaseLock",payload:{lockId:this.lockId,clientRequestId:this.clientRequestId}};this.socketManager.sendMessage(e),this.onReleaseSubject.next()}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}class br{constructor(e,t){this.documentStore=e,this.destructManager=t,this.changeNotifier=new d.BehaviorSubject({}),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 mr{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t){let r=this.documents.get(e);if(r)return r;r=new Gt(e,L(this.dataManager,"dataManager not found"),t);const{integrationId:n,collectionName:i}=Ft(e);this.documents.set(e,r);const o=this.getCollectionKey(n,i),s=this.documentsForCollection.get(o)||[];return this.documentsForCollection.set(o,s.concat(r)),r}setDataManager(e){this.dataManager=e}getDocumentsForCollection(e,t){const r=this.getCollectionKey(e,t);return(this.documentsForCollection.get(r)||[]).filter(e=>e.hasData)}migrateDocIds(e){for(const[,t]of this.documents)t.migrateDocIds(e);Object.entries(e).forEach(([e,t])=>{const r=Ft(e),n=Ft(t);ft(this.documents,r.docId,n.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class _r{constructor(){this.squidDocIdToDoc=new Map}saveDocument(e,t){const r=this.squidDocIdToDoc.get(e);if(void 0===r&&!t)return;if(void 0!==r){if(t){const r=bt(t),n=this.removeInternalProperties(r);return this.squidDocIdToDoc.set(e,n),n}return void this.squidDocIdToDoc.delete(e)}const n=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,n),t}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocument(e){return L(this.getDocumentOrUndefined(e))}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}compareSquidDocs(e,t,r){for(const{fieldName:n,asc:i}of r){const r=_t(lt(e,n),lt(t,n));if(0!==r)return i?r:-r}return 0}group(e,t){return Object.values(St(e,e=>It(t.map(t=>lt(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const r=[...e].map(e=>this.squidDocIdToDoc.get(e)).filter(q),{sortOrder:n,limitBy:i}=t,o=r.sort((e,t)=>this.compareSquidDocs(e,t,n)),s=t.limit<0?2e3:t.limit;if(!i)return o.slice(0,s);const{limit:a,fields:c,reverseSort:u}=i,l=this.group(o,c);let d;return d=u?l.map(e=>e.slice(-a)):l.map(e=>e.slice(0,a)),d.flat().slice(0,s)}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}migrateDocId(e,t){const r=this.getDocumentOrUndefined(e);if(!r)return;ft(this.squidDocIdToDoc,e,t);const n=Ft(t),i=Mt(n.docId);this.saveDocument(t,{...r,...i,__docId__:n.docId})}}class Sr{constructor(e){this.rpcManager=e}async extractDataFromDocumentFile(e,t){t||(t={});const r={options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentFile",r,[e],"file")}async extractDataFromDocumentUrl(e,t){t||(t={});const r={url:e,options:t};return await this.rpcManager.post("extraction/extractDataFromDocumentUrl",r)}async createPdf(e){return await this.rpcManager.post("extraction/createPdf",e)}}class wr{constructor(e,t,r){this.socketManager=e,this.rpcManager=t,this.clientIdService=r,this.isListening=!1,this.listeners={},this.clientIdService.observeClientId().pipe((0,d.distinctUntilChanged)(),(0,d.skip)(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Pt.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e})})}async getJob(e){return(await this.rpcManager.post("job/getJob",{jobId:e})).job}async awaitJob(e){this.maybeListenToJobs(),await this.socketManager.awaitConnectionReady();const t=this.listeners[e]||new d.ReplaySubject(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}),(0,d.firstValueFrom)(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe((0,d.filter)(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,r=t.id,n=this.listeners[r];n&&("completed"===t.status?n.next(t.result):"failed"===t.status?n.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",r),delete this.listeners[r])}))}}class Ir{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=dr(e),n=r.map(e=>`sendMutation_${Bt(e.squidDocIdObj)}`);await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:r,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Pt.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class Or{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class Mr{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.observeNotifications().pipe((0,d.filter)(e=>"userNotification"===e.type),(0,d.map)(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 Er={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class Tr{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},r=Object.keys(t).filter(e=>!kr.test(e)||e.length>=Ar);B(0===r.length,()=>`Tag name is not allowed: ${r.join(",")}`),this.isReporting=!0;const n={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},i=this.rpcManager.post("/observability/metrics",{metrics:[n]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==i),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(i)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...Er,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const r=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:r,noDataBehavior:n}=e,i=void 0===e.fillValue?null:e.fillValue,o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:r,pointIntervalAlignment:n}){if("align-by-start-time"===n)return e;const i=t-e;let o=t-Math.floor(i/r)*r;return o>e&&(o-=r),o}(e),s=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:r,pointIntervalAlignment:n}){if("align-by-end-time"===n)return t-r;const i=t-e;let o=e+Math.floor(i/r)*r;return o>=t&&(o-=r),o}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const r=[];for(let t=0;t<e.groupByTags.length;t++){const n=e.groupByTags[t],i=a[n]?.[0]||"";r.push(i)}t.push({tagValues:r,points:[]})}else"return-result-group-with-default-values"===n&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[r,n]of Object.entries(a)){const i=e.groupByTags.indexOf(r);if(!(i<0))for(let e=0;e<t.length;e++){const r=t[e],o=new Set(n);for(let e=0;e<t.length;e++){const n=t[e];r.tagValues.every((e,t)=>t===i||e===n.tagValues[t])&&o.delete(n.tagValues[i])}if(0!==o.size)for(const e of o){const n={tagValues:[...r.tagValues],points:[]};n.tagValues[i]=e,t.push(n)}}}for(const n of t){if(0!==n.points.length){const e=n.points[0][0],t=n.points[n.points.length-1][0];B(e>=o,()=>`Invalid first point time: ${e}`),B(t<=s,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:i,u=Array.isArray(e.fn)?e.fn.map(c):[i];for(let e=o;e<=s;e+=r){const r=n.points[a];r?r[0]===e?(t.push(r),a++):(B(r[0]>e,()=>`Result point has invalid time: ${r[0]}`),t.push([e,...u])):t.push([e,...u])}n.points=t}}(t,r.resultGroups),r}}const kr=/^[a-zA-Z0-9_-]+$/,Ar=1e3;class jr{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const r={authCode:e,personalStorageConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("personalStorage/saveAuthCode",r)}async getAccessToken(e){const t={personalStorageConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("personalStorage/getAccessToken",t)}async indexDocumentOrFolder(e,t,r,n){const i={documentOrFolderId:e,metadata:n,personalStorageConfig:{identifier:t,integrationId:this.integrationId},agentId:r};await this.rpcManager.post("personalStorage/indexDocumentOrFolder",i)}async listIndexedDocuments(e,t,r){const n={personalStorageConfig:{identifier:e,integrationId:this.integrationId},agentId:t,type:r};return(await this.rpcManager.post("personalStorage/listIndexedDocuments",n)).documents}async unindexDocument(e,t,r){const n={documentId:e,personalStorageConfig:{identifier:t,integrationId:this.integrationId},agentId:r};await this.rpcManager.post("personalStorage/unindexDocument",n)}}async function Cr(e,t,r=500){const n=Date.now(),i=e.paginate({pageSize:r,subscribe:!1});let o=0,s=await i.waitForData();for(;;){for(const e of s.data)o++,await t(e.data);if(!s.hasNext)break;s=await i.next()}return{count:o,time:Date.now()-n}}function xr(e,t){switch(t.type){case"simple":return function(e,t){const{query:r,dereference:n}=t,{collectionName:i,integrationId:o}=r;let s=e.collection(i,o).query();return s=Pr(s,r),n?s.dereference():s}(e,t);case"join":return function(e,t){const{root:r,joins:n,joinConditions:i,dereference:o,grouped:s}=t,{collectionName:a,integrationId:c}=r.query;let u=e.collection(a,c).joinQuery(r.alias);return u=Pr(u,r.query),Object.entries(n).map(([t,r])=>{const{collectionName:n,integrationId:o}=r,{left:s,right:a,leftAlias:c}=i[t];let l=e.collection(n,o).query();l=Pr(l,r),u=u.join(l,t,{left:s,right:a},{leftAlias:c})}),o&&s?u.grouped().dereference():o?u.dereference():s?u.grouped():u}(e,t);case"merged":return function(e,t){const{queries:r}=t,{collectionName:n,integrationId:i}=Dr(r[0]),o=r.map(t=>xr(e,t));return e.collection(n,i).or(...o)}(e,t)}}function Pr(e,t){const{conditions:r,limit:n,sortOrder:i}=t;for(const t of r){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:r,operator:n,value:i}=t;e.where(r,n,i)}e.limit(n);for(const{fieldName:t,asc:r}of i)e.sortBy(t,r);return e}function Dr(e){switch(e.type){case"simple":{const{collectionName:t,integrationId:r}=e.query;return{collectionName:t,integrationId:r}}case"join":{const{collectionName:t,integrationId:r}=e.root.query;return{collectionName:t,integrationId:r}}case"merged":return Dr(e.queries[0])}}const Nr={"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)=>Rr(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>Rr(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>Rr(e,t)&&Fr(t),"like_cs:like_cs":(e,t)=>Rr(e,t),"like:not like":(e,t)=>!qr(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!qr(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!qr(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!qr(e,t),"not like:like":(e,t)=>Lr(e,t),"not like_cs:like":(e,t)=>Lr(e,t),"not like:like_cs":(e,t)=>Lr(e,t),"not like_cs:like_cs":(e,t)=>Lr(e,t),"not like:not like":(e,t)=>Rr(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>Rr(t,e)&&Fr(e),"not like:not like_cs":(e,t)=>Rr(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>Rr(t,e),"in:like":(e,t)=>e.every(e=>Lt(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Lt(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>Lt(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>Lt(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&&Br(e)||Qr(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Br(e)||Qr(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Br(t)||Qr(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Br(t)||Qr(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=>Lt(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Lt(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Lt(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Lt(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 Rr(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return Br(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?Rr(e,t,r+1,n+1)||Rr(e,t,r+1,n):"%"!==i&&("%"===o?Rr(e,t,r,n+1)||Rr(e,t,r+1,n):(i===o||"_"===o)&&Rr(e,t,r+1,n+1))}function qr(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return Br(t.substring(n));if(n>=t.length)return Br(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?qr(e,t,r+1,n+1)||qr(e,t,r,n+1)||qr(e,t,r+1,n):"%"===i||"%"===o?qr(e,t,r,n+1)||qr(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&qr(e,t,r+1,n+1)}function Fr(e){return!/[a-zA-Z]/.test(e)}function Br(e){return e.split("").every(e=>"%"===e)}function Lr(e,t){return e.length>0&&Br(e)||t.length>0&&Br(t)||Qr(e)&&0===t.length}function Qr(e){let t=!1,r=!1;for(const n of e)switch(n){case"%":t=!0;break;case"_":if(r)return!1;r=!0;break;default:return!1}return t&&r}class Ur{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter($t))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){return!e.find((e,t)=>!gt(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,r){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:r})}isSubqueryOfCondition(e){return!!this.parsedConditions.filter(t=>t.fieldName===e.fieldName).find(t=>this.evaluateSubset(t,e))}isSubqueryOfConditions(e){return this.parseConditions(e).every(e=>this.isSubqueryOfCondition(e))}isSubqueryOfQuery(e){if(e.collectionName!==this.collectionName||e.integrationId!==this.integrationId)return!1;const t=e.conditions.filter($t),r=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),i=-1===e.limit||this.limit>-1&&this.limit<e.limit;return r&&n&&i}getConditionsFor(...e){return this.parsedConditions.filter(t=>e.includes(t.fieldName))}getConditionsForField(e){return this.parsedConditions.filter(t=>t.fieldName===e)}documentMatchesQuery(e){for(const t of this.parsedConditions){const r=t.fieldName,n=t.operator,i=lt(e,r);if("in"===n){if(t.value.includes(i))continue;return!1}if("not in"!==n){if(!Lt(t.value,i,n))return!1}else if(t.value.includes(i))return!1}return!0}evaluateSubset(e,t){const{operator:r,value:n}=e,{operator:i,value:o}=this.parseConditions([t])[0],s=Nr[`${r}:${i}`];return!!s&&s(n,o)}parseConditions(e){const t=[],r=new Map,n=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":r.set(e.fieldName,(r.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),r.forEach((e,r)=>{t.push({fieldName:r,operator:"in",value:e})}),n.forEach((e,r)=>{t.push({fieldName:r,operator:"not in",value:e})}),t}}class $r{constructor(e,t,r){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=r}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:r}=e,n=new Ur(e),i=this.documentReferenceFactory.getDocumentsForCollection(t,r).filter(e=>n.documentMatchesQuery(e.data)),o={};return i.forEach(e=>{o[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(o)),e).map(e=>o[Bt(e.__docId__,r,t)])}}function Gr(e,t){return p(function(r,n){var i=0;r.subscribe(D(n,function(r){return e.call(t,r,i++)&&n.next(r)}))})}class Vr{constructor(e,t){this.rpcManager=e,this.destructManager=t,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new d.BehaviorSubject(!0),this.inflightQueriesCount=new d.BehaviorSubject(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new d.Subject,r=(0,d.firstValueFrom)(t);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:t}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),r):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.safeToSendQueriesToServer.pipe(Gr(Boolean),(0,d.take)(1)).subscribe(()=>{this.processQueryBatch()})},0),r)}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()),r=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const r=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,i=r.errors[e],o=r.results[e];i?n.error(i):n.next(o)}}catch(e){r.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}async waitForAllQueriesToFinish(){return(0,d.firstValueFrom)(this.inflightQueriesCount.pipe(Gr(e=>0===e))).then(()=>{})}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Wr={37:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.windowTime=void 0;var n=r(6808),i=r(2326),o=r(9879),s=r(5212),a=r(7214),c=r(4830),u=r(6404),l=r(8619);t.windowTime=function(e){for(var t,r,d=[],h=1;h<arguments.length;h++)d[h-1]=arguments[h];var p=null!==(t=u.popScheduler(d))&&void 0!==t?t:i.asyncScheduler,f=null!==(r=d[0])&&void 0!==r?r:null,y=d[1]||1/0;return s.operate(function(t,r){var i=[],s=!1,u=function(e){var t=e.window,r=e.subs;t.complete(),r.unsubscribe(),c.arrRemove(i,e),s&&d()},d=function(){if(i){var t=new o.Subscription;r.add(t);var s=new n.Subject,a={window:s,subs:t,seen:0};i.push(a),r.next(s.asObservable()),l.executeSchedule(t,p,function(){return u(a)},e)}};null!==f&&f>=0?l.executeSchedule(r,p,d,f,!0):s=!0,d();var h=function(e){return i.slice().forEach(e)},g=function(e){h(function(t){var r=t.window;return e(r)}),e(r),r.unsubscribe()};return t.subscribe(a.createOperatorSubscriber(r,function(e){h(function(t){t.window.next(e),y<=++t.seen&&u(t)})},function(){return g(function(e){return e.complete()})},function(e){return g(function(t){return t.error(e)})})),function(){i=null}})}},96:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.max=void 0;var n=r(2070),i=r(281);t.max=function(e){return n.reduce(i.isFunction(e)?function(t,r){return e(t,r)>0?t:r}:function(e,t){return e>t?e:t})}},131:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scheduled=void 0;var n=r(5650),i=r(4530),o=r(4950),s=r(6805),a=r(7873),c=r(629),u=r(7552),l=r(4975),d=r(2187),h=r(8263),p=r(6297),f=r(5462),y=r(380);t.scheduled=function(e,t){if(null!=e){if(c.isInteropObservable(e))return n.scheduleObservable(e,t);if(l.isArrayLike(e))return o.scheduleArray(e,t);if(u.isPromise(e))return i.schedulePromise(e,t);if(h.isAsyncIterable(e))return a.scheduleAsyncIterable(e,t);if(d.isIterable(e))return s.scheduleIterable(e,t);if(f.isReadableStreamLike(e))return y.scheduleReadableStreamLike(e,t)}throw p.createInvalidObservableTypeError(e)}},142:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.min=void 0;var n=r(2070),i=r(281);t.min=function(e){return n.reduce(i.isFunction(e)?function(t,r){return e(t,r)<0?t:r}:function(e,t){return e<t?e:t})}},201:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatAll=void 0;var n=r(8087);t.concatAll=function(){return n.mergeAll(1)}},281:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isFunction=void 0,t.isFunction=function(e){return"function"==typeof e}},380:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleReadableStreamLike=void 0;var n=r(7873),i=r(5462);t.scheduleReadableStreamLike=function(e,t){return n.scheduleAsyncIterable(i.readableStreamLikeToAsyncGenerator(e),t)}},381:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.ReplaySubject=void 0;var o=r(6808),s=r(3275),a=function(e){function t(t,r,n){void 0===t&&(t=1/0),void 0===r&&(r=1/0),void 0===n&&(n=s.dateTimestampProvider);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=r,i._timestampProvider=n,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=r===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,r),i}return i(t,e),t.prototype.next=function(t){var r=this,n=r.isStopped,i=r._buffer,o=r._infiniteTimeWindow,s=r._timestampProvider,a=r._windowTime;n||(i.push(t),!o&&i.push(s.now()+a)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),r=this._infiniteTimeWindow,n=this._buffer.slice(),i=0;i<n.length&&!e.closed;i+=r?1:2)e.next(n[i]);return this._checkFinalizedStatuses(e),t},t.prototype._trimBuffer=function(){var e=this,t=e._bufferSize,r=e._timestampProvider,n=e._buffer,i=e._infiniteTimeWindow,o=(i?1:2)*t;if(t<1/0&&o<n.length&&n.splice(0,n.length-o),!i){for(var s=r.now(),a=0,c=1;c<n.length&&n[c]<=s;c+=2)a=c;a&&n.splice(0,a+1)}},t}(o.Subject);t.ReplaySubject=a},439:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.argsArgArrayOrObject=void 0;var r=Array.isArray,n=Object.getPrototypeOf,i=Object.prototype,o=Object.keys;t.argsArgArrayOrObject=function(e){if(1===e.length){var t=e[0];if(r(t))return{args:t,keys:null};if((a=t)&&"object"==typeof a&&n(a)===i){var s=o(t);return{args:s.map(function(e){return t[e]}),keys:s}}}var a;return{args:e,keys:null}}},597:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timeoutWith=void 0;var n=r(2326),i=r(5345),o=r(1713);t.timeoutWith=function(e,t,r){var s,a,c;if(r=null!=r?r:n.async,i.isValidDate(e)?s=e:"number"==typeof e&&(a=e),!t)throw new TypeError("No observable provided to switch to");if(c=function(){return t},null==s&&null==a)throw new TypeError("No timeout provided.");return o.timeout({first:s,each:a,scheduler:r,with:c})}},598:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.takeWhile=void 0;var n=r(5212),i=r(7214);t.takeWhile=function(e,t){return void 0===t&&(t=!1),n.operate(function(r,n){var o=0;r.subscribe(i.createOperatorSubscriber(n,function(r){var i=e(r,o++);(i||t)&&n.next(r),!i&&n.complete()}))})}},629:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isInteropObservable=void 0;var n=r(2884),i=r(281);t.isInteropObservable=function(e){return i.isFunction(e[n.observable])}},632:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.throwIfEmpty=void 0;var n=r(9328),i=r(5212),o=r(7214);function s(){return new n.EmptyError}t.throwIfEmpty=function(e){return void 0===e&&(e=s),i.operate(function(t,r){var n=!1;t.subscribe(o.createOperatorSubscriber(r,function(e){n=!0,r.next(e)},function(){return n?r.complete():r.error(e())}))})}},680:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.switchMap=void 0;var n=r(9724),i=r(5212),o=r(7214);t.switchMap=function(e,t){return i.operate(function(r,i){var s=null,a=0,c=!1,u=function(){return c&&!s&&i.complete()};r.subscribe(o.createOperatorSubscriber(i,function(r){null==s||s.unsubscribe();var c=0,l=a++;n.innerFrom(e(r,l)).subscribe(s=o.createOperatorSubscriber(i,function(e){return i.next(t?t(r,e,l,c++):e)},function(){s=null,u()}))},function(){c=!0,u()}))})}},706:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.buffer=void 0;var n=r(5212),i=r(5717),o=r(7214),s=r(9724);t.buffer=function(e){return n.operate(function(t,r){var n=[];return t.subscribe(o.createOperatorSubscriber(r,function(e){return n.push(e)},function(){r.next(n),r.complete()})),s.innerFrom(e).subscribe(o.createOperatorSubscriber(r,function(){var e=n;n=[],r.next(e)},i.noop)),function(){n=null}})}},719:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.joinAllInternals=void 0;var n=r(7699),i=r(3916),o=r(1898),s=r(7478),a=r(3484);t.joinAllInternals=function(e,t){return o.pipe(a.toArray(),s.mergeMap(function(t){return e(t)}),t?i.mapOneOrManyArgs(t):n.identity)}},761:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.switchMapTo=void 0;var n=r(680),i=r(281);t.switchMapTo=function(e,t){return i.isFunction(t)?n.switchMap(function(){return e},t):n.switchMap(function(){return e})}},839:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ObjectUnsubscribedError=void 0;var n=r(9619);t.ObjectUnsubscribedError=n.createErrorClass(function(e){return function(){e(this),this.name="ObjectUnsubscribedError",this.message="object unsubscribed"}})},1071:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.fromSubscribable=void 0;var n=r(8051);t.fromSubscribable=function(e){return new n.Observable(function(t){return e.subscribe(t)})}},1245:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.observeNotification=t.Notification=t.NotificationKind=void 0;var n,i=r(4885),o=r(1587),s=r(6680),a=r(281);(n=t.NotificationKind||(t.NotificationKind={})).NEXT="N",n.ERROR="E",n.COMPLETE="C";var c=function(){function e(e,t,r){this.kind=e,this.value=t,this.error=r,this.hasValue="N"===e}return e.prototype.observe=function(e){return u(this,e)},e.prototype.do=function(e,t,r){var n=this,i=n.kind,o=n.value,s=n.error;return"N"===i?null==e?void 0:e(o):"E"===i?null==t?void 0:t(s):null==r?void 0:r()},e.prototype.accept=function(e,t,r){var n;return a.isFunction(null===(n=e)||void 0===n?void 0:n.next)?this.observe(e):this.do(e,t,r)},e.prototype.toObservable=function(){var e=this,t=e.kind,r=e.value,n=e.error,a="N"===t?o.of(r):"E"===t?s.throwError(function(){return n}):"C"===t?i.EMPTY:0;if(!a)throw new TypeError("Unexpected notification kind "+t);return a},e.createNext=function(t){return new e("N",t)},e.createError=function(t){return new e("E",void 0,t)},e.createComplete=function(){return e.completeNotification},e.completeNotification=new e("C"),e}();function u(e,t){var r,n,i,o=e,s=o.kind,a=o.value,c=o.error;if("string"!=typeof s)throw new TypeError('Invalid notification, missing "kind"');"N"===s?null===(r=t.next)||void 0===r||r.call(t,a):"E"===s?null===(n=t.error)||void 0===n||n.call(t,c):null===(i=t.complete)||void 0===i||i.call(t)}t.Notification=c,t.observeNotification=u},1279:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.elementAt=void 0;var n=r(7024),i=r(5934),o=r(632),s=r(8799),a=r(4383);t.elementAt=function(e,t){if(e<0)throw new n.ArgumentOutOfRangeError;var r=arguments.length>=2;return function(c){return c.pipe(i.filter(function(t,r){return r===e}),a.take(1),r?s.defaultIfEmpty(t):o.throwIfEmpty(function(){return new n.ArgumentOutOfRangeError}))}}},1361:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.every=void 0;var n=r(5212),i=r(7214);t.every=function(e,t){return n.operate(function(r,n){var o=0;r.subscribe(i.createOperatorSubscriber(n,function(i){e.call(t,i,o++,r)||(n.next(!1),n.complete())},function(){n.next(!0),n.complete()}))})}},1415:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.zip=void 0;var o=r(8051),s=r(9724),a=r(7652),c=r(4885),u=r(7214),l=r(6404);t.zip=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=l.popResultSelector(e),d=a.argsOrArgArray(e);return d.length?new o.Observable(function(e){var t=d.map(function(){return[]}),o=d.map(function(){return!1});e.add(function(){t=o=null});for(var a=function(a){s.innerFrom(d[a]).subscribe(u.createOperatorSubscriber(e,function(s){if(t[a].push(s),t.every(function(e){return e.length})){var c=t.map(function(e){return e.shift()});e.next(r?r.apply(void 0,i([],n(c))):c),t.some(function(e,t){return!e.length&&o[t]})&&e.complete()}},function(){o[a]=!0,!t[a].length&&e.complete()}))},c=0;!e.closed&&c<d.length;c++)a(c);return function(){t=o=null}}):c.EMPTY}},1464:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.exhaust=void 0;var n=r(7977);t.exhaust=n.exhaustAll},1587:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.of=void 0;var n=r(6404),i=r(7058);t.of=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=n.popScheduler(e);return i.from(e,r)}},1608:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.auditTime=void 0;var n=r(2326),i=r(8877),o=r(5825);t.auditTime=function(e,t){return void 0===t&&(t=n.asyncScheduler),i.audit(function(){return o.timer(e,t)})}},1666:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.Action=void 0;var o=function(e){function t(t,r){return e.call(this)||this}return i(t,e),t.prototype.schedule=function(e,t){return void 0===t&&(t=0),this},t}(r(9879).Subscription);t.Action=o},1713:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timeout=t.TimeoutError=void 0;var n=r(2326),i=r(5345),o=r(5212),s=r(9724),a=r(9619),c=r(7214),u=r(8619);function l(e){throw new t.TimeoutError(e)}t.TimeoutError=a.createErrorClass(function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}}),t.timeout=function(e,t){var r=i.isValidDate(e)?{first:e}:"number"==typeof e?{each:e}:e,a=r.first,d=r.each,h=r.with,p=void 0===h?l:h,f=r.scheduler,y=void 0===f?null!=t?t:n.asyncScheduler:f,g=r.meta,v=void 0===g?null:g;if(null==a&&null==d)throw new TypeError("No timeout provided.");return o.operate(function(e,t){var r,n,i=null,o=0,l=function(e){n=u.executeSchedule(t,y,function(){try{r.unsubscribe(),s.innerFrom(p({meta:v,lastValue:i,seen:o})).subscribe(t)}catch(e){t.error(e)}},e)};r=e.subscribe(c.createOperatorSubscriber(t,function(e){null==n||n.unsubscribe(),o++,t.next(i=e),d>0&&l(d)},void 0,void 0,function(){(null==n?void 0:n.closed)||null==n||n.unsubscribe(),i=null})),!o&&l(null!=a?"number"==typeof a?a:+a-y.now():d)})}},1719:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.bufferTime=void 0;var i=r(9879),o=r(5212),s=r(7214),a=r(4830),c=r(2326),u=r(6404),l=r(8619);t.bufferTime=function(e){for(var t,r,d=[],h=1;h<arguments.length;h++)d[h-1]=arguments[h];var p=null!==(t=u.popScheduler(d))&&void 0!==t?t:c.asyncScheduler,f=null!==(r=d[0])&&void 0!==r?r:null,y=d[1]||1/0;return o.operate(function(t,r){var o=[],c=!1,u=function(e){var t=e.buffer;e.subs.unsubscribe(),a.arrRemove(o,e),r.next(t),c&&d()},d=function(){if(o){var t=new i.Subscription;r.add(t);var n={buffer:[],subs:t};o.push(n),l.executeSchedule(t,p,function(){return u(n)},e)}};null!==f&&f>=0?l.executeSchedule(r,p,d,f,!0):c=!0,d();var h=s.createOperatorSubscriber(r,function(e){var t,r,i=o.slice();try{for(var s=n(i),a=s.next();!a.done;a=s.next()){var c=a.value,l=c.buffer;l.push(e),y<=l.length&&u(c)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(r=s.return)&&r.call(s)}finally{if(t)throw t.error}}},function(){for(;null==o?void 0:o.length;)r.next(o.shift().buffer);null==h||h.unsubscribe(),r.complete(),r.unsubscribe()},void 0,function(){return o=null});t.subscribe(h)})}},1762:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.debounceTime=void 0;var n=r(2326),i=r(5212),o=r(7214);t.debounceTime=function(e,t){return void 0===t&&(t=n.asyncScheduler),i.operate(function(r,n){var i=null,s=null,a=null,c=function(){if(i){i.unsubscribe(),i=null;var e=s;s=null,n.next(e)}};function u(){var r=a+e,o=t.now();if(o<r)return i=this.schedule(void 0,r-o),void n.add(i);c()}r.subscribe(o.createOperatorSubscriber(n,function(r){s=r,a=t.now(),i||(i=t.schedule(u,e),n.add(i))},function(){c(),n.complete()},void 0,function(){s=i=null}))})}},1778:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.bufferToggle=void 0;var i=r(9879),o=r(5212),s=r(9724),a=r(7214),c=r(5717),u=r(4830);t.bufferToggle=function(e,t){return o.operate(function(r,o){var l=[];s.innerFrom(e).subscribe(a.createOperatorSubscriber(o,function(e){var r=[];l.push(r);var n=new i.Subscription;n.add(s.innerFrom(t(e)).subscribe(a.createOperatorSubscriber(o,function(){u.arrRemove(l,r),o.next(r),n.unsubscribe()},c.noop)))},c.noop)),r.subscribe(a.createOperatorSubscriber(o,function(e){var t,r;try{for(var i=n(l),o=i.next();!o.done;o=i.next())o.value.push(e)}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}},function(){for(;l.length>0;)o.next(l.shift());o.complete()}))})}},1898:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pipeFromArray=t.pipe=void 0;var n=r(7699);function i(e){return 0===e.length?n.identity:1===e.length?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)}}t.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return i(e)},t.pipeFromArray=i},1903:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.onErrorResumeNext=void 0;var n=r(8051),i=r(7652),o=r(7214),s=r(5717),a=r(9724);t.onErrorResumeNext=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=i.argsOrArgArray(e);return new n.Observable(function(e){var t=0,n=function(){if(t<r.length){var i=void 0;try{i=a.innerFrom(r[t++])}catch(e){return void n()}var c=new o.OperatorSubscriber(e,void 0,s.noop,s.noop);i.subscribe(c),c.add(n)}else e.complete()};n()})}},2044:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.combineLatestWith=void 0;var o=r(4948);t.combineLatestWith=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return o.combineLatest.apply(void 0,i([],n(e)))}},2070:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reduce=void 0;var n=r(8531),i=r(5212);t.reduce=function(e,t){return i.operate(n.scanInternals(e,t,arguments.length>=2,!1,!0))}},2071:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.observeOn=void 0;var n=r(8619),i=r(5212),o=r(7214);t.observeOn=function(e,t){return void 0===t&&(t=0),i.operate(function(r,i){r.subscribe(o.createOperatorSubscriber(i,function(r){return n.executeSchedule(i,e,function(){return i.next(r)},t)},function(){return n.executeSchedule(i,e,function(){return i.complete()},t)},function(r){return n.executeSchedule(i,e,function(){return i.error(r)},t)}))})}},2139:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.repeatWhen=void 0;var n=r(9724),i=r(6808),o=r(5212),s=r(7214);t.repeatWhen=function(e){return o.operate(function(t,r){var o,a,c=!1,u=!1,l=!1,d=function(){return l&&u&&(r.complete(),!0)},h=function(){l=!1,o=t.subscribe(s.createOperatorSubscriber(r,void 0,function(){l=!0,!d()&&(a||(a=new i.Subject,n.innerFrom(e(a)).subscribe(s.createOperatorSubscriber(r,function(){o?h():c=!0},function(){u=!0,d()}))),a).next()})),c&&(o.unsubscribe(),o=null,c=!1,h())};h()})}},2187:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isIterable=void 0;var n=r(4891),i=r(281);t.isIterable=function(e){return i.isFunction(null==e?void 0:e[n.iterator])}},2275:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.interval=void 0;var n=r(2326),i=r(5825);t.interval=function(e,t){return void 0===e&&(e=0),void 0===t&&(t=n.asyncScheduler),e<0&&(e=0),i.timer(e,e,t)}},2326:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.async=t.asyncScheduler=void 0;var n=r(4772),i=r(9533);t.asyncScheduler=new i.AsyncScheduler(n.AsyncAction),t.async=t.asyncScheduler},2359:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.skipLast=void 0;var n=r(7699),i=r(5212),o=r(7214);t.skipLast=function(e){return e<=0?n.identity:i.operate(function(t,r){var n=new Array(e),i=0;return t.subscribe(o.createOperatorSubscriber(r,function(t){var o=i++;if(o<e)n[o]=t;else{var s=o%e,a=n[s];n[s]=t,r.next(a)}})),function(){n=null}})}},2508:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeInterval=t.timeInterval=void 0;var n=r(2326),i=r(5212),o=r(7214);t.timeInterval=function(e){return void 0===e&&(e=n.asyncScheduler),i.operate(function(t,r){var n=e.now();t.subscribe(o.createOperatorSubscriber(r,function(t){var i=e.now(),o=i-n;n=i,r.next(new s(t,o))}))})};var s=function(e,t){this.value=e,this.interval=t};t.TimeInterval=s},2568:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.last=void 0;var n=r(9328),i=r(5934),o=r(5279),s=r(632),a=r(8799),c=r(7699);t.last=function(e,t){var r=arguments.length>=2;return function(u){return u.pipe(e?i.filter(function(t,r){return e(t,r,u)}):c.identity,o.takeLast(1),r?a.defaultIfEmpty(t):s.throwIfEmpty(function(){return new n.EmptyError}))}}},2574:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeInternals=void 0;var n=r(9724),i=r(8619),o=r(7214);t.mergeInternals=function(e,t,r,s,a,c,u,l){var d=[],h=0,p=0,f=!1,y=function(){!f||d.length||h||t.complete()},g=function(e){return h<s?v(e):d.push(e)},v=function(e){c&&t.next(e),h++;var l=!1;n.innerFrom(r(e,p++)).subscribe(o.createOperatorSubscriber(t,function(e){null==a||a(e),c?g(e):t.next(e)},function(){l=!0},void 0,function(){if(l)try{h--;for(var e=function(){var e=d.shift();u?i.executeSchedule(t,u,function(){return v(e)}):v(e)};d.length&&h<s;)e();y()}catch(e){t.error(e)}}))};return e.subscribe(o.createOperatorSubscriber(t,g,function(){f=!0,y()})),function(){null==l||l()}}},2688:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.captureError=t.errorContext=void 0;var n=r(3728),i=null;t.errorContext=function(e){if(n.config.useDeprecatedSynchronousErrorHandling){var t=!i;if(t&&(i={errorThrown:!1,error:null}),e(),t){var r=i,o=r.errorThrown,s=r.error;if(i=null,o)throw s}}else e()},t.captureError=function(e){n.config.useDeprecatedSynchronousErrorHandling&&i&&(i.errorThrown=!0,i.error=e)}},2708:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.EMPTY_OBSERVER=t.SafeSubscriber=t.Subscriber=void 0;var o=r(281),s=r(9879),a=r(3728),c=r(2980),u=r(5717),l=r(2767),d=r(4808),h=r(2688),p=function(e){function r(r){var n=e.call(this)||this;return n.isStopped=!1,r?(n.destination=r,s.isSubscription(r)&&r.add(n)):n.destination=t.EMPTY_OBSERVER,n}return i(r,e),r.create=function(e,t,r){return new v(e,t,r)},r.prototype.next=function(e){this.isStopped?m(l.nextNotification(e),this):this._next(e)},r.prototype.error=function(e){this.isStopped?m(l.errorNotification(e),this):(this.isStopped=!0,this._error(e))},r.prototype.complete=function(){this.isStopped?m(l.COMPLETE_NOTIFICATION,this):(this.isStopped=!0,this._complete())},r.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},r.prototype._next=function(e){this.destination.next(e)},r.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},r.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},r}(s.Subscription);t.Subscriber=p;var f=Function.prototype.bind;function y(e,t){return f.call(e,t)}var g=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){b(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){b(e)}else b(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){b(e)}},e}(),v=function(e){function t(t,r,n){var i,s,c=e.call(this)||this;return o.isFunction(t)||!t?i={next:null!=t?t:void 0,error:null!=r?r:void 0,complete:null!=n?n:void 0}:c&&a.config.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return c.unsubscribe()},i={next:t.next&&y(t.next,s),error:t.error&&y(t.error,s),complete:t.complete&&y(t.complete,s)}):i=t,c.destination=new g(i),c}return i(t,e),t}(p);function b(e){a.config.useDeprecatedSynchronousErrorHandling?h.captureError(e):c.reportUnhandledError(e)}function m(e,t){var r=a.config.onStoppedNotification;r&&d.timeoutProvider.setTimeout(function(){return r(e,t)})}t.SafeSubscriber=v,t.EMPTY_OBSERVER={closed:!0,next:u.noop,error:function(e){throw e},complete:u.noop}},2719:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.catchError=void 0;var n=r(9724),i=r(7214),o=r(5212);t.catchError=function e(t){return o.operate(function(r,o){var s,a=null,c=!1;a=r.subscribe(i.createOperatorSubscriber(o,void 0,void 0,function(i){s=n.innerFrom(t(i,e(t)(r))),a?(a.unsubscribe(),a=null,s.subscribe(o)):c=!0})),c&&(a.unsubscribe(),a=null,s.subscribe(o))})}},2767:(e,t)=>{function r(e,t,r){return{kind:e,value:t,error:r}}Object.defineProperty(t,"__esModule",{value:!0}),t.createNotification=t.nextNotification=t.errorNotification=t.COMPLETE_NOTIFICATION=void 0,t.COMPLETE_NOTIFICATION=r("C",void 0,void 0),t.errorNotification=function(e){return r("E",void 0,e)},t.nextNotification=function(e){return r("N",e,void 0)},t.createNotification=r},2794:(e,t,r)=>{t.Tj=t.pb=void 0,r(8877),r(1608),r(706),r(9287),r(1719),r(1778),r(6606),r(2719),r(9244),r(7933),r(4948),r(2044),r(6328),r(201),r(9512),r(9913),r(8032),r(7812),r(8589),r(3143),r(1762),r(8799),r(5797),r(2885),r(9818),r(7876),r(9663),r(6035),r(1279),r(6791),r(1361),r(1464),r(7977),r(6632),r(5544);var n=r(5934);Object.defineProperty(t,"pb",{enumerable:!0,get:function(){return n.filter}}),r(7802),r(8183),r(9035),r(9980),r(5128),r(2959),r(9915),r(2568);var i=r(6872);Object.defineProperty(t,"Tj",{enumerable:!0,get:function(){return i.map}}),r(3337),r(5019),r(96),r(9330),r(8087),r(4613),r(7478),r(6075),r(6707),r(9694),r(142),r(8464),r(2071),r(5513),r(6744),r(9516),r(6355),r(3197),r(2955),r(6569),r(8710),r(6081),r(6677),r(2070),r(6131),r(2139),r(3352),r(3956),r(9224),r(3434),r(4143),r(5565),r(3929),r(3405),r(7782),r(5440),r(3079),r(2359),r(7783),r(5774),r(9054),r(5455),r(6201),r(680),r(761),r(8461),r(4383),r(5279),r(6911),r(598),r(7400),r(4880),r(7245),r(632),r(2508),r(1713),r(597),r(3866),r(3484),r(8072),r(2893),r(37),r(8996),r(5156),r(6975),r(6749),r(5362),r(6977)},2884:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.observable=void 0,t.observable="function"==typeof Symbol&&Symbol.observable||"@@observable"},2885:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.delayWhen=void 0;var n=r(9546),i=r(4383),o=r(2959),s=r(3337),a=r(7478),c=r(9724);t.delayWhen=function e(t,r){return r?function(s){return n.concat(r.pipe(i.take(1),o.ignoreElements()),s.pipe(e(t)))}:a.mergeMap(function(e,r){return c.innerFrom(t(e,r)).pipe(i.take(1),s.mapTo(e))})}},2893:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.windowCount=void 0;var i=r(6808),o=r(5212),s=r(7214);t.windowCount=function(e,t){void 0===t&&(t=0);var r=t>0?t:e;return o.operate(function(t,o){var a=[new i.Subject],c=0;o.next(a[0].asObservable()),t.subscribe(s.createOperatorSubscriber(o,function(t){var s,u;try{for(var l=n(a),d=l.next();!d.done;d=l.next())d.value.next(t)}catch(e){s={error:e}}finally{try{d&&!d.done&&(u=l.return)&&u.call(l)}finally{if(s)throw s.error}}var h=c-e+1;if(h>=0&&h%r==0&&a.shift().complete(),++c%r==0){var p=new i.Subject;a.push(p),o.next(p.asObservable())}},function(){for(;a.length>0;)a.shift().complete();o.complete()},function(e){for(;a.length>0;)a.shift().error(e);o.error(e)},function(){a=null}))})}},2955:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.publishBehavior=void 0;var n=r(7314),i=r(4359);t.publishBehavior=function(e){return function(t){var r=new n.BehaviorSubject(e);return new i.ConnectableObservable(t,function(){return r})}}},2959:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ignoreElements=void 0;var n=r(5212),i=r(7214),o=r(5717);t.ignoreElements=function(){return n.operate(function(e,t){e.subscribe(i.createOperatorSubscriber(t,o.noop))})}},2980:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.reportUnhandledError=void 0;var n=r(3728),i=r(4808);t.reportUnhandledError=function(e){i.timeoutProvider.setTimeout(function(){var t=n.config.onUnhandledError;if(!t)throw e;t(e)})}},3079:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.skip=void 0;var n=r(5934);t.skip=function(e){return n.filter(function(t,r){return e<=r})}},3143:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.debounce=void 0;var n=r(5212),i=r(5717),o=r(7214),s=r(9724);t.debounce=function(e){return n.operate(function(t,r){var n=!1,a=null,c=null,u=function(){if(null==c||c.unsubscribe(),c=null,n){n=!1;var e=a;a=null,r.next(e)}};t.subscribe(o.createOperatorSubscriber(r,function(t){null==c||c.unsubscribe(),n=!0,a=t,c=o.createOperatorSubscriber(r,u,i.noop),s.innerFrom(e(t)).subscribe(c)},function(){u(),r.complete()},void 0,function(){a=c=null}))})}},3197:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.publish=void 0;var n=r(6808),i=r(8464),o=r(7812);t.publish=function(e){return e?function(t){return o.connect(e)(t)}:function(e){return i.multicast(new n.Subject)(e)}}},3275:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dateTimestampProvider=void 0,t.dateTimestampProvider={now:function(){return(t.dateTimestampProvider.delegate||Date).now()},delegate:void 0}},3337:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mapTo=void 0;var n=r(6872);t.mapTo=function(e){return n.map(function(){return e})}},3352:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retry=void 0;var n=r(5212),i=r(7214),o=r(7699),s=r(5825),a=r(9724);t.retry=function(e){var t;void 0===e&&(e=1/0);var r=(t=e&&"object"==typeof e?e:{count:e}).count,c=void 0===r?1/0:r,u=t.delay,l=t.resetOnSuccess,d=void 0!==l&&l;return c<=0?o.identity:n.operate(function(e,t){var r,n=0,o=function(){var l=!1;r=e.subscribe(i.createOperatorSubscriber(t,function(e){d&&(n=0),t.next(e)},void 0,function(e){if(n++<c){var d=function(){r?(r.unsubscribe(),r=null,o()):l=!0};if(null!=u){var h="number"==typeof u?s.timer(u):a.innerFrom(u(e,n)),p=i.createOperatorSubscriber(t,function(){p.unsubscribe(),d()},function(){t.complete()});h.subscribe(p)}else d()}else t.error(e)})),l&&(r.unsubscribe(),r=null,o())};o()})}},3405:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.share=void 0;var o=r(9724),s=r(6808),a=r(2708),c=r(5212);function u(e,t){for(var r=[],s=2;s<arguments.length;s++)r[s-2]=arguments[s];if(!0!==t){if(!1!==t){var c=new a.SafeSubscriber({next:function(){c.unsubscribe(),e()}});return o.innerFrom(t.apply(void 0,i([],n(r)))).subscribe(c)}}else e()}t.share=function(e){void 0===e&&(e={});var t=e.connector,r=void 0===t?function(){return new s.Subject}:t,n=e.resetOnError,i=void 0===n||n,l=e.resetOnComplete,d=void 0===l||l,h=e.resetOnRefCountZero,p=void 0===h||h;return function(e){var t,n,s,l=0,h=!1,f=!1,y=function(){null==n||n.unsubscribe(),n=void 0},g=function(){y(),t=s=void 0,h=f=!1},v=function(){var e=t;g(),null==e||e.unsubscribe()};return c.operate(function(e,c){l++,f||h||y();var b=s=null!=s?s:r();c.add(function(){0!=--l||f||h||(n=u(v,p))}),b.subscribe(c),!t&&l>0&&(t=new a.SafeSubscriber({next:function(e){return b.next(e)},error:function(e){f=!0,y(),n=u(g,i,e),b.error(e)},complete:function(){h=!0,y(),n=u(g,d),b.complete()}}),o.innerFrom(e).subscribe(t))})(e)}}},3434:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sample=void 0;var n=r(9724),i=r(5212),o=r(5717),s=r(7214);t.sample=function(e){return i.operate(function(t,r){var i=!1,a=null;t.subscribe(s.createOperatorSubscriber(r,function(e){i=!0,a=e})),n.innerFrom(e).subscribe(s.createOperatorSubscriber(r,function(){if(i){i=!1;var e=a;a=null,r.next(e)}},o.noop))})}},3484:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toArray=void 0;var n=r(2070),i=r(5212),o=function(e,t){return e.push(t),e};t.toArray=function(){return i.operate(function(e,t){n.reduce(o,[])(e).subscribe(t)})}},3506:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.NotFoundError=void 0;var n=r(9619);t.NotFoundError=n.createErrorClass(function(e){return function(t){e(this),this.name="NotFoundError",this.message=t}})},3728:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.config=void 0,t.config={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1}},3866:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timestamp=void 0;var n=r(3275),i=r(6872);t.timestamp=function(e){return void 0===e&&(e=n.dateTimestampProvider),i.map(function(t){return{value:t,timestamp:e.now()}})}},3916:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.mapOneOrManyArgs=void 0;var o=r(6872),s=Array.isArray;t.mapOneOrManyArgs=function(e){return o.map(function(t){return function(e,t){return s(t)?e.apply(void 0,i([],n(t))):e(t)}(e,t)})}},3929:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sequenceEqual=void 0;var n=r(5212),i=r(7214),o=r(9724);t.sequenceEqual=function(e,t){return void 0===t&&(t=function(e,t){return e===t}),n.operate(function(r,n){var s={buffer:[],complete:!1},a={buffer:[],complete:!1},c=function(e){n.next(e),n.complete()},u=function(e,r){var o=i.createOperatorSubscriber(n,function(n){var i=r.buffer,o=r.complete;0===i.length?o?c(!1):e.buffer.push(n):!t(n,i.shift())&&c(!1)},function(){e.complete=!0;var t=r.complete,n=r.buffer;t&&c(0===n.length),null==o||o.unsubscribe()});return o};r.subscribe(u(s,a)),o.innerFrom(e).subscribe(u(a,s))})}},3956:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.retryWhen=void 0;var n=r(9724),i=r(6808),o=r(5212),s=r(7214);t.retryWhen=function(e){return o.operate(function(t,r){var o,a,c=!1,u=function(){o=t.subscribe(s.createOperatorSubscriber(r,void 0,void 0,function(t){a||(a=new i.Subject,n.innerFrom(e(a)).subscribe(s.createOperatorSubscriber(r,function(){return o?u():c=!0}))),a&&a.next(t)})),c&&(o.unsubscribe(),o=null,c=!1,u())};u()})}},4120:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.not=void 0,t.not=function(e,t){return function(r,n){return!e.call(t,r,n)}}},4143:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.sampleTime=void 0;var n=r(2326),i=r(3434),o=r(2275);t.sampleTime=function(e,t){return void 0===t&&(t=n.asyncScheduler),i.sample(o.interval(e,t))}},4359:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.ConnectableObservable=void 0;var o=r(8051),s=r(9879),a=r(9224),c=r(7214),u=r(5212),l=function(e){function t(t,r){var n=e.call(this)||this;return n.source=t,n.subjectFactory=r,n._subject=null,n._refCount=0,n._connection=null,u.hasLift(t)&&(n.lift=t.lift),n}return i(t,e),t.prototype._subscribe=function(e){return this.getSubject().subscribe(e)},t.prototype.getSubject=function(){var e=this._subject;return e&&!e.isStopped||(this._subject=this.subjectFactory()),this._subject},t.prototype._teardown=function(){this._refCount=0;var e=this._connection;this._subject=this._connection=null,null==e||e.unsubscribe()},t.prototype.connect=function(){var e=this,t=this._connection;if(!t){t=this._connection=new s.Subscription;var r=this.getSubject();t.add(this.source.subscribe(c.createOperatorSubscriber(r,void 0,function(){e._teardown(),r.complete()},function(t){e._teardown(),r.error(t)},function(){return e._teardown()}))),t.closed&&(this._connection=null,t=s.Subscription.EMPTY)}return t},t.prototype.refCount=function(){return a.refCount()(this)},t}(o.Observable);t.ConnectableObservable=l},4383:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.take=void 0;var n=r(4885),i=r(5212),o=r(7214);t.take=function(e){return e<=0?function(){return n.EMPTY}:i.operate(function(t,r){var n=0;t.subscribe(o.createOperatorSubscriber(r,function(t){++n<=e&&(r.next(t),e<=n&&r.complete())}))})}},4530:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.schedulePromise=void 0;var n=r(9724),i=r(2071),o=r(5455);t.schedulePromise=function(e,t){return n.innerFrom(e).pipe(o.subscribeOn(t),i.observeOn(t))}},4613:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.flatMap=void 0;var n=r(7478);t.flatMap=n.mergeMap},4708:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SequenceError=void 0;var n=r(9619);t.SequenceError=n.createErrorClass(function(e){return function(t){e(this),this.name="SequenceError",this.message=t}})},4772:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncAction=void 0;var o=r(1666),s=r(8284),a=r(4830),c=function(e){function t(t,r){var n=e.call(this,t,r)||this;return n.scheduler=t,n.work=r,n.pending=!1,n}return i(t,e),t.prototype.schedule=function(e,t){var r;if(void 0===t&&(t=0),this.closed)return this;this.state=e;var n=this.id,i=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(i,n,t)),this.pending=!0,this.delay=t,this.id=null!==(r=this.id)&&void 0!==r?r:this.requestAsyncId(i,this.id,t),this},t.prototype.requestAsyncId=function(e,t,r){return void 0===r&&(r=0),s.intervalProvider.setInterval(e.flush.bind(e,this),r)},t.prototype.recycleAsyncId=function(e,t,r){if(void 0===r&&(r=0),null!=r&&this.delay===r&&!1===this.pending)return t;null!=t&&s.intervalProvider.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var r=this._execute(e,t);if(r)return r;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var r,n=!1;try{this.work(e)}catch(e){n=!0,r=e||new Error("Scheduled action threw falsy error")}if(n)return this.unsubscribe(),r},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,r=this.scheduler,n=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,a.arrRemove(n,this),null!=t&&(this.id=this.recycleAsyncId(r,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(o.Action);t.AsyncAction=c},4808:function(e,t){var r=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},n=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.timeoutProvider=void 0,t.timeoutProvider={setTimeout:function(e,i){for(var o=[],s=2;s<arguments.length;s++)o[s-2]=arguments[s];var a=t.timeoutProvider.delegate;return(null==a?void 0:a.setTimeout)?a.setTimeout.apply(a,n([e,i],r(o))):setTimeout.apply(void 0,n([e,i],r(o)))},clearTimeout:function(e){var r=t.timeoutProvider.delegate;return((null==r?void 0:r.clearTimeout)||clearTimeout)(e)},delegate:void 0}},4830:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.arrRemove=void 0,t.arrRemove=function(e,t){if(e){var r=e.indexOf(t);0<=r&&e.splice(r,1)}}},4880:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.throttle=void 0;var n=r(5212),i=r(7214),o=r(9724);t.throttle=function(e,t){return n.operate(function(r,n){var s=null!=t?t:{},a=s.leading,c=void 0===a||a,u=s.trailing,l=void 0!==u&&u,d=!1,h=null,p=null,f=!1,y=function(){null==p||p.unsubscribe(),p=null,l&&(b(),f&&n.complete())},g=function(){p=null,f&&n.complete()},v=function(t){return p=o.innerFrom(e(t)).subscribe(i.createOperatorSubscriber(n,y,g))},b=function(){if(d){d=!1;var e=h;h=null,n.next(e),!f&&v(e)}};r.subscribe(i.createOperatorSubscriber(n,function(e){d=!0,h=e,(!p||p.closed)&&(c?b():v(e))},function(){f=!0,(!(l&&d&&p)||p.closed)&&n.complete()}))})}},4885:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.empty=t.EMPTY=void 0;var n=r(8051);t.EMPTY=new n.Observable(function(e){return e.complete()}),t.empty=function(e){return e?function(e){return new n.Observable(function(t){return e.schedule(function(){return t.complete()})})}(e):t.EMPTY}},4891:(e,t)=>{function r(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}Object.defineProperty(t,"__esModule",{value:!0}),t.iterator=t.getSymbolIterator=void 0,t.getSymbolIterator=r,t.iterator=r()},4948:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.combineLatest=void 0;var o=r(8246),s=r(5212),a=r(7652),c=r(3916),u=r(1898),l=r(6404);t.combineLatest=function e(){for(var t=[],r=0;r<arguments.length;r++)t[r]=arguments[r];var d=l.popResultSelector(t);return d?u.pipe(e.apply(void 0,i([],n(t))),c.mapOneOrManyArgs(d)):s.operate(function(e,r){o.combineLatestInit(i([e],n(a.argsOrArgArray(t))))(r)})}},4950:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleArray=void 0;var n=r(8051);t.scheduleArray=function(e,t){return new n.Observable(function(r){var n=0;return t.schedule(function(){n===e.length?r.complete():(r.next(e[n++]),r.closed||this.schedule())})})}},4975:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isArrayLike=void 0,t.isArrayLike=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e}},5019:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.materialize=void 0;var n=r(1245),i=r(5212),o=r(7214);t.materialize=function(){return i.operate(function(e,t){e.subscribe(o.createOperatorSubscriber(t,function(e){t.next(n.Notification.createNext(e))},function(){t.next(n.Notification.createComplete()),t.complete()},function(e){t.next(n.Notification.createError(e)),t.complete()}))})}},5128:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.groupBy=void 0;var n=r(8051),i=r(9724),o=r(6808),s=r(5212),a=r(7214);t.groupBy=function(e,t,r,c){return s.operate(function(s,u){var l;t&&"function"!=typeof t?(r=t.duration,l=t.element,c=t.connector):l=t;var d=new Map,h=function(e){d.forEach(e),e(u)},p=function(e){return h(function(t){return t.error(e)})},f=0,y=!1,g=new a.OperatorSubscriber(u,function(t){try{var s=e(t),h=d.get(s);if(!h){d.set(s,h=c?c():new o.Subject);var v=(m=s,_=h,(S=new n.Observable(function(e){f++;var t=_.subscribe(e);return function(){t.unsubscribe(),0==--f&&y&&g.unsubscribe()}})).key=m,S);if(u.next(v),r){var b=a.createOperatorSubscriber(h,function(){h.complete(),null==b||b.unsubscribe()},void 0,void 0,function(){return d.delete(s)});g.add(i.innerFrom(r(v)).subscribe(b))}}h.next(l?l(t):t)}catch(e){p(e)}var m,_,S},function(){return h(function(e){return e.complete()})},p,function(){return d.clear()},function(){return y=!0,0===f});s.subscribe(g)})}},5130:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncSubject=void 0;var o=function(e){function t(){var t=null!==e&&e.apply(this,arguments)||this;return t._value=null,t._hasValue=!1,t._isComplete=!1,t}return i(t,e),t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,n=t._hasValue,i=t._value,o=t.thrownError,s=t.isStopped,a=t._isComplete;r?e.error(o):(s||a)&&(n&&e.next(i),e.complete())},t.prototype.next=function(e){this.isStopped||(this._value=e,this._hasValue=!0)},t.prototype.complete=function(){var t=this,r=t._hasValue,n=t._value;t._isComplete||(this._isComplete=!0,r&&e.prototype.next.call(this,n),e.prototype.complete.call(this))},t}(r(6808).Subject);t.AsyncSubject=o},5156:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.windowWhen=void 0;var n=r(6808),i=r(5212),o=r(7214),s=r(9724);t.windowWhen=function(e){return i.operate(function(t,r){var i,a,c=function(e){i.error(e),r.error(e)},u=function(){var t;null==a||a.unsubscribe(),null==i||i.complete(),i=new n.Subject,r.next(i.asObservable());try{t=s.innerFrom(e())}catch(e){return void c(e)}t.subscribe(a=o.createOperatorSubscriber(r,u,u,c))};u(),t.subscribe(o.createOperatorSubscriber(r,function(e){return i.next(e)},function(){i.complete(),r.complete()},c,function(){null==a||a.unsubscribe(),i=null}))})}},5212:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.operate=t.hasLift=void 0;var n=r(281);function i(e){return n.isFunction(null==e?void 0:e.lift)}t.hasLift=i,t.operate=function(e){return function(t){if(i(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")}}},5279:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.takeLast=void 0;var i=r(4885),o=r(5212),s=r(7214);t.takeLast=function(e){return e<=0?function(){return i.EMPTY}:o.operate(function(t,r){var i=[];t.subscribe(s.createOperatorSubscriber(r,function(t){i.push(t),e<i.length&&i.shift()},function(){var e,t;try{for(var o=n(i),s=o.next();!s.done;s=o.next()){var a=s.value;r.next(a)}}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}r.complete()},void 0,function(){i=null}))})}},5345:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isValidDate=void 0,t.isValidDate=function(e){return e instanceof Date&&!isNaN(e)}},5362:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.zipAll=void 0;var n=r(1415),i=r(719);t.zipAll=function(e){return i.joinAllInternals(n.zip,e)}},5440:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.single=void 0;var n=r(9328),i=r(4708),o=r(3506),s=r(5212),a=r(7214);t.single=function(e){return s.operate(function(t,r){var s,c=!1,u=!1,l=0;t.subscribe(a.createOperatorSubscriber(r,function(n){u=!0,e&&!e(n,l++,t)||(c&&r.error(new i.SequenceError("Too many matching values")),c=!0,s=n)},function(){c?(r.next(s),r.complete()):r.error(u?new o.NotFoundError("No matching values"):new n.EmptyError)}))})}},5455:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.subscribeOn=void 0;var n=r(5212);t.subscribeOn=function(e,t){return void 0===t&&(t=0),n.operate(function(r,n){n.add(e.schedule(function(){return r.subscribe(n)},t))})}},5462:function(e,t,r){var n=this&&this.__generator||function(e,t){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((i=(i=s.trys).length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,a])}}},i=this&&this.__await||function(e){return this instanceof i?(this.v=e,this):new i(e)},o=this&&this.__asyncGenerator||function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,o=r.apply(e,t||[]),s=[];return n={},a("next"),a("throw"),a("return"),n[Symbol.asyncIterator]=function(){return this},n;function a(e){o[e]&&(n[e]=function(t){return new Promise(function(r,n){s.push([e,t,r,n])>1||c(e,t)})})}function c(e,t){try{(r=o[e](t)).value instanceof i?Promise.resolve(r.value.v).then(u,l):d(s[0][2],r)}catch(e){d(s[0][3],e)}var r}function u(e){c("next",e)}function l(e){c("throw",e)}function d(e,t){e(t),s.shift(),s.length&&c(s[0][0],s[0][1])}};Object.defineProperty(t,"__esModule",{value:!0}),t.isReadableStreamLike=t.readableStreamLikeToAsyncGenerator=void 0;var s=r(281);t.readableStreamLikeToAsyncGenerator=function(e){return o(this,arguments,function(){var t,r,o;return n(this,function(n){switch(n.label){case 0:t=e.getReader(),n.label=1;case 1:n.trys.push([1,,9,10]),n.label=2;case 2:return[4,i(t.read())];case 3:return r=n.sent(),o=r.value,r.done?[4,i(void 0)]:[3,5];case 4:return[2,n.sent()];case 5:return[4,i(o)];case 6:return[4,n.sent()];case 7:return n.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})},t.isReadableStreamLike=function(e){return s.isFunction(null==e?void 0:e.getReader)}},5513:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.onErrorResumeNext=t.onErrorResumeNextWith=void 0;var o=r(7652),s=r(1903);function a(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=o.argsOrArgArray(e);return function(e){return s.onErrorResumeNext.apply(void 0,i([e],n(r)))}}t.onErrorResumeNextWith=a,t.onErrorResumeNext=a},5544:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.expand=void 0;var n=r(5212),i=r(2574);t.expand=function(e,t,r){return void 0===t&&(t=1/0),t=(t||0)<1?1/0:t,n.operate(function(n,o){return i.mergeInternals(n,o,e,t,void 0,!0,r)})}},5565:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scan=void 0;var n=r(5212),i=r(8531);t.scan=function(e,t){return n.operate(i.scanInternals(e,t,arguments.length>=2,!0))}},5650:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleObservable=void 0;var n=r(9724),i=r(2071),o=r(5455);t.scheduleObservable=function(e,t){return n.innerFrom(e).pipe(o.subscribeOn(t),i.observeOn(t))}},5717:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noop=void 0,t.noop=function(){}},5774:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.skipWhile=void 0;var n=r(5212),i=r(7214);t.skipWhile=function(e){return n.operate(function(t,r){var n=!1,o=0;t.subscribe(i.createOperatorSubscriber(r,function(t){return(n||(n=!e(t,o++)))&&r.next(t)}))})}},5797:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.delay=void 0;var n=r(2326),i=r(2885),o=r(5825);t.delay=function(e,t){void 0===t&&(t=n.asyncScheduler);var r=o.timer(e,t);return i.delayWhen(function(){return r})}},5810:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createObject=void 0,t.createObject=function(e,t){return e.reduce(function(e,r,n){return e[r]=t[n],e},{})}},5825:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.timer=void 0;var n=r(8051),i=r(2326),o=r(8596),s=r(5345);t.timer=function(e,t,r){void 0===e&&(e=0),void 0===r&&(r=i.async);var a=-1;return null!=t&&(o.isScheduler(t)?r=t:a=t),new n.Observable(function(t){var n=s.isValidDate(e)?+e-r.now():e;n<0&&(n=0);var i=0;return r.schedule(function(){t.closed||(t.next(i++),0<=a?this.schedule(void 0,a):t.complete())},n)})}},5881:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Scheduler=void 0;var n=r(3275),i=function(){function e(t,r){void 0===r&&(r=e.now),this.schedulerActionCtor=t,this.now=r}return e.prototype.schedule=function(e,t,r){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(r,t)},e.now=n.dateTimestampProvider.now,e}();t.Scheduler=i},5934:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.filter=void 0;var n=r(5212),i=r(7214);t.filter=function(e,t){return n.operate(function(r,n){var o=0;r.subscribe(i.createOperatorSubscriber(n,function(r){return e.call(t,r,o++)&&n.next(r)}))})}},6035:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distinctUntilKeyChanged=void 0;var n=r(9663);t.distinctUntilKeyChanged=function(e,t){return n.distinctUntilChanged(function(r,n){return t?t(r[e],n[e]):r[e]===n[e]})}},6075:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeMapTo=void 0;var n=r(7478),i=r(281);t.mergeMapTo=function(e,t,r){return void 0===r&&(r=1/0),i.isFunction(t)?n.mergeMap(function(){return e},t,r):("number"==typeof t&&(r=t),n.mergeMap(function(){return e},r))}},6081:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.race=void 0;var o=r(7652),s=r(6677);t.race=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return s.raceWith.apply(void 0,i([],n(o.argsOrArgArray(e))))}},6131:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.repeat=void 0;var n=r(4885),i=r(5212),o=r(7214),s=r(9724),a=r(5825);t.repeat=function(e){var t,r,c=1/0;return null!=e&&("object"==typeof e?(t=e.count,c=void 0===t?1/0:t,r=e.delay):c=e),c<=0?function(){return n.EMPTY}:i.operate(function(e,t){var n,i=0,u=function(){if(null==n||n.unsubscribe(),n=null,null!=r){var e="number"==typeof r?a.timer(r):s.innerFrom(r(i)),c=o.createOperatorSubscriber(t,function(){c.unsubscribe(),l()});e.subscribe(c)}else l()},l=function(){var r=!1;n=e.subscribe(o.createOperatorSubscriber(t,void 0,function(){++i<c?n?u():r=!0:t.complete()})),r&&u()};l()})}},6201:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.switchAll=void 0;var n=r(680),i=r(7699);t.switchAll=function(){return n.switchMap(i.identity)}},6297:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createInvalidObservableTypeError=void 0,t.createInvalidObservableTypeError=function(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}},6328:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.concat=void 0;var o=r(5212),s=r(201),a=r(6404),c=r(7058);t.concat=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=a.popScheduler(e);return o.operate(function(t,o){s.concatAll()(c.from(i([t],n(e)),r)).subscribe(o)})}},6355:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pluck=void 0;var n=r(6872);t.pluck=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=e.length;if(0===r)throw new Error("list of properties cannot be empty.");return n.map(function(t){for(var n=t,i=0;i<r;i++){var o=null==n?void 0:n[e[i]];if(void 0===o)return;n=o}return n})}},6404:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.popNumber=t.popScheduler=t.popResultSelector=void 0;var n=r(281),i=r(8596);function o(e){return e[e.length-1]}t.popResultSelector=function(e){return n.isFunction(o(e))?e.pop():void 0},t.popScheduler=function(e){return i.isScheduler(o(e))?e.pop():void 0},t.popNumber=function(e,t){return"number"==typeof o(e)?e.pop():t}},6569:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.publishLast=void 0;var n=r(5130),i=r(4359);t.publishLast=function(){return function(e){var t=new n.AsyncSubject;return new i.ConnectableObservable(e,function(){return t})}}},6606:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.bufferWhen=void 0;var n=r(5212),i=r(5717),o=r(7214),s=r(9724);t.bufferWhen=function(e){return n.operate(function(t,r){var n=null,a=null,c=function(){null==a||a.unsubscribe();var t=n;n=[],t&&r.next(t),s.innerFrom(e()).subscribe(a=o.createOperatorSubscriber(r,c,i.noop))};c(),t.subscribe(o.createOperatorSubscriber(r,function(e){return null==n?void 0:n.push(e)},function(){n&&r.next(n),r.complete()},void 0,function(){return n=a=null}))})}},6632:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.exhaustMap=void 0;var n=r(6872),i=r(9724),o=r(5212),s=r(7214);t.exhaustMap=function e(t,r){return r?function(o){return o.pipe(e(function(e,o){return i.innerFrom(t(e,o)).pipe(n.map(function(t,n){return r(e,t,o,n)}))}))}:o.operate(function(e,r){var n=0,o=null,a=!1;e.subscribe(s.createOperatorSubscriber(r,function(e){o||(o=s.createOperatorSubscriber(r,void 0,function(){o=null,a&&r.complete()}),i.innerFrom(t(e,n++)).subscribe(o))},function(){a=!0,!o&&r.complete()}))})}},6677:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.raceWith=void 0;var o=r(9795),s=r(5212),a=r(7699);t.raceWith=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return e.length?s.operate(function(t,r){o.raceInit(i([t],n(e)))(r)}):a.identity}},6680:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.throwError=void 0;var n=r(8051),i=r(281);t.throwError=function(e,t){var r=i.isFunction(e)?e:function(){return e},o=function(e){return e.error(r())};return new n.Observable(t?function(e){return t.schedule(o,0,e)}:o)}},6707:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeScan=void 0;var n=r(5212),i=r(2574);t.mergeScan=function(e,t,r){return void 0===r&&(r=1/0),n.operate(function(n,o){var s=t;return i.mergeInternals(n,o,function(t,r){return e(s,t,r)},r,function(e){s=e},!1,void 0,function(){return s=null})})}},6744:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.pairwise=void 0;var n=r(5212),i=r(7214);t.pairwise=function(){return n.operate(function(e,t){var r,n=!1;e.subscribe(i.createOperatorSubscriber(t,function(e){var i=r;r=e,n&&t.next([i,e]),n=!0}))})}},6749:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.zip=void 0;var o=r(1415),s=r(5212);t.zip=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return s.operate(function(t,r){o.zip.apply(void 0,i([t],n(e))).subscribe(r)})}},6791:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.endWith=void 0;var o=r(9546),s=r(1587);t.endWith=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return function(t){return o.concat(t,s.of.apply(void 0,i([],n(e))))}}},6805:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleIterable=void 0;var n=r(8051),i=r(4891),o=r(281),s=r(8619);t.scheduleIterable=function(e,t){return new n.Observable(function(r){var n;return s.executeSchedule(r,t,function(){n=e[i.iterator](),s.executeSchedule(r,t,function(){var e,t,i;try{t=(e=n.next()).value,i=e.done}catch(e){return void r.error(e)}i?r.complete():r.next(t)},0,!0)}),function(){return o.isFunction(null==n?void 0:n.return)&&n.return()}})}},6808:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}),o=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.AnonymousSubject=t.Subject=void 0;var s=r(8051),a=r(9879),c=r(839),u=r(4830),l=r(2688),d=function(e){function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return i(t,e),t.prototype.lift=function(e){var t=new h(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new c.ObjectUnsubscribedError},t.prototype.next=function(e){var t=this;l.errorContext(function(){var r,n;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||(t.currentObservers=Array.from(t.observers));try{for(var i=o(t.currentObservers),s=i.next();!s.done;s=i.next())s.value.next(e)}catch(e){r={error:e}}finally{try{s&&!s.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}}})},t.prototype.error=function(e){var t=this;l.errorContext(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var r=t.observers;r.length;)r.shift().error(e)}})},t.prototype.complete=function(){var e=this;l.errorContext(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){var e;return(null===(e=this.observers)||void 0===e?void 0:e.length)>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,r=this,n=r.hasError,i=r.isStopped,o=r.observers;return n||i?a.EMPTY_SUBSCRIPTION:(this.currentObservers=null,o.push(e),new a.Subscription(function(){t.currentObservers=null,u.arrRemove(o,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,r=t.hasError,n=t.thrownError,i=t.isStopped;r?e.error(n):i&&e.complete()},t.prototype.asObservable=function(){var e=new s.Observable;return e.source=this,e},t.create=function(e,t){return new h(e,t)},t}(s.Observable);t.Subject=d;var h=function(e){function t(t,r){var n=e.call(this)||this;return n.destination=t,n.source=r,n}return i(t,e),t.prototype.next=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===r||r.call(t,e)},t.prototype.error=function(e){var t,r;null===(r=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===r||r.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,r;return null!==(r=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==r?r:a.EMPTY_SUBSCRIPTION},t}(d);t.AnonymousSubject=h},6872:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.map=void 0;var n=r(5212),i=r(7214);t.map=function(e,t){return n.operate(function(r,n){var o=0;r.subscribe(i.createOperatorSubscriber(n,function(r){n.next(e.call(t,r,o++))}))})}},6911:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.takeUntil=void 0;var n=r(5212),i=r(7214),o=r(9724),s=r(5717);t.takeUntil=function(e){return n.operate(function(t,r){o.innerFrom(e).subscribe(i.createOperatorSubscriber(r,function(){return r.complete()},s.noop)),!r.closed&&t.subscribe(r)})}},6975:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.withLatestFrom=void 0;var o=r(5212),s=r(7214),a=r(9724),c=r(7699),u=r(5717),l=r(6404);t.withLatestFrom=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=l.popResultSelector(e);return o.operate(function(t,o){for(var l=e.length,d=new Array(l),h=e.map(function(){return!1}),p=!1,f=function(t){a.innerFrom(e[t]).subscribe(s.createOperatorSubscriber(o,function(e){d[t]=e,p||h[t]||(h[t]=!0,(p=h.every(c.identity))&&(h=null))},u.noop))},y=0;y<l;y++)f(y);t.subscribe(s.createOperatorSubscriber(o,function(e){if(p){var t=i([e],n(d));o.next(r?r.apply(void 0,i([],n(t))):t)}}))})}},6977:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.zipWith=void 0;var o=r(6749);t.zipWith=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return o.zip.apply(void 0,i([],n(e)))}},7024:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ArgumentOutOfRangeError=void 0;var n=r(9619);t.ArgumentOutOfRangeError=n.createErrorClass(function(e){return function(){e(this),this.name="ArgumentOutOfRangeError",this.message="argument out of range"}})},7058:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.from=void 0;var n=r(131),i=r(9724);t.from=function(e,t){return t?n.scheduled(e,t):i.innerFrom(e)}},7214:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.OperatorSubscriber=t.createOperatorSubscriber=void 0;var o=r(2708);t.createOperatorSubscriber=function(e,t,r,n,i){return new s(e,t,r,n,i)};var s=function(e){function t(t,r,n,i,o,s){var a=e.call(this,t)||this;return a.onFinalize=o,a.shouldUnsubscribe=s,a._next=r?function(e){try{r(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return i(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var r=this.closed;e.prototype.unsubscribe.call(this),!r&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(o.Subscriber);t.OperatorSubscriber=s},7245:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.throttleTime=void 0;var n=r(2326),i=r(4880),o=r(5825);t.throttleTime=function(e,t,r){void 0===t&&(t=n.asyncScheduler);var s=o.timer(e,t);return i.throttle(function(){return s},r)}},7314:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.BehaviorSubject=void 0;var o=function(e){function t(t){var r=e.call(this)||this;return r._value=t,r}return i(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var r=e.prototype._subscribe.call(this,t);return!r.closed&&t.next(this._value),r},t.prototype.getValue=function(){var e=this,t=e.hasError,r=e.thrownError,n=e._value;if(t)throw r;return this._throwIfClosed(),n},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(r(6808).Subject);t.BehaviorSubject=o},7400:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.tap=void 0;var n=r(281),i=r(5212),o=r(7214),s=r(7699);t.tap=function(e,t,r){var a=n.isFunction(e)||t||r?{next:e,error:t,complete:r}:e;return a?i.operate(function(e,t){var r;null===(r=a.subscribe)||void 0===r||r.call(a);var n=!0;e.subscribe(o.createOperatorSubscriber(t,function(e){var r;null===(r=a.next)||void 0===r||r.call(a,e),t.next(e)},function(){var e;n=!1,null===(e=a.complete)||void 0===e||e.call(a),t.complete()},function(e){var r;n=!1,null===(r=a.error)||void 0===r||r.call(a,e),t.error(e)},function(){var e,t;n&&(null===(e=a.unsubscribe)||void 0===e||e.call(a)),null===(t=a.finalize)||void 0===t||t.call(a)}))}):s.identity}},7478:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeMap=void 0;var n=r(6872),i=r(9724),o=r(5212),s=r(2574),a=r(281);t.mergeMap=function e(t,r,c){return void 0===c&&(c=1/0),a.isFunction(r)?e(function(e,o){return n.map(function(t,n){return r(e,t,o,n)})(i.innerFrom(t(e,o)))},c):("number"==typeof r&&(c=r),o.operate(function(e,r){return s.mergeInternals(e,r,t,c)}))}},7552:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isPromise=void 0;var n=r(281);t.isPromise=function(e){return n.isFunction(null==e?void 0:e.then)}},7652:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.argsOrArgArray=void 0;var r=Array.isArray;t.argsOrArgArray=function(e){return 1===e.length&&r(e[0])?e[0]:e}},7699:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.identity=void 0,t.identity=function(e){return e}},7782:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.shareReplay=void 0;var n=r(381),i=r(3405);t.shareReplay=function(e,t,r){var o,s,a,c,u=!1;return e&&"object"==typeof e?(o=e.bufferSize,c=void 0===o?1/0:o,s=e.windowTime,t=void 0===s?1/0:s,u=void 0!==(a=e.refCount)&&a,r=e.scheduler):c=null!=e?e:1/0,i.share({connector:function(){return new n.ReplaySubject(c,t,r)},resetOnError:!0,resetOnComplete:!1,resetOnRefCountZero:u})}},7783:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.skipUntil=void 0;var n=r(5212),i=r(7214),o=r(9724),s=r(5717);t.skipUntil=function(e){return n.operate(function(t,r){var n=!1,a=i.createOperatorSubscriber(r,function(){null==a||a.unsubscribe(),n=!0},s.noop);o.innerFrom(e).subscribe(a),t.subscribe(i.createOperatorSubscriber(r,function(e){return n&&r.next(e)}))})}},7802:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.finalize=void 0;var n=r(5212);t.finalize=function(e){return n.operate(function(t,r){try{t.subscribe(r)}finally{r.add(e)}})}},7812:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.connect=void 0;var n=r(6808),i=r(9724),o=r(5212),s=r(1071),a={connector:function(){return new n.Subject}};t.connect=function(e,t){void 0===t&&(t=a);var r=t.connector;return o.operate(function(t,n){var o=r();i.innerFrom(e(s.fromSubscribable(o))).subscribe(n),n.add(t.subscribe(o))})}},7873:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scheduleAsyncIterable=void 0;var n=r(8051),i=r(8619);t.scheduleAsyncIterable=function(e,t){if(!e)throw new Error("Iterable cannot be null");return new n.Observable(function(r){i.executeSchedule(r,t,function(){var n=e[Symbol.asyncIterator]();i.executeSchedule(r,t,function(){n.next().then(function(e){e.done?r.complete():r.next(e.value)})},0,!0)})})}},7876:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distinct=void 0;var n=r(5212),i=r(7214),o=r(5717),s=r(9724);t.distinct=function(e,t){return n.operate(function(r,n){var a=new Set;r.subscribe(i.createOperatorSubscriber(n,function(t){var r=e?e(t):t;a.has(r)||(a.add(r),n.next(t))})),t&&s.innerFrom(t).subscribe(i.createOperatorSubscriber(n,function(){return a.clear()},o.noop))})}},7933:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.combineLatestAll=void 0;var n=r(8246),i=r(719);t.combineLatestAll=function(e){return i.joinAllInternals(n.combineLatest,e)}},7977:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.exhaustAll=void 0;var n=r(6632),i=r(7699);t.exhaustAll=function(){return n.exhaustMap(i.identity)}},8032:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.concatWith=void 0;var o=r(6328);t.concatWith=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return o.concat.apply(void 0,i([],n(e)))}},8051:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Observable=void 0;var n=r(2708),i=r(9879),o=r(2884),s=r(1898),a=r(3728),c=r(281),u=r(2688),l=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var r=new e;return r.source=this,r.operator=t,r},e.prototype.subscribe=function(e,t,r){var o,s=this,a=(o=e)&&o instanceof n.Subscriber||function(e){return e&&c.isFunction(e.next)&&c.isFunction(e.error)&&c.isFunction(e.complete)}(o)&&i.isSubscription(o)?e:new n.SafeSubscriber(e,t,r);return u.errorContext(function(){var e=s,t=e.operator,r=e.source;a.add(t?t.call(a,r):r?s._subscribe(a):s._trySubscribe(a))}),a},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var r=this;return new(t=d(t))(function(t,i){var o=new n.SafeSubscriber({next:function(t){try{e(t)}catch(e){i(e),o.unsubscribe()}},error:i,complete:t});r.subscribe(o)})},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[o.observable]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return s.pipeFromArray(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=d(e))(function(e,r){var n;t.subscribe(function(e){return n=e},function(e){return r(e)},function(){return e(n)})})},e.create=function(t){return new e(t)},e}();function d(e){var t;return null!==(t=null!=e?e:a.config.Promise)&&void 0!==t?t:Promise}t.Observable=l},8072:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.window=void 0;var n=r(6808),i=r(5212),o=r(7214),s=r(5717),a=r(9724);t.window=function(e){return i.operate(function(t,r){var i=new n.Subject;r.next(i.asObservable());var c=function(e){i.error(e),r.error(e)};return t.subscribe(o.createOperatorSubscriber(r,function(e){return null==i?void 0:i.next(e)},function(){i.complete(),r.complete()},c)),a.innerFrom(e).subscribe(o.createOperatorSubscriber(r,function(){i.complete(),r.next(i=new n.Subject)},s.noop,c)),function(){null==i||i.unsubscribe(),i=null}})}},8087:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mergeAll=void 0;var n=r(7478),i=r(7699);t.mergeAll=function(e){return void 0===e&&(e=1/0),n.mergeMap(i.identity,e)}},8183:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createFind=t.find=void 0;var n=r(5212),i=r(7214);function o(e,t,r){var n="index"===r;return function(r,o){var s=0;r.subscribe(i.createOperatorSubscriber(o,function(i){var a=s++;e.call(t,i,a,r)&&(o.next(n?a:i),o.complete())},function(){o.next(n?-1:void 0),o.complete()}))}}t.find=function(e,t){return n.operate(o(e,t,"value"))},t.createFind=o},8246:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.combineLatestInit=t.combineLatest=void 0;var n=r(8051),i=r(439),o=r(7058),s=r(7699),a=r(3916),c=r(6404),u=r(5810),l=r(7214),d=r(8619);function h(e,t,r){return void 0===r&&(r=s.identity),function(n){p(t,function(){for(var i=e.length,s=new Array(i),a=i,c=i,u=function(i){p(t,function(){var u=o.from(e[i],t),d=!1;u.subscribe(l.createOperatorSubscriber(n,function(e){s[i]=e,d||(d=!0,c--),c||n.next(r(s.slice()))},function(){--a||n.complete()}))},n)},d=0;d<i;d++)u(d)},n)}}function p(e,t,r){e?d.executeSchedule(r,e,t):t()}t.combineLatest=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=c.popScheduler(e),l=c.popResultSelector(e),d=i.argsArgArrayOrObject(e),p=d.args,f=d.keys;if(0===p.length)return o.from([],r);var y=new n.Observable(h(p,r,f?function(e){return u.createObject(f,e)}:s.identity));return l?y.pipe(a.mapOneOrManyArgs(l)):y},t.combineLatestInit=h},8263:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAsyncIterable=void 0;var n=r(281);t.isAsyncIterable=function(e){return Symbol.asyncIterator&&n.isFunction(null==e?void 0:e[Symbol.asyncIterator])}},8284:function(e,t){var r=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},n=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.intervalProvider=void 0,t.intervalProvider={setInterval:function(e,i){for(var o=[],s=2;s<arguments.length;s++)o[s-2]=arguments[s];var a=t.intervalProvider.delegate;return(null==a?void 0:a.setInterval)?a.setInterval.apply(a,n([e,i],r(o))):setInterval.apply(void 0,n([e,i],r(o)))},clearInterval:function(e){var r=t.intervalProvider.delegate;return((null==r?void 0:r.clearInterval)||clearInterval)(e)},delegate:void 0}},8461:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.switchScan=void 0;var n=r(680),i=r(5212);t.switchScan=function(e,t){return i.operate(function(r,i){var o=t;return n.switchMap(function(t,r){return e(o,t,r)},function(e,t){return o=t,t})(r).subscribe(i),function(){o=null}})}},8464:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.multicast=void 0;var n=r(4359),i=r(281),o=r(7812);t.multicast=function(e,t){var r=i.isFunction(e)?e:function(){return e};return i.isFunction(t)?o.connect(t,{connector:r}):function(e){return new n.ConnectableObservable(e,r)}}},8531:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.scanInternals=void 0;var n=r(7214);t.scanInternals=function(e,t,r,i,o){return function(s,a){var c=r,u=t,l=0;s.subscribe(n.createOperatorSubscriber(a,function(t){var r=l++;u=c?e(u,t,r):(c=!0,t),i&&a.next(u)},o&&function(){c&&a.next(u),a.complete()}))}}},8589:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.count=void 0;var n=r(2070);t.count=function(e){return n.reduce(function(t,r,n){return!e||e(r,n)?t+1:t},0)}},8596:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isScheduler=void 0;var n=r(281);t.isScheduler=function(e){return e&&n.isFunction(e.schedule)}},8619:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.executeSchedule=void 0,t.executeSchedule=function(e,t,r,n,i){void 0===n&&(n=0),void 0===i&&(i=!1);var o=t.schedule(function(){r(),i?e.add(this.schedule(null,n)):this.unsubscribe()},n);if(e.add(o),!i)return o}},8710:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.publishReplay=void 0;var n=r(381),i=r(8464),o=r(281);t.publishReplay=function(e,t,r,s){r&&!o.isFunction(r)&&(s=r);var a=o.isFunction(r)?r:void 0;return function(r){return i.multicast(new n.ReplaySubject(e,t,s),a)(r)}}},8799:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.defaultIfEmpty=void 0;var n=r(5212),i=r(7214);t.defaultIfEmpty=function(e){return n.operate(function(t,r){var n=!1;t.subscribe(i.createOperatorSubscriber(r,function(e){n=!0,r.next(e)},function(){n||r.next(e),r.complete()}))})}},8877:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.audit=void 0;var n=r(5212),i=r(9724),o=r(7214);t.audit=function(e){return n.operate(function(t,r){var n=!1,s=null,a=null,c=!1,u=function(){if(null==a||a.unsubscribe(),a=null,n){n=!1;var e=s;s=null,r.next(e)}c&&r.complete()},l=function(){a=null,c&&r.complete()};t.subscribe(o.createOperatorSubscriber(r,function(t){n=!0,s=t,a||i.innerFrom(e(t)).subscribe(a=o.createOperatorSubscriber(r,u,l))},function(){c=!0,(!n||!a||a.closed)&&r.complete()}))})}},8996:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.windowToggle=void 0;var i=r(6808),o=r(9879),s=r(5212),a=r(9724),c=r(7214),u=r(5717),l=r(4830);t.windowToggle=function(e,t){return s.operate(function(r,s){var d=[],h=function(e){for(;0<d.length;)d.shift().error(e);s.error(e)};a.innerFrom(e).subscribe(c.createOperatorSubscriber(s,function(e){var r=new i.Subject;d.push(r);var n,p=new o.Subscription;try{n=a.innerFrom(t(e))}catch(e){return void h(e)}s.next(r.asObservable()),p.add(n.subscribe(c.createOperatorSubscriber(s,function(){l.arrRemove(d,r),r.complete(),p.unsubscribe()},u.noop,h)))},u.noop)),r.subscribe(c.createOperatorSubscriber(s,function(e){var t,r,i=d.slice();try{for(var o=n(i),s=o.next();!s.done;s=o.next())s.value.next(e)}catch(e){t={error:e}}finally{try{s&&!s.done&&(r=o.return)&&r.call(o)}finally{if(t)throw t.error}}},function(){for(;0<d.length;)d.shift().complete();s.complete()},h,function(){for(;0<d.length;)d.shift().unsubscribe()}))})}},9035:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.findIndex=void 0;var n=r(5212),i=r(8183);t.findIndex=function(e,t){return n.operate(i.createFind(e,t,"index"))}},9054:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.startWith=void 0;var n=r(9546),i=r(6404),o=r(5212);t.startWith=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=i.popScheduler(e);return o.operate(function(t,i){(r?n.concat(e,t,r):n.concat(e,t)).subscribe(i)})}},9224:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.refCount=void 0;var n=r(5212),i=r(7214);t.refCount=function(){return n.operate(function(e,t){var r=null;e._refCount++;var n=i.createOperatorSubscriber(t,void 0,void 0,void 0,function(){if(!e||e._refCount<=0||0<--e._refCount)r=null;else{var n=e._connection,i=r;r=null,!n||i&&n!==i||n.unsubscribe(),t.unsubscribe()}});e.subscribe(n),n.closed||(r=e.connect())})}},9244:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.combineAll=void 0;var n=r(7933);t.combineAll=n.combineLatestAll},9287:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.bufferCount=void 0;var i=r(5212),o=r(7214),s=r(4830);t.bufferCount=function(e,t){return void 0===t&&(t=null),t=null!=t?t:e,i.operate(function(r,i){var a=[],c=0;r.subscribe(o.createOperatorSubscriber(i,function(r){var o,u,l,d,h=null;c++%t==0&&a.push([]);try{for(var p=n(a),f=p.next();!f.done;f=p.next())(v=f.value).push(r),e<=v.length&&(h=null!=h?h:[]).push(v)}catch(e){o={error:e}}finally{try{f&&!f.done&&(u=p.return)&&u.call(p)}finally{if(o)throw o.error}}if(h)try{for(var y=n(h),g=y.next();!g.done;g=y.next()){var v=g.value;s.arrRemove(a,v),i.next(v)}}catch(e){l={error:e}}finally{try{g&&!g.done&&(d=y.return)&&d.call(y)}finally{if(l)throw l.error}}},function(){var e,t;try{for(var r=n(a),o=r.next();!o.done;o=r.next()){var s=o.value;i.next(s)}}catch(t){e={error:t}}finally{try{o&&!o.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}i.complete()},void 0,function(){a=null}))})}},9328:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EmptyError=void 0;var n=r(9619);t.EmptyError=n.createErrorClass(function(e){return function(){e(this),this.name="EmptyError",this.message="no elements in sequence"}})},9330:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.merge=void 0;var o=r(5212),s=r(8087),a=r(6404),c=r(7058);t.merge=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var r=a.popScheduler(e),u=a.popNumber(e,1/0);return o.operate(function(t,o){s.mergeAll(u)(c.from(i([t],n(e)),r)).subscribe(o)})}},9512:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatMap=void 0;var n=r(7478),i=r(281);t.concatMap=function(e,t){return i.isFunction(t)?n.mergeMap(e,t,1):n.mergeMap(e,1)}},9516:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.partition=void 0;var n=r(4120),i=r(5934);t.partition=function(e,t){return function(r){return[i.filter(e,t)(r),i.filter(n.not(e,t))(r)]}}},9517:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnsubscriptionError=void 0;var n=r(9619);t.UnsubscriptionError=n.createErrorClass(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}})},9533:function(e,t,r){var n,i=this&&this.__extends||(n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},n(e,t)},function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)});Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncScheduler=void 0;var o=r(5881),s=function(e){function t(t,r){void 0===r&&(r=o.Scheduler.now);var n=e.call(this,t,r)||this;return n.actions=[],n._active=!1,n}return i(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var r;this._active=!0;do{if(r=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,r){for(;e=t.shift();)e.unsubscribe();throw r}}},t}(o.Scheduler);t.AsyncScheduler=s},9546:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concat=void 0;var n=r(201),i=r(6404),o=r(7058);t.concat=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return n.concatAll()(o.from(e,i.popScheduler(e)))}},9619:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createErrorClass=void 0,t.createErrorClass=function(e){var t=e(function(e){Error.call(e),e.stack=(new Error).stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}},9663:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.distinctUntilChanged=void 0;var n=r(7699),i=r(5212),o=r(7214);function s(e,t){return e===t}t.distinctUntilChanged=function(e,t){return void 0===t&&(t=n.identity),e=null!=e?e:s,i.operate(function(r,n){var i,s=!0;r.subscribe(o.createOperatorSubscriber(n,function(r){var o=t(r);!s&&e(i,o)||(s=!1,i=o,n.next(r))}))})}},9694:function(e,t,r){var n=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},i=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.mergeWith=void 0;var o=r(9330);t.mergeWith=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return o.merge.apply(void 0,i([],n(e)))}},9724:function(e,t,r){var n=this&&this.__awaiter||function(e,t,r,n){return new(r||(r=Promise))(function(i,o){function s(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r(function(e){e(t)})).then(s,a)}c((n=n.apply(e,t||[])).next())})},i=this&&this.__generator||function(e,t){var r,n,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function a(o){return function(a){return function(o){if(r)throw new TypeError("Generator is already executing.");for(;s;)try{if(r=1,n&&(i=2&o[0]?n.return:o[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,o[1])).done)return i;switch(n=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,n=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!((i=(i=s.trys).length>0&&i[i.length-1])||6!==o[0]&&2!==o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=t.call(e,s)}catch(e){o=[6,e],n=0}finally{r=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,a])}}},o=this&&this.__asyncValues||function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e="function"==typeof s?s(e):e[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise(function(n,i){!function(e,t,r,n){Promise.resolve(n).then(function(t){e({value:t,done:r})},t)}(n,i,(t=e[r](t)).done,t.value)})}}},s=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.fromReadableStreamLike=t.fromAsyncIterable=t.fromIterable=t.fromPromise=t.fromArrayLike=t.fromInteropObservable=t.innerFrom=void 0;var a=r(4975),c=r(7552),u=r(8051),l=r(629),d=r(8263),h=r(6297),p=r(2187),f=r(5462),y=r(281),g=r(2980),v=r(2884);function b(e){return new u.Observable(function(t){var r=e[v.observable]();if(y.isFunction(r.subscribe))return r.subscribe(t);throw new TypeError("Provided object does not correctly implement Symbol.observable")})}function m(e){return new u.Observable(function(t){for(var r=0;r<e.length&&!t.closed;r++)t.next(e[r]);t.complete()})}function _(e){return new u.Observable(function(t){e.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,g.reportUnhandledError)})}function S(e){return new u.Observable(function(t){var r,n;try{for(var i=s(e),o=i.next();!o.done;o=i.next()){var a=o.value;if(t.next(a),t.closed)return}}catch(e){r={error:e}}finally{try{o&&!o.done&&(n=i.return)&&n.call(i)}finally{if(r)throw r.error}}t.complete()})}function w(e){return new u.Observable(function(t){(function(e,t){var r,s,a,c;return n(this,void 0,void 0,function(){var n,u;return i(this,function(i){switch(i.label){case 0:i.trys.push([0,5,6,11]),r=o(e),i.label=1;case 1:return[4,r.next()];case 2:if((s=i.sent()).done)return[3,4];if(n=s.value,t.next(n),t.closed)return[2];i.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return u=i.sent(),a={error:u},[3,11];case 6:return i.trys.push([6,,9,10]),s&&!s.done&&(c=r.return)?[4,c.call(r)]:[3,8];case 7:i.sent(),i.label=8;case 8:return[3,10];case 9:if(a)throw a.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})})(e,t).catch(function(e){return t.error(e)})})}function I(e){return w(f.readableStreamLikeToAsyncGenerator(e))}t.innerFrom=function(e){if(e instanceof u.Observable)return e;if(null!=e){if(l.isInteropObservable(e))return b(e);if(a.isArrayLike(e))return m(e);if(c.isPromise(e))return _(e);if(d.isAsyncIterable(e))return w(e);if(p.isIterable(e))return S(e);if(f.isReadableStreamLike(e))return I(e)}throw h.createInvalidObservableTypeError(e)},t.fromInteropObservable=b,t.fromArrayLike=m,t.fromPromise=_,t.fromIterable=S,t.fromAsyncIterable=w,t.fromReadableStreamLike=I},9795:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.raceInit=t.race=void 0;var n=r(8051),i=r(9724),o=r(7652),s=r(7214);function a(e){return function(t){for(var r=[],n=function(n){r.push(i.innerFrom(e[n]).subscribe(s.createOperatorSubscriber(t,function(e){if(r){for(var i=0;i<r.length;i++)i!==n&&r[i].unsubscribe();r=null}t.next(e)})))},o=0;r&&!t.closed&&o<e.length;o++)n(o)}}t.race=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return 1===(e=o.argsOrArgArray(e)).length?i.innerFrom(e[0]):new n.Observable(a(e))},t.raceInit=a},9818:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.dematerialize=void 0;var n=r(1245),i=r(5212),o=r(7214);t.dematerialize=function(){return i.operate(function(e,t){e.subscribe(o.createOperatorSubscriber(t,function(e){return n.observeNotification(e,t)}))})}},9879:function(e,t,r){var n=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")},i=this&&this.__read||function(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)s.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return s},o=this&&this.__spreadArray||function(e,t){for(var r=0,n=t.length,i=e.length;r<n;r++,i++)e[i]=t[r];return e};Object.defineProperty(t,"__esModule",{value:!0}),t.isSubscription=t.EMPTY_SUBSCRIPTION=t.Subscription=void 0;var s=r(281),a=r(9517),c=r(4830),u=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,r,c,u;if(!this.closed){this.closed=!0;var d=this._parentage;if(d)if(this._parentage=null,Array.isArray(d))try{for(var h=n(d),p=h.next();!p.done;p=h.next())p.value.remove(this)}catch(t){e={error:t}}finally{try{p&&!p.done&&(t=h.return)&&t.call(h)}finally{if(e)throw e.error}}else d.remove(this);var f=this.initialTeardown;if(s.isFunction(f))try{f()}catch(e){u=e instanceof a.UnsubscriptionError?e.errors:[e]}var y=this._finalizers;if(y){this._finalizers=null;try{for(var g=n(y),v=g.next();!v.done;v=g.next()){var b=v.value;try{l(b)}catch(e){u=null!=u?u:[],e instanceof a.UnsubscriptionError?u=o(o([],i(u)),i(e.errors)):u.push(e)}}}catch(e){r={error:e}}finally{try{v&&!v.done&&(c=g.return)&&c.call(g)}finally{if(r)throw r.error}}}if(u)throw new a.UnsubscriptionError(u)}},e.prototype.add=function(t){var r;if(t&&t!==this)if(this.closed)l(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(r=this._finalizers)&&void 0!==r?r:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&c.arrRemove(t,e)},e.prototype.remove=function(t){var r=this._finalizers;r&&c.arrRemove(r,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function l(e){s.isFunction(e)?e():e.unsubscribe()}t.Subscription=u,t.EMPTY_SUBSCRIPTION=u.EMPTY,t.isSubscription=function(e){return e instanceof u||e&&"closed"in e&&s.isFunction(e.remove)&&s.isFunction(e.add)&&s.isFunction(e.unsubscribe)}},9913:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatMapTo=void 0;var n=r(9512),i=r(281);t.concatMapTo=function(e,t){return i.isFunction(t)?n.concatMap(function(){return e},t):n.concatMap(function(){return e})}},9915:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isEmpty=void 0;var n=r(5212),i=r(7214);t.isEmpty=function(){return n.operate(function(e,t){e.subscribe(i.createOperatorSubscriber(t,function(){t.next(!1),t.complete()},function(){t.next(!0),t.complete()}))})}},9980:(e,t,r)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.first=void 0;var n=r(9328),i=r(5934),o=r(4383),s=r(8799),a=r(632),c=r(7699);t.first=function(e,t){var r=arguments.length>=2;return function(u){return u.pipe(e?i.filter(function(t,r){return e(t,r,u)}):c.identity,o.take(1),r?s.defaultIfEmpty(t):a.throwIfEmpty(function(){return new n.EmptyError}))}}}},Hr={};function zr(e){var t=Hr[e];if(void 0!==t)return t.exports;var r=Hr[e]={exports:{}};return Wr[e].call(r.exports,r,r.exports,zr),r.exports}function Kr(e,t,...r){e||function(e,...t){const r=function(e){return void 0===e?"":"string"==typeof e?e:e()}(e);if("object"==typeof r)throw r;throw(e=>new Error(e))(r||"Assertion error",...t)}(t,...r)}function Jr(e,t){switch(t.type){case"set":return function(e,t,r){if(void 0===r)return Yr(e,t);if(0===t.length)return Kr("object"==typeof r&&null!==r&&!Array.isArray(r),()=>`Root state must be a record. Trying to set '${r}', type: ${typeof r}`),r;function n(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let i=e;for(let e=0;e<t.length-1&&void 0!==i;e++){const r=t[e];Kr(!Array.isArray(i)||n(r),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${r}'`),i=i[r],Kr(void 0===i||"object"==typeof i&&null!==i,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===i?"<null>":typeof i}'`)}const o=t[t.length-1];return Kr(!Array.isArray(i)||n(o),()=>`Invalid array index Path: '${t}`),(null==i?void 0:i[o])===r?e:Zr(e,t,r)}(e,t.path,t.value);case"delete":return Yr(e,t.path);case"batch":return t.actions.reduce((e,t)=>Jr(e,t),e)}}function Yr(e,t){Kr(0!==t.length,"Can't delete an empty path");let r=e;for(let n=0;n<t.length-1;n++){const i=t[n];if(r=r[i],void 0===r)return e;Kr("object"==typeof r&&null!==r,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,n+1)}', type: ${null===r?"<null>":typeof r}`)}const n=t[t.length-1];return void 0===r[n]?e:Zr(e,t,void 0)}function Zr(e,t,r){function n(e,r){Kr(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[r]}const i=Object.assign({},e);let o=i;for(let e=0;e<t.length-1;e++){const i=t[e],s=o[i];Kr(void 0===s||"object"==typeof s&&null!==s,()=>`Internal error: sub-path has an invalid type and can't be patched: '${t.slice(0,e+1)}', type: '${null===s?null:typeof s}'`);const a=void 0===s?void 0===r?void 0:{}:Array.isArray(s)?[...s]:Object.assign({},s);if(void 0===a)return n(o,i),o;o[i]=a,o=a}const s=t[t.length-1];return void 0===r?n(o,s):o[s]=r,i}function Xr(e,t){const r=[];if("set"===e.type||"delete"===e.type)r.push(e.path);else if("batch"===e.type)for(const t of e.actions)r.push(...Xr(t,"as-is"));return"unique-and-sorted"===t?rn(r):r}function en(e,t){if(e.length<t.length)return!1;for(let r=0;r<t.length;r++)if(e[r]!==t[r])return!1;return!0}function tn(e){const t=[...e];return t.sort((e,t)=>{for(let r=0;r<e.length;r++){if(r===t.length)return 1;const n=e[r].localeCompare(t[r]);if(0!==n)return n}return e.length-t.length}),t}function rn(e){const t=tn(e),r=t;for(let e=0;e<t.length-1;e++){const n=t[e];for(let i=e+1;i<t.length;i++){const o=t[i];n.length===o.length&&en(n,o)&&(r[i]=void 0,e++)}}return r.filter(e=>void 0!==e)}zr.d=(e,t)=>{for(var r in t)zr.o(t,r)&&!zr.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},zr.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const nn=(on={Observable:()=>d.Observable,Subject:()=>d.Subject},sn={},zr.d(sn,on),sn);var on,sn,an,cn=zr(2794);class un{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 r=this._buildPath(e);if(void 0!==r.value)return r.value;const n=t(e);return this._setNodeValue(r,n,void 0===n),n}set(e,t){const r=void 0===t?this._findNode(e):this._buildPath(e);r&&this._setNodeValue(r,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 r=(void 0===t.value?0:1)+t.childrenWithValue;r>0&&this._updateChildrenWithValue(t,-r),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const r=this.getNode(e);return void 0===r?0:r.childrenWithValue+("node-and-children"===t&&void 0!==r.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const r=[];let n=this.root,i=t(n.value,r);if(i!==un.StopFillToken){this._setNodeValue(n,i,!1);for(let o=0;o<e.length;o++){const s=e[o];r.push(s);let a=n.children.get(s);if(i=t(null==a?void 0:a.value,r),i===un.StopFillToken)break;a||(a={children:new Map,parent:n,childrenWithValue:0},n.children.set(s,a)),this._setNodeValue(a,i,!1),n=a}this._runGc(n)}}visitDfs(e,t,r=[]){const n=this.getNode(r);void 0!==n&&this._visitDfs(e,n,t,[...r])}_visitDfs(e,t,r,n){if("pre-order"===e&&!1===r(t.value,n))return!1;for(const[i,o]of t.children){if(n.push(i),!this._visitDfs(e,o,r,n))return!1;n.pop()}return"in-order"!==e||!1!==r(t.value,n)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const r of e)if(t=t.children.get(r),!t)return;return t}_findNode(e){let t=this.root;for(let r=0;r<e.length&&t;r++)t=t.children.get(e[r]);return t}_buildPath(e){let t=this.root;for(let r=0;r<e.length;r++){const n=e[r];let i=t.children.get(n);i||(i={children:new Map,parent:t,childrenWithValue:0},t.children.set(n,i)),t=i}return t}_setNodeValue(e,t,r){if(e.value!==t){const r=void 0===t?-1:void 0===e.value?1:0;e.value=t,this._updateChildrenWithValue(e,r)}r&&this._runGc(e)}_updateChildrenWithValue(e,t){if(0!==t)for(let r=e.parent;r;r=r.parent)if(r.childrenWithValue+=t,r.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))}}un.StopFillToken=Symbol("Trie.StopFillToken");class ln extends nn.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class dn{constructor(e){this.rootState=e,this.observersTrie=new un,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,cn.Tj)(e=>e.value))}observeChanges(e,t=[]){return this._observeChanges(e,t,"all-details")}set(e,t,r){(null==r?void 0:r(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=Jr(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Xr(e,"unique-and-sorted"),r=this.selectChildPathsWithObservers(t),n=rn([...t,...r]),i=new un;for(const e of n)i.fillPath(e,()=>!0);i.visitDfs("pre-order",(t,r)=>{const n=this.observersTrie.get(r);if(n){const t=this.get(r),i=n.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,r):void 0;n.next({action:e,value:t,oldValue:i})}})}_observeChanges(e,t=[],r){const n=0===t.length?void 0:new un;for(const e of t)null==n||n.set(e,!0);return new nn.Observable(t=>{const i=this.observersTrie.getOrSet(e,()=>new ln);i.isAllDetailsMode=i.isAllDetailsMode||"all-details"===r;const o={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(o);const s=i.pipe((0,cn.pb)(({action:e})=>void 0===n||Xr(e,"as-is").some(e=>!n.get(e))),(0,cn.Tj)(({action:t,value:r,oldValue:n})=>{let o=this.stubForUnusedPaths;if(i.isAllDetailsMode){const r=Xr(t,"as-is");o=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=tn(e),r=t;for(let e=0;e<r.length-1;e++){const n=t[e];for(let i=e+1;i<t.length;i++)en(t[i],n)&&(r[i]=void 0,e++)}return r.filter(e=>void 0!==e)}(e.length>0?r.filter(t=>en(t,e)).map(t=>t.slice(e.length)):r)}return{value:r,oldValue:n,paths:o}})).subscribe(t);return()=>{s.unsubscribe(),i.observed||this.observersTrie.delete(e)}})}_get(e,t){let r=e;for(let e=0;e<t.length&&void 0!==r;e++){const n=t[e];r=null==r?void 0:r[n]}return r}selectChildPathsWithObservers(e){const t=[];for(const r of e)this.observersTrie.count(r,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,r)=>{e&&t.push([...r])},r);return t}}function hn(e,t,r=(e,t)=>e>t?1:e<t?-1:0,n=0,i=e.length-1){if(i<n)return-1;const o=Math.trunc((n+i)/2);return 0===r(t,e[o])?o:r(t,e[o])>0?hn(e,t,r,o+1,i):hn(e,t,r,n,o-1)}function pn(e,t,r=(e,t)=>e>t?1:e<t?-1:0){if(-1!==hn(e,t,r))return;let n;for(n=e.length-1;n>=0&&r(e[n],t)>0;n--)e[n+1]=e[n];e[n+1]=t}function fn(e,t,r=(e,t)=>e>t?1:e<t?-1:0){const n=hn(e,t,r);n>-1&&e.splice(n,1)}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(an||(an={}));const yn=100;class gn{constructor(e,t,r,n,i,o,s){this.rpcManager=e,this.clientIdService=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.querySender=o,this.socketManager=s,this.onOrphanDocuments=new d.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new bn,this.queryResultsSubject=new d.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe(()=>{this.refreshOngoingQueries()}),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}dumpSubscriptionInfo(){console.log("Ongoing queries:",this.ongoingQueries),console.log("ClientRequestId to local documents:",this.clientRequestIdToLocalDocuments),console.log("Local documents to clientRequestId:",this.localDocumentToClientRequestIds)}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return L(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:r,integrationId:n}=Ft(t),i=this.queryMappingManager.getMapping(r,n);return i?function(e,t){const r=[...e.unconditional||[]],n=new Map;for(const[r,i]of Object.entries(e.conditional||{})){const e=Mt(r);let o;if($t(e)){const r=lt(t,e.fieldName)??null;o=Lt(e.value,r,e.operator)}else o=vn(e,t);if(o)for(const e of i)n.set(e,(n.get(e)||0)+1)}for(const[t,i]of n.entries())i>=e.queriesMetadata[t].condCount&&r.push(t);return r}(i,e):[]}setClientRequestIdsForLocalDoc(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set,n=new Set(t?this.findQueriesForDocument(t,e).map(e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId):[]),i=new Set([...r,...n]);for(const t of[...r]){if(n.has(t))continue;r.delete(t);const i=this.clientRequestIdToLocalDocuments.get(t);i&&(i.delete(e),i.size||this.clientRequestIdToLocalDocuments.delete(t)),r.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let r=this.localDocumentToClientRequestIds.get(e);r||(r=new Set,this.localDocumentToClientRequestIds.set(e,r)),r.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...i]}errorOutAllQueries(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of r){const r=this.ongoingQueries.get(e);r&&(this.destructManager.isDestructing?r.dataSubject.complete():r.dataSubject.error(t),r.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const r of e){const e=this.ongoingQueries.get(r);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(r)||new Set,i=this.documentStore.sortAndLimitDocs(n,e.query),o=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(i,e)).some(Boolean);let s=e;for(;!s.allObservables;)s=L(s?.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case an.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+yn?an.ENABLED:an.DISABLED;break;case an.DISABLED:break;case an.ENABLED:if(n.size<e.query.limit+20){e.limitUnderflowState=an.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);L(e.allObservables).next(t)}}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 Ur(e.query);for(const r of this.ongoingQueries.values()){if(e===r)return;if(this.isValidParent(r)&&t.isSubqueryOfQuery(r.query))return r}}findValidParentOfQuery(e){const t=new Ur(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,r,n,i,o){return i&&this.socketManager.notifyWebSocketIsNeeded(),(0,d.defer)(()=>{const s=this.createOngoingQueryGraph(e,t,r,n,i,!0);o&&(s.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(s),s.allObservables=new d.ReplaySubject(1);const a=s.allObservables.pipe((0,d.switchMap)(e=>(0,d.combineLatest)(e).pipe(R(e=>this.joinResults(e,n,s)))),Gr(()=>this.allOngoingQueriesGotInitialResult(s)),(0,d.startWith)(void 0),(0,d.pairwise)(),Gr(([e,t])=>!gt(e,t)),R(([,e])=>e),i?(0,d.tap)():(0,d.take)(1),(0,d.finalize)(()=>{s.dataSubject.complete(),s.done=!0,this.completeAllSupportedQueries(s).then(),s.allObservables?.complete()})),c=this.collectAllObservables(s);return s.allObservables.next(c),a}).pipe((0,d.share)())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const r=[];for(const n of t){const t=L(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r)}registerQueryFinalizer(e){const t=e.clientRequestId,r=Ut(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,d.finalize)(async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,d.firstValueFrom)((0,d.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Gr(e=>0===e)))),this.queryMappingManager.removeQuery(r).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const r={clientRequestId:t};this.rpcManager.post("query/unsubscribe",r).catch(t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)})}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)}),Gr(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,o,s={}){if(s[t])return s[t];const a=this.clientIdService.generateClientRequestId(),c=[],u={clientRequestId:a,activated:o,alias:t,query:e,subscribe:i,dataSubject:new d.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new d.BehaviorSubject(0),queryRegistered:new d.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:i?an.UNKNOWN:an.DISABLED};this.registerQueryFinalizer(u),this.ongoingQueries.set(a,u),s[t]=u;for(const[e,o]of Object.entries(n)){const a=o.leftAlias;if(a!==t&&e!==t)continue;const l=a===t?e:a;if(a===t){const e=this.createOngoingQueryGraph(r[l],l,r,n,i,!1,s);e.joinCondition=o,c.push(e)}else u.supportingOngoingQuery=this.createOngoingQueryGraph(r[l],l,r,n,i,!1,s)}return u}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(Gr(Boolean),R(e=>({docs:e,alias:r}))));for(const r of e.supportedQueries)this.collectAllObservables(r,t);return t}joinResults(e,t,r){const n=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let i=n[r.alias].map(e=>({[r.alias]:e}));const o=this.getOngoingQueriesBfs(r),s=new Set;for(let e=1;e<o.length;e++){const r=o[e].alias;s.has(r)||(s.add(r),i=this.join(i,r,n[r],t[r]))}return i}join(e,t,r,n){if(!e.length)return e;const i=Object.keys(e[0]);if(!n||!i.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const o=new Map;return(r||[]).forEach(e=>{const t=this.transformKey(e[n.right]);o.has(t)||o.set(t,[]),L(o.get(t)).push(e)}),e.flatMap(e=>{const r=o.get(this.transformKey(e[n.leftAlias]?.[n.left]))||[];return r.length?r.map(r=>({...e,[t]:r})):n.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=L(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){const r=L(t.joinCondition),n=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const i=L(t.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===t.alias),o=new Set(e.map(e=>e[r.left]??null));for(const e of i)e.query.conditions.filter($t).filter(e=>e.fieldName===r.right).forEach(e=>{o.delete(e.value)});if(0===o.size)return!1;const s=bt(n);s.conditions=s.conditions.filter(e=>!$t(e)||e.fieldName!==r.right),[...o].forEach(e=>{s.conditions.push({fieldName:r.right,operator:"==",value:e})});const a={...t,query:s,activated:!0,gotInitialResponse:!1,dataSubject:new d.BehaviorSubject(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(a),this.ongoingQueries.set(a.clientRequestId,a),L(t.supportingOngoingQuery).supportedQueries.push(a),this.sendQueryToServerOrUseParentQuery(a),!0}{if(t.activated=!0,n.conditions.filter($t).filter(e=>e.fieldName===r.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const i=e.map(e=>e[r.left]??null).map(e=>({fieldName:r.right,operator:"==",value:e}));return i.length?(n.conditions.push(...i),this.sendQueryToServerOrUseParentQuery(t)):t.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=L(t.shift());t.push(...e.supportedQueries||[]),await(0,d.firstValueFrom)(e.unsubscribeBlockerCount.pipe(Gr(e=>0===e))),e.dataSubject.complete()}}transformKey(e){return e instanceof Date?`DATE AS string KEY: ${e.toISOString()}`:e}preDestruct(){this.unsubscribe()}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}sendQueryToServerOrUseParentQuery(e,t=!1){if(this.destructManager.isDestructing)return;const r=e.query,n=e.clientRequestId,i=Ut(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(r,i),this.ongoingQueries.set(n,e);const o=t?void 0:this.findValidParentOfOngoingQuery(e);o?this.useParentOngoingQuery(e,o).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const r={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new Ur(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,d.firstValueFrom)(t.queryRegistered.pipe(Gr(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",r).then(()=>{e.isInFlight=!1,e.queryRegistered.next(!0)}).catch(r=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,t.query,r),e.dataSubject.error(r)),e.done=!0}).finally(()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1)});const i=(0,d.race)(e.queryRegistered.pipe(Gr(Boolean),(0,d.delay)(2e3),(0,d.take)(1)),this.destructManager.observeIsDestructing().pipe((0,d.take)(1)));t.dataSubject.pipe((0,d.takeWhile)(()=>!e.done),(0,d.takeUntil)(i),Gr(Boolean),(0,d.tap)(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),R(e=>e.filter(e=>n.documentMatchesQuery(e)))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(Bt(r.__docId__,e.query.collectionName,e.query.integrationId),r);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>{this.destructManager.isDestructing?e.dataSubject.complete():e.dataSubject.error(t)}})}sendQueryToServer(e){const t=e.query.limit,r=t>0&&e.subscribe?t+yn:t,n={query:{...e.query,limit:r},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(n).then(t=>{e.isInFlight=!1,e.queryRegistered.next(!0),this.queryResultsSubject.next(t)}).catch(t=>{e.isInFlight=!1,this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(Pt.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0})}refreshOngoingQueries(){for(const e of this.ongoingQueries.values())this.sendQueryToServerOrUseParentQuery(e,!0)}migrateDocIds(e){const t=Object.keys(e);for(const r of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{r.has(t)&&(r.delete(t),r.add(e[t]))});t.forEach(t=>{ft(this.localDocumentToClientRequestIds,t,e[t])})}}function vn(e,t){for(const r of e.fields){const e=lt(t,r.fieldName)??null;if(Lt(r.value,e,r.operator))return!0;if(Lt(r.value,e,"!="))return!1}return!1}class bn{constructor(){this.stateService=new dn({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let r=0;const n=new Set;for(const i of e.conditions){if($t(i)&&["=="].includes(i.operator)){const e=Et(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];pn(s,t),this.stateService.set(o,s)}if(!e.conditions.length){const r=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(r)||[]];pn(n,t),this.stateService.set(r,n)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],r)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const r of t.conditions){const n=this.getConditionStatePath(t,r),i=[...this.stateService.get(n)||[]];fn(i,e),i.length?this.stateService.set(n,i):this.stateService.delete(n)}if(!t.conditions.length){const r=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(r)||[]];fn(n,e),this.stateService.set(r,n)}this.stateService.delete(this.getQueryMetadataStatePath(t,e))}),t}getMapping(e,t){return this.stateService.get(["queryMapping",e,t,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",(r=t,It(r))];var r}}class mn{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(0,d.lastValueFrom)((0,d.combineLatest)(t).pipe((0,d.filter)(e=>!e.includes(!0)),(0,d.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=L(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){B(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new d.BehaviorSubject(!0)}}class _n{constructor(e,t,r){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)}),r.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let r=this.queueManagers.get(e);r||(r=new Map,this.queueManagers.set(e,r));let n=r.get(t);return n||(n=new wn(e,t,this.rpcManager,this.socketManager),r.set(t,n)),n}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const Sn="subscriptionMutex";class wn{constructor(e,t,r,n){this.integrationId=e,this.topicName=t,this.rpcManager=r,this.socketManager=n,this.messagesSubject=new d.Subject,this.subscriberCount=0,this.lockManager=new mn}async produce(e){await this.lockManager.lock(Sn);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(Sn)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),(0,d.defer)(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,d.finalize)(()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))}async performSubscribe(){await this.lockManager.lock(Sn);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 d.Subject}finally{this.lockManager.release(Sn)}}async performUnsubscribe(){await this.lockManager.lock(Sn);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(Sn)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class In{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(0,d.firstValueFrom)((0,d.interval)(10).pipe((0,d.filter)(()=>this.attemptConsume()),(0,d.first)()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}const On={TRACE_ID:"x-squid-traceid",SECRET:"x-squid-secret",APP_API_KEY:"x-app-api-key",APP_ID:"x-squid-appid",CLIENT_ID:"x-squid-clientid",CLIENT_VERSION:"x-squid-client-version",SOURCE_IP:"x-squid-source-ip"},Mn=e=>e();class En extends Error{constructor(e,t,r,n,i){super(e),this.statusCode=t,this.url=r,this.headers=n,this.body=i}}const Tn="1.0.393";async function kn(e){const t=await Pn({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage});return t.body=Dn(t.body),t}async function An(e){const t=await Pn({...e,method:"GET",files:[],filesFieldName:""});return t.body=Dn(t.body),t}async function jn(e){const t=await Pn({...e,method:"PUT"});return t.body=Dn(t.body),t}async function Cn(e){const t=await Pn({...e,method:"PATCH"});return t.body=Dn(t.body),t}async function xn(e){const t=await Pn({...e,method:"DELETE",files:[],filesFieldName:""});return t.body=Dn(t.body),t}async function Pn({headers:e,files:t,filesFieldName:r,message:n,url:i,extractErrorMessage:o,method:s}){const a=new Headers(e);a.append(On.TRACE_ID,function(e="n_"){return`${e}${z(10).toLowerCase()}`}("c_")),a.append(On.CLIENT_VERSION,Tn);const c={method:s,headers:a,body:void 0};if("GET"!==s&&"DELETE"!==s)if(t&&t.length){const e=new FormData;for(const n of t)e.append(r||"files",n,n.name);e.append("body",Ot(n)),c.body=e}else void 0!==n&&(a.append("Content-Type","application/json"),c.body=Ot(n));else"DELETE"===s&&void 0!==n&&(a.append("Content-Type","application/json"),c.body=Ot(n));try{const e=await fetch(i,c),t={};if(e.headers.forEach((e,r)=>{t[r]=e}),!e.ok){const r=await e.text(),n=Dn(r);if(!o)throw new En(r,e.status,i,t,n);let s;try{s="string"==typeof n?n:n?.message||r}catch{}throw s||(s=e.statusText),new En(s,e.status,i,t,n)}const r=await e.text();return Pt.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Pt.debug(`Unable to perform fetch request to url: ${i}`,e),e}}function Dn(e){if(e){try{return Mt(e)}catch{}return e}}class Nn{constructor(e,t,r,n,i,o){this.region=e,this.appId=t,this.authManager=i,this.clientIdService=o,this.staticHeaders={},this.onGoingRpcCounter=new d.BehaviorSubject(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")}),r.onDestruct(async()=>{await this.awaitAllSettled()});const s=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new In(60*s,5),ai:new In(20*s,5),secret:new In(20*s,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:r}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return r&&(n+=`; IntegrationId ${r}`),{Authorization:n}}async awaitAllSettled(){await(0,d.firstValueFrom)(this.onGoingRpcCounter.pipe((0,d.filter)(e=>0===e)))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,r=[],n="files"){return(await this.rawPost(e,t,r,n)).body}async rawPost(e,t,r=[],n="files",i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const s=await this.getAuthHeaders(),a={...this.staticHeaders,...s};Pt.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:o(this.region,this.appId,e);return await kn({url:c,headers:a,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async get(e,t,r=!0){return(await this.rawGet(e,t,r)).body}async rawGet(e,t,r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),i={...this.staticHeaders,...n};let s=e.startsWith("http://")||e.startsWith("https://")?e:o(this.region,this.appId,e);if(t&&Object.keys(t).length>0){const e=new URLSearchParams;Object.entries(t).forEach(([t,r])=>{e.append(t,String(r))}),s+=`?${e.toString()}`}return Pt.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await An({url:s,headers:i,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async put(e,t,r=[],n="files"){return(await this.rawPut(e,t,r,n)).body}async rawPut(e,t,r=[],n="files",i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const s=await this.getAuthHeaders(),a={...this.staticHeaders,...s};Pt.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:o(this.region,this.appId,e);return await jn({url:c,headers:a,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async patch(e,t,r=[],n="files"){return(await this.rawPatch(e,t,r,n)).body}async rawPatch(e,t,r=[],n="files",i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const s=await this.getAuthHeaders(),a={...this.staticHeaders,...s};Pt.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:o(this.region,this.appId,e);return await Cn({url:c,headers:a,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async delete(e,t,r=!0){return(await this.rawDelete(e,t,r)).body}async rawDelete(e,t,r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),i={...this.staticHeaders,...n};Pt.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const s=e.startsWith("http://")||e.startsWith("https://")?e:o(this.region,this.appId,e);return await xn({url:s,headers:i,message:t,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?L(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?L(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):L(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class Rn{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 qn(){}const Fn="undefined"!=typeof process&&process.versions?.node?r(86):xt().WebSocket;class Bn{constructor(e,t,r,n=Mn,i,o){this.clientIdService=e,this.region=t,this.appId=r,this.messageNotificationWrapper=n,this.destructManager=i,this.authManager=o,this.webSocketObserver=new d.Subject,this.allMessagesObserver=new d.Subject,this.connectionReady=new d.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new d.Subject,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new d.BehaviorSubject(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe((0,d.filter)(Boolean),(0,d.take)(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe((0,d.skip)(1),(0,d.filter)(e=>!e),(0,d.switchMap)(()=>(0,d.race)((0,d.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,d.filter)(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Pt.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Pt.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe((0,d.filter)(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe((0,d.filter)(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?Pt.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Pt.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Pt.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Pt.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}getClientInfo(){this.sendMessage({type:"getClientInfo"})}keepAlive(){this.lastTick&&(Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(Pt.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,d.distinctUntilChanged)())}async awaitConnectionReady(){await(0,d.firstValueFrom)(this.observeConnectionReady().pipe((0,d.filter)(Boolean)))}notifyWebSocketIsNeeded(){this.webSocketNeededSubject.next(!0)}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){this.webSocketNeededSubject.next(!0),await(0,d.firstValueFrom)(this.connectionReady.pipe((0,d.filter)(Boolean)));const t=await this.authManager.getToken();if(this.connectionReady.value)try{B(this.socket,"Socket is undefined in sendMessageAsync");const r=Ot({message:e,authToken:t});Pt.debug(this.clientIdService.getClientId(),"Sending message to socket: ",r),this.socket.send(r)}catch(t){this.socket?.connected?console.error("Websocket message is ignored due to a non-recoverable error",t):(this.connectionReady.next(!1),await this.sendMessageAsync(e))}else await this.sendMessageAsync(e)}sendKillMessage(){this.socket?.connected&&this.socket.send(Ot({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=o(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();Pt.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const r=`${e}?clientId=${t}`;this.socket=function(e,t={}){let r,n=0,i=1;const o={connected:!1,closeCalled:!1,open(){r=new(Fn?.WebSocket??Fn)(e,t.protocols||[]),r.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.")}:qn,r.onopen=function(e){o.connected=!0,(t.onopen||qn)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return Pt.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||qn)(e),void o.reconnect(e);(t.onclose||qn)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):o.closeCalled||(t.onerror||qn)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout(function(){(t.onreconnect||qn)(e),Pt.debug("WebSocket trying to reconnect..."),o.open()},t.timeoutMillis||1e3):(t.onmaximum||qn)(e)},json(e){r.send(JSON.stringify(e))},send(e){r.send(e)},close(e=4999,t){o.closeCalled=!0;try{o.connected=!1,clearTimeout(i),i=void 0,r.close(e,t)}catch(e){}}};return o.open(),o}(r,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Pt.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Pt.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Pt.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Pt.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Pt.debug(t,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}disconnectForTest(){this.connectionReady.next(!1),this.socket?.close(4998)}onConnectionReady(){this.connectionReady.next(!0),this.connectedAtLeastOnce?this.sendMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return Pt.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=Mt(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Pt.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new d.Subject;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe((0,d.tap)(e=>t.push(e)),(0,d.debounceTime)(100)).subscribe(async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await(0,d.firstValueFrom)((0,d.timer)(0)),this.connectionReady.next(!1),await(0,d.firstValueFrom)((0,d.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Ln(e){var t,r;r="Invalid application ID",B(function(e){return"string"==typeof e}(t=e),()=>U(r,"Not a string",t));const[n,i,o,s]=e.split("-");return B(!s,`Invalid application ID: ${e}`),{appId:n,environmentId:i??"prod",squidDeveloperId:o}}function Qn(e,t){return`${Ln(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function Un(e,t,r){return`${Qn(e,t)}${r?`-${r}`:""}`}function $n(e){const t=Ln(e);return Qn(t.appId,t.environmentId)}class Gn{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,r){const n={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:r};await this.rpcManager.post("storage/uploadFile",n,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const r={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",r)}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 Vn{constructor(e,t,r,n){this.rpcManager=e,this.region=t,this.appId=r,this.apiKey=n}async aiSearch(e){return await this.rpcManager.post("web/aiSearch",{query:e})}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e,t){B(this.apiKey,"API key is required to create a short URL");const r=s(this.region,"openapi/sqd/shorten"),n={url:e,appId:this.appId,secondsToLive:t},i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!i.ok)throw console.error("Error making POST request to shorten endpoint",i.statusText),new Error(`${i.statusText}: ${i.text}`);return await i.json()}async createShortUrls(e,t){B(this.apiKey,"API key is required to create a short URL");const r=s(this.region,"openapi/sqd/shortenMany"),n={urls:e,appId:this.appId,secondsToLive:t},i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!i.ok)throw console.error("Error making POST request to shortenMany endpoint",i.statusText),new Error(`${i.statusText}: ${i.text}`);return await i.json()}async deleteShortUrl(e){B(this.apiKey,"API key is required to delete a short URL");const t=s(this.region,"openapi/sqd/delete"),r={id:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(r)});if(!n.ok)throw console.error("Error making POST request to delete endpoint",n.statusText),new Error(n.statusText)}async deleteShortUrls(e){B(this.apiKey,"API key is required to delete a short URL");const t=s(this.region,"openapi/sqd/deleteMany"),r={ids:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(r)});if(!n.ok)throw console.error("Error making POST request to delete endpoint",n.statusText),new Error(n.statusText)}}class Wn{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new yr,B(e.appId,"APP_ID_MUST_BE_PROVIDED");for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this))){const t=this[e];"function"!=typeof t||"constructor"===e||e.startsWith("_")||(this[e]=t.bind(this))}const t="prod"!==e.environmentId&&e.squidDeveloperId,r=Un(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Dt(this.destructManager),Pt.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new ct(e.apiKey,e.authProvider),this.socketManager=new Bn(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Nn(e.region,r,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new Mr(this.socketManager,this.rpcManager),this.jobClient=new wr(this.socketManager,this.rpcManager,this.clientIdService),this.aiClient=new ot(this.socketManager,this.rpcManager,this.jobClient),this.apiClient=new at(this.rpcManager),this.documentStore=new _r,this.lockManager=new mn,this.distributedLockManager=new gr(this.socketManager,this.destructManager),this.documentIdentityService=new br(this.documentStore,this.destructManager),this.documentReferenceFactory=new mr(this.documentIdentityService),this.querySender=new Vr(this.rpcManager,this.destructManager),this.observabilityClient=new Tr(this.rpcManager),this.schedulerClient=new Rn(this.rpcManager),this._appId=r,this.querySubscriptionManager=new gn(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager),this.localQueryManager=new $r(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const n=new Ir(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Wt(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new pr(this.documentStore,n,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new nr(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new jt(this.rpcManager),this.nativeQueryManager=new Or(this.rpcManager),this._connectionDetails=new ir(this.clientIdService,this.socketManager),this.queueManagerFactory=new _n(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new l(this.rpcManager,this.options.region,$n(r)),this.webClient=new Vn(this.rpcManager,this.options.region,$n(r),this.options.apiKey)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}static getInstance(e){const t=It(e);let r=Wn.squidInstancesMap[t];return r||(r=new Wn(e),Wn.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(Wn.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=We){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)}executeNativeRelationalQuery(e,t,r={}){const n={type:"relational",query:t,params:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,r){const n={type:"mongo",collectionName:t,aggregationPipeline:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeElasticQuery(e,t,r,n="_search",i="GET"){const o={type:"elasticsearch",index:t,endpoint:n,method:i,body:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(o)}ai(){return this._validateNotDestructed(),this.aiClient}job(){return this._validateNotDestructed(),this.jobClient}api(){return this._validateNotDestructed(),this.apiClient}admin(){return this._validateNotDestructed(),this.adminClient}web(){return this._validateNotDestructed(),this.webClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new Gn(e,this.rpcManager)}personalStorage(e){return this._validateNotDestructed(),new jr(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new Sr(this.rpcManager)}acquireLock(e){return this._validateNotDestructed(),this.distributedLockManager.lock(e)}async withLock(e,t){const r=await this.acquireLock(e);try{return await t(r)}finally{r.release()}}queue(e,t=He){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(Wn.squidInstancesMap).find(([,e])=>e===this);e&&delete Wn.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,r)=>o(e,t,r),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,r)=>Un(e,t,r)}}_validateNotDestructed(){B(!this.destructManager.isDestructing,"The client was already destructed.")}}var Hn=exports;for(var zn in n)Hn[zn]=n[zn];n.__esModule&&Object.defineProperty(Hn,"__esModule",{value:!0})})();
|
|
1
|
+
(()=>{"use strict";var e={86:e=>{e.exports=require("ws")},150:function(e,t,i){var n=this&&this.__createBinding||(Object.create?function(e,t,i,n){void 0===n&&(n=i);var r=Object.getOwnPropertyDescriptor(t,i);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,n,r)}:function(e,t,i,n){void 0===n&&(n=i),e[n]=t[i]}),r=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||n(t,e,i)};Object.defineProperty(t,"__esModule",{value:!0});const s=i(642);t.default=s.PromisePool,r(i(273),t),r(i(642),t),r(i(837),t),r(i(426),t),r(i(858),t),r(i(172),t)},172:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValidationError=void 0;class i extends Error{constructor(e){super(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e){return new this(e)}}t.ValidationError=i},234:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolExecutor=void 0;const n=i(642),r=i(172),s=i(837),o=i(858);t.PromisePoolExecutor=class{constructor(){this.meta={tasks:[],items:[],errors:[],results:[],stopped:!1,concurrency:10,shouldResultsCorrespond:!1,processedItems:[],taskTimeout:0},this.handler=e=>e,this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[]}useConcurrency(e){if(!this.isValidConcurrency(e))throw r.ValidationError.createFrom(`"concurrency" must be a number, 1 or up. Received "${e}" (${typeof e})`);return this.meta.concurrency=e,this}isValidConcurrency(e){return"number"==typeof e&&e>=1}withTaskTimeout(e){return this.meta.taskTimeout=e,this}concurrency(){return this.meta.concurrency}useCorrespondingResults(e){return this.meta.shouldResultsCorrespond=e,this}shouldUseCorrespondingResults(){return this.meta.shouldResultsCorrespond}taskTimeout(){return this.meta.taskTimeout}for(e){return this.meta.items=e,this}items(){return this.meta.items}itemsCount(){const e=this.items();return Array.isArray(e)?e.length:NaN}tasks(){return this.meta.tasks}activeTaskCount(){return this.activeTasksCount()}activeTasksCount(){return this.tasks().length}processedItems(){return this.meta.processedItems}processedCount(){return this.processedItems().length}processedPercentage(){return this.processedCount()/this.itemsCount()*100}results(){return this.meta.results}errors(){return this.meta.errors}withHandler(e){return this.handler=e,this}hasErrorHandler(){return!!this.errorHandler}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers=e,this}onTaskFinished(e){return this.onTaskFinishedHandlers=e,this}hasReachedConcurrencyLimit(){return this.activeTasksCount()>=this.concurrency()}stop(){throw this.markAsStopped(),new o.StopThePromisePoolError}markAsStopped(){return this.meta.stopped=!0,this}isStopped(){return this.meta.stopped}async start(){return await this.validateInputs().prepareResultsArray().process()}validateInputs(){if("function"!=typeof this.handler)throw r.ValidationError.createFrom("The first parameter for the .process(fn) method must be a function");const e=this.taskTimeout();if(!(null==e||"number"==typeof e&&e>=0))throw r.ValidationError.createFrom(`"timeout" must be undefined or a number. A number must be 0 or up. Received "${String(e)}" (${typeof e})`);if(!this.areItemsValid())throw r.ValidationError.createFrom(`"items" must be an array, an iterable or an async iterable. Received "${typeof this.items()}"`);if(this.errorHandler&&"function"!=typeof this.errorHandler)throw r.ValidationError.createFrom(`The error handler must be a function. Received "${typeof this.errorHandler}"`);return this.onTaskStartedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw r.ValidationError.createFrom(`The onTaskStarted handler must be a function. Received "${typeof e}"`)}),this.onTaskFinishedHandlers.forEach(e=>{if(e&&"function"!=typeof e)throw r.ValidationError.createFrom(`The error handler must be a function. Received "${typeof e}"`)}),this}areItemsValid(){const e=this.items();return!!Array.isArray(e)||"function"==typeof e[Symbol.iterator]||"function"==typeof e[Symbol.asyncIterator]}prepareResultsArray(){const e=this.items();return Array.isArray(e)&&this.shouldUseCorrespondingResults()?(this.meta.results=Array(e.length).fill(n.PromisePool.notRun),this):this}async process(){let e=0;for await(const t of this.items()){if(this.isStopped())break;this.shouldUseCorrespondingResults()&&(this.results()[e]=n.PromisePool.notRun),this.startProcessing(t,e),e+=1,await this.waitForProcessingSlot()}return await this.drained()}async waitForProcessingSlot(){for(;this.hasReachedConcurrencyLimit();)await this.waitForActiveTaskToFinish()}async waitForActiveTaskToFinish(){await Promise.race(this.tasks())}startProcessing(e,t){const i=this.createTaskFor(e,t).then(e=>{this.save(e,t).removeActive(i)}).catch(async n=>{await this.handleErrorFor(n,e,t),this.removeActive(i)}).finally(()=>{this.processedItems().push(e),this.runOnTaskFinishedHandlers(e)});this.tasks().push(i),this.runOnTaskStartedHandlers(e)}async createTaskFor(e,t){if(void 0===this.taskTimeout())return this.handler(e,t,this);const[i,n]=this.createTaskTimeout(e);return Promise.race([this.handler(e,t,this),i()]).finally(n)}createTaskTimeout(e){let t;return[async()=>new Promise((i,n)=>{t=setTimeout(()=>{n(new s.PromisePoolError(`Task in promise pool timed out after ${this.taskTimeout()}ms`,e))},this.taskTimeout())}),()=>clearTimeout(t)]}save(e,t){return this.shouldUseCorrespondingResults()?this.results()[t]=e:this.results().push(e),this}removeActive(e){return this.tasks().splice(this.tasks().indexOf(e),1),this}async handleErrorFor(e,t,i){if(this.shouldUseCorrespondingResults()&&(this.results()[i]=n.PromisePool.failed),!this.isStoppingThePoolError(e)){if(this.isValidationError(e))throw this.markAsStopped(),e;this.hasErrorHandler()?await this.runErrorHandlerFor(e,t):this.saveErrorFor(e,t)}}isStoppingThePoolError(e){return e instanceof o.StopThePromisePoolError}isValidationError(e){return e instanceof r.ValidationError}async runErrorHandlerFor(e,t){try{await(this.errorHandler?.(e,t,this))}catch(e){this.rethrowIfNotStoppingThePool(e)}}runOnTaskStartedHandlers(e){this.onTaskStartedHandlers.forEach(t=>{t(e,this)})}runOnTaskFinishedHandlers(e){this.onTaskFinishedHandlers.forEach(t=>{t(e,this)})}rethrowIfNotStoppingThePool(e){if(!this.isStoppingThePoolError(e))throw e}saveErrorFor(e,t){this.errors().push(s.PromisePoolError.createFrom(e,t))}async drained(){return await this.drainActiveTasks(),{errors:this.errors(),results:this.results()}}async drainActiveTasks(){await Promise.all(this.tasks())}}},273:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},426:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},642:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePool=void 0;const n=i(234);class r{constructor(e){this.timeout=void 0,this.concurrency=10,this.items=e??[],this.errorHandler=void 0,this.onTaskStartedHandlers=[],this.onTaskFinishedHandlers=[],this.shouldResultsCorrespond=!1}withConcurrency(e){return this.concurrency=e,this}static withConcurrency(e){return(new this).withConcurrency(e)}withTaskTimeout(e){return this.timeout=e,this}static withTaskTimeout(e){return(new this).withTaskTimeout(e)}for(e){const t=new r(e).withConcurrency(this.concurrency);return"function"==typeof this.errorHandler&&t.handleError(this.errorHandler),"number"==typeof this.timeout?t.withTaskTimeout(this.timeout):t}static for(e){return(new this).for(e)}handleError(e){return this.errorHandler=e,this}onTaskStarted(e){return this.onTaskStartedHandlers.push(e),this}onTaskFinished(e){return this.onTaskFinishedHandlers.push(e),this}useCorrespondingResults(){return this.shouldResultsCorrespond=!0,this}async process(e){return(new n.PromisePoolExecutor).useConcurrency(this.concurrency).useCorrespondingResults(this.shouldResultsCorrespond).withTaskTimeout(this.timeout).withHandler(e).handleError(this.errorHandler).onTaskStarted(this.onTaskStartedHandlers).onTaskFinished(this.onTaskFinishedHandlers).for(this.items).start()}}t.PromisePool=r,r.notRun=Symbol("notRun"),r.failed=Symbol("failed")},837:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PromisePoolError=void 0;class i extends Error{constructor(e,t){super(),this.raw=e,this.item=t,this.name=this.constructor.name,this.message=this.messageFrom(e),Error.captureStackTrace&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}static createFrom(e,t){return new this(e,t)}messageFrom(e){return e instanceof Error||"object"==typeof e?e.message:"string"==typeof e||"number"==typeof e?e.toString():""}}t.PromisePoolError=i},858:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.StopThePromisePoolError=void 0;class i extends Error{}t.StopThePromisePoolError=i}},t={};function i(n){var r=t[n];if(void 0!==r)return r.exports;var s=t[n]={exports:{}};return e[n].call(s.exports,s,s.exports,i),s.exports}i.d=(e,t)=>{for(var n in t)i.o(t,n)&&!i.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},i.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var n={};i.r(n),i.d(n,{AI_AGENTS_INTEGRATION_ID:()=>Le,AI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Re,AI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Ne,AI_EMBEDDINGS_MODEL_NAMES:()=>_e,AI_IMAGE_MODEL_NAMES:()=>qe,AI_PROVIDER_TYPES:()=>ye,AI_STATUS_MESSAGE_PARENT_MESSAGE_ID_TAG:()=>pe,AI_STATUS_MESSAGE_RESULT_TAG:()=>ge,ALL_OPERATORS:()=>nt,ANTHROPIC_CHAT_MODEL_NAMES:()=>ve,API_INJECTION_FIELD_TYPES:()=>xe,ARRAY_OPERATORS:()=>it,AUTH_INTEGRATION_TYPES:()=>$e,AdminClient:()=>l,AiAgentClient:()=>ne,AiAgentReference:()=>te,AiAssistantClient:()=>se,AiAudioClient:()=>oe,AiClient:()=>ot,AiImageClient:()=>ae,AiKnowledgeBaseClient:()=>le,AiKnowledgeBaseReference:()=>ue,AiMatchMakingClient:()=>he,ApiClient:()=>ct,ApiKeysSecretClient:()=>u,AuthManager:()=>ut,BUILT_IN_AGENT_ID:()=>G,BUILT_IN_DB_INTEGRATION_ID:()=>Ke,BUILT_IN_QUEUE_INTEGRATION_ID:()=>We,BUILT_IN_STORAGE_INTEGRATION_ID:()=>ze,BackendFunctionManager:()=>At,BaseQueryBuilder:()=>Wt,CLIENT_CONNECTION_STATES:()=>st,CLIENT_ID_GENERATOR_KEY:()=>jt,CLIENT_REQUEST_ID_GENERATOR_KEY:()=>xt,Changes:()=>Yt,ClientIdService:()=>Ft,CollectionReference:()=>ii,CollectionReferenceFactory:()=>ri,ConnectionDetails:()=>si,DATA_INTEGRATION_TYPES:()=>Ue,DEFAULT_SHORT_ID_LENGTH:()=>K,DataManager:()=>gi,DereferencedJoin:()=>Xt,DestructManager:()=>yi,DistributedLockImpl:()=>bi,DistributedLockManager:()=>mi,DocumentReference:()=>Vt,DocumentReferenceFactory:()=>vi,DocumentStore:()=>Si,EMPTY_CHAT_ID:()=>re,ENVIRONMENT_IDS:()=>$,ExtractionClient:()=>wi,FETCH_BEYOND_LIMIT:()=>yn,FLUX_MODEL_NAMES:()=>Ae,GEMINI_CHAT_MODEL_NAMES:()=>be,GRAPHQL_INTEGRATION_TYPES:()=>Ge,GROK_CHAT_MODEL_NAMES:()=>Ie,GroupedJoin:()=>ti,HTTP_INTEGRATION_TYPES:()=>Ve,HttpStatus:()=>Be,INTEGRATION_SCHEMA_TYPES:()=>He,INTEGRATION_TYPES:()=>Qe,IntegrationClient:()=>a,JobClient:()=>Mi,JoinQueryBuilder:()=>Zt,LastUsedValueExecuteFunctionCache:()=>Dt,LimitUnderflowState:()=>un,LocalQueryManager:()=>Gi,METRIC_DOMAIN:()=>et,METRIC_FUNCTIONS:()=>Xe,METRIC_INTERVAL_ALIGNMENT:()=>tt,MatchMaker:()=>de,MutationSender:()=>Ti,NOOP_FN:()=>kn,NativeQueryManager:()=>_i,NotificationClient:()=>ki,OPENAI_AUDIO_CREATE_SPEECH_MODEL_NAMES:()=>Ce,OPENAI_AUDIO_MODEL_NAMES:()=>Oe,OPENAI_AUDIO_TRANSCRIPTION_MODEL_NAMES:()=>Ee,OPENAI_CHAT_MODEL_NAMES:()=>me,OPENAI_EMBEDDINGS_MODEL_NAMES:()=>Me,OPENAI_IMAGE_MODEL_NAMES:()=>ke,OPEN_AI_CREATE_SPEECH_FORMATS:()=>Fe,ObservabilityClient:()=>Ci,Pagination:()=>Ht,PersonalStorageClient:()=>Ai,QueryBuilder:()=>Jt,QueryBuilderFactory:()=>Kt,QuerySender:()=>Hi,QuerySubscriptionManager:()=>mn,QueueManagerFactory:()=>Sn,QueueManagerImpl:()=>Mn,RAG_TYPES:()=>je,RERANK_PROVIDERS:()=>fe,RateLimiter:()=>Tn,RpcManager:()=>jn,SQUID_BUILT_IN_INTEGRATION_IDS:()=>Je,SQUID_METRIC_NAMES:()=>Ze,SQUID_REGIONS:()=>rt,STABLE_DIFFUSION_MODEL_NAMES:()=>De,SchedulerClient:()=>xn,SecretClient:()=>c,SocketManager:()=>Ln,Squid:()=>Kn,SquidClientError:()=>En,StorageClient:()=>Vn,VENDOR_AI_CHAT_MODEL_NAMES:()=>Se,VOYAGE_EMBEDDING_MODEL_NAMES:()=>Te,WebClient:()=>Hn,base64ToFile:()=>ee,compareArgsByReference:()=>Ct,compareArgsBySerializedValue:()=>Ot,deserializeQuery:()=>Ni,generateId:()=>H,generateShortId:()=>z,generateShortIds:()=>J,generateUUID:()=>V,getConsoleUrl:()=>o,getCustomizationFlag:()=>qt,isBuiltInIntegrationId:()=>Ye,isPlaceholderParam:()=>Pe,isVendorAiChatModelName:()=>we,rawSquidHttpDelete:()=>Nn,rawSquidHttpGet:()=>Dn,rawSquidHttpPatch:()=>qn,rawSquidHttpPost:()=>On,rawSquidHttpPut:()=>An,tryDeserializing:()=>Fn,visitQueryResults:()=>qi});const r=["aiData","api","application","application-kotlin","auth","backend-function","connector","integration","internal-storage","internalCodeExecutor","mutation","named-query","native-query","observability","openapi","query","queue","quota","scheduler","secret","storage","webhooks","ws","personalStorage","internal-extraction","notification"];function s(e,t,i,n,s){let o="https",a=`${n||t}.${s||e}.${new URL("https://squid.cloud").host}`,c="";/^local/.test(e)&&(o="http",c=r.includes(i.replace(/^\//,"").split("/")[0]||"")?"8001":"8000",/android$/.test(e)?a="10.0.2.2":function(e){return/ios$/.test(e)}(e)&&(a="localhost"));const u=o+"://"+a+(c?`:${c}`:""),l=i.replace(/^\/+/,"");return l?`${u}/${l}`:u}function o(e,t=""){return s(function(e){return e.includes("sandbox")?"us-east-1.aws.sandbox":e.includes("local")?"local":e.includes("staging")?"us-central1.gcp.staging":"us-east-1.aws"}(e),"console",t)}class a{constructor(e,t,i){this.rpcManager=e,this.iacBaseUrl=o(t,`openapi/iac/applications/${i}/integrations`)}async list(e){const t=await this.rpcManager.get(this.iacBaseUrl);return e?t.filter(t=>t.type===e):t}async get(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}`)}async getIntegrationSchema(e){return await this.rpcManager.get(`${this.iacBaseUrl}/${e}/schema`)}async delete(e){await this.rpcManager.delete(`${this.iacBaseUrl}/${e}`)}async deleteMany(e){await Promise.all(e.map(e=>this.delete(e)))}async upsertIntegration(e){await this.rpcManager.put(`${this.iacBaseUrl}/${e.id}`,e)}}class c{constructor(e){this.rpcManager=e}async get(e){const t={key:e};return await this.rpcManager.post("secret/get",t)||void 0}getAll(){return this.rpcManager.post("secret/getAll",{})}async upsert(e,t){return this.upsertMany([{key:e,value:t}]).then(e=>e[0])}async upsertMany(e){if(0===e.length)return[];const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e,t=!1){const i={keys:[e],force:t};return this.rpcManager.post("secret/delete",i)}async deleteMany(e,t=!1){if(0===e.length)return;const i={keys:e,force:t};return this.rpcManager.post("secret/delete",i)}get apiKeys(){return new u(this.rpcManager)}}class u{constructor(e){this.rpcManager=e}get(e){const t={key:e};return this.rpcManager.post("secret/api-key/get",t)}getAll(){return this.rpcManager.post("secret/api-key/getAll",{})}upsert(e){const t={key:e};return this.rpcManager.post("secret/api-key/upsert",t)}delete(e){const t={key:e};return this.rpcManager.post("secret/api-key/delete",t)}}class l{constructor(e,t,i){this.rpcManager=e,this.region=t,this.appId=i,this.integrationClient=new a(this.rpcManager,this.region,this.appId),this.secretClient=new c(this.rpcManager)}integrations(){return this.integrationClient}secrets(){return this.secretClient}}const h=require("rxjs");function d(e){return"function"==typeof e}function p(e){return function(t){if(function(e){return d(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}var g=function(e,t){return g=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},g(e,t)};function f(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}g(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function y(e){var t="function"==typeof Symbol&&Symbol.iterator,i=t&&e[t],n=0;if(i)return i.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function m(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var n,r,s=i.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(n=s.next()).done;)o.push(n.value)}catch(e){r={error:e}}finally{try{n&&!n.done&&(i=s.return)&&i.call(s)}finally{if(r)throw r.error}}return o}function b(e,t,i){if(i||2===arguments.length)for(var n,r=0,s=t.length;r<s;r++)!n&&r in t||(n||(n=Array.prototype.slice.call(t,0,r)),n[r]=t[r]);return e.concat(n||Array.prototype.slice.call(t))}Object.create,Object.create,"function"==typeof SuppressedError&&SuppressedError;var I,v=((I=function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map(function(e,t){return t+1+") "+e.toString()}).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}(function(e){Error.call(e),e.stack=(new Error).stack})).prototype=Object.create(Error.prototype),I.prototype.constructor=I,I);function S(e,t){if(e){var i=e.indexOf(t);0<=i&&e.splice(i,1)}}var w=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,i,n,r;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=y(s),a=o.next();!a.done;a=o.next())a.value.remove(this)}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var c=this.initialTeardown;if(d(c))try{c()}catch(e){r=e instanceof v?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=y(u),h=l.next();!h.done;h=l.next()){var p=h.value;try{M(p)}catch(e){r=null!=r?r:[],e instanceof v?r=b(b([],m(r)),m(e.errors)):r.push(e)}}}catch(e){i={error:e}}finally{try{h&&!h.done&&(n=l.return)&&n.call(l)}finally{if(i)throw i.error}}}if(r)throw new v(r)}},e.prototype.add=function(t){var i;if(t&&t!==this)if(this.closed)M(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(i=this._finalizers)&&void 0!==i?i:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&S(t,e)},e.prototype.remove=function(t){var i=this._finalizers;i&&S(i,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function M(e){d(e)?e():e.unsubscribe()}w.EMPTY;var T={setTimeout:function(e,t){for(var i=[],n=2;n<arguments.length;n++)i[n-2]=arguments[n];var r=T.delegate;return(null==r?void 0:r.setTimeout)?r.setTimeout.apply(r,b([e,t],m(i))):setTimeout.apply(void 0,b([e,t],m(i)))},clearTimeout:function(e){var t=T.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function _(){}var k=E("C",void 0,void 0);function E(e,t,i){return{kind:e,value:t,error:i}}var C=function(e){function t(t){var i,n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,((i=t)instanceof w||i&&"closed"in i&&d(i.remove)&&d(i.add)&&d(i.unsubscribe))&&t.add(n)):n.destination=N,n}return f(t,e),t.create=function(e,t,i){return new D(e,t,i)},t.prototype.next=function(e){this.isStopped?q(function(e){return E("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?q(E("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?q(k,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(w);Function.prototype.bind;var O=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){A(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){A(e)}else A(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){A(e)}},e}(),D=function(e){function t(t,i,n){var r,s=e.call(this)||this;return r=d(t)||!t?{next:null!=t?t:void 0,error:null!=i?i:void 0,complete:null!=n?n:void 0}:t,s.destination=new O(r),s}return f(t,e),t}(C);function A(e){!function(e){T.setTimeout(function(){throw e})}(e)}function q(e,t){var i=null;i&&T.setTimeout(function(){return i(e,t)})}var N={closed:!0,next:_,error:function(e){throw e},complete:_};function R(e,t,i,n,r){return new F(e,t,i,n,r)}var F=function(e){function t(t,i,n,r,s,o){var a=e.call(this,t)||this;return a.onFinalize=s,a.shouldUnsubscribe=o,a._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=r?function(e){try{r(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=n?function(){try{n()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return f(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(C);function j(e,t){return p(function(i,n){var r=0;i.subscribe(R(n,function(i){n.next(e.call(t,i,r++))}))})}function x(e){return null!=e}let P=e=>new Error(e);function B(e,t,...i){e||function(e,...t){const i=Q(e);if("object"==typeof i)throw i;throw P(i||"Assertion error",...t)}(t,...i)}function L(e,t,...i){return B(e,t,...i),e}function Q(e){return void 0===e?"":"string"==typeof e?e:e()}function U(e,t,i){const n=Q(e);if("object"==typeof n)throw n;return`${n?`${n}: `:""}${t} ${function(e){return void 0===e?"<undefined>":"symbol"==typeof e?e.toString():null===e?"<null>":`<${typeof e}:${e}>`}(i)}`}const $=["dev","prod"],G="built_in_agent";function V(){return globalThis.crypto.randomUUID()}function H(){return V()}const K=18,W="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function z(e=K,t=""){B(t.length<e,"ID prefix is too long");let i="";for(let t=0;t<e;t++)i+=W.charAt(Math.floor(Math.random()*W.length));return t.length>0&&(i=t+i.substring(t.length)),i}function J({count:e,length:t,prefix:i}){B(e>=0,`Invalid IDs count: ${e}`);const n=new Set;for(;n.size<e;)n.add(z(t||K,i||""));return[...n]}const Y=["groupId","appId","integrationId","profileId","index","text","filePathInBucket"];function Z(e){for(const t in e){const i=e[t];if("string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i&&void 0!==i)throw new Error(`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`);if(Y.includes(t))throw new Error(`Invalid metadata key ${t} - cannot be an internal key. Internal keys: ${Y.join(", ")}`);if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}function X(e){if(function(e){return"$and"in e}(e))for(const t of e.$and)X(t);else if(function(e){return"$or"in e}(e))for(const t of e.$or)X(t);else for(const t in e){if(!/^[a-zA-Z0-9_]+$/.test(t))throw new Error(`Invalid metadata filter key ${t} - can only contain letters, numbers, and underscores`);if(Y.includes(t))throw new Error(`Invalid metadata filter key ${t} - cannot be an internal key. Internal keys: ${Y.join(", ")}`);const i=e[t];if("object"!=typeof i&&"string"!=typeof i&&"number"!=typeof i&&"boolean"!=typeof i)throw new Error(`Invalid metadata filter value for key ${t} - cannot be of type ${typeof i}`)}}function ee(e,t,i){const n=atob(e),r=new Uint8Array(n.length);for(let e=0;e<n.length;e++)r[e]=n.charCodeAt(e);return new File([r],t,{type:i||"application/octet-stream"})}class te{constructor(e,t,i,n,r){this.agentId=e,this.ongoingChatSequences=t,this.rpcManager=i,this.socketManager=n,this.jobClient=r}async get(){const e=await this.rpcManager.post("ai/agent/getAgent",{agentId:this.agentId});return e?.agent}async upsert(e){await this.rpcManager.post("ai/agent/upsertAgent",{...e,id:this.agentId})}async delete(){await this.rpcManager.post("ai/agent/deleteAgent",{agentId:this.agentId})}async updateInstructions(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,instructions:e}})}async updateModel(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,model:e}})}async updateConnectedAgents(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,connectedAgents:e}})}async getContext(e){return await this.rpcManager.post("ai/agent/getContext",{agentId:this.agentId,contextId:e})}async listContexts(){return(await this.rpcManager.post("ai/agent/listContexts",{agentId:this.agentId})).contexts||[]}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/agent/deleteContexts",{agentId:this.agentId,contextIds:e})}async upsertContext(e,t){const{failures:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&Z(t.metadata);return await this.rpcManager.post("ai/agent/upsertContexts",{agentId:this.agentId,contextRequests:e},t)}async provideFeedback(e){await this.rpcManager.post("ai/agent/provideFeedback",{agentId:this.agentId,feedback:e})}async resetFeedback(){await this.rpcManager.post("ai/agent/resetFeedback",{agentId:this.agentId})}async updateGuardrails(e){const t=await this.get();B(t,"Agent not found"),await this.upsert({...t,options:{...t.options,guardrails:{...t.options?.guardrails,...e}}})}async updateCustomGuardrails(e){await this.rpcManager.post("ai/agent/upsertCustomGuardrails",{agentId:this.agentId,customGuardrail:e})}async deleteCustomGuardrail(){await this.rpcManager.post("ai/agent/deleteCustomGuardrails",{agentId:this.agentId})}chat(e,t,i){return this.chatInternal(e,t,i).responseStream}async transcribeAndChat(e,t,i){const n=this.chatInternal(e,t,i),r=await L(n.serverResponse,"TRANSCRIPTION_RESPONSE_NOT_FOUND");return{responseStream:n.responseStream,transcribedPrompt:r.transcribedPrompt}}async search(e){B(this.agentId!==G,"Cannot search the built-in agent");const t={options:e,agentId:this.agentId};return(await this.rpcManager.post("ai/chatbot/search",t)).chunks}async ask(e,t,i){const n=await this.askInternal(e,!1,t,i);let r=n.responseString;for(const[e,t]of Object.entries(n.annotations||{})){let i="";switch(t.aiFileUrl.type){case"image":i=``;break;case"document":i=`[${t.aiFileUrl.fileName}](${t.aiFileUrl.url})`}r=r.replace(`\${id:${e}}`,i)}return r}async askWithAnnotations(e,t,i){const n=await this.askInternal(e,!1,t,i);return{responseString:n.responseString,annotations:n.annotations}}async askAsync(e,t,i){const n={agentId:this.agentId,prompt:e,options:i,jobId:t};await this.rpcManager.post("ai/chatbot/askAsync",n)}observeStatusUpdates(){return this.socketManager.notifyWebSocketIsNeeded(),this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiStatus"===e.type&&e.agentId===this.agentId),j(e=>({agentId:this.agentId,jobId:e.jobId,chatId:e.chatId,tags:e.payload.tags,title:e.payload.title,messageId:e.messageId})))}async transcribeAndAsk(e,t,i){return await this.askInternal(e,!1,t,i)}async transcribeAndAskWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),r=n.voiceResponse;return{responseString:n.responseString,transcribedPrompt:n.transcribedPrompt,voiceResponseFile:ee(r.base64File,`voice.${r.extension}`,r.mimeType)}}async askWithVoiceResponse(e,t,i){const n=await this.askInternal(e,!0,t,i),r=n.voiceResponse;return{responseString:n.responseString,voiceResponseFile:ee(r.base64File,`voice.${r.extension}`,r.mimeType)}}async askInternal(e,t,i,n){if(i?.contextMetadataFilter&&X(i.contextMetadataFilter),i?.contextMetadataFilterForKnowledgeBase)for(const e in i.contextMetadataFilterForKnowledgeBase)X(i.contextMetadataFilterForKnowledgeBase[e]);n=n||V(),i={...ie,...i||{}};const r="string"==typeof e;let s="ai/chatbot/";s+=r||t?!r&&t?"transcribeAndAskWithVoiceResponse":r&&t?"askWithVoiceResponse":"ask":"transcribeAndAsk";const o={agentId:this.agentId,prompt:r?e:void 0,options:i,jobId:n},a=r?void 0:[e];return await this.rpcManager.post(s,o,a,"file"),await this.jobClient.awaitJob(n)}chatInternal(e,t,i){if(this.socketManager.notifyWebSocketIsNeeded(),t?.contextMetadataFilter&&X(t.contextMetadataFilter),t?.contextMetadataFilterForKnowledgeBase)for(const e in t.contextMetadataFilterForKnowledgeBase)X(t.contextMetadataFilterForKnowledgeBase[e]);const n=V(),r=void 0===(t={...ie,...t||{}}).smoothTyping||t.smoothTyping;let s="";const o=new h.Subject,a=new h.Subject;this.ongoingChatSequences[n]=a;let c=-1;a.pipe((0,h.tap)(({tokenIndex:e})=>{void 0!==e&&e<c&&console.warn("Received token index out of order",e,c),void 0!==e&&(c=e)}),(0,h.concatMap)(({value:e,complete:t})=>t?(0,h.of)({value:e,complete:t}):(0,h.of)(e).pipe(r?(0,h.delay)(0):(0,h.tap)(),j(e=>({value:e,complete:!1})))),(0,h.takeWhile)(({complete:e})=>!e,!0)).subscribe({next:({value:e})=>{s+=e,o.next(s)},error:e=>{console.error(e)},complete:()=>{o.complete()}});const u="string"==typeof e;i=i||V();const l={agentId:this.agentId,jobId:i,prompt:u?e:void 0,options:t,clientRequestId:n},d={responseStream:o.pipe((0,h.finalize)(()=>{delete this.ongoingChatSequences[n]}),(0,h.share)())};return u?this.rpcManager.post("ai/chatbot/chat",l).catch(e=>{o.error(e),o.complete()}):this.rpcManager.post("ai/chatbot/transcribeAndChat",l,[e],"file").catch(e=>{throw o.error(e),o.complete(),e}),d.serverResponse=this.jobClient.awaitJob(i).catch(e=>{o.error(e),o.complete()}),d}}const ie={smoothTyping:!0,responseFormat:"text"};class ne{constructor(e,t,i){this.rpcManager=e,this.socketManager=t,this.jobClient=i,this.ongoingChatSequences={},this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"aiChatbot"===e.type),j(e=>e)).subscribe(e=>{this.handleChatResponse(e).then()})}agent(e){return new te(e,this.ongoingChatSequences,this.rpcManager,this.socketManager,this.jobClient)}async listAgents(){return(await this.rpcManager.post("ai/agent/listAgents",{})).agents}async handleChatResponse(e){const t=this.ongoingChatSequences[e.clientRequestId];if(!t)return;const{token:i,complete:n,tokenIndex:r}=e.payload;if(n&&!i.length)t.next({value:"",complete:!0,tokenIndex:void 0});else if(i.match(/\[.*?]\((.*?)\)/g))t.next({value:i,complete:n,tokenIndex:void 0===r?void 0:r});else for(let e=0;e<i.length;e++)t.next({value:i[e],complete:n&&e===i.length-1,tokenIndex:void 0===r?void 0:r})}}const re="__squid_empty_chat_id";class se{constructor(e){this.rpcManager=e}async createAssistant(e,t,i,n){const r={name:e,instructions:t,functions:i,toolTypes:n};return(await this.rpcManager.post("ai/assistant/createAssistant",r)).assistantId}async deleteAssistant(e){const t={assistantId:e};await this.rpcManager.post("ai/assistant/deleteAssistant",t)}async createThread(e){const t={assistantId:e};return(await this.rpcManager.post("ai/assistant/createThread",t)).threadId}async deleteThread(e){const t={threadId:e};await this.rpcManager.post("ai/assistant/deleteThread",t)}async queryAssistant(e,t,i,n,r){const s={assistantId:e,threadId:t,prompt:i,fileIds:n,options:r};return(await this.rpcManager.post("ai/assistant/queryAssistant",s)).answer}async addFileToAssistant(e,t){const i={assistantId:e};return(await this.rpcManager.post("ai/assistant/addFileToAssistant",i,[t],"file")).fileId}async removeFileFromAssistant(e,t){const i={assistantId:e,fileId:t};await this.rpcManager.post("ai/assistant/removeFileFromAssistant",i)}async addFileToThread(e,t){const i={threadId:e};return(await this.rpcManager.post("ai/assistant/addFileToThread",i,[t],"file")).fileId}}class oe{constructor(e){this.rpcManager=e}async transcribe(e,t={modelName:"whisper-1"}){return this.rpcManager.post("ai/audio/transcribe",t,[e])}async createSpeech(e,t){const i={input:e,options:t},n=await this.rpcManager.post("ai/audio/createSpeech",i);return ee(n.base64File,`audio.${n.extension}`,n.mimeType)}}class ae{constructor(e){this.rpcManager=e}async generate(e,t){const i={prompt:e,options:t};return await this.rpcManager.post("ai/image/generate",i)}async removeBackground(e){return await this.rpcManager.post("ai/image/removeBackground",{},[e])}}function ce(e){for(const t in e){const i=e[t];B("string"==typeof i||"number"==typeof i||"boolean"==typeof i||void 0===i,`Invalid metadata value for key ${t} - cannot be of type ${typeof i}`),B(/^[a-zA-Z0-9_]+$/.test(t),`Invalid metadata key ${t} - can only contain letters, numbers, and underscores`)}}class ue{constructor(e,t,i){this.knowledgeBaseId=e,this.rpcManager=t,this.jobClient=i}async getKnowledgeBase(){return(await this.rpcManager.post("ai/knowledge-base/getKnowledgeBase",{id:this.knowledgeBaseId})).knowledgeBase}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async upsertKnowledgeBase(e){await this.rpcManager.post("ai/knowledge-base/upsertKnowledgeBase",{knowledgeBase:{id:this.knowledgeBaseId,...e}})}async delete(){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:this.knowledgeBaseId})}async listContexts(){return(await this.rpcManager.post("ai/knowledge-base/listContexts",{id:this.knowledgeBaseId})).contexts||[]}async getContext(e){return(await this.rpcManager.post("ai/knowledge-base/getContext",{knowledgeBaseId:this.knowledgeBaseId,contextId:e})).context}async deleteContext(e){await this.deleteContexts([e])}async deleteContexts(e){await this.rpcManager.post("ai/knowledge-base/deleteContexts",{knowledgeBaseId:this.knowledgeBaseId,contextIds:e})}async upsertContext(e,t){const{failures:i}=await this.upsertContexts([e],t?[t]:void 0);return i.length>0?{failure:i[0]}:{}}async upsertContexts(e,t){for(const t of e)t.metadata&&ce(t.metadata);const i=V();return await this.rpcManager.post("ai/knowledge-base/upsertContexts",{knowledgeBaseId:this.knowledgeBaseId,contextRequests:e,jobId:i},t),await this.jobClient.awaitJob(i)}async search(e){const t={options:e,prompt:e.prompt,knowledgeBaseId:this.knowledgeBaseId};return(await this.rpcManager.post("ai/knowledge-base/search",t)).chunks}}class le{constructor(e,t){this.rpcManager=e,this.jobClient=t}knowledgeBase(e){return new ue(e,this.rpcManager,this.jobClient)}async listKnowledgeBases(){return(await this.rpcManager.post("ai/knowledge-base/listKnowledgeBases",void 0)).knowledgeBases}async delete(e){await this.rpcManager.post("ai/knowledge-base/deleteKnowledgeBase",{id:e})}}class he{constructor(e){this.rpcManager=e}async createMatchMaker(e){const t=await this.rpcManager.post("matchMaking/createMatchMaker",{matchMaker:e});return new de(t,this.rpcManager)}async getMatchMaker(e){const t=(await this.rpcManager.post("matchMaking/getMatchMaker",{matchMakerId:e})).matchMaker;if(t)return new de(t,this.rpcManager)}async listMatchMakers(){return await this.rpcManager.post("matchMaking/listMatchMakers",{})}}class de{constructor(e,t){this.matchMaker=e,this.rpcManager=t,this.id=e.id}async insertEntity(e){await this.rpcManager.post("matchMaking/insertEntity",{matchMakerId:this.id,entity:e})}async insertManyEntities(e){await this.rpcManager.post("matchMaking/insertEntities",{matchMakerId:this.id,entities:e})}async delete(){await this.rpcManager.post("matchMaking/deleteMatchMaker",{matchMakerId:this.id})}async deleteEntity(e){await this.rpcManager.post("matchMaking/deleteEntity",{entityId:e,matchMakerId:this.id})}async findMatches(e,t={}){return(await this.rpcManager.post("matchMaking/findMatches",{matchMakerId:this.id,entityId:e,options:t})).matches}async findMatchesForEntity(e,t={}){return(await this.rpcManager.post("matchMaking/findMatchesForEntity",{matchMakerId:this.id,entity:e,options:t})).matches}async listEntities(e,t={}){return await this.rpcManager.post("matchMaking/listEntities",{categoryId:e,options:t,matchMakerId:this.id})}async getEntity(e){return(await this.rpcManager.post("matchMaking/getEntity",{matchMakerId:this.id,entityId:e})).entity}getMatchMakerDetails(){return this.matchMaker}}const pe="parent",ge="result",fe=["cohere","none"],ye=["anthropic","flux","gemini","openai","grok","stability","voyage","external"],me=["o1","o3","o3-mini","o4-mini","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"],be=["gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite"],Ie=["grok-3","grok-3-fast","grok-3-mini","grok-3-mini-fast","grok-4"],ve=["claude-3-7-sonnet-latest","claude-opus-4-20250514","claude-opus-4-1-20250805","claude-sonnet-4-20250514"],Se=[...me,...ve,...be,...Ie];function we(e){return Se.includes(e)}const Me=["text-embedding-3-small"],Te=["voyage-3-large"],_e=[...Me,...Te],ke=["dall-e-3"],Ee=["whisper-1","gpt-4o-transcribe","gpt-4o-mini-transcribe"],Ce=["tts-1","tts-1-hd","gpt-4o-mini-tts"],Oe=[...Ee,...Ce],De=["stable-diffusion-core"],Ae=["flux-pro-1.1","flux-kontext-pro"],qe=[...ke,...De,...Ae],Ne=[...Ee],Re=[...Ce],Fe=["mp3","opus","aac","flac","wav","pcm"],je=["contextual","basic"],xe=["secret","regular"];function Pe(e){return!!e&&"object"==typeof e&&"__squid_placeholder__"in e}const Be={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},Le="ai_agents",Qe=["active_directory","ai_agents","ai_chatbot","algolia","alloydb","api","auth0","azure_cosmosdb","azure_postgresql","azure_sql","bigquery","built_in_db","built_in_gcs","built_in_queue","built_in_s3","cassandra","clickhouse","cloudsql","cockroach","cognito","connected_knowledgebases","confluence","confluent","datadog","db2","descope","documentdb","dynamodb","elasticsearch","firebase_auth","firestore","gcs","google_docs","google_drive","graphql","hubspot","jira","jwt_hmac","jwt_rsa","kafka","linear","mariadb","monday","mongo","mssql","databricks","mysql","newrelic","okta","onedrive","oracledb","pinecone","postgres","redis","s3","salesforce_crm","sap_hana","sentry","servicenow","snowflake","spanner","xata","zendesk","mail","slack","mcp","a2a"],Ue=["bigquery","built_in_db","clickhouse","cockroach","mongo","mssql","databricks","mysql","oracledb","postgres","sap_hana","snowflake","elasticsearch"],$e=["auth0","jwt_rsa","jwt_hmac","cognito","okta","descope","firebase_auth"],Ge=["graphql","linear"],Ve=["api","confluence"],He=["data","api","graphql"],Ke="built_in_db",We="built_in_queue",ze="built_in_storage",Je=[Ke,We,ze];function Ye(e){return Je.includes(e)}const Ze=["squid_functionExecution_count","squid_functionExecution_time"],Xe=["sum","max","min","average","median","p95","p99","count"],et=["user","squid"],tt=["align-by-start-time","align-by-end-time"],it=["in","not in","array_includes_some","array_includes_all","array_not_includes"],nt=[...it,"==","!=",">=","<=",">","<","like","not like","like_cs","not like_cs"],rt=["us-east-1.aws","ap-south-1.aws","us-central1.gcp"],st=["CONNECTED","DISCONNECTED","REMOVED"];class ot{constructor(e,t,i){this.socketManager=e,this.rpcManager=t,this.jobClient=i,this.aiAssistantClient=new se(this.rpcManager)}agent(e=G){return this.getAiAgentClient().agent(e)}knowledgeBase(e){return this.getAiKnowledgeBaseClient().knowledgeBase(e)}async listAgents(){return this.getAiAgentClient().listAgents()}async listKnowledgeBases(){return this.getAiKnowledgeBaseClient().listKnowledgeBases()}assistant(){return this.aiAssistantClient}image(){return new ae(this.rpcManager)}audio(){return new oe(this.rpcManager)}matchMaking(){return new he(this.rpcManager)}executeAiQuery(e,t,i){const n={integrationId:e,prompt:t,options:i};return this.rpcManager.post("ai/query/executeDataQuery",n)}executeAiApiCall(e,t,i,n){const r={integrationId:e,prompt:t,allowedEndpoints:i,provideExplanation:n};return this.rpcManager.post("ai/query/executeApiQuery",r)}async getApplicationAiSettings(){return(await this.rpcManager.post("ai/settings/getApplicationAiSettings",{})).settings}async setApplicationAiSettings(e){const t={settings:e};await this.rpcManager.post("ai/settings/setApplicationAiSettings",t)}async setAiProviderApiKeySecret(e,t){const i={providerType:e,secretKey:t};return(await this.rpcManager.post("ai/settings/setAiProviderApiKeySecret",i)).settings}getAiAgentClient(){return this.aiAgentClient||(this.aiAgentClient=new ne(this.rpcManager,this.socketManager,this.jobClient)),this.aiAgentClient}getAiKnowledgeBaseClient(){return this.aiKnowledgeBaseClient||(this.aiKnowledgeBaseClient=new le(this.rpcManager,this.jobClient)),this.aiKnowledgeBaseClient}}const at={headers:{},queryParams:{},pathParams:{}};class ct{constructor(e){this.rpcManager=e}async get(e,t,i){return this.request(e,t,void 0,i,"get")}async post(e,t,i,n){return this.request(e,t,i,n,"post")}async delete(e,t,i,n){return this.request(e,t,i,n,"delete")}async patch(e,t,i,n){return this.request(e,t,i,n,"patch")}async put(e,t,i,n){return this.request(e,t,i,n,"put")}async request(e,t,i,n,r){const s={integrationId:e,endpointId:t,body:i,options:{...at,...this.convertOptionsToStrings(n||{})},overrideMethod:r};return await this.rpcManager.rawPost("api/callApi",s,void 0,void 0,!1)}convertOptionsToStrings(e){return{headers:this.convertToStrings(e.headers),queryParams:this.convertToStrings(e.queryParams),pathParams:this.convertToStrings(e.pathParams)}}convertToStrings(e){if(!e)return{};const t=Object.entries(e).filter(([,e])=>void 0!==e).map(([e,t])=>[e,String(t)]);return Object.fromEntries(t)}}class ut{constructor(e,t){this.apiKey=e,this.authProvider=t}setAuthProvider(e){this.authProvider=e}async getAuthData(){return{token:await this.getTokenFromAuthProvider(),integrationId:this.authProvider?.integrationId}}async getTokenFromAuthProvider(){const e=this.authProvider?.getToken();return"object"==typeof e?await e:e}getApiKey(){return this.apiKey}async getToken(){if(this.apiKey)return{type:"ApiKey",token:this.apiKey};const e=await this.getTokenFromAuthProvider();return e?{type:"Bearer",token:e,integrationId:this.authProvider?.integrationId}:void 0}}const lt=/[.\[\]]/;function ht(e,t){if(!e)return;const i=t.split(lt);let n,r=e;for(;r&&i.length;){const e=i.shift();if(e){if("object"!=typeof r||!(e in r))return;n=r[e],r=n}}return n}function dt(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)}function pt(e,t,i,n="."){const r=t.split(n);let s=e;for(;r.length;){const e=L(r.shift());if(r.length){const t=s[e],i=dt(t)?vt(t)??{}:{};s[e]=i,s=i}else s[e]=i}}function gt(e,t,i="."){const n=t.split(i);let r=e;for(;n.length;){const e=L(n.shift());if(n.length){const t=dt(r[e])?vt(r[e])??{}:{};r[e]=t,r=t}else delete r[e]}}function ft(e,t,i){if(e.has(t)){const n=e.get(t);e.delete(t),e.set(i,n)}}function yt(e){return null==e}function mt(e,t){if(e===t)return!0;if(null===e||null===t)return!1;const i=typeof e;if(i!==typeof t)return!1;if("object"!==i)return e===t;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const i of n)if(!r.includes(i)||!mt(e[i],t[i]))return!1;return!0}function bt(e,t){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=It(e[n],t);return i}function It(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 bt(e,t);if(e instanceof Map)return new Map(bt(Array.from(e),t));if(e instanceof Set)return new Set(bt(Array.from(e),t));if(ArrayBuffer.isView(e))return(n=e)instanceof Buffer?Buffer.from(n):new n.constructor(n.buffer.slice(),n.byteOffset,n.length);var n;const r={};for(const i in e)Object.hasOwnProperty.call(e,i)&&(r[i]=It(e[i],t));return r}function vt(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 St(e,t){if(e===t||yt(e)&&yt(t))return 0;if(yt(e))return-1;if(yt(t))return 1;const i=typeof e,n=typeof t;return i!==n?i<n?-1:1:"number"==typeof e?(B("number"==typeof t),isNaN(e)&&isNaN(t)?0:isNaN(e)?-1:isNaN(t)?1:e<t?-1:1):"boolean"==typeof e?(B("boolean"==typeof t),e<t?-1:1):"bigint"==typeof e?(B("bigint"==typeof t),e<t?-1:1):"string"==typeof e?(B("string"==typeof t),e<t?-1:1):e instanceof Date&&t instanceof Date?Math.sign(e.getTime()-t.getTime()):0}function wt(e,t){return e.reduce((e,i)=>{const n=t(i);return e[n]?e[n].push(i):e[n]=[i],e},{})}function Mt(e){if(Array.isArray(e))return e.map(e=>Mt(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]=Mt(e[t])}),i}function Tt(e){return _t(Mt(e))}function _t(e){if(void 0===e)return null;const t=It(e,e=>function(e){return"[object Date]"===Object.prototype.toString.call(e)}(e)?{$date:e.toISOString()}:void 0);return JSON.stringify(t)}function kt(e){return It(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 Et(e){if(void 0===e)throw new Error("INVALID_ENCODE_VALUE");const t=_t(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 Ct=(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},Ot=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(_t(e[i])!==_t(t[i]))return!1;return!0};class Dt{constructor(e){this.options=e}get(e){const t=this.cachedEntry,i=this.options.argsComparator||Ct,n=this.options.valueExpirationMillis||1/0;return t&&Date.now()<t.cacheTimeMillis+n&&i(t.args,e)?{found:!0,value:t.result}:{found:!1}}set(e,t){this.cachedEntry={args:e,result:t,cacheTimeMillis:Date.now()}}}class At{constructor(e){this.rpcManager=e,this.inFlightDedupCalls=[]}executeFunction(e,...t){const{argsArray:i,fileArray:n}=this.transformFileArgs(t),r="string"==typeof e?e:e.functionName,s="string"==typeof e?void 0:e.caching,o=s?.cache;if(o){const e=o.get(i);if(e.found)return Promise.resolve(e.value)}const a="string"==typeof e?void 0:e.deduplication;if(a){const e="boolean"==typeof a?Ct:a.argsComparator,t=this.inFlightDedupCalls.find(t=>t.functionName===r&&e(t.args,i));if(t)return t.promise}const c=this.createExecuteCallPromise(r,i,n,o);return a&&(this.inFlightDedupCalls.push({functionName:r,args:i,promise:c}),c.finally(()=>{this.inFlightDedupCalls=this.inFlightDedupCalls.filter(e=>e.promise!==c)})),c}createExecuteCallPromise(e,t,i,n){const r=`backend-function/execute?${encodeURIComponent(e)}`,s={functionName:e,paramsArrayStr:_t(t)};return(0,h.firstValueFrom)((0,h.race)((0,h.from)(this.rpcManager.post(r,s,i.length>0?i:[])).pipe(j(e=>{if(!e.success)throw new Error(e.payload);const i=kt(e.payload);if(i?.__isSquidBase64File__){const e=i;return ee(e.base64,e.filename,e.mimetype)}return n&&n.set(t,i),i}))))}transformFileArgs(e){const t=[],i=[];let n=0;for(const r of e)if("undefined"!=typeof File)if(r instanceof File){i.push(r);const e={type:"file",__squid_placeholder__:!0,fileIndex:n++};t.push(e)}else if(this.isArrayOfFiles(r)){const e={type:"fileArray",__squid_placeholder__:!0,fileIndexes:r.map((e,t)=>(i.push(r[t]),n++))};t.push(e)}else t.push(r);else t.push(r);return{argsArray:t,fileArray:i}}isArrayOfFiles(e){return"undefined"!=typeof File&&Array.isArray(e)&&!!e.length&&e.every(e=>e instanceof File)}}function qt(e){if("undefined"!=typeof globalThis)return globalThis[e]}function Nt(){if("undefined"!=typeof window)return window;if(void 0!==i.g)return i.g;if("undefined"!=typeof self)return self;throw new Error("Unable to locate global object")}!function(e=!0){Nt().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 Rt{static debug(...e){(function(){const e=Nt();return!0===e?.SQUID_LOG_DEBUG_ENABLED})()&&console.debug(`${function(){if(function(){const e=Nt();return!0!==e?.SQUID_LOG_TIMESTAMPS_DISABLED}()){const e=new Date;return`[${e.toLocaleTimeString()}.${e.getMilliseconds()}] squid`}return"squid"}()} DEBUG`,...e)}}class Ft{constructor(e){this.destructManager=e,this.clientTooOldSubject=new h.BehaviorSubject(!1),this.isTenant=!0===Nt().squidTenant,this.clientIdSubject=new h.BehaviorSubject(this.generateClientId()),this.destructManager.onDestruct(()=>{this.clientTooOldSubject.complete(),this.clientIdSubject.complete()})}observeClientId(){return this.clientIdSubject}observeClientTooOld(){return this.clientTooOldSubject.pipe((0,h.filter)(e=>e),(0,h.map)(()=>{}))}notifyClientTooOld(){this.clientTooOldSubject.next(!0),this.clientIdSubject.next(this.generateClientId())}notifyClientNotTooOld(){this.clientTooOldSubject.next(!1)}observeClientReadyToBeRegenerated(){return this.clientTooOldSubject.pipe((0,h.skip)(1),(0,h.filter)(e=>!e),(0,h.map)(()=>{}))}getClientId(){return this.clientIdSubject.value}isClientTooOld(){return this.clientTooOldSubject.value}generateClientId(){const e=Nt()[jt];if(e)return e();let t=`${this.isTenant?"tenant-":""}${V()}`;return"object"==typeof navigator&&!0===navigator.userAgent?.toLowerCase()?.includes("playwright")&&(t=`e2e${t.substring(3)}`),t}generateClientRequestId(){const e=Nt()[xt];return e?e():V()}}const jt="SQUID_CLIENT_ID_GENERATOR",xt="SQUID_CLIENT_REQUEST_ID_GENERATOR",Pt="__squidId";function Bt(e){return kt(e)}function Lt(...e){const[t,i,n]=e,r="object"==typeof t?t:{docId:t,collectionName:i,integrationId:n};return r.integrationId||(r.integrationId=void 0),Tt(r)}function Qt(e,t,i){if(e=e instanceof Date?e.getTime():e??null,t=t instanceof Date?t.getTime():t??null,"=="===i)return mt(e,t);if("!="===i)return!mt(e,t);switch(i){case"<":return!yt(e)&&(!!yt(t)||t<e);case"<=":return!!yt(t)||!yt(e)&&t<=e;case">":return!yt(t)&&(!!yt(e)||t>e);case">=":return!!yt(e)||!yt(t)&&t>=e;case"like":return"string"==typeof t&&"string"==typeof e&&Ut(t,e,!1);case"not like":return!("string"==typeof t&&"string"==typeof e&&Ut(t,e,!1));case"like_cs":return"string"==typeof t&&"string"==typeof e&&Ut(t,e,!0);case"not like_cs":return!("string"==typeof t&&"string"==typeof e&&Ut(t,e,!0));case"array_includes_some":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.some(e=>L(i,"VALUE_CANNOT_BE_NULL").some(t=>mt(t,e)))}case"array_includes_all":{const i=t;return Array.isArray(e)&&Array.isArray(t)&&e.every(e=>L(i,"VALUE_CANNOT_BE_NULL").some(t=>mt(t,e)))}case"array_not_includes":{const i=t;return Array.isArray(t)&&Array.isArray(e)&&e.every(e=>!L(i,"VALUE_CANNOT_BE_NULL").some(t=>mt(t,e)))}default:throw new Error(`Unsupported operator comparison: ${i}`)}}function Ut(e,t,i){i||(e=e.toLowerCase(),t=t.toLowerCase());const n=function(e){let t="";for(let i=0;i<e.length;++i)"\\"===e[i]?i+1<e.length&&["%","_"].includes(e[i+1])?(t+=e[i+1],i++):i+1<e.length&&"\\"===e[i+1]?(t+="\\\\",i++):t+="\\":"%"===e[i]?t+="[\\s\\S]*":"_"===e[i]?t+="[\\s\\S]":("/-\\^$*+?.()[]{}|".includes(e[i])&&(t+="\\"),t+=e[i]);return t}(t);return new RegExp(`^${n}$`).test(e)}function $t(e,t){return`${e}_${t}`}function Gt(e){return"fieldName"in e}class Vt{constructor(e,t,i){this._squidDocId=e,this.dataManager=t,this.queryBuilderFactory=i,this.refId=V()}get squidDocId(){return this._squidDocId}get data(){return It(this.dataRef)}get dataRef(){return L(this.dataManager.getProperties(this.squidDocId),()=>{const{collectionName:e,integrationId:t,docId:i}=Bt(this.squidDocId);return`No data found for document reference: ${JSON.stringify({docId:i,collectionName:e,integrationId:t},null,2)}`})}get hasData(){return!!this.dataManager.getProperties(this.squidDocId)}async snapshot(){if(this.hasSquidPlaceholderId())throw new Error("Cannot invoke snapshot of a document that was created locally without storing it on the server.");if(this.isTracked()&&this.hasData)return this.data;const e=await this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshot();return L(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0}snapshots(){return this.queryBuilderFactory.getForDocument(this.squidDocId).dereference().snapshots().pipe((0,h.map)(e=>(L(e.length<=1,"Got more than one doc for the same id:"+this.squidDocId),e.length?e[0]:void 0)))}peek(){return this.isTracked()&&this.hasData?this.data:void 0}isDirty(){return this.dataManager.isDirty(this.squidDocId)}isTracked(){return this.dataManager.isTracked(this.squidDocId)}async update(e,t){const i={};Object.entries(e).forEach(([e,t])=>{const n=void 0!==t?{type:"update",value:t}:{type:"removeProperty"};i[e]=[n]});const n={type:"update",squidDocIdObj:Bt(this.squidDocId),properties:i};return this.dataManager.applyOutgoingMutation(n,t)}async setInPath(e,t,i){return this.update({[e]:It(t)},i)}async deleteInPath(e,t){return this.update({[e]:void 0},t)}incrementInPath(e,t,i){const n={type:"applyNumericFn",fn:"increment",value:t},r={type:"update",squidDocIdObj:Bt(this.squidDocId),properties:{[e]:[n]}};return this.dataManager.applyOutgoingMutation(r,i)}decrementInPath(e,t,i){return this.incrementInPath(e,-t,i)}async insert(e,t){const i=Bt(this.squidDocId),n=i.integrationId;let r=kt(i.docId);if(r[Pt]&&(r={}),n===Ke&&r.__id)try{const e=kt(r.__id);r={...r,...e}}catch{}const s={type:"insert",squidDocIdObj:i,properties:{...e,__docId__:i.docId,...r}};return this.dataManager.applyOutgoingMutation(s,t)}async delete(e){const t={type:"delete",squidDocIdObj:Bt(this.squidDocId)};return this.dataManager.applyOutgoingMutation(t,e)}migrateDocIds(e){const t=e[this.squidDocId];t&&(this._squidDocId=t)}hasSquidPlaceholderId(){const e=kt(this._squidDocId);if("object"==typeof e&&e.docId){const t=kt(e.docId);if("object"==typeof t&&Object.keys(t).includes(Pt))return!0}return!1}}class Ht{constructor(e,t={}){this.internalStateObserver=new h.BehaviorSubject(null),this.firstElement=null,this.isDestroyed=new h.BehaviorSubject(!1),this.snapshotSubject=new h.Subject,this.onFirstPage=!0,this.navigatingToLastPage=!1,this.lastElement=null,B(e.getSortOrders().length>0,"Unable to paginate results. Please specify a sort order."),this.snapshotSubject.pipe((0,h.switchAll)()).subscribe(e=>this.dataReceived(e)),this.templateSnapshotEmitter=e.clone(),this.paginateOptions={pageSize:100,subscribe:!0,...t},this.goToFirstPage()}goToFirstPage(){this.onFirstPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).snapshots(this.paginateOptions.subscribe);this.snapshotSubject.next(e)}compareObjects(e,t){if(e===t||yt(e)&&yt(t))return 0;if(yt(e))return-1;if(yt(t))return 1;const i=this.templateSnapshotEmitter.getSortOrders();for(const{fieldName:n,asc:r}of i){const i=St(ht(e,n),ht(t,n));if(0!==i)return r?i:-i}return 0}async dataReceived(e){const t=e.map(e=>this.templateSnapshotEmitter.extractData(e));if(0===e.length)return void(this.onFirstPage?this.internalStateObserver.next({numBefore:0,numAfter:0,data:e,extractedData:t}):this.goToFirstPage());if(null===this.firstElement)if(null!==this.lastElement){const i=t.filter(e=>1===this.compareObjects(e,this.lastElement)).length;this.firstElement=t[e.length-i-this.paginateOptions.pageSize],this.lastElement=null}else this.navigatingToLastPage&&(this.firstElement=t[e.length-this.paginateOptions.pageSize],this.navigatingToLastPage=!1);const i=t.filter(e=>-1===this.compareObjects(e,this.firstElement)).length,n=Math.max(0,e.length-i-this.paginateOptions.pageSize);i!==e.length?this.internalStateObserver.next({numBefore:i,numAfter:n,data:e,extractedData:t}):this.prevInternal({numBefore:i,numAfter:n,data:e,extractedData:t})}doNewQuery(e,t){if(this.onFirstPage=!1,t){const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder();e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?"<=":">=",value:ht(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe).pipe((0,h.map)(e=>e.reverse())))}else{const t=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize);e&&t.addCompositeCondition(this.templateSnapshotEmitter.getSortOrders().map(t=>({fieldName:t.fieldName,operator:t.asc?">=":"<=",value:ht(e,t.fieldName)||null}))),this.snapshotSubject.next(t.snapshots(this.paginateOptions.subscribe))}}async waitForInternalState(){const e=this.internalStateObserver.value;return null!==e?e:await(0,h.firstValueFrom)((0,h.race)(this.isDestroyed.pipe((0,h.filter)(Boolean),(0,h.map)(()=>({data:[],extractedData:[],numBefore:0,numAfter:0}))),this.internalStateObserver.pipe((0,h.filter)(e=>null!==e),(0,h.take)(1))))}internalStateToState(e){const{data:t,numBefore:i,numAfter:n,extractedData:r}=e;return{data:t.filter((e,t)=>-1!==this.compareObjects(r[t],this.firstElement)).slice(0,this.paginateOptions.pageSize),hasNext:n>0,hasPrev:i>0}}unsubscribe(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.internalStateObserver.complete(),this.snapshotSubject.complete()}prevInternal(e){const{numBefore:t,numAfter:i,extractedData:n}=e;this.firstElement=null,this.lastElement=n[t-1],this.internalStateObserver.next(null),this.doNewQuery(n[n.length-i-1],!0)}async prev(){return this.prevInternal(await this.waitForInternalState()),await this.waitForData()}async next(){const{numBefore:e,extractedData:t}=await this.waitForInternalState();return e+this.paginateOptions.pageSize<t.length&&(this.firstElement=t[e+this.paginateOptions.pageSize]),this.internalStateObserver.next(null),this.doNewQuery(t[e],!1),await this.waitForData()}async waitForData(){return this.internalStateToState(await this.waitForInternalState())}observeState(){return this.internalStateObserver.pipe((0,h.filter)(e=>null!==e),(0,h.map)(e=>this.internalStateToState(e)))}async first(){return await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.goToFirstPage(),await this.waitForData()}async refreshPage(){const{extractedData:e}=await this.waitForInternalState();return this.internalStateObserver.next(null),this.onFirstPage?this.goToFirstPage():this.doNewQuery(e[0],!1),await this.waitForData()}async last(){await this.waitForInternalState(),this.internalStateObserver.next(null),this.firstElement=null,this.lastElement=null,this.navigatingToLastPage=!0;const e=this.templateSnapshotEmitter.clone().limit(3*this.paginateOptions.pageSize).flipSortOrder().snapshots(this.paginateOptions.subscribe).pipe((0,h.map)(e=>e.reverse()));return this.snapshotSubject.next(e),await this.waitForData()}}Error;class Kt{constructor(e,t,i,n){this.querySubscriptionManager=e,this.localQueryManager=t,this.documentReferenceFactory=i,this.documentIdentityService=n}getForDocument(e){const{collectionName:t,integrationId:i,docId:n}=Bt(e),r=kt(n),s=this.get(t,i);for(const[e,t]of Object.entries(r))s.where(e,"==",t);return s}get(e,t){return new Jt(e,t,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this,this.documentIdentityService)}}class Wt{constructor(){this.containsEmptyInCondition=!1}eq(e,t){return this.where(e,"==",t)}neq(e,t){return this.where(e,"!=",t)}in(e,t){return this.where(e,"in",t)}nin(e,t){return this.where(e,"not in",t)}gt(e,t){return this.where(e,">",t)}gte(e,t){return this.where(e,">=",t)}lt(e,t){return this.where(e,"<",t)}lte(e,t){return this.where(e,"<=",t)}like(e,t,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"like_cs":"like",t)}notLike(e,t,i){return this.throwIfInvalidLikePattern(t),this.where(e,i?"not like_cs":"not like",t)}arrayIncludesSome(e,t){return this.where(e,"array_includes_some",t)}arrayIncludesAll(e,t){return this.where(e,"array_includes_all",t)}arrayNotIncludes(e,t){return this.where(e,"array_not_includes",t)}throwIfInvalidLikePattern(e){if(/\\(?![%_\\])/.test(e))throw new Error("Invalid pattern. Cannot have any \\ which are not followed by _, % or \\")}}class zt{constructor(e){this.queryBuilder=e}peek(){return this.queryBuilder.peek().map(e=>e.data)}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1).pipe((0,h.defaultIfEmpty)([])))}snapshots(e){return this.queryBuilder.snapshots(e).pipe(j(e=>e.map(e=>e.data)))}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new zt(this.queryBuilder.clone())}addCompositeCondition(e){return this.queryBuilder.addCompositeCondition(e),this}limit(e){return this.queryBuilder.limit(e),this}getLimit(){return this.queryBuilder.getLimit()}flipSortOrder(){return this.queryBuilder.flipSortOrder(),this}extractData(e){return e}serialize(){return{...this.queryBuilder.serialize(),dereference:!0}}paginate(e){return new Ht(this,e)}}class Jt extends Wt{constructor(e,t,i,n,r,s,o){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.localQueryManager=n,this.documentReferenceFactory=r,this.queryBuilderFactory=s,this.documentIdentityService=o,this.forceFetchFromServer=!1,this.query={integrationId:t,collectionName:e,conditions:[],limit:-1,sortOrder:[]}}where(e,t,i){if(B(nt.includes(t),`Invalid operator: ${t}`),"in"===t||"not in"===t){const n=Array.isArray(i)?[...i]:[i];"in"===t&&0===n.length&&(this.containsEmptyInCondition=!0);for(const i of n)this.query.conditions.push({fieldName:e,operator:"in"===t?"==":"!=",value:i});return this}return this.query.conditions.push({fieldName:e,operator:t,value:i}),this}limit(e){return function(e){var t;B(function(e){return"number"==typeof e}(t=e),()=>U("Limit needs to be a number","Not a number",t)),-1!==e&&(B(e>0,"query limit has to be greater than 0"),B(Math.floor(e)===e,"query limit has to be an integer"),B(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 B(mt(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};return function(e){if(!(e instanceof Object))throw new Error("Field sort has to be an object");const t=e;var i,n,r,s;B((i=t,n=["fieldName","asc"],!Array.isArray(i)&&[...Object.keys(i)].every(e=>n.includes(e))),"Field sort should only contain a fieldName and asc"),B((r=t.asc,s="boolean",Array.isArray(r)?r.every(e=>typeof e===s):typeof r===s),"Asc needs to be boolean")}(i),B(!this.query.sortOrder.some(t=>t.fieldName===e),`${e} already in the sort list.`),this.query.sortOrder.push(i),this}build(){const e=this.mergeConditions();return{...this.query,conditions:e}}mergeConditions(){const e=[],t=wt(this.query.conditions.filter(Gt)||[],e=>e.fieldName);for(const i of Object.values(t)){const t=wt(i,e=>e.operator);for(const[i,n]of Object.entries(t)){if("=="===i||"!="===i){e.push(...n);continue}const t=[...n];t.sort((e,t)=>St(e.value,t.value)),">"===i||">="===i?e.push(t[t.length-1]):e.push(t[0])}}return[...this.query.conditions.filter(e=>!Gt(e)),...e]}getSortOrder(){return this.query.sortOrder}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1).pipe((0,h.defaultIfEmpty)([])))}setForceFetchFromServer(){return this.forceFetchFromServer=!0,this}peek(){return this.localQueryManager.peek(this.build())}snapshots(e=!0){if(this.containsEmptyInCondition)return new h.BehaviorSubject([]);const t=this.build();return this.querySubscriptionManager.processQuery(t,this.collectionName,{},{},e,this.forceFetchFromServer).pipe(j(e=>e.map(e=>{B(1===Object.keys(e).length);const t=Lt(L(e[this.collectionName]).__docId__,this.collectionName,this.integrationId);return this.documentReferenceFactory.create(t,this.queryBuilderFactory)})))}changes(){let e,t=new Set;return this.snapshots().pipe((0,h.combineLatestWith)(this.documentIdentityService.observeChanges().pipe((0,h.switchMap)(t=>(Object.entries(t).forEach(([t,i])=>{!function(e,t,i){const n=e[t];void 0!==n&&(e[i]=n,delete e[t])}(e||{},t,i)}),h.NEVER)),(0,h.startWith)({}))),j(([i])=>{let n=[];const r=[],s=[];if(e){for(const s of i){const i=s.squidDocId,o=s.dataRef;if(t.has(o))delete e[i],t.delete(o);else if(e[i]){r.push(s);const n=e[i];delete e[i],t.delete(n)}else n.push(s)}for(const e of t)s.push(e)}else n=i;e={},t=new Set;for(const n of i){const i=n.dataRef;e[n.squidDocId]=i,t.add(i)}return new Yt(n,r,s)}))}get hash(){return Et(this.build())}dereference(){return new zt(this)}getSortOrders(){return this.query.sortOrder}clone(){const e=new Jt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.queryBuilderFactory,this.documentIdentityService);return e.query=It(this.query),e.containsEmptyInCondition=this.containsEmptyInCondition,e}addCompositeCondition(e){return e.length?(this.query.conditions.push({fields:e}),this):this}flipSortOrder(){return this.query.sortOrder=this.query.sortOrder.map(e=>({...e,asc:!e.asc})),this.query.limitBy&&(this.query.limitBy.reverseSort=!this.query.limitBy.reverseSort),this}serialize(){return{type:"simple",dereference:!1,query:this.build()}}extractData(e){return e.dataRef}paginate(e){return new Ht(this,e)}}class Yt{constructor(e,t,i){this.inserts=e,this.updates=t,this.deletes=i}}class Zt extends Wt{constructor(e,t,i,n,r,s,o,a,c,u,l){super(),this.collectionName=e,this.integrationId=t,this.querySubscriptionManager=i,this.documentReferenceFactory=n,this.queryBuilderFactory=r,this.rootAlias=s,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}join(e,t,i,n){const r=n?.leftAlias??this.latestAlias,s={...i,leftAlias:r,isInner:n?.isInner??!1},o={...this.leftToRight,[t]:[]};return o[r].push(t),new Zt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,t,o,{...this.joins,[t]:e.build()},{...this.joinConditions,[t]:s},this.queryBuilder)}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e=!0){return this.queryBuilder.containsEmptyInCondition?new h.BehaviorSubject([]):this.querySubscriptionManager.processQuery(this.build(),this.rootAlias,It(this.joins),It(this.joinConditions),e,!1).pipe(j(e=>e.map(e=>{const t={};for(const[i,n]of Object.entries(e)){const e=i===this.rootAlias?this.collectionName:this.joins[i].collectionName,r=i===this.rootAlias?this.integrationId:this.joins[i].integrationId,s=n?Lt(n.__docId__,e,r):void 0;t[i]=s?this.documentReferenceFactory.create(s,this.queryBuilderFactory):void 0}return t})))}peek(){throw new Error("peek is not currently supported for join queries")}grouped(){return new ti(this)}dereference(){return new Xt(this)}build(){return this.queryBuilder.build()}getSortOrders(){return this.queryBuilder.getSortOrders()}clone(){return new Zt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,this.rootAlias,this.latestAlias,It(this.leftToRight),It(this.joins),It(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 Ht(this,e)}hasIsInner(){return!!Object.values(this.joinConditions).find(e=>e.isInner)}}class Xt{constructor(e){this.joinQueryBuilder=e}grouped(){return this.joinQueryBuilder.grouped().dereference()}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(j(e=>e.map(e=>function(e,t){const i={},n=Object.keys(e);for(const r of n){const n=e[r];i[r]=t(n)}return i}(e,e=>e?.data))))}peek(){throw new Error("peek is not currently supported for join queries")}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new Xt(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 Ht(this,e)}serialize(){return{...this.joinQueryBuilder.serialize(),dereference:!0}}getLimit(){return this.joinQueryBuilder.getLimit()}}class ei{constructor(e){this.groupedJoin=e}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.groupedJoin.snapshots(e).pipe(j(e=>e.map(e=>this.dereference(e,this.groupedJoin.joinQueryBuilder.rootAlias))))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(e,t){const i=this.groupedJoin.joinQueryBuilder.leftToRight[t];if(i.length){const n={[t]:e[t].data};for(const t of i)n[t]=e[t].map(e=>this.dereference(e,t));return n}return e.data}getSortOrders(){return this.groupedJoin.getSortOrders()}clone(){return new ei(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 Ht(this,e)}}class ti{constructor(e){this.joinQueryBuilder=e}snapshot(){return(0,h.firstValueFrom)(this.snapshots(!1))}snapshots(e){return this.joinQueryBuilder.snapshots(e).pipe(j(e=>this.groupData(e,this.joinQueryBuilder.rootAlias)))}peek(){throw new Error("peek is not currently supported for join queries")}dereference(){return new ei(this)}groupData(e,t){const i=wt(e,e=>e[t]?.squidDocId);return Object.values(i).filter(e=>void 0!==e[0][t]).map(e=>{const i=this.joinQueryBuilder.leftToRight[t],n=e[0][t];if(0===i.length)return n;const r={[t]:n};for(const t of i)r[t]=this.groupData(e,t);return r})}getSortOrders(){return this.joinQueryBuilder.getSortOrders()}clone(){return new ti(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 Ht(this,e)}}class ii{constructor(e,t,i,n,r,s){this.collectionName=e,this.integrationId=t,this.documentReferenceFactory=i,this.queryBuilderFactory=n,this.querySubscriptionManager=r,this.dataManager=s,this.refId=V()}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!==Ke)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={[Pt]:V()};else e=e&&"string"!=typeof e?{__id:Tt(e)}:{__id:e||V()};const t=Lt(Tt(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).insert(i.data,t)},t)}async deleteMany(e,t){0!==e.length&&await this.dataManager.runInTransaction(async t=>{for(const i of e)i instanceof Vt?await i.delete(t):await this.doc(i).delete(t)},t)}query(){return this.queryBuilderFactory.get(this.collectionName,this.integrationId)}joinQuery(e){return new Zt(this.collectionName,this.integrationId,this.querySubscriptionManager,this.documentReferenceFactory,this.queryBuilderFactory,e,e,{[e]:[]},{},{},this.query())}or(...e){return new ni(...e)}}class ni{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(0,h.firstValueFrom)(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")}or(e,...t){return(0,h.combineLatest)([...t]).pipe((0,h.map)(t=>{const i=new Set,n=t.flat(),r=[];for(const e of n)i.has(this.extractData(e))||(i.add(this.extractData(e)),r.push(e));return r.sort((t,i)=>{for(const{fieldName:n,asc:r}of e){const e=ht(this.extractData(t),n),s=ht(this.extractData(i),n);if(!Qt(e,s,"=="))return Qt(s,e,"<")?r?-1:1:r?1:-1}return 0}).slice(0,this.getLimit())}))}clone(){return new ni(...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 Ht(this,e)}}class ri{constructor(e,t,i,n){this.documentReferenceFactory=e,this.queryBuilderFactory=t,this.querySubscriptionManager=i,this.dataManager=n,this.collections=new Map}get(e,t){let i=this.collections.get(t);i||(i=new Map,this.collections.set(t,i));let n=i.get(e);return n||(n=new ii(e,t,this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),i.set(e,n)),n}}class si{constructor(e,t){this.clientIdService=e,this.socketManager=t,this.isConnected=!1,this.socketManager.observeConnectionReady().subscribe(e=>{this.isConnected=e})}get connected(){return this.isConnected}get clientId(){return this.clientIdService.getClientId()}observeConnected(){return this.socketManager.observeConnectionReady()}}var oi=i(150);function ai(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?It(t.value):t.value;case"removeProperty":return;default:throw new Error("Unknown property mutation type: "+JSON.stringify(t))}}function ci(e){return Object.entries(e.properties).sort(([e],[t])=>e.split(".").length-t.split(".").length)}function ui(e,t){if("insert"===t.type)return t;if("delete"===t.type)return t;if("delete"===e.type)return e;if(B("update"===t.type,"Invalid mutation type"),"update"===e.type)return function(e,t){const i=It(e);t=It(t);for(const[e]of ci(i)){const n=e.split(".").length;Object.entries(t.properties).some(([t])=>e.startsWith(t+".")&&n>t.split(".").length)&&delete i.properties[e]}for(const[e,n]of ci(t))i.properties[e]=li([...i.properties[e]||[],...n]);return i}(e,t);const i=It(e);for(const[e,n]of ci(t)){const t=n;for(const n of t){const t=ai(ht(i.properties,e),n);void 0===t?gt(i.properties,e):pt(i.properties,e,t)}}return i}function li(e){let t=0;for(;t+1<e.length;){const i=hi(e[t],e[t+1]);i?e.splice(t,2,i):++t}return e}function hi(e,t){return"removeProperty"===t.type||"update"===t.type?t:"applyNumericFn"===t.type?(B("increment"===t.fn,"Unrecognized applyNumericFn"),"applyNumericFn"===e.type?(B("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 di(e){const t={};for(const i of e){const e=`${i.squidDocIdObj.integrationId}/${i.squidDocIdObj.collectionName}/${i.squidDocIdObj.docId}`;t[e]||(t[e]=[]),t[e].push(i)}const i=[];for(const e in t){const n=t[e].reduce((e,t)=>L(ui(e,t),"Merge result cannot be null"));i.push(n)}return i}const pi="dataManager_runInTransaction";class gi{constructor(e,t,i,n,r,s,o,a,c){this.documentStore=e,this.mutationSender=t,this.socketManager=i,this.querySubscriptionManager=n,this.queryBuilderFactory=r,this.lockManager=s,this.destructManager=o,this.documentIdentityService=a,this.querySender=c,this.docIdToLocalTimestamp=new Map,this.batchClientRequestIds=new Set,this.docIdToServerTimestamp=new Map,this.pendingIncomingUpdates=new Map,this.pendingOutgoingMutations=new Map,this.pendingOutgoingMutationsChanged=new h.Subject,this.outgoingMutationsEmpty=new h.BehaviorSubject(!0),this.knownDirtyDocs=new Set,this.failedDocsToResync=[],this.refreshDocIdToTimestamp=new Map,this.handleIncomingMessagesForTests=!0,this.destructManager.onDestruct(()=>{this.destruct()}),this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.handleNotifications(),this.startDeleteExpiredTimestampsJob(),this.handleOrphanDocs(),this.outgoingMutationsEmpty.subscribe(e=>{this.querySender.safeToSendQueriesToServer.next(e)})}getProperties(e){return this.documentStore.getDocumentOrUndefined(e)}isDirty(e){if(this.knownDirtyDocs.has(e))return!0;if(this.pendingOutgoingMutations.get(e)?.length)return!0;const t=this.docIdToServerTimestamp.get(e),i=t&&!t.expireTimestamp?t.timestamp:void 0,n=this.docIdToLocalTimestamp.get(e);return!((!n||i)&&!this.isForgotten(e)&&!this.isLocalOnly(e)&&n===i)}async runInTransaction(e,t){if(t)return B(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),e(t).then(e=>Promise.resolve(e));this.lockManager.canGetLock(pi)?this.lockManager.lockSync(pi):await this.lockManager.lock(pi);let i=fi;const n=()=>i!==fi;return new Promise(async(t,r)=>{try{let s;this.currentTransactionId=V();try{s=await e(this.currentTransactionId)}catch(e){i=e}finally{this.finishTransaction(n()?void 0:{resolve:()=>t(s),reject:r})}}catch(e){i=n()?i:e}finally{try{this.lockManager.release(pi)}catch(e){i=n()?i:e}}n()&&r(i)})}async applyOutgoingMutation(e,t){const i=Lt(e.squidDocIdObj);this.knownDirtyDocs.add(i),t||this.lockManager.canGetLock(pi)||(await this.lockManager.lock(pi),this.lockManager.release(pi)),this.knownDirtyDocs.delete(i);const n=this.pendingOutgoingMutations.get(i)?.slice(-1)[0];if(n&&!n.sentToServer)n.mutation=L(di([n.mutation,this.removeInternalProperties(e)])[0],"Failed to reduce mutations"),this.outgoingMutationsEmpty.next(!1);else{const t={mutation:this.removeInternalProperties(e),sentToServer:!1},n=this.pendingOutgoingMutations.get(i)||[];n.push(t),this.pendingOutgoingMutations.set(i,n),this.outgoingMutationsEmpty.next(!1),this.pendingOutgoingMutationsChanged.next()}return this.runInTransaction(async()=>{const t=this.documentStore.getDocumentOrUndefined(i),n="delete"===e.type?void 0:"update"===e.type?function(e,t){if(!e)return;const i={...e},n=ci(t);for(const[e,t]of n){const n=t;for(const t of n){const n=ai(ht(i,e),t);void 0===n?gt(i,e):pt(i,e,n)}}return i}(t,e):{...e.properties};this.updateDocumentFromSnapshot(i,n)&&("insert"===e.type&&this.docIdToLocalTimestamp.set(i,(new Date).getTime()),this.querySubscriptionManager.setClientRequestIdsForLocalDoc(i,n).forEach(e=>this.batchClientRequestIds.add(e)))},t)}async runInTransactionSync(e,t){if(t)return B(t===this.currentTransactionId,()=>`Invalid transaction ID: ${t}`),void e(t);await this.lockManager.lock(pi);try{this.currentTransactionId=V();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(pi)}}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((0,h.filter)(e=>"mutations"===e.type),j(e=>e)).subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.handleIncomingMutations(e.payload)})}),this.querySubscriptionManager.observeQueryResults().subscribe(e=>{this.outgoingMutationsEmpty.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.handleIncomingQuerySnapshots(e)})})}handleIncomingMutations(e){if(!this.handleIncomingMessagesForTests)return;const t=e.reduce((e,t)=>this.querySubscriptionManager.hasOngoingQuery(t.clientRequestId)?(e[t.squidDocId]={properties:t.doc,timestamp:t.mutationTimestamp},e):e,{});this.applyIncomingUpdates(t)}handleIncomingQuerySnapshots(e){if(!this.handleIncomingMessagesForTests)return;if(!this.querySubscriptionManager.hasOngoingQuery(e.clientRequestId))return;const t=this.querySubscriptionManager.getQuery(e.clientRequestId),i={};for(const n of e.docs){const e=Lt(n.__docId__,t.collectionName,t.integrationId);i[e]={properties:n,timestamp:n.__ts__}}this.runInTransactionSync(t=>{this.querySubscriptionManager.setGotInitialResult(e.clientRequestId),this.batchClientRequestIds.add(e.clientRequestId),this.applyIncomingUpdates(i,t)&&this.querySubscriptionManager.hasSubscription(e.clientRequestId)&&this.batchClientRequestIds.delete(e.clientRequestId)}).then()}applyIncomingUpdates(e,t){let i=!1;const n=new Set,r=new Set;for(const[t,s]of Object.entries(e)){const e=this.pendingIncomingUpdates.get(t),o=this.docIdToServerTimestamp.get(t);e&&e.timestamp>s.timestamp?i=!0:o&&o.timestamp>s.timestamp?r.add(t):(this.pendingIncomingUpdates.set(t,s),n.add(t))}return this.runInTransactionSync(()=>{for(const e of n)this.maybeApplyIncomingUpdate(e);for(const e of r)this.refreshQueryMapping(e)},t).then(),i}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)}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)}updateDocumentFromSnapshot(e,t){const i=this.documentStore.getDocumentOrUndefined(e);return!(!i&&!t||i===t)&&((!i||!t||Tt({...t,__ts__:void 0})!==Tt(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).then()}async sendAllUnsentOutgoingMutations(e){const t=this.groupOutgoingMutationsByIntegrationId();try{await oi.PromisePool.for(t).withConcurrency(t.length||1).useCorrespondingResults().handleError(e=>{throw e}).process(async([e,t])=>{await this.sendMutationsForIntegration([...t],e)}),this.pendingOutgoingMutations.size||this.outgoingMutationsEmpty.next(!0),await this.refreshUpdatedDocuments(),this.hasPendingSentMutations()?(await(0,h.firstValueFrom)(this.pendingOutgoingMutationsChanged.pipe((0,h.filter)(()=>!this.hasPendingSentMutations()))),e?.resolve()):e?.resolve()}catch(t){this.pendingOutgoingMutations.size||(this.outgoingMutationsEmpty.next(!0),await this.resyncFailedUpdates()),e?.reject(t)}}async sendMutationsForIntegration(e,t){try{const{timestamp:i,idResolutionMap:n={},refreshList:r=[]}=await this.mutationSender.sendMutations(e.map(e=>e.mutation),t);this.documentIdentityService.migrate(n),r.forEach(e=>{this.refreshDocIdToTimestamp.set(n[e]||e,i)});for(const t of e){let e=this.removeOutgoingMutation(t);n[e]&&(e=n[e]),this.acknowledgeDocument(e,i),this.isTracked(e)||(this.setExpiration(e,!0),this.forgetDocument(e,!1))}}catch(t){for(const t of e){const e=this.removeOutgoingMutation(t);this.forgetDocument(e,!1),(this.hasBeenAcknowledged(e)||"insert"===t.mutation.type)&&this.failedDocsToResync.push(e)}throw t}}removeOutgoingMutation(e){const t=Lt(e.mutation.squidDocIdObj),i=L(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}=Bt(t);this.setExpiration(t,!0);try{const i=e.includes(Pt)?[]:await this.queryBuilderFactory.getForDocument(t).setForceFetchFromServer().snapshot();if(L(i.length<=1,"Got more than one doc for the same id:"+t),!i.length){this.forgetDocument(t,!1);const e=this.querySubscriptionManager.setClientRequestIdsForLocalDoc(t,void 0);this.querySubscriptionManager.notifyAllSubscriptions(e)}}catch(e){this.querySubscriptionManager.errorOutAllQueries(t,e)}}}async refreshUpdatedDocuments(){const e=[];for(const[t,i]of this.refreshDocIdToTimestamp.entries()){const n=this.docIdToServerTimestamp.get(t)?.timestamp;n&&n>i||e.push(t)}this.refreshDocIdToTimestamp.clear(),await Promise.allSettled(e.map(e=>this.queryBuilderFactory.getForDocument(e).snapshot()))}groupOutgoingMutationsByIntegrationId(){const e={};for(const[,t]of[...this.pendingOutgoingMutations.entries()]){const i=t[t.length-1];if(i&&!i.sentToServer){const t=i.mutation.squidDocIdObj.integrationId;(e[t]||=[]).push(i),i.sentToServer=!0}}return Object.entries(e)}handleOrphanDocs(){this.querySubscriptionManager.onOrphanDocuments.subscribe(e=>{for(const t of e)this.isTracked(t)||this.forgetDocument(t,!1)})}acknowledgeDocument(e,t,i=!1){this.docIdToServerTimestamp.set(e,{timestamp:t}),this.setExpiration(e,i)}setExpiration(e,t){const i=this.docIdToServerTimestamp.get(e);i&&(i.expireTimestamp=t?Date.now()+2e4:void 0)}forgetDocument(e,t){this.docIdToLocalTimestamp.delete(e),t&&this.documentStore.saveDocument(e,void 0),this.setExpiration(e,!0)}migrateDocIds(e){this.pendingOutgoingMutations.forEach(t=>{t.forEach(t=>{const i=Lt(t.mutation.squidDocIdObj),n=e[i];n&&(t.mutation.squidDocIdObj=Bt(n))})}),Object.entries(e).forEach(([e,t])=>{ft(this.pendingOutgoingMutations,e,t),ft(this.docIdToLocalTimestamp,e,t),ft(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 fi=Symbol("undefined");class yi{constructor(){this.preDestructors=[],this.destructors=[],this.isDestructedSubject=new h.BehaviorSubject(!1)}get isDestructing(){return this.isDestructedSubject.value}observeIsDestructing(){return this.isDestructedSubject.asObservable().pipe((0,h.filter)(Boolean),j(()=>{}))}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 mi{constructor(e,t){this.socketManager=e,this.destructManager=t,this.ongoingLocks={},this.acquireLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"lockAcquired"===e.type)),this.releaseLockMessagesFromServer=this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"lockReleased"===e.type)),this.lockWaitForConnectionThreshold=2e3,t.onPreDestruct(()=>{this.releaseAllLocks()}),this.socketManager.observeConnectionReady().subscribe(e=>{e||this.releaseAllLocks()}),this.releaseLockMessagesFromServer.subscribe(e=>{const t=this.ongoingLocks[e.payload.clientRequestId];void 0!==t&&t.release()})}async lock(e,t=2e3){if(this.socketManager.notifyWebSocketIsNeeded(),!await(0,h.firstValueFrom)((0,h.race)((0,h.timer)(this.lockWaitForConnectionThreshold).pipe(j(()=>!1)),this.socketManager.observeConnectionReady().pipe((0,h.filter)(Boolean)),this.destructManager.observeIsDestructing())))return Promise.reject("CLIENT_NOT_CONNECTED");const i=V(),n={type:"acquireLock",payload:{mutex:e,timeoutMillis:t,clientRequestId:i}};this.socketManager.sendMessage(n);const r=await(0,h.firstValueFrom)((0,h.race)((0,h.timer)(t+4e3).pipe((0,h.take)(1),j(()=>({payload:{error:`TIMEOUT_GETTING_LOCK: ${e}`,lockId:void 0}}))),this.acquireLockMessagesFromServer.pipe((0,h.filter)(e=>e.payload.clientRequestId===i))));if(this.destructManager.isDestructing)throw new Error("Destructing");if(!r.payload.lockId)throw new Error(`Failed to acquire lock: ${r.payload.error}`);const s=r.payload.lockId,o=new bi(s,i,this.ongoingLocks,this.socketManager);return this.ongoingLocks[s]=o,o}releaseAllLocks(){for(const[e,t]of Object.entries(this.ongoingLocks))t.release(),delete this.ongoingLocks[e]}}class bi{constructor(e,t,i,n){this.lockId=e,this.clientRequestId=t,this.ongoingLocks=i,this.socketManager=n,this.released=!1,this.onReleaseSubject=new h.Subject}release(){if(this.released)return;this.released=!0,delete this.ongoingLocks[this.lockId];const e={type:"releaseLock",payload:{lockId:this.lockId,clientRequestId:this.clientRequestId}};this.socketManager.sendMessage(e),this.onReleaseSubject.next()}observeRelease(){return this.onReleaseSubject.asObservable()}isReleased(){return this.released}}class Ii{constructor(e,t){this.documentStore=e,this.destructManager=t,this.changeNotifier=new h.BehaviorSubject({}),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 vi{constructor(e){this.documentIdentityService=e,this.documents=new Map,this.documentsForCollection=new Map,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this))}create(e,t){let i=this.documents.get(e);if(i)return i;i=new Vt(e,L(this.dataManager,"dataManager not found"),t);const{integrationId:n,collectionName:r}=Bt(e);this.documents.set(e,i);const s=this.getCollectionKey(n,r),o=this.documentsForCollection.get(s)||[];return this.documentsForCollection.set(s,o.concat(i)),i}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=Bt(e),n=Bt(t);ft(this.documents,i.docId,n.docId)})}getCollectionKey(e,t){return`${e}_${t}`}}class Si{constructor(){this.squidDocIdToDoc=new Map}saveDocument(e,t){const i=this.squidDocIdToDoc.get(e);if(void 0===i&&!t)return;if(void 0!==i){if(t){const i=It(t),n=this.removeInternalProperties(i);return this.squidDocIdToDoc.set(e,n),n}return void this.squidDocIdToDoc.delete(e)}const n=this.removeInternalProperties(t);return this.squidDocIdToDoc.set(e,n),t}hasData(e){return void 0!==this.squidDocIdToDoc.get(e)}getDocument(e){return L(this.getDocumentOrUndefined(e))}getDocumentOrUndefined(e){return this.squidDocIdToDoc.get(e)}compareSquidDocs(e,t,i){for(const{fieldName:n,asc:r}of i){const i=St(ht(e,n),ht(t,n));if(0!==i)return r?i:-i}return 0}group(e,t){return Object.values(wt(e,e=>Tt(t.map(t=>ht(e,t)))))}sortAndLimitDocs(e,t){if(0===e.size)return[];const i=[...e].map(e=>this.squidDocIdToDoc.get(e)).filter(x),{sortOrder:n,limitBy:r}=t,s=i.sort((e,t)=>this.compareSquidDocs(e,t,n)),o=t.limit<0?2e3:t.limit;if(!r)return s.slice(0,o);const{limit:a,fields:c,reverseSort:u}=r,l=this.group(s,c);let h;return h=u?l.map(e=>e.slice(-a)):l.map(e=>e.slice(0,a)),h.flat().slice(0,o)}removeInternalProperties(e){if(!e)return;const t={...e};return delete t.__ts__,t}migrateDocId(e,t){const i=this.getDocumentOrUndefined(e);if(!i)return;ft(this.squidDocIdToDoc,e,t);const n=Bt(t),r=kt(n.docId);this.saveDocument(t,{...i,...r,__docId__:n.docId})}}class wi{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 Mi{constructor(e,t,i){this.socketManager=e,this.rpcManager=t,this.clientIdService=i,this.isListening=!1,this.listeners={},this.clientIdService.observeClientId().pipe((0,h.distinctUntilChanged)(),(0,h.skip)(1)).subscribe(()=>{for(const e of Object.keys(this.listeners))Rt.debug("Got new client ID, resubscribing to job:",e),this.rpcManager.post("job/subscribeToJob",{jobId:e})})}async getJob(e){return(await this.rpcManager.post("job/getJob",{jobId:e})).job}async awaitJob(e){this.maybeListenToJobs(),await this.socketManager.awaitConnectionReady();const t=this.listeners[e]||new h.ReplaySubject(1);return this.listeners[e]=t,this.rpcManager.post("job/subscribeToJob",{jobId:e}),(0,h.firstValueFrom)(t)}maybeListenToJobs(){this.isListening||(this.socketManager.notifyWebSocketIsNeeded(),this.isListening=!0,this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"jobStatus"===e.type)).subscribe(e=>{const t=e.payload,i=t.id,n=this.listeners[i];n&&("completed"===t.status?n.next(t.result):"failed"===t.status?n.error(new Error(t.error||"Job failed")):console.error("Unexpected job status:",t.status,"for jobId:",i),delete this.listeners[i])}))}}class Ti{constructor(e,t,i){this.rpcManager=e,this.lockManager=t,this.querySender=i}async sendMutations(e,t){const i=di(e),n=i.map(e=>`sendMutation_${Lt(e.squidDocIdObj)}`);await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:i,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Rt.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(i,null,2)}),e}finally{this.lockManager.release(...n)}}}class _i{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}class ki{constructor(e,t){this.socketManager=e,this.rpcManager=t}observeNotifications(){return this.socketManager.observeNotifications().pipe((0,h.filter)(e=>"userNotification"===e.type),(0,h.map)(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 Ei={groupByTags:[],orderByTags:[],pointIntervalAlignment:"align-by-start-time",tagFilter:{},tagDomains:{},noDataBehavior:"return-no-result-groups",fillValue:null,pointIntervalSeconds:0};class Ci{constructor(e){this.rpcManager=e,this.pendingPromises=[],this.isReporting=!1}reportMetric(e){const t=e.tags||{},i=Object.keys(t).filter(e=>!Oi.test(e)||e.length>=Di);B(0===i.length,()=>`Tag name is not allowed: ${i.join(",")}`),this.isReporting=!0;const n={...e,tags:t,timestamp:void 0===e.timestamp?Date.now():e.timestamp},r=this.rpcManager.post("/observability/metrics",{metrics:[n]}).finally(()=>{this.pendingPromises=this.pendingPromises.filter(e=>e!==r),this.isReporting=this.pendingPromises.length>0});this.pendingPromises.push(r)}async flush(){this.isReporting&&await Promise.all(this.pendingPromises)}async queryMetrics(e){const t={...Ei,...e,fn:Array.isArray(e.fn)?e.fn:[e.fn]};t.pointIntervalSeconds||(t.pointIntervalSeconds=t.periodEndSeconds-t.periodStartSeconds);const i=await this.rpcManager.post("/observability/metrics/query",t);return function(e,t){const{pointIntervalSeconds:i,noDataBehavior:n}=e,r=void 0===e.fillValue?null:e.fillValue,s=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-start-time"===n)return e;const r=t-e;let s=t-Math.floor(r/i)*i;return s>e&&(s-=i),s}(e),o=function({periodStartSeconds:e,periodEndSeconds:t,pointIntervalSeconds:i,pointIntervalAlignment:n}){if("align-by-end-time"===n)return t-i;const r=t-e;let s=e+Math.floor(r/i)*i;return s>=t&&(s-=i),s}(e),a=e.tagDomains||{},c=Object.entries(a);if(0===t.length)if(c.length>0){const i=[];for(let t=0;t<e.groupByTags.length;t++){const n=e.groupByTags[t],r=a[n]?.[0]||"";i.push(r)}t.push({tagValues:i,points:[]})}else"return-result-group-with-default-values"===n&&t.push({tagValues:e.groupByTags.map(()=>""),points:[]});for(const[i,n]of Object.entries(a)){const r=e.groupByTags.indexOf(i);if(!(r<0))for(let e=0;e<t.length;e++){const i=t[e],s=new Set(n);for(let e=0;e<t.length;e++){const n=t[e];i.tagValues.every((e,t)=>t===r||e===n.tagValues[t])&&s.delete(n.tagValues[r])}if(0!==s.size)for(const e of s){const n={tagValues:[...i.tagValues],points:[]};n.tagValues[r]=e,t.push(n)}}}for(const n of t){if(0!==n.points.length){const e=n.points[0][0],t=n.points[n.points.length-1][0];B(e>=s,()=>`Invalid first point time: ${e}`),B(t<=o,()=>`Invalid last point time: ${t}`)}const t=[];let a=0;const c=e=>"count"===e?0:r,u=Array.isArray(e.fn)?e.fn.map(c):[r];for(let e=s;e<=o;e+=i){const i=n.points[a];i?i[0]===e?(t.push(i),a++):(B(i[0]>e,()=>`Result point has invalid time: ${i[0]}`),t.push([e,...u])):t.push([e,...u])}n.points=t}}(t,i.resultGroups),i}}const Oi=/^[a-zA-Z0-9_-]+$/,Di=1e3;class Ai{constructor(e,t){this.integrationId=e,this.rpcManager=t}async saveAuthCode(e,t){const i={authCode:e,personalStorageConfig:{identifier:t,integrationId:this.integrationId}};return await this.rpcManager.post("personalStorage/saveAuthCode",i)}async getAccessToken(e){const t={personalStorageConfig:{identifier:e,integrationId:this.integrationId}};return await this.rpcManager.post("personalStorage/getAccessToken",t)}async indexDocumentOrFolder(e,t,i,n){const r={documentOrFolderId:e,metadata:n,personalStorageConfig:{identifier:t,integrationId:this.integrationId},agentId:i};await this.rpcManager.post("personalStorage/indexDocumentOrFolder",r)}async listIndexedDocuments(e,t,i){const n={personalStorageConfig:{identifier:e,integrationId:this.integrationId},agentId:t,type:i};return(await this.rpcManager.post("personalStorage/listIndexedDocuments",n)).documents}async unindexDocument(e,t,i){const n={documentId:e,personalStorageConfig:{identifier:t,integrationId:this.integrationId},agentId:i};await this.rpcManager.post("personalStorage/unindexDocument",n)}}async function qi(e,t,i=500){const n=Date.now(),r=e.paginate({pageSize:i,subscribe:!1});let s=0,o=await r.waitForData();for(;;){for(const e of o.data)s++,await t(e.data);if(!o.hasNext)break;o=await r.next()}return{count:s,time:Date.now()-n}}function Ni(e,t){switch(t.type){case"simple":return function(e,t){const{query:i,dereference:n}=t,{collectionName:r,integrationId:s}=i;let o=e.collection(r,s).query();return o=Ri(o,i),n?o.dereference():o}(e,t);case"join":return function(e,t){const{root:i,joins:n,joinConditions:r,dereference:s,grouped:o}=t,{collectionName:a,integrationId:c}=i.query;let u=e.collection(a,c).joinQuery(i.alias);return u=Ri(u,i.query),Object.entries(n).map(([t,i])=>{const{collectionName:n,integrationId:s}=i,{left:o,right:a,leftAlias:c}=r[t];let l=e.collection(n,s).query();l=Ri(l,i),u=u.join(l,t,{left:o,right:a},{leftAlias:c})}),s&&o?u.grouped().dereference():s?u.dereference():o?u.grouped():u}(e,t);case"merged":return function(e,t){const{queries:i}=t,{collectionName:n,integrationId:r}=Fi(i[0]),s=i.map(t=>Ni(e,t));return e.collection(n,r).or(...s)}(e,t)}}function Ri(e,t){const{conditions:i,limit:n,sortOrder:r}=t;for(const t of i){if(!("operator"in t))throw new Error("Composite conditions are not support in query serialization.");const{fieldName:i,operator:n,value:r}=t;e.where(i,n,r)}e.limit(n);for(const{fieldName:t,asc:i}of r)e.sortBy(t,i);return e}function Fi(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 Fi(e.queries[0])}}const ji={"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)=>xi(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>xi(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>xi(e,t)&&Bi(t),"like_cs:like_cs":(e,t)=>xi(e,t),"like:not like":(e,t)=>!Pi(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!Pi(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!Pi(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!Pi(e,t),"not like:like":(e,t)=>Qi(e,t),"not like_cs:like":(e,t)=>Qi(e,t),"not like:like_cs":(e,t)=>Qi(e,t),"not like_cs:like_cs":(e,t)=>Qi(e,t),"not like:not like":(e,t)=>xi(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>xi(t,e)&&Bi(e),"not like:not like_cs":(e,t)=>xi(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>xi(t,e),"in:like":(e,t)=>e.every(e=>Qt(t,e,"like")),"in:like_cs":(e,t)=>e.every(e=>Qt(t,e,"like_cs")),"in:not like":(e,t)=>e.every(e=>Qt(t,e,"not like")),"in:not like_cs":(e,t)=>e.every(e=>Qt(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&&Li(e)||Ui(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&Li(e)||Ui(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&Li(t)||Ui(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&Li(t)||Ui(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=>Qt(e,t,"not like")),"like_cs:not in":(e,t)=>t.every(t=>Qt(e,t,"not like_cs")),"not like:not in":(e,t)=>t.every(t=>Qt(e,t,"like")),"not like_cs:not in":(e,t)=>t.every(t=>Qt(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 xi(e,t,i=0,n=0){if(n>=t.length)return i>=e.length;if(i>=e.length)return Li(t.substring(n));const r=e[i],s=t[n];return"%"===r&&"%"===s?xi(e,t,i+1,n+1)||xi(e,t,i+1,n):"%"!==r&&("%"===s?xi(e,t,i,n+1)||xi(e,t,i+1,n):(r===s||"_"===s)&&xi(e,t,i+1,n+1))}function Pi(e,t,i=0,n=0){if(i>=e.length&&n>=t.length)return!0;if(i>=e.length)return Li(t.substring(n));if(n>=t.length)return Li(e.substring(i));const r=i<e.length?e[i]:"",s=n<t.length?t[n]:"";return"%"===r&&"%"===s?Pi(e,t,i+1,n+1)||Pi(e,t,i,n+1)||Pi(e,t,i+1,n):"%"===r||"%"===s?Pi(e,t,i,n+1)||Pi(e,t,i+1,n):(r===s||"_"===r||"_"===s)&&Pi(e,t,i+1,n+1)}function Bi(e){return!/[a-zA-Z]/.test(e)}function Li(e){return e.split("").every(e=>"%"===e)}function Qi(e,t){return e.length>0&&Li(e)||t.length>0&&Li(t)||Ui(e)&&0===t.length}function Ui(e){let t=!1,i=!1;for(const n of e)switch(n){case"%":t=!0;break;case"_":if(i)return!1;i=!0;break;default:return!1}return t&&i}class $i{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Gt))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){return!e.find((e,t)=>!mt(this.query.sortOrder[t],{...e,asc:e.asc??!0}))}sortedByExact(e){return e.length===this.query.sortOrder.length&&this.sortedBy(e)}isSubqueryOf(e,t,i){return this.isSubqueryOfCondition({fieldName:e,operator:t,value:i})}isSubqueryOfCondition(e){return!!this.parsedConditions.filter(t=>t.fieldName===e.fieldName).find(t=>this.evaluateSubset(t,e))}isSubqueryOfConditions(e){return this.parseConditions(e).every(e=>this.isSubqueryOfCondition(e))}isSubqueryOfQuery(e){if(e.collectionName!==this.collectionName||e.integrationId!==this.integrationId)return!1;const t=e.conditions.filter(Gt),i=this.isSubqueryOfConditions(t),n=this.sortedBy(e.sortOrder),r=-1===e.limit||this.limit>-1&&this.limit<e.limit;return i&&n&&r}getConditionsFor(...e){return this.parsedConditions.filter(t=>e.includes(t.fieldName))}getConditionsForField(e){return this.parsedConditions.filter(t=>t.fieldName===e)}documentMatchesQuery(e){for(const t of this.parsedConditions){const i=t.fieldName,n=t.operator,r=ht(e,i);if("in"===n){if(t.value.includes(r))continue;return!1}if("not in"!==n){if(!Qt(t.value,r,n))return!1}else if(t.value.includes(r))return!1}return!0}evaluateSubset(e,t){const{operator:i,value:n}=e,{operator:r,value:s}=this.parseConditions([t])[0],o=ji[`${i}:${r}`];return!!o&&o(n,s)}parseConditions(e){const t=[],i=new Map,n=new Map;return e.forEach(e=>{switch(e.operator){case"==":case"in":i.set(e.fieldName,(i.get(e.fieldName)||[]).concat(e.value));break;case"!=":case"not in":n.set(e.fieldName,(n.get(e.fieldName)||[]).concat(e.value));break;default:t.push(e)}}),i.forEach((e,i)=>{t.push({fieldName:i,operator:"in",value:e})}),n.forEach((e,i)=>{t.push({fieldName:i,operator:"not in",value:e})}),t}}class Gi{constructor(e,t,i){this.documentStore=e,this.documentReferenceFactory=t,this.querySubscriptionManager=i}peek(e){if(!this.querySubscriptionManager.findValidParentOfQuery(e))return[];const{integrationId:t,collectionName:i}=e,n=new $i(e),r=this.documentReferenceFactory.getDocumentsForCollection(t,i).filter(e=>n.documentMatchesQuery(e.data)),s={};return r.forEach(e=>{s[e.squidDocId]=e}),this.documentStore.sortAndLimitDocs(new Set(Object.keys(s)),e).map(e=>s[Lt(e.__docId__,i,t)])}}function Vi(e,t){return p(function(i,n){var r=0;i.subscribe(R(n,function(i){return e.call(t,i,r++)&&n.next(i)}))})}class Hi{constructor(e,t){this.rpcManager=e,this.destructManager=t,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new h.BehaviorSubject(!0),this.inflightQueriesCount=new h.BehaviorSubject(0),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}async sendQuery(e){const t=new h.Subject,i=(0,h.firstValueFrom)(t);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:t}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),i):(this.pendingQueryBatchTimeout=setTimeout(()=>{this.safeToSendQueriesToServer.pipe(Vi(Boolean),(0,h.take)(1)).subscribe(()=>{this.processQueryBatch()})},0),i)}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=Array.from(e.map(({queryRequest:e})=>e).reduce((e,t)=>(e.set(t.clientRequestId,t),e),new Map).values()),i=e.map(({responseSubject:e})=>e);this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const i=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,r=i.errors[e],s=i.results[e];r?n.error(r):n.next(s)}}catch(e){i.forEach(t=>t.error(e))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}async waitForAllQueriesToFinish(){return(0,h.firstValueFrom)(this.inflightQueriesCount.pipe(Vi(e=>0===e))).then(()=>{})}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var Ki={d:(e,t)=>{for(var i in t)Ki.o(t,i)&&!Ki.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};function Wi(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 zi(e,t){switch(t.type){case"set":return function(e,t,i){if(void 0===i)return Ji(e,t);if(0===t.length)return Wi("object"==typeof i&&null!==i&&!Array.isArray(i),()=>`Root state must be a record. Trying to set '${i}', type: ${typeof i}`),i;function n(e){const t=Number(e);return!isNaN(t)&&t>=0&&t!==1/0}let r=e;for(let e=0;e<t.length-1&&void 0!==r;e++){const i=t[e];Wi(!Array.isArray(r)||n(i),()=>`Invalid array index. Path: '${t.slice(0,e+1)}', index: '${i}'`),r=r[i],Wi(void 0===r||"object"==typeof r&&null!==r,()=>`Cannot set a property to a non-record parent. Path: '${t.slice(0,e+1)}', type: '${null===r?"<null>":typeof r}'`)}const s=t[t.length-1];return Wi(!Array.isArray(r)||n(s),()=>`Invalid array index Path: '${t}`),(null==r?void 0:r[s])===i?e:Yi(e,t,i)}(e,t.path,t.value);case"delete":return Ji(e,t.path);case"batch":return t.actions.reduce((e,t)=>zi(e,t),e)}}function Ji(e,t){Wi(0!==t.length,"Can't delete an empty path");let i=e;for(let n=0;n<t.length-1;n++){const r=t[n];if(i=i[r],void 0===i)return e;Wi("object"==typeof i&&null!==i,()=>`Cannot delete a property from a non-record parent. Path: '${t.slice(0,n+1)}', type: ${null===i?"<null>":typeof i}`)}const n=t[t.length-1];return void 0===i[n]?e:Yi(e,t,void 0)}function Yi(e,t,i){function n(e,i){Wi(!Array.isArray(e),()=>`Can't delete element of array. Path: '${t}'`),delete e[i]}const r=Object.assign({},e);let s=r;for(let e=0;e<t.length-1;e++){const r=t[e],o=s[r];Wi(void 0===o||"object"==typeof o&&null!==o,()=>`Internal error: sub-path has an invalid type and can't be patched: '${t.slice(0,e+1)}', type: '${null===o?null:typeof o}'`);const a=void 0===o?void 0===i?void 0:{}:Array.isArray(o)?[...o]:Object.assign({},o);if(void 0===a)return n(s,r),s;s[r]=a,s=a}const o=t[t.length-1];return void 0===i?n(s,o):s[o]=i,r}function Zi(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(...Zi(t,"as-is"));return"unique-and-sorted"===t?tn(i):i}function Xi(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 en(e){const t=[...e];return t.sort((e,t)=>{for(let i=0;i<e.length;i++){if(i===t.length)return 1;const n=e[i].localeCompare(t[i]);if(0!==n)return n}return e.length-t.length}),t}function tn(e){const t=en(e),i=t;for(let e=0;e<t.length-1;e++){const n=t[e];for(let r=e+1;r<t.length;r++){const s=t[r];n.length===s.length&&Xi(n,s)&&(i[r]=void 0,e++)}}return i.filter(e=>void 0!==e)}const nn=(rn={Observable:()=>h.Observable,Subject:()=>h.Subject},sn={},Ki.d(sn,rn),sn);var rn,sn;const on=(an={filter:()=>Vi,map:()=>j},cn={},Ki.d(cn,an),cn);var an,cn,un;class ln{constructor(){this.root={children:new Map,childrenWithValue:0}}get(e){var t;return null===(t=this.getNode(e))||void 0===t?void 0:t.value}getOrSet(e,t){const i=this._buildPath(e);if(void 0!==i.value)return i.value;const n=t(e);return this._setNodeValue(i,n,void 0===n),n}set(e,t){const i=void 0===t?this._findNode(e):this._buildPath(e);i&&this._setNodeValue(i,t,!0)}delete(e){const t=this._findNode(e);if(void 0===t)return;if(void 0===t.parent){if(t!==this.root)throw new Error("Only root node can have no parent.");return this.root.value=void 0,this.root.children.clear(),void(this.root.childrenWithValue=0)}const i=(void 0===t.value?0:1)+t.childrenWithValue;i>0&&this._updateChildrenWithValue(t,-i),t.parent.children.delete(e[e.length-1]),this._runGc(t.parent)}clear(){this.delete([])}count(e=[],t="node-and-children"){const i=this.getNode(e);return void 0===i?0:i.childrenWithValue+("node-and-children"===t&&void 0!==i.value?1:0)}get isEmpty(){return 0===this.count()}fillPath(e,t){const i=[];let n=this.root,r=t(n.value,i);if(r!==ln.StopFillToken){this._setNodeValue(n,r,!1);for(let s=0;s<e.length;s++){const o=e[s];i.push(o);let a=n.children.get(o);if(r=t(null==a?void 0:a.value,i),r===ln.StopFillToken)break;a||(a={children:new Map,parent:n,childrenWithValue:0},n.children.set(o,a)),this._setNodeValue(a,r,!1),n=a}this._runGc(n)}}visitDfs(e,t,i=[]){const n=this.getNode(i);void 0!==n&&this._visitDfs(e,n,t,[...i])}_visitDfs(e,t,i,n){if("pre-order"===e&&!1===i(t.value,n))return!1;for(const[r,s]of t.children){if(n.push(r),!this._visitDfs(e,s,i,n))return!1;n.pop()}return"in-order"!==e||!1!==i(t.value,n)}getNode(e){return this._getNode(e)}_getNode(e){let t=this.root;for(const i of e)if(t=t.children.get(i),!t)return;return t}_findNode(e){let t=this.root;for(let i=0;i<e.length&&t;i++)t=t.children.get(e[i]);return t}_buildPath(e){let t=this.root;for(let i=0;i<e.length;i++){const n=e[i];let r=t.children.get(n);r||(r={children:new Map,parent:t,childrenWithValue:0},t.children.set(n,r)),t=r}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))}}ln.StopFillToken=Symbol("Trie.StopFillToken");class hn extends nn.Subject{constructor(){super(...arguments),this.isAllDetailsMode=!1}}class dn{constructor(e){this.rootState=e,this.observersTrie=new ln,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,on.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=zi(this.rootState,e),this.rootState===this.rootStateBeforeBatchStart||this.observersTrie.isEmpty||(this.batchDepth>0?this.appliedBatchActions.push(e):this._notify(e))}_notify(e){const t=Zi(e,"unique-and-sorted"),i=this.selectChildPathsWithObservers(t),n=tn([...t,...i]),r=new ln;for(const e of n)r.fillPath(e,()=>!0);r.visitDfs("pre-order",(t,i)=>{const n=this.observersTrie.get(i);if(n){const t=this.get(i),r=n.isAllDetailsMode?this._get(this.rootStateBeforeBatchStart,i):void 0;n.next({action:e,value:t,oldValue:r})}})}_observeChanges(e,t=[],i){const n=0===t.length?void 0:new ln;for(const e of t)null==n||n.set(e,!0);return new nn.Observable(t=>{const r=this.observersTrie.getOrSet(e,()=>new hn);r.isAllDetailsMode=r.isAllDetailsMode||"all-details"===i;const s={oldValue:void 0,value:this.get(e),paths:[[]]};t.next(s);const o=r.pipe((0,on.filter)(({action:e})=>void 0===n||Zi(e,"as-is").some(e=>!n.get(e))),(0,on.map)(({action:t,value:i,oldValue:n})=>{let s=this.stubForUnusedPaths;if(r.isAllDetailsMode){const i=Zi(t,"as-is");s=function(e){if(1===e.length)return[...e];if(e.some(e=>0===e.length))return[[]];const t=en(e),i=t;for(let e=0;e<i.length-1;e++){const n=t[e];for(let r=e+1;r<t.length;r++)Xi(t[r],n)&&(i[r]=void 0,e++)}return i.filter(e=>void 0!==e)}(e.length>0?i.filter(t=>Xi(t,e)).map(t=>t.slice(e.length)):i)}return{value:i,oldValue:n,paths:s}})).subscribe(t);return()=>{o.unsubscribe(),r.observed||this.observersTrie.delete(e)}})}_get(e,t){let i=e;for(let e=0;e<t.length&&void 0!==i;e++){const n=t[e];i=null==i?void 0:i[n]}return i}selectChildPathsWithObservers(e){const t=[];for(const i of e)this.observersTrie.count(i,"children-only")>0&&this.observersTrie.visitDfs("pre-order",(e,i)=>{e&&t.push([...i])},i);return t}}function pn(e,t,i=(e,t)=>e>t?1:e<t?-1:0,n=0,r=e.length-1){if(r<n)return-1;const s=Math.trunc((n+r)/2);return 0===i(t,e[s])?s:i(t,e[s])>0?pn(e,t,i,s+1,r):pn(e,t,i,n,s-1)}function gn(e,t,i=(e,t)=>e>t?1:e<t?-1:0){if(-1!==pn(e,t,i))return;let n;for(n=e.length-1;n>=0&&i(e[n],t)>0;n--)e[n+1]=e[n];e[n+1]=t}function fn(e,t,i=(e,t)=>e>t?1:e<t?-1:0){const n=pn(e,t,i);n>-1&&e.splice(n,1)}!function(e){e[e.UNKNOWN=0]="UNKNOWN",e[e.DISABLED=1]="DISABLED",e[e.ENABLED=2]="ENABLED"}(un||(un={}));const yn=100;class mn{constructor(e,t,i,n,r,s,o){this.rpcManager=e,this.clientIdService=t,this.documentStore=i,this.destructManager=n,this.documentIdentityService=r,this.querySender=s,this.socketManager=o,this.onOrphanDocuments=new h.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new In,this.queryResultsSubject=new h.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe(()=>{this.refreshOngoingQueries()}),this.destructManager.onPreDestruct(()=>{this.preDestruct()})}dumpSubscriptionInfo(){console.log("Ongoing queries:",this.ongoingQueries),console.log("ClientRequestId to local documents:",this.clientRequestIdToLocalDocuments),console.log("Local documents to clientRequestId:",this.localDocumentToClientRequestIds)}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return L(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);t?.gotInitialResponse&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:i,integrationId:n}=Bt(t),r=this.queryMappingManager.getMapping(i,n);return r?function(e,t){const i=[...e.unconditional||[]],n=new Map;for(const[i,r]of Object.entries(e.conditional||{})){const e=kt(i);let s;if(Gt(e)){const i=ht(t,e.fieldName)??null;s=Qt(e.value,i,e.operator)}else s=bn(e,t);if(s)for(const e of r)n.set(e,(n.get(e)||0)+1)}for(const[t,r]of n.entries())r>=e.queriesMetadata[t].condCount&&i.push(t);return i}(r,e):[]}setClientRequestIdsForLocalDoc(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set,n=new Set(t?this.findQueriesForDocument(t,e).map(e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId):[]),r=new Set([...i,...n]);for(const t of[...i]){if(n.has(t))continue;i.delete(t);const r=this.clientRequestIdToLocalDocuments.get(t);r&&(r.delete(e),r.size||this.clientRequestIdToLocalDocuments.delete(t)),i.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let i=this.localDocumentToClientRequestIds.get(e);i||(i=new Set,this.localDocumentToClientRequestIds.set(e,i)),i.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...r]}errorOutAllQueries(e,t){const i=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of i){const i=this.ongoingQueries.get(e);i&&(this.destructManager.isDestructing?i.dataSubject.complete():i.dataSubject.error(t),i.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const i of e){const e=this.ongoingQueries.get(i);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(i)||new Set,r=this.documentStore.sortAndLimitDocs(n,e.query),s=e.supportedQueries.map(e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(r,e)).some(Boolean);let o=e;for(;!o.allObservables;)o=L(o?.supportingOngoingQuery);if(s&&t.add(o),e.query.limit>0)switch(e.limitUnderflowState){case un.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+yn?un.ENABLED:un.DISABLED;break;case un.DISABLED:break;case un.ENABLED:if(n.size<e.query.limit+20){e.limitUnderflowState=un.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(r)}for(const e of t){const t=this.collectAllObservables(e);L(e.allObservables).next(t)}}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 $i(e.query);for(const i of this.ongoingQueries.values()){if(e===i)return;if(this.isValidParent(i)&&t.isSubqueryOfQuery(i.query))return i}}findValidParentOfQuery(e){const t=new $i(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,i,n,r,s){return r&&this.socketManager.notifyWebSocketIsNeeded(),(0,h.defer)(()=>{const o=this.createOngoingQueryGraph(e,t,i,n,r,!0);s&&(o.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(o),o.allObservables=new h.ReplaySubject(1);const a=o.allObservables.pipe((0,h.switchMap)(e=>(0,h.combineLatest)(e).pipe(j(e=>this.joinResults(e,n,o)))),Vi(()=>this.allOngoingQueriesGotInitialResult(o)),(0,h.startWith)(void 0),(0,h.pairwise)(),Vi(([e,t])=>!mt(e,t)),j(([,e])=>e),r?(0,h.tap)():(0,h.take)(1),(0,h.finalize)(()=>{o.dataSubject.complete(),o.done=!0,this.completeAllSupportedQueries(o).then(),o.allObservables?.complete()})),c=this.collectAllObservables(o);return o.allObservables.next(c),a}).pipe((0,h.share)())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const i=[];for(const n of t){const t=L(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),i.push(n))}i.length&&this.onOrphanDocuments.next(i)}registerQueryFinalizer(e){const t=e.clientRequestId,i=$t(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,h.finalize)(async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,h.firstValueFrom)((0,h.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(Vi(e=>0===e)))),this.queryMappingManager.removeQuery(i).then(),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),this.ongoingQueries.delete(t)}),Vi(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,i,n,r,s,o={}){if(o[t])return o[t];const a=this.clientIdService.generateClientRequestId(),c=[],u={clientRequestId:a,activated:s,alias:t,query:e,subscribe:r,dataSubject:new h.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new h.BehaviorSubject(0),queryRegistered:new h.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:r?un.UNKNOWN:un.DISABLED};this.registerQueryFinalizer(u),this.ongoingQueries.set(a,u),o[t]=u;for(const[e,s]of Object.entries(n)){const a=s.leftAlias;if(a!==t&&e!==t)continue;const l=a===t?e:a;if(a===t){const e=this.createOngoingQueryGraph(i[l],l,i,n,r,!1,o);e.joinCondition=s,c.push(e)}else u.supportingOngoingQuery=this.createOngoingQueryGraph(i[l],l,i,n,r,!1,o)}return u}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const i=e.alias;t.push(e.dataSubject.pipe(Vi(Boolean),j(e=>({docs:e,alias:i}))));for(const i of e.supportedQueries)this.collectAllObservables(i,t);return t}joinResults(e,t,i){const n=e.reduce((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e),{});let r=n[i.alias].map(e=>({[i.alias]:e}));const s=this.getOngoingQueriesBfs(i),o=new Set;for(let e=1;e<s.length;e++){const i=s[e].alias;o.has(i)||(o.add(i),r=this.join(r,i,n[i],t[i]))}return r}join(e,t,i,n){if(!e.length)return e;const r=Object.keys(e[0]);if(!n||!r.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const s=new Map;return(i||[]).forEach(e=>{const t=this.transformKey(e[n.right]);s.has(t)||s.set(t,[]),L(s.get(t)).push(e)}),e.flatMap(e=>{const i=s.get(this.transformKey(e[n.leftAlias]?.[n.left]))||[];return i.length?i.map(i=>({...e,[t]:i})):n.isInner?[]:[{...e,[t]:void 0}]})}getOngoingQueriesBfs(e){const t=[],i=[e];for(;i.length;){const e=L(i.shift());e.isEmptyForJoin||(t.push(e),i.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){const i=L(t.joinCondition),n=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const r=L(t.supportingOngoingQuery?.supportedQueries).filter(e=>e.alias===t.alias),s=new Set(e.map(e=>e[i.left]??null));for(const e of r)e.query.conditions.filter(Gt).filter(e=>e.fieldName===i.right).forEach(e=>{s.delete(e.value)});if(0===s.size)return!1;const o=It(n);o.conditions=o.conditions.filter(e=>!Gt(e)||e.fieldName!==i.right),[...s].forEach(e=>{o.conditions.push({fieldName:i.right,operator:"==",value:e})});const a={...t,query:o,activated:!0,gotInitialResponse:!1,dataSubject:new h.BehaviorSubject(null),clientRequestId:this.clientIdService.generateClientRequestId(),isEmptyForJoin:!1};return this.registerQueryFinalizer(a),this.ongoingQueries.set(a.clientRequestId,a),L(t.supportingOngoingQuery).supportedQueries.push(a),this.sendQueryToServerOrUseParentQuery(a),!0}{if(t.activated=!0,n.conditions.filter(Gt).filter(e=>e.fieldName===i.right&&"=="===e.operator).map(e=>e.value).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const r=e.map(e=>e[i.left]??null).map(e=>({fieldName:i.right,operator:"==",value:e}));return r.length?(n.conditions.push(...r),this.sendQueryToServerOrUseParentQuery(t)):t.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=L(t.shift());t.push(...e.supportedQueries||[]),await(0,h.firstValueFrom)(e.unsubscribeBlockerCount.pipe(Vi(e=>0===e))),e.dataSubject.complete()}}transformKey(e){return e instanceof Date?`DATE AS string KEY: ${e.toISOString()}`:e}preDestruct(){this.unsubscribe()}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}sendQueryToServerOrUseParentQuery(e,t=!1){if(this.destructManager.isDestructing)return;const i=e.query,n=e.clientRequestId,r=$t(this.clientIdService.getClientId(),n);this.queryMappingManager.addQuery(i,r),this.ongoingQueries.set(n,e);const s=t?void 0:this.findValidParentOfOngoingQuery(e);s?this.useParentOngoingQuery(e,s).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const i={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new $i(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,h.firstValueFrom)(t.queryRegistered.pipe(Vi(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 r=(0,h.race)(e.queryRegistered.pipe(Vi(Boolean),(0,h.delay)(2e3),(0,h.take)(1)),this.destructManager.observeIsDestructing().pipe((0,h.take)(1)));t.dataSubject.pipe((0,h.takeWhile)(()=>!e.done),(0,h.takeUntil)(r),Vi(Boolean),(0,h.tap)(()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)}),j(e=>e.filter(e=>n.documentMatchesQuery(e)))).subscribe({next:t=>{for(const i of t)this.setClientRequestIdsForLocalDoc(Lt(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+yn:t,n={query:{...e.query,limit:i},clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(n).then(t=>{e.isInFlight=!1,e.queryRegistered.next(!0),this.queryResultsSubject.next(t)}).catch(t=>{e.isInFlight=!1,this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(Rt.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0})}refreshOngoingQueries(){for(const e of this.ongoingQueries.values())this.sendQueryToServerOrUseParentQuery(e,!0)}migrateDocIds(e){const t=Object.keys(e);for(const i of this.clientRequestIdToLocalDocuments.values())t.forEach(t=>{i.has(t)&&(i.delete(t),i.add(e[t]))});t.forEach(t=>{ft(this.localDocumentToClientRequestIds,t,e[t])})}}function bn(e,t){for(const i of e.fields){const e=ht(t,i.fieldName)??null;if(Qt(i.value,e,i.operator))return!0;if(Qt(i.value,e,"!="))return!1}return!1}class In{constructor(){this.stateService=new dn({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch(()=>{let i=0;const n=new Set;for(const r of e.conditions){if(Gt(r)&&["=="].includes(r.operator)){const e=Et(r.fieldName);n.has(e)||(i++,n.add(e))}else i++;const s=this.getConditionStatePath(e,r),o=[...this.stateService.get(s)||[]];gn(o,t),this.stateService.set(s,o)}if(!e.conditions.length){const i=["queryMapping",e.collectionName,e.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];gn(n,t),this.stateService.set(i,n)}this.stateService.set([...this.getQueryMetadataStatePath(e,t),"condCount"],i)}),this.querySubscriptionIdToQuery[t]=e}async removeQuery(e){const t=this.querySubscriptionIdToQuery[e];if(t)return this.stateService.runInBatch(()=>{for(const i of t.conditions){const n=this.getConditionStatePath(t,i),r=[...this.stateService.get(n)||[]];fn(r,e),r.length?this.stateService.set(n,r):this.stateService.delete(n)}if(!t.conditions.length){const i=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.get(i)||[]];fn(n,e),this.stateService.set(i,n)}this.stateService.delete(this.getQueryMetadataStatePath(t,e))}),t}getMapping(e,t){return this.stateService.get(["queryMapping",e,t,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",(i=t,Tt(i))];var i}}class vn{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(0,h.lastValueFrom)((0,h.combineLatest)(t).pipe((0,h.filter)(e=>!e.includes(!0)),(0,h.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=L(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some(e=>this.locks[e]?.value)}lockSync(...e){B(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new h.BehaviorSubject(!0)}}class Sn{constructor(e,t,i){this.rpcManager=e,this.socketManager=t,this.queueManagers=new Map,this.socketManager.observeNotifications().subscribe(e=>{const t=this.getOrUndefined(e.integrationId,e.topicName);t&&t.onMessages(e.payload)}),i.onPreDestruct(()=>{for(const e of this.queueManagers.values())for(const t of e.values())t.destruct()})}get(e,t){let i=this.queueManagers.get(e);i||(i=new Map,this.queueManagers.set(e,i));let n=i.get(t);return n||(n=new Mn(e,t,this.rpcManager,this.socketManager),i.set(t,n)),n}getOrUndefined(e,t){return this.queueManagers.get(e)?.get(t)}}const wn="subscriptionMutex";class Mn{constructor(e,t,i,n){this.integrationId=e,this.topicName=t,this.rpcManager=i,this.socketManager=n,this.messagesSubject=new h.Subject,this.subscriberCount=0,this.lockManager=new vn}async produce(e){await this.lockManager.lock(wn);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(wn)}}consume(){return this.socketManager.notifyWebSocketIsNeeded(),(0,h.defer)(()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,h.finalize)(()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))}async performSubscribe(){await this.lockManager.lock(wn);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 h.Subject}finally{this.lockManager.release(wn)}}async performUnsubscribe(){await this.lockManager.lock(wn);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(wn)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class Tn{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(0,h.firstValueFrom)((0,h.interval)(10).pipe((0,h.filter)(()=>this.attemptConsume()),(0,h.first)()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}const _n={TRACE_ID:"x-squid-traceid",SECRET:"x-squid-secret",APP_API_KEY:"x-app-api-key",APP_ID:"x-squid-appid",CLIENT_ID:"x-squid-clientid",CLIENT_VERSION:"x-squid-client-version",SOURCE_IP:"x-squid-source-ip"},kn=e=>e();class En extends Error{constructor(e,t,i,n,r){super(e),this.statusCode=t,this.url=i,this.headers=n,this.body=r}}const Cn="1.0.395";async function On(e){const t=await Rn({url:e.url,headers:e.headers,method:"POST",message:e.message,files:e.files,filesFieldName:e.filesFieldName,extractErrorMessage:e.extractErrorMessage});return t.body=Fn(t.body),t}async function Dn(e){const t=await Rn({...e,method:"GET",files:[],filesFieldName:""});return t.body=Fn(t.body),t}async function An(e){const t=await Rn({...e,method:"PUT"});return t.body=Fn(t.body),t}async function qn(e){const t=await Rn({...e,method:"PATCH"});return t.body=Fn(t.body),t}async function Nn(e){const t=await Rn({...e,method:"DELETE",files:[],filesFieldName:""});return t.body=Fn(t.body),t}async function Rn({headers:e,files:t,filesFieldName:i,message:n,url:r,extractErrorMessage:s,method:o}){const a=new Headers(e);a.append(_n.TRACE_ID,function(e="n_"){return`${e}${z(10).toLowerCase()}`}("c_")),a.append(_n.CLIENT_VERSION,Cn);const c={method:o,headers:a,body:void 0};if("GET"!==o&&"DELETE"!==o)if(t&&t.length){const e=new FormData;for(const n of t)e.append(i||"files",n,n.name);e.append("body",_t(n)),c.body=e}else void 0!==n&&(a.append("Content-Type","application/json"),c.body=_t(n));else"DELETE"===o&&void 0!==n&&(a.append("Content-Type","application/json"),c.body=_t(n));try{const e=await fetch(r,c),t={};if(e.headers.forEach((e,i)=>{t[i]=e}),!e.ok){const i=await e.text(),n=Fn(i);if(!s)throw new En(i,e.status,r,t,n);let o;try{o="string"==typeof n?n:n?.message||i}catch{}throw o||(o=e.statusText),new En(o,e.status,r,t,n)}const i=await e.text();return Rt.debug(`received response from url ${r}: ${JSON.stringify(i)}`),{body:i,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Rt.debug(`Unable to perform fetch request to url: ${r}`,e),e}}function Fn(e){if(e){try{return kt(e)}catch{}return e}}class jn{constructor(e,t,i,n,r,s){this.region=e,this.appId=t,this.authManager=r,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new h.BehaviorSubject(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")}),i.onDestruct(async()=>{await this.awaitAllSettled()});const o=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Tn(60*o,5),ai:new Tn(20*o,5),secret:new Tn(20*o,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:i}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return i&&(n+=`; IntegrationId ${i}`),{Authorization:n}}async awaitAllSettled(){await(0,h.firstValueFrom)(this.onGoingRpcCounter.pipe((0,h.filter)(e=>0===e)))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,i=[],n="files"){return(await this.rawPost(e,t,i,n)).body}async rawPost(e,t,i=[],n="files",r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o};Rt.debug(`sending POST request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await On({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async get(e,t,i=!0){return(await this.rawGet(e,t,i)).body}async rawGet(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),r={...this.staticHeaders,...n};let o=e.startsWith("http://")||e.startsWith("https://")?e:s(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))}),o+=`?${e.toString()}`}return Rt.debug(`sending GET request: path: ${e}, queryParams: ${JSON.stringify(t)}`),await Dn({url:o,headers:r,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async put(e,t,i=[],n="files"){return(await this.rawPut(e,t,i,n)).body}async rawPut(e,t,i=[],n="files",r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o};Rt.debug(`sending PUT request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await An({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async patch(e,t,i=[],n="files"){return(await this.rawPatch(e,t,i,n)).body}async rawPatch(e,t,i=[],n="files",r=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),a={...this.staticHeaders,...o};Rt.debug(`sending PATCH request: path: ${e} message: ${JSON.stringify(t)}`);const c=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await qn({url:c,headers:a,message:t,files:i,filesFieldName:n,extractErrorMessage:r})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}async delete(e,t,i=!0){return(await this.rawDelete(e,t,i)).body}async rawDelete(e,t,i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const n=await this.getAuthHeaders(),r={...this.staticHeaders,...n};Rt.debug(`sending DELETE request: path: ${e}, body: ${JSON.stringify(t)}`);const o=e.startsWith("http://")||e.startsWith("https://")?e:s(this.region,this.appId,e);return await Nn({url:o,headers:r,message:t,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?L(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?L(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):L(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class xn{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 Pn(){}const Bn="undefined"!=typeof process&&process.versions?.node?i(86):Nt().WebSocket;class Ln{constructor(e,t,i,n=kn,r,s){this.clientIdService=e,this.region=t,this.appId=i,this.messageNotificationWrapper=n,this.destructManager=r,this.authManager=s,this.webSocketObserver=new h.Subject,this.allMessagesObserver=new h.Subject,this.connectionReady=new h.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new h.Subject,this.connectedAtLeastOnce=!1,this.webSocketNeededSubject=new h.BehaviorSubject(!1),this.clientTooOldThreshold=3e4,this.destructManager.onDestruct(()=>this.destruct()),this.setupMessageAcknowledgments(),this.webSocketNeededSubject.pipe((0,h.filter)(Boolean),(0,h.take)(1)).subscribe(()=>{this.connect(),this.lastTick=new Date,this.tickInterval=setInterval(()=>this.keepAlive(),5e3)}),this.observeConnectionReady().pipe((0,h.skip)(1),(0,h.filter)(e=>!e),(0,h.switchMap)(()=>(0,h.race)((0,h.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,h.filter)(Boolean)),this.destructManager.observeIsDestructing()))).subscribe(()=>{this.connectionReady.value?Rt.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Rt.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())}),this.observeConnectionReady().pipe((0,h.filter)(Boolean)).subscribe(()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}),this.observeNotifications().pipe((0,h.filter)(e=>"clientInfo"===e.type)).subscribe(e=>{console.log("Client info message received",e)})}refreshClient(){this.destructManager.isDestructing?Rt.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Rt.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Rt.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Rt.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}getClientInfo(){this.sendMessage({type:"getClientInfo"})}keepAlive(){this.lastTick&&(Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(Rt.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date)}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,h.distinctUntilChanged)())}async awaitConnectionReady(){await(0,h.firstValueFrom)(this.observeConnectionReady().pipe((0,h.filter)(Boolean)))}notifyWebSocketIsNeeded(){this.webSocketNeededSubject.next(!0)}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){this.webSocketNeededSubject.next(!0),await(0,h.firstValueFrom)(this.connectionReady.pipe((0,h.filter)(Boolean)));const t=await this.authManager.getToken();if(this.connectionReady.value)try{B(this.socket,"Socket is undefined in sendMessageAsync");const i=_t({message:e,authToken:t});Rt.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.sendMessageAsync(e))}else await this.sendMessageAsync(e)}sendKillMessage(){this.socket?.connected&&this.socket.send(_t({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=s(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();Rt.debug(this.clientIdService.getClientId(),"Connecting to socket at:",e);const i=`${e}?clientId=${t}`;this.socket=function(e,t={}){let i,n=0,r=1;const s={connected:!1,closeCalled:!1,open(){i=new(Bn?.WebSocket??Bn)(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.")}:Pn,i.onopen=function(e){s.connected=!0,(t.onopen||Pn)(e),n=0},i.onclose=function(e){if(s.connected=!1,4999!==e.code&&4001!==e.code)return Rt.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Pn)(e),void s.reconnect(e);(t.onclose||Pn)(e)},i.onerror=function(e){s.connected=!1,e&&"ECONNREFUSED"===e.code?s.reconnect(e):s.closeCalled||(t.onerror||Pn)(e)}},reconnect(e){const i=void 0!==t.maxAttempts?t.maxAttempts:1/0;r&&n++<i?r=setTimeout(function(){(t.onreconnect||Pn)(e),Rt.debug("WebSocket trying to reconnect..."),s.open()},t.timeoutMillis||1e3):(t.onmaximum||Pn)(e)},json(e){i.send(JSON.stringify(e))},send(e){i.send(e)},close(e=4999,t){s.closeCalled=!0;try{s.connected=!1,clearTimeout(r),r=void 0,i.close(e,t)}catch(e){}}};return s.open(),s}(i,{timeoutMillis:1e4,onmessage:e=>this.onMessage(e.data),onopen:()=>{Rt.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{Rt.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Rt.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Rt.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):Rt.debug(t,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}disconnectForTest(){this.connectionReady.next(!1),this.socket?.close(4998)}onConnectionReady(){this.connectionReady.next(!0),this.connectedAtLeastOnce?this.sendMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return Rt.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=kt(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Rt.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper(()=>{this.webSocketObserver.next(e)}))}setupMessageAcknowledgments(){const e=new h.Subject;this.allMessagesObserver.subscribe(t=>{t?.messageId&&e.next(t.messageId)});const t=[];e.pipe((0,h.tap)(e=>t.push(e)),(0,h.debounceTime)(100)).subscribe(async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})})}async destruct(){this.sendKillMessage(),await(0,h.firstValueFrom)((0,h.timer)(0)),this.connectionReady.next(!1),await(0,h.firstValueFrom)((0,h.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Qn(e){var t,i;i="Invalid application ID",B(function(e){return"string"==typeof e}(t=e),()=>U(i,"Not a string",t));const[n,r,s,o]=e.split("-");return B(!o,`Invalid application ID: ${e}`),{appId:n,environmentId:r??"prod",squidDeveloperId:s}}function Un(e,t){return`${Qn(e).appId}${t&&"prod"!==t?`-${t}`:""}`}function $n(e,t,i){return`${Un(e,t)}${i?`-${i}`:""}`}function Gn(e){const t=Qn(e);return Un(t.appId,t.environmentId)}class Vn{constructor(e="built_in_storage",t){this.integrationId=e,this.rpcManager=t}async uploadFile(e,t,i){const n={integrationId:this.integrationId,dirPathInBucket:e,expirationInSeconds:i};await this.rpcManager.post("storage/uploadFile",n,[t])}async getFileMetadata(e){const t={integrationId:this.integrationId,filePathInBucket:e};return await this.rpcManager.post("storage/getFileMetadata",t)}async getDownloadUrl(e,t){const i={integrationId:this.integrationId,filePathInBucket:e,urlExpirationInSeconds:t};return await this.rpcManager.post("storage/getDownloadUrl",i)}async listDirectoryContents(e){const t={integrationId:this.integrationId,dirPathInBucket:e};return await this.rpcManager.post("storage/listDirectoryContents",t)}async deleteFile(e){await this.deleteFiles([e])}async deleteFiles(e){const t={integrationId:this.integrationId,filePathsInBucket:e};await this.rpcManager.post("storage/deleteFiles",t)}}class Hn{constructor(e,t,i,n){this.rpcManager=e,this.region=t,this.appId=i,this.apiKey=n}async aiSearch(e){return await this.rpcManager.post("web/aiSearch",{query:e})}async getUrlContent(e){return(await this.rpcManager.post("web/getUrlContent",{url:e})).markdownText}async createShortUrl(e,t){B(this.apiKey,"API key is required to create a short URL");const i=o(this.region,"openapi/sqd/shorten"),n={url:e,appId:this.appId,secondsToLive:t},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!r.ok)throw console.error("Error making POST request to shorten endpoint",r.statusText),new Error(`${r.statusText}: ${r.text}`);return await r.json()}async createShortUrls(e,t){B(this.apiKey,"API key is required to create a short URL");const i=o(this.region,"openapi/sqd/shortenMany"),n={urls:e,appId:this.appId,secondsToLive:t},r=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(n)});if(!r.ok)throw console.error("Error making POST request to shortenMany endpoint",r.statusText),new Error(`${r.statusText}: ${r.text}`);return await r.json()}async deleteShortUrl(e){B(this.apiKey,"API key is required to delete a short URL");const t=o(this.region,"openapi/sqd/delete"),i={id:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!n.ok)throw console.error("Error making POST request to delete endpoint",n.statusText),new Error(n.statusText)}async deleteShortUrls(e){B(this.apiKey,"API key is required to delete a short URL");const t=o(this.region,"openapi/sqd/deleteMany"),i={ids:e,appId:this.appId},n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json","x-app-api-key":this.apiKey},body:JSON.stringify(i)});if(!n.ok)throw console.error("Error making POST request to delete endpoint",n.statusText),new Error(n.statusText)}}class Kn{static{this.squidInstancesMap={}}constructor(e){this.options=e,this.destructManager=new yi,B(e.appId,"APP_ID_MUST_BE_PROVIDED");for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this))){const t=this[e];"function"!=typeof t||"constructor"===e||e.startsWith("_")||(this[e]=t.bind(this))}const t="prod"!==e.environmentId&&e.squidDeveloperId,i=$n(e.appId,e.environmentId,t?e.squidDeveloperId:void 0);this.clientIdService=new Ft(this.destructManager),Rt.debug(this.clientIdService.getClientId(),"New Squid instance created"),this.authManager=new ut(e.apiKey,e.authProvider),this.socketManager=new Ln(this.clientIdService,e.region,i,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new jn(e.region,i,this.destructManager,{},this.authManager,this.clientIdService),this.notificationClient=new ki(this.socketManager,this.rpcManager),this.jobClient=new Mi(this.socketManager,this.rpcManager,this.clientIdService),this.aiClient=new ot(this.socketManager,this.rpcManager,this.jobClient),this.apiClient=new ct(this.rpcManager),this.documentStore=new Si,this.lockManager=new vn,this.distributedLockManager=new mi(this.socketManager,this.destructManager),this.documentIdentityService=new Ii(this.documentStore,this.destructManager),this.documentReferenceFactory=new vi(this.documentIdentityService),this.querySender=new Hi(this.rpcManager,this.destructManager),this.observabilityClient=new Ci(this.rpcManager),this.schedulerClient=new xn(this.rpcManager),this._appId=i,this.querySubscriptionManager=new mn(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender,this.socketManager),this.localQueryManager=new Gi(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const n=new Ti(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Kt(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new gi(this.documentStore,n,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new ri(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new At(this.rpcManager),this.nativeQueryManager=new _i(this.rpcManager),this._connectionDetails=new si(this.clientIdService,this.socketManager),this.queueManagerFactory=new Sn(this.rpcManager,this.socketManager,this.destructManager),this.adminClient=new l(this.rpcManager,this.options.region,Gn(i)),this.webClient=new Hn(this.rpcManager,this.options.region,Gn(i),this.options.apiKey)}get observability(){return this.observabilityClient}get schedulers(){return this.schedulerClient}get appId(){return this._appId}static getInstance(e){const t=Tt(e);let i=Kn.squidInstancesMap[t];return i||(i=new Kn(e),Kn.squidInstancesMap[t]=i,i)}static getInstances(){return Object.values(Kn.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Ke){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)}executeNativeRelationalQuery(e,t,i={}){const n={type:"relational",query:t,params:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,i){const n={type:"mongo",collectionName:t,aggregationPipeline:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeElasticQuery(e,t,i,n="_search",r="GET"){const s={type:"elasticsearch",index:t,endpoint:n,method:r,body:i,integrationId:e};return this.nativeQueryManager.executeNativeQuery(s)}ai(){return this._validateNotDestructed(),this.aiClient}job(){return this._validateNotDestructed(),this.jobClient}api(){return this._validateNotDestructed(),this.apiClient}admin(){return this._validateNotDestructed(),this.adminClient}web(){return this._validateNotDestructed(),this.webClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new Vn(e,this.rpcManager)}personalStorage(e){return this._validateNotDestructed(),new Ai(e,this.rpcManager)}extraction(){return this._validateNotDestructed(),new wi(this.rpcManager)}acquireLock(e){return this._validateNotDestructed(),this.distributedLockManager.lock(e)}async withLock(e,t){const i=await this.acquireLock(e);try{return await t(i)}finally{i.release()}}queue(e,t=We){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally(()=>{const e=Object.entries(Kn.squidInstancesMap).find(([,e])=>e===this);e&&delete Kn.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)=>s(e,t,i),getStaticHeaders:()=>e.getStaticHeaders(),getAuthHeaders:()=>e.getAuthHeaders(),appIdWithEnvironmentIdAndDevId:(e,t,i)=>$n(e,t,i)}}_validateNotDestructed(){B(!this.destructManager.isDestructing,"The client was already destructed.")}}var Wn=exports;for(var zn in n)Wn[zn]=n[zn];n.__esModule&&Object.defineProperty(Wn,"__esModule",{value:!0})})();
|