@squidcloud/client 1.0.246 → 1.0.247
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:Ka`
|
|
4
4
|
${e.query}
|
|
5
|
-
`})).data}}class nu{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 ru(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class iu{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=mt(e),n=r.map((e=>`sendMutation_${He(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 we.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class ou{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}function su(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=au(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=au(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=au(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}=uu(r[0]),o=r.map((t=>su(e,t)));return e.collection(n,i).or(...o)}(e,t)}}function au(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 uu(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 uu(e.queries[0])}}const cu={"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)=>lu(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>lu(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>lu(e,t)&&du(t),"like_cs:like_cs":(e,t)=>lu(e,t),"like:not like":(e,t)=>!hu(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!hu(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!hu(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!hu(e,t),"not like:like":(e,t)=>pu(e,t),"not like_cs:like":(e,t)=>pu(e,t),"not like:like_cs":(e,t)=>pu(e,t),"not like_cs:like_cs":(e,t)=>pu(e,t),"not like:not like":(e,t)=>lu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>lu(t,e)&&du(e),"not like:not like_cs":(e,t)=>lu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>lu(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&&fu(e)||vu(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&fu(e)||vu(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&fu(t)||vu(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&fu(t)||vu(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"))),"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 lu(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return fu(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?lu(e,t,r+1,n+1)||lu(e,t,r+1,n):"%"!==i&&("%"===o?lu(e,t,r,n+1)||lu(e,t,r+1,n):(i===o||"_"===o)&&lu(e,t,r+1,n+1))}function hu(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return fu(t.substring(n));if(n>=t.length)return fu(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?hu(e,t,r+1,n+1)||hu(e,t,r,n+1)||hu(e,t,r+1,n):"%"===i||"%"===o?hu(e,t,r,n+1)||hu(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&hu(e,t,r+1,n+1)}function du(e){return!/[a-zA-Z]/.test(e)}function fu(e){return e.split("").every((e=>"%"===e))}function pu(e,t){return e.length>0&&fu(e)||t.length>0&&fu(t)||vu(e)&&0===t.length}function vu(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 yu{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Ve))}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!he(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(Ve),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=oe(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=cu[`${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&&he(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 bu{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 yu(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[He(e.__docId__,r,t)]))}}function mu(e,t){return a((function(r,n){var i=0;r.subscribe(L(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}class gu{constructor(e,t){this.rpcManager=e,this.destructManager=t,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new o.BehaviorSubject(!0),this.inflightQueriesCount=new o.BehaviorSubject(0),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}async sendQuery(e){const t=new o.Subject,r=(0,o.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(mu(Boolean),(0,o.take)(1)).subscribe((()=>{this.processQueryBatch()}))}),0),r)}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,o.firstValueFrom)(this.inflightQueriesCount.pipe(mu((e=>0===e)))).then((()=>{}))}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var _u,Ou=r(4123);function Su(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?Su(e,t,r,o+1,i):Su(e,t,r,n,o-1)}function Eu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){if(-1!==Su(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=Su(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"}(_u||(_u={}));const Tu=100,Iu=20;class Au{constructor(e,t,r,n,i,s){this.rpcManager=e,this.clientIdService=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.querySender=s,this.onOrphanDocuments=new o.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Mu,this.queryResultsSubject=new o.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,V.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}=Ge(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=_e(n);let s;if(Ve(e)){const n=null!==(r=oe(t,e.fieldName))&&void 0!==r?r:null;s=at(e.value,n,e.operator)}else s=Fu(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,V.truthy)(null==s?void 0:s.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case _u.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+Tu?_u.ENABLED:_u.DISABLED;break;case _u.DISABLED:break;case _u.ENABLED:if(n.size<e.query.limit+Iu){e.limitUnderflowState=_u.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);(0,V.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 yu(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 yu(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,r,n,i,s){return(0,o.defer)((()=>{const a=this.createOngoingQueryGraph(e,t,r,n,i,!0);s&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new o.ReplaySubject(1);const u=a.allObservables.pipe((0,o.switchMap)((e=>(0,o.combineLatest)(e).pipe(Q((e=>this.joinResults(e,n,a)))))),mu((()=>this.allOngoingQueriesGotInitialResult(a))),(0,o.startWith)(void 0),(0,o.pairwise)(),mu((([e,t])=>!he(e,t))),Q((([,e])=>e)),i?(0,o.tap)():(0,o.take)(1),(0,o.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,o.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,V.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 t=e.clientRequestId,r=ct(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,o.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,o.firstValueFrom)((0,o.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(mu((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)})),mu(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,s,a={}){if(a[t])return a[t];const u=U(),c=[],l={clientRequestId:u,activated:s,alias:t,query:e,subscribe:i,dataSubject:new o.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new o.BehaviorSubject(0),queryRegistered:new o.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:i?_u.UNKNOWN:_u.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(u,l),a[t]=l;for(const[e,o]of Object.entries(n)){const s=o.leftAlias;if(s!==t&&e!==t)continue;const u=s===t?e:s;if(s===t){const e=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,a);e.joinCondition=o,c.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(mu(Boolean),Q((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,V.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,V.truthy)(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=(0,V.truthy)(t.joinCondition),i=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const s=(0,V.truthy)(null===(r=t.supportingOngoingQuery)||void 0===r?void 0:r.supportedQueries).filter((e=>e.alias===t.alias)),a=new Set(e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})));for(const e of s)e.query.conditions.filter(Ve).filter((e=>e.fieldName===n.right)).forEach((e=>{a.delete(e.value)}));if(0===a.size)return!1;const u=fe(i);u.conditions=u.conditions.filter((e=>!Ve(e)||e.fieldName!==n.right)),[...a].forEach((e=>{u.conditions.push({fieldName:n.right,operator:"==",value:e})}));const c=Object.assign(Object.assign({},t),{query:u,activated:!0,gotInitialResponse:!1,dataSubject:new o.BehaviorSubject(null),clientRequestId:U(),isEmptyForJoin:!1});return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),(0,V.truthy)(t.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(t.activated=!0,i.conditions.filter(Ve).filter((e=>e.fieldName===n.right&&"=="===e.operator)).map((e=>e.value)).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const r=e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})).map((e=>({fieldName:n.right,operator:"==",value:e})));return r.length?(i.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=(0,V.truthy)(t.shift());t.push(...e.supportedQueries||[]),await(0,o.firstValueFrom)(e.unsubscribeBlockerCount.pipe(mu((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,t=!1){if(this.destructManager.isDestructing)return;const r=e.query,n=e.clientRequestId,i=ct(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 yu(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,o.firstValueFrom)(t.queryRegistered.pipe(mu(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,o.race)(e.queryRegistered.pipe(mu(Boolean),(0,o.delay)(2e3),(0,o.take)(1)),this.destructManager.observeIsDestructing().pipe((0,o.take)(1)));t.dataSubject.pipe((0,o.takeWhile)((()=>!e.done)),(0,o.takeUntil)(i),mu(Boolean),(0,o.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),Q((e=>e.filter((e=>n.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(He(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+Tu: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()):(we.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=>{ce(this.localDocumentToClientRequestIds,t,e[t])}))}}function Fu(e,t){var r;for(const n of e.fields){const e=null!==(r=oe(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 Ou.TrieStore({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch((()=>{let r=0;const n=new Set;for(const i of e.conditions){if(Ve(i)&&["=="].includes(i.operator)){const e=Oe(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];Eu(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)||[]];Eu(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,me(r))];var r}}class ku{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,o.lastValueFrom)((0,o.combineLatest)(t).pipe((0,o.filter)((e=>!e.includes(!0))),(0,o.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=(0,V.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,V.assertTruthy)(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new o.BehaviorSubject(!0)}}class Du{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 xu(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 ju="subscriptionMutex";class xu{constructor(e,t,r){this.integrationId=e,this.topicName=t,this.rpcManager=r,this.messagesSubject=new o.Subject,this.subscriberCount=0,this.lockManager=new ku}async produce(e){await this.lockManager.lock(ju);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(ju)}}consume(){return(0,o.defer)((()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,o.finalize)((()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))))}async performSubscribe(){await this.lockManager.lock(ju);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 o.Subject}finally{this.lockManager.release(ju)}}async performUnsubscribe(){await this.lockManager.lock(ju);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(ju)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class Pu{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,o.firstValueFrom)((0,o.interval)(10).pipe((0,o.filter)((()=>this.attemptConsume())),(0,o.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 Nu 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 Cu(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=(Blob,n.name);e.append(r,t,i)}e.append("body",ge(n)),a.body=e}else s.append("Content-Type","application/json"),a.body=ge(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 Nu(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 Nu(e.status,e.statusText,i,t,n,s)}const r=await e.text();return we.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw we.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 _e(e)}catch(e){}return e}}class qu{constructor(e,t,r,n,i,s){this.region=e,this.appId=t,this.authManager=i,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new o.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 a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Pu(60*a,5),ai:new Pu(20*a,5),secret:new Pu(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,o.firstValueFrom)(this.onGoingRpcCounter.pipe((0,o.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);we.debug(`sending request: path: ${e} message: ${JSON.stringify(t)}`);const a=eu(this.region,this.appId,e);return await Cu({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,V.truthy)(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?(0,V.truthy)(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):(0,V.truthy)(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class Lu{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 Bu(this.rpcManager)}}class Bu{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 Qu=e=>e();var Vu;function Uu(){}const zu="undefined"!=typeof process&&(null===(Vu=process.versions)||void 0===Vu?void 0:Vu.node)?r(5086):Ee().WebSocket;class Yu{constructor(e,t,r,n=Qu,i,s){this.clientIdService=e,this.region=t,this.appId=r,this.messageNotificationWrapper=n,this.destructManager=i,this.authManager=s,this.webSocketObserver=new o.Subject,this.allMessagesObserver=new o.Subject,this.connectionReady=new o.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new o.Subject,this.connectedAtLeastOnce=!1,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,o.skip)(1),(0,o.filter)((e=>!e)),(0,o.switchMap)((()=>(0,o.race)((0,o.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,o.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value?we.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(we.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())})),this.observeConnectionReady().pipe((0,o.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}))}refreshClient(){this.destructManager.isDestructing?we.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?we.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(we.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),we.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}tick(){Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(we.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,o.distinctUntilChanged)())}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){var t;await(0,o.firstValueFrom)(this.connectionReady.pipe((0,o.filter)(Boolean)));const r=await this.authManager.getToken();if(this.connectionReady.value)try{(0,V.assertTruthy)(this.socket,"Socket is undefined in sendMessageAsync");const t=ge({message:e,authToken:r});we.debug(this.clientIdService.getClientId(),"Sending message to socket: ",t),this.socket.send(t)}catch(r){(null===(t=this.socket)||void 0===t?void 0:t.connected)?console.error("Websocket message is ignored due to a non-recoverable error",r):(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(ge({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=eu(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();we.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(){var i;const s=null!==(i=null==zu?void 0:zu.WebSocket)&&void 0!==i?i:zu;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.")}:Uu,r.onopen=function(e){o.connected=!0,(t.onopen||Uu)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return we.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Uu)(e),void o.reconnect(e);(t.onclose||Uu)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):o.closeCalled||(t.onerror||Uu)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout((function(){(t.onreconnect||Uu)(e),we.debug("WebSocket trying to reconnect..."),o.open()}),t.timeoutMillis||1e3):(t.onmaximum||Uu)(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:()=>{we.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{we.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):we.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{we.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):we.debug(t,`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.connectedAtLeastOnce?this.sendMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return we.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=_e(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),we.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}setupMessageAcknowledgments(){const e=new o.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,o.tap)((e=>t.push(e))),(0,o.debounceTime)(100)).subscribe((async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){this.sendKillMessage(),await(0,o.firstValueFrom)((0,o.timer)(0)),this.connectionReady.next(!1),await(0,o.firstValueFrom)((0,o.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Wu(e,t){return`${function(e){(0,V.assertString)(e,"Invalid application ID");const[t,r,n,i]=e.split("-");return(0,V.assertTruthy)(!i,`Invalid application ID: ${e}`),{appId:t,environmentId:null!=r?r:"prod",squidDeveloperId:n}}(e).appId}${t&&"prod"!==t?`-${t}`:""}`}class $u{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 Gu{constructor(e){this.options=e,this.destructManager=new St,(0,V.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`${Wu(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return tu(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new Te(this.destructManager),this.authManager=new ne(e.apiKey,e.authProvider),this.socketManager=new Yu(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new qu(e.region,r,this.destructManager,n,this.authManager,this.clientIdService),this.aiClientFactory=new X(this.rpcManager,this.socketManager),this.aiClient=new ee(this.aiClientFactory,this.rpcManager),this.apiClient=new re(this.rpcManager),this.documentStore=new At,this.lockManager=new ku,this.distributedLockManager=new Et(this.socketManager,this.destructManager),this.documentIdentityService=new Tt(this.documentStore,this.destructManager),this.documentReferenceFactory=new It(this.documentIdentityService),this.querySender=new gu(this.rpcManager,this.destructManager),this.querySubscriptionManager=new Au(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender),this.localQueryManager=new bu(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new iu(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Xe(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new _t(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 Se(this.clientIdService,this.rpcManager),this.nativeQueryManager=new ou(this.rpcManager),this.graphqlClientFactory=new nu(this.rpcManager,e.region,r),this.secretClient=new Lu(this.rpcManager),this._connectionDetails=new ft(this.clientIdService,this.socketManager),this.queueManagerFactory=new Du(this.rpcManager,this.socketManager,this.destructManager)}static getInstance(e){const t=me(e);let r=Gu.squidInstancesMap[t];return r||(r=new Gu(e),Gu.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(Gu.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Be.built_in_db){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...t){return this._validateNotDestructed(),(0,o.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(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)}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 $u(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=Be.built_in_queue){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally((()=>{const e=Object.entries(Gu.squidInstancesMap).find((([,e])=>e===this));e&&delete Gu.squidInstancesMap[e[0]]}))}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}_validateNotDestructed(){(0,V.assertTruthy)(!this.destructManager.isDestructing,"The client was already destructed.")}}Gu.squidInstancesMap={};var Hu=exports;for(var Ku in n)Hu[Ku]=n[Ku];n.__esModule&&Object.defineProperty(Hu,"__esModule",{value:!0})})();
|
|
5
|
+
`})).data}}class nu{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 ru(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class iu{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=mt(e),n=r.map((e=>`sendMutation_${He(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 we.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class ou{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}function su(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=au(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=au(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=au(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}=uu(r[0]),o=r.map((t=>su(e,t)));return e.collection(n,i).or(...o)}(e,t)}}function au(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 uu(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 uu(e.queries[0])}}const cu={"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)=>lu(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>lu(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>lu(e,t)&&du(t),"like_cs:like_cs":(e,t)=>lu(e,t),"like:not like":(e,t)=>!hu(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!hu(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!hu(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!hu(e,t),"not like:like":(e,t)=>pu(e,t),"not like_cs:like":(e,t)=>pu(e,t),"not like:like_cs":(e,t)=>pu(e,t),"not like_cs:like_cs":(e,t)=>pu(e,t),"not like:not like":(e,t)=>lu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>lu(t,e)&&du(e),"not like:not like_cs":(e,t)=>lu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>lu(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&&fu(e)||vu(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&fu(e)||vu(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&fu(t)||vu(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&fu(t)||vu(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"))),"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 lu(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return fu(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?lu(e,t,r+1,n+1)||lu(e,t,r+1,n):"%"!==i&&("%"===o?lu(e,t,r,n+1)||lu(e,t,r+1,n):(i===o||"_"===o)&&lu(e,t,r+1,n+1))}function hu(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return fu(t.substring(n));if(n>=t.length)return fu(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?hu(e,t,r+1,n+1)||hu(e,t,r,n+1)||hu(e,t,r+1,n):"%"===i||"%"===o?hu(e,t,r,n+1)||hu(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&hu(e,t,r+1,n+1)}function du(e){return!/[a-zA-Z]/.test(e)}function fu(e){return e.split("").every((e=>"%"===e))}function pu(e,t){return e.length>0&&fu(e)||t.length>0&&fu(t)||vu(e)&&0===t.length}function vu(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 yu{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(Ve))}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!he(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(Ve),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=oe(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=cu[`${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&&he(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 bu{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 yu(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[He(e.__docId__,r,t)]))}}function mu(e,t){return a((function(r,n){var i=0;r.subscribe(L(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}class gu{constructor(e,t){this.rpcManager=e,this.destructManager=t,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new o.BehaviorSubject(!0),this.inflightQueriesCount=new o.BehaviorSubject(0),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}async sendQuery(e){const t=new o.Subject,r=(0,o.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(mu(Boolean),(0,o.take)(1)).subscribe((()=>{this.processQueryBatch()}))}),0),r)}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,o.firstValueFrom)(this.inflightQueriesCount.pipe(mu((e=>0===e)))).then((()=>{}))}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var _u,Ou=r(4123);function Su(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?Su(e,t,r,o+1,i):Su(e,t,r,n,o-1)}function Eu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){if(-1!==Su(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=Su(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"}(_u||(_u={}));const Tu=100,Iu=20;class Au{constructor(e,t,r,n,i,s){this.rpcManager=e,this.clientIdService=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.querySender=s,this.onOrphanDocuments=new o.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new Mu,this.queryResultsSubject=new o.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,V.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}=Ge(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=_e(n);let s;if(Ve(e)){const n=null!==(r=oe(t,e.fieldName))&&void 0!==r?r:null;s=at(e.value,n,e.operator)}else s=Fu(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,V.truthy)(null==s?void 0:s.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case _u.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+Tu?_u.ENABLED:_u.DISABLED;break;case _u.DISABLED:break;case _u.ENABLED:if(n.size<e.query.limit+Iu){e.limitUnderflowState=_u.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);(0,V.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 yu(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 yu(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,r,n,i,s){return(0,o.defer)((()=>{const a=this.createOngoingQueryGraph(e,t,r,n,i,!0);s&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new o.ReplaySubject(1);const u=a.allObservables.pipe((0,o.switchMap)((e=>(0,o.combineLatest)(e).pipe(Q((e=>this.joinResults(e,n,a)))))),mu((()=>this.allOngoingQueriesGotInitialResult(a))),(0,o.startWith)(void 0),(0,o.pairwise)(),mu((([e,t])=>!he(e,t))),Q((([,e])=>e)),i?(0,o.tap)():(0,o.take)(1),(0,o.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,o.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,V.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 t=e.clientRequestId,r=ct(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,o.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,o.firstValueFrom)((0,o.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(mu((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)})),mu(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,s,a={}){if(a[t])return a[t];const u=U(),c=[],l={clientRequestId:u,activated:s,alias:t,query:e,subscribe:i,dataSubject:new o.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new o.BehaviorSubject(0),queryRegistered:new o.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:i?_u.UNKNOWN:_u.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(u,l),a[t]=l;for(const[e,o]of Object.entries(n)){const s=o.leftAlias;if(s!==t&&e!==t)continue;const u=s===t?e:s;if(s===t){const e=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,a);e.joinCondition=o,c.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(r[u],u,r,n,i,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(mu(Boolean),Q((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,V.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,V.truthy)(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=(0,V.truthy)(t.joinCondition),i=t.query;if(t.activated){if(!t.canExpandForJoin)return!1;const s=(0,V.truthy)(null===(r=t.supportingOngoingQuery)||void 0===r?void 0:r.supportedQueries).filter((e=>e.alias===t.alias)),a=new Set(e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})));for(const e of s)e.query.conditions.filter(Ve).filter((e=>e.fieldName===n.right)).forEach((e=>{a.delete(e.value)}));if(0===a.size)return!1;const u=fe(i);u.conditions=u.conditions.filter((e=>!Ve(e)||e.fieldName!==n.right)),[...a].forEach((e=>{u.conditions.push({fieldName:n.right,operator:"==",value:e})}));const c=Object.assign(Object.assign({},t),{query:u,activated:!0,gotInitialResponse:!1,dataSubject:new o.BehaviorSubject(null),clientRequestId:U(),isEmptyForJoin:!1});return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),(0,V.truthy)(t.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(t.activated=!0,i.conditions.filter(Ve).filter((e=>e.fieldName===n.right&&"=="===e.operator)).map((e=>e.value)).length)return this.sendQueryToServerOrUseParentQuery(t),t.canExpandForJoin=!1,!0;const r=e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})).map((e=>({fieldName:n.right,operator:"==",value:e})));return r.length?(i.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=(0,V.truthy)(t.shift());t.push(...e.supportedQueries||[]),await(0,o.firstValueFrom)(e.unsubscribeBlockerCount.pipe(mu((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,t=!1){if(this.destructManager.isDestructing)return;const r=e.query,n=e.clientRequestId,i=ct(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 yu(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,o.firstValueFrom)(t.queryRegistered.pipe(mu(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,o.race)(e.queryRegistered.pipe(mu(Boolean),(0,o.delay)(2e3),(0,o.take)(1)),this.destructManager.observeIsDestructing().pipe((0,o.take)(1)));t.dataSubject.pipe((0,o.takeWhile)((()=>!e.done)),(0,o.takeUntil)(i),mu(Boolean),(0,o.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),Q((e=>e.filter((e=>n.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(He(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+Tu: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()):(we.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=>{ce(this.localDocumentToClientRequestIds,t,e[t])}))}}function Fu(e,t){var r;for(const n of e.fields){const e=null!==(r=oe(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 Ou.TrieStore({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch((()=>{let r=0;const n=new Set;for(const i of e.conditions){if(Ve(i)&&["=="].includes(i.operator)){const e=Oe(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];Eu(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)||[]];Eu(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,me(r))];var r}}class ku{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,o.lastValueFrom)((0,o.combineLatest)(t).pipe((0,o.filter)((e=>!e.includes(!0))),(0,o.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=(0,V.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,V.assertTruthy)(this.canGetLock(...e),"Cannot acquire lock sync");for(const t of e)this.locks[t]=new o.BehaviorSubject(!0)}}class Du{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 xu(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 ju="subscriptionMutex";class xu{constructor(e,t,r){this.integrationId=e,this.topicName=t,this.rpcManager=r,this.messagesSubject=new o.Subject,this.subscriberCount=0,this.lockManager=new ku}async produce(e){await this.lockManager.lock(ju);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(ju)}}consume(){return(0,o.defer)((()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,o.finalize)((()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))))}async performSubscribe(){await this.lockManager.lock(ju);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 o.Subject}finally{this.lockManager.release(ju)}}async performUnsubscribe(){await this.lockManager.lock(ju);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(ju)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class Pu{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,o.firstValueFrom)((0,o.interval)(10).pipe((0,o.filter)((()=>this.attemptConsume())),(0,o.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 Nu 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 Cu(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=(Blob,n.name);e.append(r,t,i)}e.append("body",ge(n)),a.body=e}else s.append("Content-Type","application/json"),a.body=ge(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 Nu(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 Nu(e.status,e.statusText,i,t,n,s)}const r=await e.text();return we.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw we.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 _e(e)}catch(e){}return e}}class qu{constructor(e,t,r,n,i,s){this.region=e,this.appId=t,this.authManager=i,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new o.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 a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Pu(60*a,5),ai:new Pu(20*a,5),secret:new Pu(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,o.firstValueFrom)(this.onGoingRpcCounter.pipe((0,o.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);we.debug(`sending request: path: ${e} message: ${JSON.stringify(t)}`);const a=eu(this.region,this.appId,e);return await Cu({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,V.truthy)(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?(0,V.truthy)(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):(0,V.truthy)(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class Lu{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 Bu(this.rpcManager)}}class Bu{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 Qu=e=>e();var Vu;function Uu(){}const zu="undefined"!=typeof process&&(null===(Vu=process.versions)||void 0===Vu?void 0:Vu.node)?r(5086):Ee().WebSocket;class Yu{constructor(e,t,r,n=Qu,i,s){this.clientIdService=e,this.region=t,this.appId=r,this.messageNotificationWrapper=n,this.destructManager=i,this.authManager=s,this.webSocketObserver=new o.Subject,this.allMessagesObserver=new o.Subject,this.connectionReady=new o.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new o.Subject,this.connectedAtLeastOnce=!1,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,o.skip)(1),(0,o.filter)((e=>!e)),(0,o.switchMap)((()=>(0,o.race)((0,o.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,o.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value?we.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(we.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())})),this.observeConnectionReady().pipe((0,o.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}))}refreshClient(){this.destructManager.isDestructing?we.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?we.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(we.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),we.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}tick(){Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(we.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,o.distinctUntilChanged)())}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){var t;await(0,o.firstValueFrom)(this.connectionReady.pipe((0,o.filter)(Boolean)));const r=await this.authManager.getToken();if(this.connectionReady.value)try{(0,V.assertTruthy)(this.socket,"Socket is undefined in sendMessageAsync");const t=ge({message:e,authToken:r});we.debug(this.clientIdService.getClientId(),"Sending message to socket: ",t),this.socket.send(t)}catch(r){(null===(t=this.socket)||void 0===t?void 0:t.connected)?console.error("Websocket message is ignored due to a non-recoverable error",r):(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(ge({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=eu(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),t=this.clientIdService.getClientId();we.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(){var i;const s=null!==(i=null==zu?void 0:zu.WebSocket)&&void 0!==i?i:zu;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.")}:Uu,r.onopen=function(e){o.connected=!0,(t.onopen||Uu)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return we.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Uu)(e),void o.reconnect(e);(t.onclose||Uu)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):o.closeCalled||(t.onerror||Uu)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout((function(){(t.onreconnect||Uu)(e),we.debug("WebSocket trying to reconnect..."),o.open()}),t.timeoutMillis||1e3):(t.onmaximum||Uu)(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:()=>{we.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${e}`)},onreconnect:()=>{we.debug(t,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):we.debug(t,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{we.debug(t,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===t?this.connectionReady.value&&this.connectionReady.next(!1):we.debug(t,`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.connectedAtLeastOnce?this.sendMessage({type:"catchup"}):this.connectedAtLeastOnce=!0}onMessage(e){if("connectionReady"===e)return we.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=_e(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),we.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}setupMessageAcknowledgments(){const e=new o.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,o.tap)((e=>t.push(e))),(0,o.debounceTime)(100)).subscribe((async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){this.sendKillMessage(),await(0,o.firstValueFrom)((0,o.timer)(0)),this.connectionReady.next(!1),await(0,o.firstValueFrom)((0,o.timer)(0)),clearInterval(this.tickInterval),this.closeCurrentSocketSilently(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Wu(e,t){return`${function(e){(0,V.assertString)(e,"Invalid application ID");const[t,r,n,i]=e.split("-");return(0,V.assertTruthy)(!i,`Invalid application ID: ${e}`),{appId:t,environmentId:null!=r?r:"prod",squidDeveloperId:n}}(e).appId}${t&&"prod"!==t?`-${t}`:""}`}class $u{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 Gu{constructor(e){this.options=e,this.destructManager=new St,(0,V.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`${Wu(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return tu(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new Te(this.destructManager),this.authManager=new ne(e.apiKey,e.authProvider),this.socketManager=new Yu(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new qu(e.region,r,this.destructManager,n,this.authManager,this.clientIdService),this.aiClientFactory=new X(this.rpcManager,this.socketManager),this.aiClient=new ee(this.aiClientFactory,this.rpcManager),this.apiClient=new re(this.rpcManager),this.documentStore=new At,this.lockManager=new ku,this.distributedLockManager=new Et(this.socketManager,this.destructManager),this.documentIdentityService=new Tt(this.documentStore,this.destructManager),this.documentReferenceFactory=new It(this.documentIdentityService),this.querySender=new gu(this.rpcManager,this.destructManager),this.querySubscriptionManager=new Au(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender),this.localQueryManager=new bu(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new iu(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new Xe(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new _t(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 Se(this.clientIdService,this.rpcManager),this.nativeQueryManager=new ou(this.rpcManager),this.graphqlClientFactory=new nu(this.rpcManager,e.region,r),this.secretClient=new Lu(this.rpcManager),this._connectionDetails=new ft(this.clientIdService,this.socketManager),this.queueManagerFactory=new Du(this.rpcManager,this.socketManager,this.destructManager)}static getInstance(e){const t=me(e);let r=Gu.squidInstancesMap[t];return r||(r=new Gu(e),Gu.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(Gu.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=Be.built_in_db){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...t){return this._validateNotDestructed(),(0,o.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(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)}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 $u(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=Be.built_in_queue){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally((()=>{const e=Object.entries(Gu.squidInstancesMap).find((([,e])=>e===this));e&&delete Gu.squidInstancesMap[e[0]]}))}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}_validateNotDestructed(){(0,V.assertTruthy)(!this.destructManager.isDestructing,"The client was already destructed.")}internal(){const{rpcManager:e}=this;return{getApplicationUrl:(e,t,r)=>eu(e,t,r),getStaticHeaders:()=>e.getStaticHeaders()}}}Gu.squidInstancesMap={};var Hu=exports;for(var Ku in n)Hu[Ku]=n[Ku];n.__esModule&&Object.defineProperty(Hu,"__esModule",{value:!0})})();
|
|
@@ -26,7 +26,6 @@ export interface SnapshotEmitter<ReturnType> {
|
|
|
26
26
|
* @returns An array of query results.
|
|
27
27
|
*/
|
|
28
28
|
peek(): Array<ReturnType>;
|
|
29
|
-
limit(limit: number): SnapshotEmitter<ReturnType>;
|
|
30
29
|
/**
|
|
31
30
|
* Returns a pagination wrapper for this query.
|
|
32
31
|
* @param options The pagination options. Defaults to `{ subscribe: true, pageSize: 100 }`.
|