@squidcloud/client 1.0.224 → 1.0.226

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 CHANGED
@@ -2,4 +2,4 @@
2
2
  ${e.query}
3
3
  `,variables:e.variables})).data}async mutate(e){return(await this.client.mutate({mutation:Ha`
4
4
  ${e.query}
5
- `})).data}}class ru{constructor(e,t,r){this.rpcManager=e,this.region=t,this.appId=r,this.clientsMap=new Map}get(e){let t=this.clientsMap.get(e);return t||(t=new tu(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class nu{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=bt(e),n=r.map((e=>`sendMutation_${Ge(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 Se.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class iu{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}function ou(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=su(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:u}=r.query;let c=e.collection(a,u).joinQuery(r.alias);return c=su(c,r.query),Object.entries(n).map((([t,r])=>{const{collectionName:n,integrationId:o}=r,{left:s,right:a,leftAlias:u}=i[t];let l=e.collection(n,o).query();l=su(l,r),c=c.join(l,t,{left:s,right:a},{leftAlias:u})})),o&&s?c.grouped().dereference():o?c.dereference():s?c.grouped():c}(e,t);case"merged":return function(e,t){const{queries:r}=t,{collectionName:n,integrationId:i}=au(r[0]),o=r.map((t=>ou(e,t)));return e.collection(n,i).or(...o)}(e,t)}}function su(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 au(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 au(e.queries[0])}}const uu={"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)=>cu(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>cu(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>cu(e,t)&&hu(t),"like_cs:like_cs":(e,t)=>cu(e,t),"like:not like":(e,t)=>!lu(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!lu(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!lu(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!lu(e,t),"not like:like":(e,t)=>fu(e,t),"not like_cs:like":(e,t)=>fu(e,t),"not like:like_cs":(e,t)=>fu(e,t),"not like_cs:like_cs":(e,t)=>fu(e,t),"not like:not like":(e,t)=>cu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>cu(t,e)&&hu(e),"not like:not like_cs":(e,t)=>cu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>cu(t,e),"in:like":(e,t)=>e.every((e=>at(t,e,"like"))),"in:like_cs":(e,t)=>e.every((e=>at(t,e,"like_cs"))),"in:not like":(e,t)=>e.every((e=>at(t,e,"not like"))),"in:not like_cs":(e,t)=>e.every((e=>at(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&&du(e)||pu(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&du(e)||pu(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&du(t)||pu(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&du(t)||pu(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=>at(e,t,"not like"))),"like_cs:not in":(e,t)=>t.every((t=>at(e,t,"not like_cs"))),"not like:not in":(e,t)=>t.every((t=>at(e,t,"like"))),"not like_cs:not in":(e,t)=>t.every((t=>at(e,t,"like_cs")))};function cu(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return du(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?cu(e,t,r+1,n+1)||cu(e,t,r+1,n):"%"!==i&&("%"===o?cu(e,t,r,n+1)||cu(e,t,r+1,n):(i===o||"_"===o)&&cu(e,t,r+1,n+1))}function lu(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return du(t.substring(n));if(n>=t.length)return du(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?lu(e,t,r+1,n+1)||lu(e,t,r,n+1)||lu(e,t,r+1,n):"%"===i||"%"===o?lu(e,t,r,n+1)||lu(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&lu(e,t,r+1,n+1)}function hu(e){return!/[a-zA-Z]/.test(e)}function du(e){return e.split("").every((e=>"%"===e))}function fu(e,t){return e.length>0&&du(e)||t.length>0&&du(t)||pu(e)&&0===t.length}function pu(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 vu{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Qe))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){const t=e.find(((e,t)=>{var r;return!ce(this.query.sortOrder[t],Object.assign(Object.assign({},e),{asc:null===(r=e.asc)||void 0===r||r}))}));return!t}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(Qe),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=ne(e,r);if("in"===n){if(t.value.includes(i))continue;return!1}if("not in"!==n){if(!at(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=uu[`${r}:${i}`];return!!s&&s(n,o)}evaluateIncludes(e,t){const{operator:r,value:n}=e,{operator:i,value:o}=this.parseConditions([t])[0],s=Array.isArray(n)?n.sort():n,a=Array.isArray(o)?o.sort():o;return i===r&&ce(a,s)}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 yu{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 vu(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[Ge(e.__docId__,r,t)]))}}function bu(e,t){return o((function(r,n){var i=0;r.subscribe(C(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}class mu{constructor(e,r){this.rpcManager=e,this.destructManager=r,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new t.BehaviorSubject(!0),this.inflightQueriesCount=new t.BehaviorSubject(0),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}async sendQuery(e){const r=new t.Subject,n=(0,t.firstValueFrom)(r);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:r}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),n):(this.pendingQueryBatchTimeout=setTimeout((()=>{this.safeToSendQueriesToServer.pipe(bu(Boolean),(0,t.take)(1)).subscribe((()=>{this.processQueryBatch()}))}),0),n)}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=e.map((({queryRequest:e})=>e)),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,t.firstValueFrom)(this.inflightQueriesCount.pipe(bu((e=>0===e)))).then((()=>{}))}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var gu,_u=r(4123);function Ou(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?Ou(e,t,r,o+1,i):Ou(e,t,r,n,o-1)}function Su(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){if(-1!==Ou(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 wu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){const n=Ou(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"}(gu||(gu={}));const Eu=100,Tu=20;class Iu{constructor(e,r,n,i,o,s){this.rpcManager=e,this.clientIdService=r,this.documentStore=n,this.destructManager=i,this.documentIdentityService=o,this.querySender=s,this.onOrphanDocuments=new t.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Mu,this.queryResultsSubject=new t.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe((()=>{this.refreshOngoingQueries()})),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return(0,B.truthy)(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);(null==t?void 0:t.gotInitialResponse)&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=$e(t),i=this.queryMappingManager.getMapping(r,n);return i?function(e,t){var r;const n=[...e.unconditional||[]],i=new Map;for(const[n,o]of Object.entries(e.conditional||{})){const e=me(n);let s;if(Qe(e)){const n=null!==(r=ne(t,e.fieldName))&&void 0!==r?r:null;s=at(e.value,n,e.operator)}else s=Au(e,t);if(s)for(const e of o)i.set(e,(i.get(e)||0)+1)}for(const[t,r]of i.entries())r>=e.queriesMetadata[t].condCount&&n.push(t);return n}(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=(0,B.truthy)(null==s?void 0:s.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case gu.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+Eu?gu.ENABLED:gu.DISABLED;break;case gu.DISABLED:break;case gu.ENABLED:if(n.size<e.query.limit+Tu){e.limitUnderflowState=gu.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);(0,B.truthy)(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 vu(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 vu(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,r,n,i,o,s){return(0,t.defer)((()=>{const a=this.createOngoingQueryGraph(e,r,n,i,o,!0);s&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new t.ReplaySubject(1);const u=a.allObservables.pipe((0,t.switchMap)((e=>(0,t.combineLatest)(e).pipe(L((e=>this.joinResults(e,i,a)))))),bu((()=>this.allOngoingQueriesGotInitialResult(a))),(0,t.startWith)(void 0),(0,t.pairwise)(),bu((([e,t])=>!ce(e,t))),L((([,e])=>e)),o?(0,t.tap)():(0,t.take)(1),(0,t.finalize)((()=>{var e;a.dataSubject.complete(),a.done=!0,this.completeAllSupportedQueries(a).then(),null===(e=a.allObservables)||void 0===e||e.complete()}))),c=this.collectAllObservables(a);return a.allObservables.next(c),u})).pipe((0,t.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=(0,B.truthy)(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 r=e.clientRequestId,n=ct(this.clientIdService.getClientId(),r);e.dataSubject.pipe((0,t.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,t.firstValueFrom)((0,t.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(bu((e=>0===e))))),this.queryMappingManager.removeQuery(n).then(),this.ongoingQueries.delete(r),e.subscribe&&!e.isEmptyForJoin&&e.activated){const t={clientRequestId:r};this.rpcManager.post("query/unsubscribe",t).catch((t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestIdMapping(r),this.ongoingQueries.delete(r)})),bu(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,r,n,i,o,s,a={}){if(a[r])return a[r];const u=Q(),c=[],l={clientRequestId:u,activated:s,alias:r,query:e,subscribe:o,dataSubject:new t.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new t.BehaviorSubject(0),queryRegistered:new t.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:o?gu.UNKNOWN:gu.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(u,l),a[r]=l;for(const[e,t]of Object.entries(i)){const s=t.leftAlias;if(s!==r&&e!==r)continue;const u=s===r?e:s;if(s===r){const e=this.createOngoingQueryGraph(n[u],u,n,i,o,!1,a);e.joinCondition=t,c.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(n[u],u,n,i,o,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(bu(Boolean),L((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=e[n.right];o.has(t)||o.set(t,[]),(0,B.truthy)(o.get(t)).push(e)})),e.flatMap((e=>{var r;const i=o.get(null===(r=e[n.leftAlias])||void 0===r?void 0:r[n.left])||[];return i.length?i.map((r=>Object.assign(Object.assign({},e),{[t]:r}))):n.isInner?[]:[Object.assign(Object.assign({},e),{[t]:void 0})]}))}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=(0,B.truthy)(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,r){var n;const i=(0,B.truthy)(r.joinCondition),o=r.query;if(r.activated){if(!r.canExpandForJoin)return!1;const s=(0,B.truthy)(null===(n=r.supportingOngoingQuery)||void 0===n?void 0:n.supportedQueries).filter((e=>e.alias===r.alias)),a=new Set(e.map((e=>{var t;return null!==(t=e[i.left])&&void 0!==t?t:null})));for(const e of s)e.query.conditions.filter(Qe).filter((e=>e.fieldName===i.right)).forEach((e=>{a.delete(e.value)}));if(0===a.size)return!1;const u=he(o);u.conditions=u.conditions.filter((e=>!Qe(e)||e.fieldName!==i.right)),[...a].forEach((e=>{u.conditions.push({fieldName:i.right,operator:"==",value:e})}));const c=Object.assign(Object.assign({},r),{query:u,activated:!0,gotInitialResponse:!1,dataSubject:new t.BehaviorSubject(null),clientRequestId:Q(),isEmptyForJoin:!1});return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),(0,B.truthy)(r.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(r.activated=!0,o.conditions.filter(Qe).filter((e=>e.fieldName===i.right&&"=="===e.operator)).map((e=>e.value)).length)return this.sendQueryToServerOrUseParentQuery(r),r.canExpandForJoin=!1,!0;const t=e.map((e=>{var t;return null!==(t=e[i.left])&&void 0!==t?t:null})).map((e=>({fieldName:i.right,operator:"==",value:e})));return t.length?(o.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(r)):r.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotInitialResult(e))))}async completeAllSupportedQueries(e){const r=[...e.supportedQueries||[]];for(;r.length;){const e=(0,B.truthy)(r.shift());r.push(...e.supportedQueries||[]),await(0,t.firstValueFrom)(e.unsubscribeBlockerCount.pipe(bu((e=>0===e)))),e.dataSubject.complete()}}preDestruct(){this.unsubscribe()}unsubscribe(){var e;const t=[...this.ongoingQueries.values()];for(const r of t)r.dataSubject.complete(),null===(e=r.allObservables)||void 0===e||e.complete()}hasSubscription(e){var t;return!!(null===(t=this.ongoingQueries.get(e))||void 0===t?void 0:t.subscribe)}sendQueryToServerOrUseParentQuery(e){if(this.destructManager.isDestructing)return;const t=e.query,r=e.clientRequestId,n=ct(this.clientIdService.getClientId(),r);this.queryMappingManager.addQuery(t,n);const i=this.findValidParentOfOngoingQuery(e);this.ongoingQueries.set(r,e),i?this.useParentOngoingQuery(e,i).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,r){const n={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:r.clientRequestId},i=new vu(e.query);r.unsubscribeBlockerCount.next(r.unsubscribeBlockerCount.value+1);try{await(0,t.firstValueFrom)(r.queryRegistered.pipe(bu(Boolean)))}catch(t){return this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(e.dataSubject.error(t),e.queryRegistered.error(t)),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",n).then((()=>{e.isInFlight=!1,e.queryRegistered.next(!0)})).catch((t=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,r.query,t),e.dataSubject.error(t)),e.done=!0})).finally((()=>{r.unsubscribeBlockerCount.next(r.unsubscribeBlockerCount.value-1)}));const o=(0,t.race)(e.queryRegistered.pipe(bu(Boolean),(0,t.delay)(2e3),(0,t.take)(1)),this.destructManager.observeIsDestructing().pipe((0,t.take)(1)));r.dataSubject.pipe((0,t.takeWhile)((()=>!e.done)),(0,t.takeUntil)(o),bu(Boolean),(0,t.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),L((e=>e.filter((e=>i.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(Ge(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+Eu:t,n={query:Object.assign(Object.assign({},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()):(Se.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)}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=>{ae(this.localDocumentToClientRequestIds,t,e[t])}))}}function Au(e,t){var r;for(const n of e.fields){const e=null!==(r=ne(t,n.fieldName))&&void 0!==r?r:null;if(at(n.value,e,n.operator))return!0;if(at(n.value,e,"!="))return!1}return!1}class Mu{constructor(){this.stateService=new _u.TrieStore({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch((()=>{let r=0;const n=new Set;for(const i of e.conditions){if(Qe(i)&&["=="].includes(i.operator)){const e=ge(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];Su(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)||[]];Su(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)||[]];wu(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)||[]];wu(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,ye(r))];var r}}class Fu{constructor(){this.locks={}}async lock(...e){if(this.canGetLock(...e))return void this.lockSync(...e);const r=Object.entries(this.locks).filter((([t])=>e.includes(t))).map((([,e])=>e));await(0,t.lastValueFrom)((0,t.combineLatest)(r).pipe((0,t.filter)((e=>!e.includes(!0))),(0,t.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=(0,B.truthy)(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some((e=>{var t;return null===(t=this.locks[e])||void 0===t?void 0:t.value}))}lockSync(...e){(0,B.assertTruthy)(this.canGetLock(...e),"Cannot acquire lock sync");for(const r of e)this.locks[r]=new t.BehaviorSubject(!0)}}class ku{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 ju(e,t,this.rpcManager),r.set(t,n)),n}getOrUndefined(e,t){var r;return null===(r=this.queueManagers.get(e))||void 0===r?void 0:r.get(t)}}const Du="subscriptionMutex";class ju{constructor(e,r,n){this.integrationId=e,this.topicName=r,this.rpcManager=n,this.messagesSubject=new t.Subject,this.subscriberCount=0,this.lockManager=new Fu}async produce(e){await this.lockManager.lock(Du);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(Du)}}consume(){return(0,t.defer)((()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,t.finalize)((()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))))}async performSubscribe(){await this.lockManager.lock(Du);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 t.Subject}finally{this.lockManager.release(Du)}}async performUnsubscribe(){await this.lockManager.lock(Du);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(Du)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class xu{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,t.firstValueFrom)((0,t.interval)(10).pipe((0,t.filter)((()=>this.attemptConsume())),(0,t.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}}class Pu extends Error{constructor(e,t,r,n,i,o){super(o||`RPC error ${e} ${t} calling ${r}`),this.statusCode=e,this.statusText=t,this.url=r,this.headers=n,this.body=i}}async function Nu(e){const t=await async function({headers:e,files:t,filesFieldName:r,message:n,url:i,extractErrorMessage:o}){const s=new Headers(e),a={method:"POST",headers:s,body:void 0};if(t.length){const e=new FormData;for(const n of t){const t=n instanceof Blob?n:n.blob,i=n instanceof Blob?void 0:n.name;e.append(r,t,i)}e.append("body",be(n)),a.body=e}else s.append("Content-Type","application/json"),a.body=be(n);try{const e=await fetch(i,a),t={};if(e.headers.forEach(((e,r)=>{t[r]=e})),!e.ok){const r=await e.text(),n=Ru(r);if(!o)throw new Pu(e.status,e.statusText,i,t,n,r);let s;try{s="string"==typeof n?n:(null==n?void 0:n.message)||r}catch(e){}throw s||(s=e.statusText),new Pu(e.status,e.statusText,i,t,n,s)}const r=await e.text();return Se.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Se.debug(`Unable to perform fetch request to url: ${i}`,e),e}}(e);return t.body=Ru(t.body),t}function Ru(e){if(e){try{return me(e)}catch(e){}return e}}class Cu{constructor(e,r,n,i,o,s){this.region=e,this.appId=r,this.authManager=o,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new t.BehaviorSubject(0);for(const[e,t]of Object.entries(i))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe((e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")})),n.onDestruct((async()=>{await this.awaitAllSettled()}));const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new xu(60*a,5),ai:new xu(20*a,5),secret:new xu(20*a,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,t.firstValueFrom)(this.onGoingRpcCounter.pipe((0,t.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 o=await this.getAuthHeaders(),s=Object.assign(Object.assign({},this.staticHeaders),o);Se.debug(`sending request: path: ${e} message: ${JSON.stringify(t)}`);const a=Za(this.region,this.appId,e);return await Nu({url:a,headers:s,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?(0,B.truthy)(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?(0,B.truthy)(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):(0,B.truthy)(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class qu{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",{})}upsert(e,t){return this.upsertMany([{key:e,value:t}]).then((e=>e[0]))}upsertMany(e){const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e){const t={keys:[e]};return this.rpcManager.post("secret/delete",t)}deleteMany(e){const t={keys:e};return this.rpcManager.post("secret/delete",t)}get apiKeys(){return new Lu(this.rpcManager)}}class Lu{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)}}const Bu=e=>e();var Qu;function Vu(){}const Uu="undefined"!=typeof process&&(null===(Qu=process.versions)||void 0===Qu?void 0:Qu.node)?r(5086):Oe().WebSocket;class zu{constructor(e,r,n,i=Bu,o,s){this.clientIdService=e,this.region=r,this.appId=n,this.messageNotificationWrapper=i,this.destructManager=o,this.authManager=s,this.webSocketObserver=new t.Subject,this.allMessagesObserver=new t.Subject,this.connectionReady=new t.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new t.Subject,this.clientTooOldThreshold=3e4,this.destructManager.onDestruct((async()=>{await this.destruct()})),this.setupMessageAcknowledgments(),this.connect(),this.lastTick=new Date,this.tickInterval=setInterval((()=>this.tick()),5e3),this.observeConnectionReady().pipe((0,t.skip)(1),(0,t.filter)((e=>!e)),(0,t.switchMap)((()=>(0,t.race)((0,t.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,t.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value?Se.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Se.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())})),this.observeConnectionReady().pipe((0,t.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}))}refreshClient(){this.destructManager.isDestructing?Se.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Se.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Se.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Se.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}tick(){Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(Se.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,t.distinctUntilChanged)())}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){var r;await(0,t.firstValueFrom)(this.connectionReady.pipe((0,t.filter)(Boolean)));const n=await this.authManager.getToken();if(this.connectionReady.value)try{(0,B.assertTruthy)(this.socket,"Socket is undefined in sendMessageAsync");const t=be({message:e,authToken:n});Se.debug(this.clientIdService.getClientId(),"Sending message to socket: ",t),this.socket.send(t)}catch(t){(null===(r=this.socket)||void 0===r?void 0:r.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(){var e;(null===(e=this.socket)||void 0===e?void 0:e.connected)&&this.socket.send(be({message:{type:"kill"}}))}connect(){var e;null===(e=this.socket)||void 0===e||e.close(),this.connectionReady.value&&this.connectionReady.next(!1);const t=Za(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),r=this.clientIdService.getClientId();Se.debug(this.clientIdService.getClientId(),"Connecting to socket at:",t);const n=`${t}?clientId=${r}`;this.socket=function(e,t={}){let r,n=0,i=1;const o={connected:!1,open(){var i;const s=null!==(i=null==Uu?void 0:Uu.WebSocket)&&void 0!==i?i:Uu;r=new s(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@squid.cloud with this message.")}:Vu,r.onopen=function(e){o.connected=!0,(t.onopen||Vu)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return Se.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Vu)(e),void o.reconnect(e);(t.onclose||Vu)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):(t.onerror||Vu)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout((function(){(t.onreconnect||Vu)(e),Se.debug("WebSocket trying to reconnect..."),o.open()}),t.timeout||1e3):(t.onmaximum||Vu)(e)},json(e){r.send(JSON.stringify(e))},send(e){r.send(e)},close(e=4999,t){try{o.connected=!1,clearTimeout(i),i=void 0,r.close(e,t)}catch(e){}}};return o.open(),o}(n,{timeout:5e3,onmessage:e=>this.onMessage(e.data),onopen:()=>{Se.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${t}`)},onreconnect:()=>{Se.debug(r,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===r?this.connectionReady.value&&this.connectionReady.next(!1):Se.debug(r,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Se.debug(r,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===r?this.connectionReady.value&&this.connectionReady.next(!1):Se.debug(r,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}disconnectForTest(){var e;this.connectionReady.next(!1),null===(e=this.socket)||void 0===e||e.close(4998)}onConnectionReady(){this.connectionReady.next(!0),this.sendMessage({type:"catchup"})}onMessage(e){if("connectionReady"===e)return Se.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=me(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Se.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}setupMessageAcknowledgments(){const e=new t.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const r=[];e.pipe((0,t.tap)((e=>r.push(e))),(0,t.debounceTime)(100)).subscribe((async()=>{const e=[...r.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){var e;this.sendKillMessage(),await(0,t.firstValueFrom)((0,t.timer)(0)),this.connectionReady.next(!1),await(0,t.firstValueFrom)((0,t.timer)(0)),clearInterval(this.tickInterval),null===(e=this.socket)||void 0===e||e.close(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Yu(e,t){return`${function(e){const[t,r,n,i]=e.split("-");return(0,B.assertTruthy)(!i,"Invalid appId: "+e),{appId:t,environmentId:null!=r?r:"prod",squidDeveloperId:n}}(e).appId}${t&&"prod"!==t?`-${t}`:""}`}class Wu{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 $u{constructor(e){this.options=e,this.destructManager=new Ot,(0,B.assertTruthy)(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=function(e,t,r){return`${Yu(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return eu(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new we(this.destructManager),this.authManager=new te(e.apiKey,e.authProvider),this.socketManager=new zu(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Cu(e.region,r,this.destructManager,n,this.authManager,this.clientIdService),this.aiClientFactory=new K(this.rpcManager,this.socketManager),this.aiClient=new X(this.aiClientFactory,this.rpcManager),this.apiClient=new ee(this.rpcManager),this.documentStore=new It,this.lockManager=new Fu,this.distributedLockManager=new St(this.socketManager,this.destructManager),this.documentIdentityService=new Et(this.documentStore,this.destructManager),this.documentReferenceFactory=new Tt(this.documentIdentityService),this.querySender=new mu(this.rpcManager,this.destructManager),this.querySubscriptionManager=new Iu(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender),this.localQueryManager=new yu(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new nu(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Xe(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new gt(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new dt(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new _e(this.clientIdService,this.rpcManager),this.nativeQueryManager=new iu(this.rpcManager),this.graphqlClientFactory=new ru(this.rpcManager,e.region,r),this.secretClient=new qu(this.rpcManager),this._connectionDetails=new ft(this.clientIdService,this.socketManager),this.queueManagerFactory=new ku(this.rpcManager,this.socketManager,this.destructManager)}static getInstance(e){const t=ye(e);let r=$u.squidInstancesMap[t];return r||(r=new $u(e),$u.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values($u.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=qe.built_in_db){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...r){return this._validateNotDestructed(),(0,t.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...r))}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)}graphql(e){return this._validateNotDestructed(),this.graphqlClientFactory.get(e)}ai(){return this._validateNotDestructed(),this.aiClient}api(){return this._validateNotDestructed(),this.apiClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new Wu(e,this.rpcManager)}get secrets(){return this.secretClient}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=qe.built_in_queue){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally((()=>{const e=Object.entries($u.squidInstancesMap).find((([,e])=>e===this));e&&delete $u.squidInstancesMap[e[0]]}))}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}_validateNotDestructed(){(0,B.assertTruthy)(!this.destructManager.isDestructing,"The client was already destructed.")}}$u.squidInstancesMap={}})();var i=exports;for(var o in n)i[o]=n[o];n.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})();
5
+ `})).data}}class ru{constructor(e,t,r){this.rpcManager=e,this.region=t,this.appId=r,this.clientsMap=new Map}get(e){let t=this.clientsMap.get(e);return t||(t=new tu(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class nu{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=bt(e),n=r.map((e=>`sendMutation_${Ge(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 Se.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class iu{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}function ou(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=su(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:u}=r.query;let c=e.collection(a,u).joinQuery(r.alias);return c=su(c,r.query),Object.entries(n).map((([t,r])=>{const{collectionName:n,integrationId:o}=r,{left:s,right:a,leftAlias:u}=i[t];let l=e.collection(n,o).query();l=su(l,r),c=c.join(l,t,{left:s,right:a},{leftAlias:u})})),o&&s?c.grouped().dereference():o?c.dereference():s?c.grouped():c}(e,t);case"merged":return function(e,t){const{queries:r}=t,{collectionName:n,integrationId:i}=au(r[0]),o=r.map((t=>ou(e,t)));return e.collection(n,i).or(...o)}(e,t)}}function su(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 au(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 au(e.queries[0])}}const uu={"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)=>cu(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>cu(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>cu(e,t)&&hu(t),"like_cs:like_cs":(e,t)=>cu(e,t),"like:not like":(e,t)=>!lu(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!lu(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!lu(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!lu(e,t),"not like:like":(e,t)=>fu(e,t),"not like_cs:like":(e,t)=>fu(e,t),"not like:like_cs":(e,t)=>fu(e,t),"not like_cs:like_cs":(e,t)=>fu(e,t),"not like:not like":(e,t)=>cu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>cu(t,e)&&hu(e),"not like:not like_cs":(e,t)=>cu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>cu(t,e),"in:like":(e,t)=>e.every((e=>at(t,e,"like"))),"in:like_cs":(e,t)=>e.every((e=>at(t,e,"like_cs"))),"in:not like":(e,t)=>e.every((e=>at(t,e,"not like"))),"in:not like_cs":(e,t)=>e.every((e=>at(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&&du(e)||pu(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&du(e)||pu(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&du(t)||pu(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&du(t)||pu(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=>at(e,t,"not like"))),"like_cs:not in":(e,t)=>t.every((t=>at(e,t,"not like_cs"))),"not like:not in":(e,t)=>t.every((t=>at(e,t,"like"))),"not like_cs:not in":(e,t)=>t.every((t=>at(e,t,"like_cs")))};function cu(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return du(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?cu(e,t,r+1,n+1)||cu(e,t,r+1,n):"%"!==i&&("%"===o?cu(e,t,r,n+1)||cu(e,t,r+1,n):(i===o||"_"===o)&&cu(e,t,r+1,n+1))}function lu(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return du(t.substring(n));if(n>=t.length)return du(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?lu(e,t,r+1,n+1)||lu(e,t,r,n+1)||lu(e,t,r+1,n):"%"===i||"%"===o?lu(e,t,r,n+1)||lu(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&lu(e,t,r+1,n+1)}function hu(e){return!/[a-zA-Z]/.test(e)}function du(e){return e.split("").every((e=>"%"===e))}function fu(e,t){return e.length>0&&du(e)||t.length>0&&du(t)||pu(e)&&0===t.length}function pu(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 vu{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Qe))}get integrationId(){return this.query.integrationId}get collectionName(){return this.query.collectionName}get limit(){return this.query.limit}sortedBy(e){const t=e.find(((e,t)=>{var r;return!ce(this.query.sortOrder[t],Object.assign(Object.assign({},e),{asc:null===(r=e.asc)||void 0===r||r}))}));return!t}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(Qe),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=ne(e,r);if("in"===n){if(t.value.includes(i))continue;return!1}if("not in"!==n){if(!at(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=uu[`${r}:${i}`];return!!s&&s(n,o)}evaluateIncludes(e,t){const{operator:r,value:n}=e,{operator:i,value:o}=this.parseConditions([t])[0],s=Array.isArray(n)?n.sort():n,a=Array.isArray(o)?o.sort():o;return i===r&&ce(a,s)}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 yu{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 vu(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[Ge(e.__docId__,r,t)]))}}function bu(e,t){return o((function(r,n){var i=0;r.subscribe(C(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}class mu{constructor(e,r){this.rpcManager=e,this.destructManager=r,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new t.BehaviorSubject(!0),this.inflightQueriesCount=new t.BehaviorSubject(0),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}async sendQuery(e){const r=new t.Subject,n=(0,t.firstValueFrom)(r);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:r}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),n):(this.pendingQueryBatchTimeout=setTimeout((()=>{this.safeToSendQueriesToServer.pipe(bu(Boolean),(0,t.take)(1)).subscribe((()=>{this.processQueryBatch()}))}),0),n)}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=e.map((({queryRequest:e})=>e)),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,t.firstValueFrom)(this.inflightQueriesCount.pipe(bu((e=>0===e)))).then((()=>{}))}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var gu,_u=r(4123);function Ou(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?Ou(e,t,r,o+1,i):Ou(e,t,r,n,o-1)}function Su(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){if(-1!==Ou(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 wu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){const n=Ou(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"}(gu||(gu={}));const Eu=100,Tu=20;class Iu{constructor(e,r,n,i,o,s){this.rpcManager=e,this.clientIdService=r,this.documentStore=n,this.destructManager=i,this.documentIdentityService=o,this.querySender=s,this.onOrphanDocuments=new t.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Mu,this.queryResultsSubject=new t.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe((()=>{this.refreshOngoingQueries()})),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return(0,B.truthy)(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);(null==t?void 0:t.gotInitialResponse)&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=$e(t),i=this.queryMappingManager.getMapping(r,n);return i?function(e,t){var r;const n=[...e.unconditional||[]],i=new Map;for(const[n,o]of Object.entries(e.conditional||{})){const e=me(n);let s;if(Qe(e)){const n=null!==(r=ne(t,e.fieldName))&&void 0!==r?r:null;s=at(e.value,n,e.operator)}else s=Au(e,t);if(s)for(const e of o)i.set(e,(i.get(e)||0)+1)}for(const[t,r]of i.entries())r>=e.queriesMetadata[t].condCount&&n.push(t);return n}(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=(0,B.truthy)(null==s?void 0:s.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case gu.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+Eu?gu.ENABLED:gu.DISABLED;break;case gu.DISABLED:break;case gu.ENABLED:if(n.size<e.query.limit+Tu){e.limitUnderflowState=gu.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);(0,B.truthy)(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 vu(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 vu(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,r,n,i,o,s){return(0,t.defer)((()=>{const a=this.createOngoingQueryGraph(e,r,n,i,o,!0);s&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new t.ReplaySubject(1);const u=a.allObservables.pipe((0,t.switchMap)((e=>(0,t.combineLatest)(e).pipe(L((e=>this.joinResults(e,i,a)))))),bu((()=>this.allOngoingQueriesGotInitialResult(a))),(0,t.startWith)(void 0),(0,t.pairwise)(),bu((([e,t])=>!ce(e,t))),L((([,e])=>e)),o?(0,t.tap)():(0,t.take)(1),(0,t.finalize)((()=>{var e;a.dataSubject.complete(),a.done=!0,this.completeAllSupportedQueries(a).then(),null===(e=a.allObservables)||void 0===e||e.complete()}))),c=this.collectAllObservables(a);return a.allObservables.next(c),u})).pipe((0,t.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=(0,B.truthy)(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 r=e.clientRequestId,n=ct(this.clientIdService.getClientId(),r);e.dataSubject.pipe((0,t.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,t.firstValueFrom)((0,t.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(bu((e=>0===e))))),this.queryMappingManager.removeQuery(n).then(),this.ongoingQueries.delete(r),e.subscribe&&!e.isEmptyForJoin&&e.activated){const t={clientRequestId:r};this.rpcManager.post("query/unsubscribe",t).catch((t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestIdMapping(r),this.ongoingQueries.delete(r)})),bu(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,r,n,i,o,s,a={}){if(a[r])return a[r];const u=Q(),c=[],l={clientRequestId:u,activated:s,alias:r,query:e,subscribe:o,dataSubject:new t.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new t.BehaviorSubject(0),queryRegistered:new t.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:o?gu.UNKNOWN:gu.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(u,l),a[r]=l;for(const[e,t]of Object.entries(i)){const s=t.leftAlias;if(s!==r&&e!==r)continue;const u=s===r?e:s;if(s===r){const e=this.createOngoingQueryGraph(n[u],u,n,i,o,!1,a);e.joinCondition=t,c.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(n[u],u,n,i,o,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(bu(Boolean),L((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=e[n.right];o.has(t)||o.set(t,[]),(0,B.truthy)(o.get(t)).push(e)})),e.flatMap((e=>{var r;const i=o.get(null===(r=e[n.leftAlias])||void 0===r?void 0:r[n.left])||[];return i.length?i.map((r=>Object.assign(Object.assign({},e),{[t]:r}))):n.isInner?[]:[Object.assign(Object.assign({},e),{[t]:void 0})]}))}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=(0,B.truthy)(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,r){var n;const i=(0,B.truthy)(r.joinCondition),o=r.query;if(r.activated){if(!r.canExpandForJoin)return!1;const s=(0,B.truthy)(null===(n=r.supportingOngoingQuery)||void 0===n?void 0:n.supportedQueries).filter((e=>e.alias===r.alias)),a=new Set(e.map((e=>{var t;return null!==(t=e[i.left])&&void 0!==t?t:null})));for(const e of s)e.query.conditions.filter(Qe).filter((e=>e.fieldName===i.right)).forEach((e=>{a.delete(e.value)}));if(0===a.size)return!1;const u=he(o);u.conditions=u.conditions.filter((e=>!Qe(e)||e.fieldName!==i.right)),[...a].forEach((e=>{u.conditions.push({fieldName:i.right,operator:"==",value:e})}));const c=Object.assign(Object.assign({},r),{query:u,activated:!0,gotInitialResponse:!1,dataSubject:new t.BehaviorSubject(null),clientRequestId:Q(),isEmptyForJoin:!1});return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),(0,B.truthy)(r.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(r.activated=!0,o.conditions.filter(Qe).filter((e=>e.fieldName===i.right&&"=="===e.operator)).map((e=>e.value)).length)return this.sendQueryToServerOrUseParentQuery(r),r.canExpandForJoin=!1,!0;const t=e.map((e=>{var t;return null!==(t=e[i.left])&&void 0!==t?t:null})).map((e=>({fieldName:i.right,operator:"==",value:e})));return t.length?(o.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(r)):r.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotInitialResult(e))))}async completeAllSupportedQueries(e){const r=[...e.supportedQueries||[]];for(;r.length;){const e=(0,B.truthy)(r.shift());r.push(...e.supportedQueries||[]),await(0,t.firstValueFrom)(e.unsubscribeBlockerCount.pipe(bu((e=>0===e)))),e.dataSubject.complete()}}preDestruct(){this.unsubscribe()}unsubscribe(){var e;const t=[...this.ongoingQueries.values()];for(const r of t)r.dataSubject.complete(),null===(e=r.allObservables)||void 0===e||e.complete()}hasSubscription(e){var t;return!!(null===(t=this.ongoingQueries.get(e))||void 0===t?void 0:t.subscribe)}sendQueryToServerOrUseParentQuery(e){if(this.destructManager.isDestructing)return;const t=e.query,r=e.clientRequestId,n=ct(this.clientIdService.getClientId(),r);this.queryMappingManager.addQuery(t,n);const i=this.findValidParentOfOngoingQuery(e);this.ongoingQueries.set(r,e),i?this.useParentOngoingQuery(e,i).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,r){const n={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:r.clientRequestId},i=new vu(e.query);r.unsubscribeBlockerCount.next(r.unsubscribeBlockerCount.value+1);try{await(0,t.firstValueFrom)(r.queryRegistered.pipe(bu(Boolean)))}catch(t){return this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(e.dataSubject.error(t),e.queryRegistered.error(t)),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",n).then((()=>{e.isInFlight=!1,e.queryRegistered.next(!0)})).catch((t=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,r.query,t),e.dataSubject.error(t)),e.done=!0})).finally((()=>{r.unsubscribeBlockerCount.next(r.unsubscribeBlockerCount.value-1)}));const o=(0,t.race)(e.queryRegistered.pipe(bu(Boolean),(0,t.delay)(2e3),(0,t.take)(1)),this.destructManager.observeIsDestructing().pipe((0,t.take)(1)));r.dataSubject.pipe((0,t.takeWhile)((()=>!e.done)),(0,t.takeUntil)(o),bu(Boolean),(0,t.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),L((e=>e.filter((e=>i.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(Ge(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+Eu:t,n={query:Object.assign(Object.assign({},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()):(Se.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)}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=>{ae(this.localDocumentToClientRequestIds,t,e[t])}))}}function Au(e,t){var r;for(const n of e.fields){const e=null!==(r=ne(t,n.fieldName))&&void 0!==r?r:null;if(at(n.value,e,n.operator))return!0;if(at(n.value,e,"!="))return!1}return!1}class Mu{constructor(){this.stateService=new _u.TrieStore({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch((()=>{let r=0;const n=new Set;for(const i of e.conditions){if(Qe(i)&&["=="].includes(i.operator)){const e=ge(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];Su(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)||[]];Su(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)||[]];wu(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)||[]];wu(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,ye(r))];var r}}class Fu{constructor(){this.locks={}}async lock(...e){if(this.canGetLock(...e))return void this.lockSync(...e);const r=Object.entries(this.locks).filter((([t])=>e.includes(t))).map((([,e])=>e));await(0,t.lastValueFrom)((0,t.combineLatest)(r).pipe((0,t.filter)((e=>!e.includes(!0))),(0,t.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=(0,B.truthy)(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some((e=>{var t;return null===(t=this.locks[e])||void 0===t?void 0:t.value}))}lockSync(...e){(0,B.assertTruthy)(this.canGetLock(...e),"Cannot acquire lock sync");for(const r of e)this.locks[r]=new t.BehaviorSubject(!0)}}class ku{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 ju(e,t,this.rpcManager),r.set(t,n)),n}getOrUndefined(e,t){var r;return null===(r=this.queueManagers.get(e))||void 0===r?void 0:r.get(t)}}const Du="subscriptionMutex";class ju{constructor(e,r,n){this.integrationId=e,this.topicName=r,this.rpcManager=n,this.messagesSubject=new t.Subject,this.subscriberCount=0,this.lockManager=new Fu}async produce(e){await this.lockManager.lock(Du);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(Du)}}consume(){return(0,t.defer)((()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,t.finalize)((()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))))}async performSubscribe(){await this.lockManager.lock(Du);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 t.Subject}finally{this.lockManager.release(Du)}}async performUnsubscribe(){await this.lockManager.lock(Du);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(Du)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class xu{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,t.firstValueFrom)((0,t.interval)(10).pipe((0,t.filter)((()=>this.attemptConsume())),(0,t.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}}class Pu extends Error{constructor(e,t,r,n,i,o){super(o||`RPC error ${e} ${t} calling ${r}`),this.statusCode=e,this.statusText=t,this.url=r,this.headers=n,this.body=i}}async function Nu(e){const t=await async function({headers:e,files:t,filesFieldName:r,message:n,url:i,extractErrorMessage:o}){const s=new Headers(e),a={method:"POST",headers:s,body:void 0};if(t.length){const e=new FormData;for(const n of t){const t=n instanceof Blob?n:n.blob,i=n instanceof Blob?void 0:n.name;e.append(r,t,i)}e.append("body",be(n)),a.body=e}else s.append("Content-Type","application/json"),a.body=be(n);try{const e=await fetch(i,a),t={};if(e.headers.forEach(((e,r)=>{t[r]=e})),!e.ok){const r=await e.text(),n=Ru(r);if(!o)throw new Pu(e.status,e.statusText,i,t,n,r);let s;try{s="string"==typeof n?n:(null==n?void 0:n.message)||r}catch(e){}throw s||(s=e.statusText),new Pu(e.status,e.statusText,i,t,n,s)}const r=await e.text();return Se.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Se.debug(`Unable to perform fetch request to url: ${i}`,e),e}}(e);return t.body=Ru(t.body),t}function Ru(e){if(e){try{return me(e)}catch(e){}return e}}class Cu{constructor(e,r,n,i,o,s){this.region=e,this.appId=r,this.authManager=o,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new t.BehaviorSubject(0);for(const[e,t]of Object.entries(i))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe((e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")})),n.onDestruct((async()=>{await this.awaitAllSettled()}));const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new xu(60*a,5),ai:new xu(20*a,5),secret:new xu(20*a,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,t.firstValueFrom)(this.onGoingRpcCounter.pipe((0,t.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 o=await this.getAuthHeaders(),s=Object.assign(Object.assign({},this.staticHeaders),o);Se.debug(`sending request: path: ${e} message: ${JSON.stringify(t)}`);const a=Za(this.region,this.appId,e);return await Nu({url:a,headers:s,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?(0,B.truthy)(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?(0,B.truthy)(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):(0,B.truthy)(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class qu{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",{})}upsert(e,t){return this.upsertMany([{key:e,value:t}]).then((e=>e[0]))}upsertMany(e){const t={entries:e};return this.rpcManager.post("secret/upsert",t)}delete(e){const t={keys:[e]};return this.rpcManager.post("secret/delete",t)}deleteMany(e){const t={keys:e};return this.rpcManager.post("secret/delete",t)}get apiKeys(){return new Lu(this.rpcManager)}}class Lu{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)}}const Bu=e=>e();var Qu;function Vu(){}const Uu="undefined"!=typeof process&&(null===(Qu=process.versions)||void 0===Qu?void 0:Qu.node)?r(5086):Oe().WebSocket;class zu{constructor(e,r,n,i=Bu,o,s){this.clientIdService=e,this.region=r,this.appId=n,this.messageNotificationWrapper=i,this.destructManager=o,this.authManager=s,this.webSocketObserver=new t.Subject,this.allMessagesObserver=new t.Subject,this.connectionReady=new t.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new t.Subject,this.clientTooOldThreshold=3e4,this.destructManager.onDestruct((async()=>{await this.destruct()})),this.setupMessageAcknowledgments(),this.connect(),this.lastTick=new Date,this.tickInterval=setInterval((()=>this.tick()),5e3),this.observeConnectionReady().pipe((0,t.skip)(1),(0,t.filter)((e=>!e)),(0,t.switchMap)((()=>(0,t.race)((0,t.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,t.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value?Se.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Se.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())})),this.observeConnectionReady().pipe((0,t.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}))}refreshClient(){this.destructManager.isDestructing?Se.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Se.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Se.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Se.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}tick(){Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(Se.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,t.distinctUntilChanged)())}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){var r;await(0,t.firstValueFrom)(this.connectionReady.pipe((0,t.filter)(Boolean)));const n=await this.authManager.getToken();if(this.connectionReady.value)try{(0,B.assertTruthy)(this.socket,"Socket is undefined in sendMessageAsync");const t=be({message:e,authToken:n});Se.debug(this.clientIdService.getClientId(),"Sending message to socket: ",t),this.socket.send(t)}catch(t){(null===(r=this.socket)||void 0===r?void 0:r.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(){var e;(null===(e=this.socket)||void 0===e?void 0:e.connected)&&this.socket.send(be({message:{type:"kill"}}))}connect(){var e;null===(e=this.socket)||void 0===e||e.close(),this.connectionReady.value&&this.connectionReady.next(!1);const t=Za(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),r=this.clientIdService.getClientId();Se.debug(this.clientIdService.getClientId(),"Connecting to socket at:",t);const n=`${t}?clientId=${r}`;this.socket=function(e,t={}){let r,n=0,i=1;const o={connected:!1,open(){var i;const s=null!==(i=null==Uu?void 0:Uu.WebSocket)&&void 0!==i?i:Uu;r=new s(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@squid.cloud with this message.")}:Vu,r.onopen=function(e){o.connected=!0,(t.onopen||Vu)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return Se.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Vu)(e),void o.reconnect(e);(t.onclose||Vu)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):(t.onerror||Vu)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout((function(){(t.onreconnect||Vu)(e),Se.debug("WebSocket trying to reconnect..."),o.open()}),t.timeout||1e3):(t.onmaximum||Vu)(e)},json(e){r.send(JSON.stringify(e))},send(e){r.send(e)},close(e=4999,t){try{o.connected=!1,clearTimeout(i),i=void 0,r.close(e,t)}catch(e){}}};return o.open(),o}(n,{timeout:5e3,onmessage:e=>this.onMessage(e.data),onopen:()=>{Se.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${t}`)},onreconnect:()=>{Se.debug(r,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===r?this.connectionReady.value&&this.connectionReady.next(!1):Se.debug(r,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Se.debug(r,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===r?this.connectionReady.value&&this.connectionReady.next(!1):Se.debug(r,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}disconnectForTest(){var e;this.connectionReady.next(!1),null===(e=this.socket)||void 0===e||e.close(4998)}onConnectionReady(){this.connectionReady.next(!0),this.sendMessage({type:"catchup"})}onMessage(e){if("connectionReady"===e)return Se.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=me(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Se.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}setupMessageAcknowledgments(){const e=new t.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const r=[];e.pipe((0,t.tap)((e=>r.push(e))),(0,t.debounceTime)(100)).subscribe((async()=>{const e=[...r.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){var e;this.sendKillMessage(),await(0,t.firstValueFrom)((0,t.timer)(0)),this.connectionReady.next(!1),await(0,t.firstValueFrom)((0,t.timer)(0)),clearInterval(this.tickInterval),null===(e=this.socket)||void 0===e||e.close(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Yu(e,t){return`${function(e){(0,B.assertString)(e,"Invalid application ID");const[t,r,n,i]=e.split("-");return(0,B.assertTruthy)(!i,`Invalid application ID: ${e}`),{appId:t,environmentId:null!=r?r:"prod",squidDeveloperId:n}}(e).appId}${t&&"prod"!==t?`-${t}`:""}`}class Wu{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 $u{constructor(e){this.options=e,this.destructManager=new Ot,(0,B.assertTruthy)(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=function(e,t,r){return`${Yu(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return eu(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new we(this.destructManager),this.authManager=new te(e.apiKey,e.authProvider),this.socketManager=new zu(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Cu(e.region,r,this.destructManager,n,this.authManager,this.clientIdService),this.aiClientFactory=new K(this.rpcManager,this.socketManager),this.aiClient=new X(this.aiClientFactory,this.rpcManager),this.apiClient=new ee(this.rpcManager),this.documentStore=new It,this.lockManager=new Fu,this.distributedLockManager=new St(this.socketManager,this.destructManager),this.documentIdentityService=new Et(this.documentStore,this.destructManager),this.documentReferenceFactory=new Tt(this.documentIdentityService),this.querySender=new mu(this.rpcManager,this.destructManager),this.querySubscriptionManager=new Iu(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender),this.localQueryManager=new yu(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new nu(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Xe(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new gt(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new dt(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new _e(this.clientIdService,this.rpcManager),this.nativeQueryManager=new iu(this.rpcManager),this.graphqlClientFactory=new ru(this.rpcManager,e.region,r),this.secretClient=new qu(this.rpcManager),this._connectionDetails=new ft(this.clientIdService,this.socketManager),this.queueManagerFactory=new ku(this.rpcManager,this.socketManager,this.destructManager)}static getInstance(e){const t=ye(e);let r=$u.squidInstancesMap[t];return r||(r=new $u(e),$u.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values($u.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=qe.built_in_db){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...r){return this._validateNotDestructed(),(0,t.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...r))}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)}graphql(e){return this._validateNotDestructed(),this.graphqlClientFactory.get(e)}ai(){return this._validateNotDestructed(),this.aiClient}api(){return this._validateNotDestructed(),this.apiClient}storage(e="built_in_storage"){return this._validateNotDestructed(),new Wu(e,this.rpcManager)}get secrets(){return this.secretClient}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=qe.built_in_queue){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally((()=>{const e=Object.entries($u.squidInstancesMap).find((([,e])=>e===this));e&&delete $u.squidInstancesMap[e[0]]}))}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}_validateNotDestructed(){(0,B.assertTruthy)(!this.destructManager.isDestructing,"The client was already destructed.")}}$u.squidInstancesMap={}})();var i=exports;for(var o in n)i[o]=n[o];n.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})();
@@ -11,4 +11,14 @@ export declare class MutationContext<T = any> {
11
11
  get after(): T | undefined;
12
12
  /** Returns true if the mutation affects the provided path. */
13
13
  affectsPath(path: Paths<T>): boolean;
14
+ /**
15
+ * Find all affected paths starting from a root path.
16
+ *
17
+ * @example
18
+ * doc before - { a: { b: 1, c: 2 }, d: 3 }
19
+ * doc after - { a: { b: 1, c: 3 }, d: 4 }
20
+ * doc.affectedPaths('a') // ['a.c']
21
+ */
22
+ affectedPaths(startingRoot?: Paths<T> | string): Array<Paths<T>>;
23
+ private checkPath;
14
24
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@squidcloud/client",
3
- "version": "1.0.224",
3
+ "version": "1.0.226",
4
4
  "description": "A typescript implementation of the Squid client",
5
5
  "main": "dist/cjs/index.js",
6
6
  "types": "dist/typescript-client/src/index.d.ts",