@squidcloud/client 1.0.204 → 1.0.206
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.js +1 -1
- package/dist/internal-common/src/public-types-backend/bundle-api.public-types.d.ts +1 -1
- package/dist/internal-common/src/public-types-backend/native-query.public-context.d.ts +17 -6
- package/dist/typescript-client/src/public-types-deprecated.d.ts +0 -3
- package/dist/typescript-client/src/public-types.d.ts +1 -1
- package/package.json +1 -1
- package/dist/internal-common/src/public-types/native-query.public-types.d.ts +0 -16
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:Qa`
|
|
4
4
|
${e.query}
|
|
5
|
-
`})).data}}class Ga{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 $a(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class Ha{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=ct(e),n=r.map((e=>`sendMutation_${Be(e.squidDocIdObj)}`));await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:r,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Se.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class Ka{constructor(e){this.rpcManager=e}async executeNativeQuery(e,t){const r=Object.assign({integrationId:e},t);return this.rpcManager.post("native-query/execute",r)}}function Ja(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=Xa(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=Xa(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=Xa(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}=Za(r[0]),o=r.map((t=>Ja(e,t)));return e.collection(n,i).or(...o)}(e,t)}}function Xa(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 Za(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 Za(e.queries[0])}}const eu={"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)=>tu(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>tu(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>tu(e,t)&&nu(t),"like_cs:like_cs":(e,t)=>tu(e,t),"like:not like":(e,t)=>!ru(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!ru(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!ru(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!ru(e,t),"not like:like":(e,t)=>ou(e,t),"not like_cs:like":(e,t)=>ou(e,t),"not like:like_cs":(e,t)=>ou(e,t),"not like_cs:like_cs":(e,t)=>ou(e,t),"not like:not like":(e,t)=>tu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>tu(t,e)&&nu(e),"not like:not like_cs":(e,t)=>tu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>tu(t,e),"in:like":(e,t)=>e.every((e=>Ze(t,e,"like"))),"in:like_cs":(e,t)=>e.every((e=>Ze(t,e,"like_cs"))),"in:not like":(e,t)=>e.every((e=>Ze(t,e,"not like"))),"in:not like_cs":(e,t)=>e.every((e=>Ze(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&&iu(e)||su(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&iu(e)||su(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&iu(t)||su(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&iu(t)||su(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=>Ze(e,t,"not like"))),"like_cs:not in":(e,t)=>t.every((t=>Ze(e,t,"not like_cs"))),"not like:not in":(e,t)=>t.every((t=>Ze(e,t,"like"))),"not like_cs:not in":(e,t)=>t.every((t=>Ze(e,t,"like_cs")))};function tu(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return iu(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?tu(e,t,r+1,n+1)||tu(e,t,r+1,n):"%"!==i&&("%"===o?tu(e,t,r,n+1)||tu(e,t,r+1,n):(i===o||"_"===o)&&tu(e,t,r+1,n+1))}function ru(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return iu(t.substring(n));if(n>=t.length)return iu(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?ru(e,t,r+1,n+1)||ru(e,t,r,n+1)||ru(e,t,r+1,n):"%"===i||"%"===o?ru(e,t,r,n+1)||ru(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&ru(e,t,r+1,n+1)}function nu(e){return!/[a-zA-Z]/.test(e)}function iu(e){return e.split("").every((e=>"%"===e))}function ou(e,t){return e.length>0&&iu(e)||t.length>0&&iu(t)||su(e)&&0===t.length}function su(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 au{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(xe))}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!ae(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(xe),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=te(e,r);if("in"===n){if(t.value.includes(i))continue;return!1}if("not in"!==n){if(!Ze(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=eu[`${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&&ae(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 uu{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 au(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[Be(e.__docId__,r,t)]))}}function cu(e,t){return o((function(r,n){var i=0;r.subscribe(C(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}class lu{constructor(e,r){this.rpcManager=e,this.destructManager=r,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new t.BehaviorSubject(!0),this.inflightQueriesCount=new t.BehaviorSubject(0),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}async sendQuery(e){const r=new t.Subject,n=(0,t.firstValueFrom)(r);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:r}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),n):(this.pendingQueryBatchTimeout=setTimeout((()=>{this.safeToSendQueriesToServer.pipe(cu(Boolean),(0,t.take)(1)).subscribe((()=>{this.processQueryBatch()}))}),0),n)}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=e.map((({queryRequest:e})=>e)),r=e.map((({responseSubject:e})=>e));this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const r=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,i=r.errors[e],o=r.results[e];i?n.error(i):n.next(o)}}catch(e){r.forEach((t=>t.error(e)))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}async waitForAllQueriesToFinish(){return(0,t.firstValueFrom)(this.inflightQueriesCount.pipe(cu((e=>0===e)))).then((()=>{}))}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var hu,du=r(511);function fu(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?fu(e,t,r,o+1,i):fu(e,t,r,n,o-1)}function pu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){if(-1!==fu(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 vu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){const n=fu(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"}(hu||(hu={}));const yu=100,bu=20;class mu{constructor(e,r,n,i,o,s){this.rpcManager=e,this.clientIdService=r,this.documentStore=n,this.destructManager=i,this.documentIdentityService=o,this.querySender=s,this.onOrphanDocuments=new t.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new _u,this.queryResultsSubject=new t.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe((()=>{this.refreshOngoingQueries()})),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return(0,B.truthy)(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);(null==t?void 0:t.gotInitialResponse)&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=Le(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=ye(n);let s;if(xe(e)){const n=null!==(r=te(t,e.fieldName))&&void 0!==r?r:null;s=Ze(e.value,n,e.operator)}else s=gu(e,t);if(s)for(const e of o)i.set(e,(i.get(e)||0)+1)}for(const[t,r]of i.entries())r>=e.queriesMetadata[t].condCount&&n.push(t);return n}(i,e):[]}setClientRequestIdsForLocalDoc(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set,n=new Set(t?this.findQueriesForDocument(t,e).map((e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId)):[]),i=new Set([...r,...n]);for(const t of[...r]){if(n.has(t))continue;r.delete(t);const i=this.clientRequestIdToLocalDocuments.get(t);i&&(i.delete(e),i.size||this.clientRequestIdToLocalDocuments.delete(t)),r.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let r=this.localDocumentToClientRequestIds.get(e);r||(r=new Set,this.localDocumentToClientRequestIds.set(e,r)),r.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...i]}errorOutAllQueries(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of r){const r=this.ongoingQueries.get(e);r&&(this.destructManager.isDestructing?r.dataSubject.complete():r.dataSubject.error(t),r.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const r of e){const e=this.ongoingQueries.get(r);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(r)||new Set,i=this.documentStore.sortAndLimitDocs(n,e.query),o=e.supportedQueries.map((e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(i,e))).some(Boolean);let s=e;for(;!s.allObservables;)s=(0,B.truthy)(null==s?void 0:s.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case hu.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+yu?hu.ENABLED:hu.DISABLED;break;case hu.DISABLED:break;case hu.ENABLED:if(n.size<e.query.limit+bu){e.limitUnderflowState=hu.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);(0,B.truthy)(e.allObservables).next(t)}}isValidParent(e){if(!e.activated||e.isInFlight||e.isEmptyForJoin||e.done||!e.subscribe||!e.gotInitialResponse||!e.dataSubject.value)return!1;const t=-1===e.query.limit?1e3:e.query.limit;return e.dataSubject.value.length<t}findValidParentOfOngoingQuery(e){if(e.forceFetchFromServer)return;const t=new au(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 au(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,r,n,i,o,s){return(0,t.defer)((()=>{const a=this.createOngoingQueryGraph(e,r,n,i,o,!0);s&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new t.ReplaySubject(1);const u=a.allObservables.pipe((0,t.switchMap)((e=>(0,t.combineLatest)(e).pipe(L((e=>this.joinResults(e,i,a)))))),cu((()=>this.allOngoingQueriesGotInitialResult(a))),(0,t.startWith)(void 0),(0,t.pairwise)(),cu((([e,t])=>!ae(e,t))),L((([,e])=>e)),o?(0,t.tap)():(0,t.take)(1),(0,t.finalize)((()=>{var e;a.dataSubject.complete(),a.done=!0,this.completeAllSupportedQueries(a).then(),null===(e=a.allObservables)||void 0===e||e.complete()}))),c=this.collectAllObservables(a);return a.allObservables.next(c),u})).pipe((0,t.share)())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const r=[];for(const n of t){const t=(0,B.truthy)(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r)}registerQueryFinalizer(e){const r=e.clientRequestId,n=tt(this.clientIdService.getClientId(),r);e.dataSubject.pipe((0,t.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,t.firstValueFrom)((0,t.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(cu((e=>0===e))))),this.queryMappingManager.removeQuery(n).then(),this.ongoingQueries.delete(r),e.subscribe&&!e.isEmptyForJoin&&e.activated){const t={clientRequestId:r};this.rpcManager.post("query/unsubscribe",t).catch((t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestIdMapping(r),this.ongoingQueries.delete(r)})),cu(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,r,n,i,o,s,a={}){if(a[r])return a[r];const u=Q(),c=[],l={clientRequestId:u,activated:s,alias:r,query:e,subscribe:o,dataSubject:new t.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new t.BehaviorSubject(0),queryRegistered:new t.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:o?hu.UNKNOWN:hu.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(u,l),a[r]=l;for(const[e,t]of Object.entries(i)){const s=t.leftAlias;if(s!==r&&e!==r)continue;const u=s===r?e:s;if(s===r){const e=this.createOngoingQueryGraph(n[u],u,n,i,o,!1,a);e.joinCondition=t,c.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(n[u],u,n,i,o,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(cu(Boolean),L((e=>({docs:e,alias:r})))));for(const r of e.supportedQueries)this.collectAllObservables(r,t);return t}joinResults(e,t,r){const n=e.reduce(((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e)),{});let i=n[r.alias].map((e=>({[r.alias]:e})));const o=this.getOngoingQueriesBfs(r),s=new Set;for(let e=1;e<o.length;e++){const r=o[e].alias;s.has(r)||(s.add(r),i=this.join(i,r,n[r],t[r]))}return i}join(e,t,r,n){if(!e.length)return e;const i=Object.keys(e[0]);if(!n||!i.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const o=new Map;return(r||[]).forEach((e=>{const t=e[n.right];o.has(t)||o.set(t,[]),(0,B.truthy)(o.get(t)).push(e)})),e.flatMap((e=>{var r;const i=o.get(null===(r=e[n.leftAlias])||void 0===r?void 0:r[n.left])||[];return i.length?i.map((r=>Object.assign(Object.assign({},e),{[t]:r}))):n.isInner?[]:[Object.assign(Object.assign({},e),{[t]:void 0})]}))}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=(0,B.truthy)(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,r){var n;const i=(0,B.truthy)(r.joinCondition),o=r.query;if(r.activated){if(!r.canExpandForJoin)return!1;const s=(0,B.truthy)(null===(n=r.supportingOngoingQuery)||void 0===n?void 0:n.supportedQueries).filter((e=>e.alias===r.alias)),a=new Set(e.map((e=>{var t;return null!==(t=e[i.left])&&void 0!==t?t:null})));for(const e of s)e.query.conditions.filter(xe).filter((e=>e.fieldName===i.right)).forEach((e=>{a.delete(e.value)}));if(0===a.size)return!1;const u=ce(o);u.conditions=u.conditions.filter((e=>!xe(e)||e.fieldName!==i.right)),[...a].forEach((e=>{u.conditions.push({fieldName:i.right,operator:"==",value:e})}));const c=Object.assign(Object.assign({},r),{query:u,activated:!0,gotInitialResponse:!1,dataSubject:new t.BehaviorSubject(null),clientRequestId:Q(),isEmptyForJoin:!1});return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),(0,B.truthy)(r.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(r.activated=!0,o.conditions.filter(xe).filter((e=>e.fieldName===i.right&&"=="===e.operator)).map((e=>e.value)).length)return this.sendQueryToServerOrUseParentQuery(r),r.canExpandForJoin=!1,!0;const t=e.map((e=>{var t;return null!==(t=e[i.left])&&void 0!==t?t:null})).map((e=>({fieldName:i.right,operator:"==",value:e})));return t.length?(o.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(r)):r.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotInitialResult(e))))}async completeAllSupportedQueries(e){const r=[...e.supportedQueries||[]];for(;r.length;){const e=(0,B.truthy)(r.shift());r.push(...e.supportedQueries||[]),await(0,t.firstValueFrom)(e.unsubscribeBlockerCount.pipe(cu((e=>0===e)))),e.dataSubject.complete()}}preDestruct(){this.unsubscribe()}unsubscribe(){var e;const t=[...this.ongoingQueries.values()];for(const r of t)r.dataSubject.complete(),null===(e=r.allObservables)||void 0===e||e.complete()}hasSubscription(e){var t;return!!(null===(t=this.ongoingQueries.get(e))||void 0===t?void 0:t.subscribe)}sendQueryToServerOrUseParentQuery(e){if(this.destructManager.isDestructing)return;const t=e.query,r=e.clientRequestId,n=tt(this.clientIdService.getClientId(),r);this.queryMappingManager.addQuery(t,n);const i=this.findValidParentOfOngoingQuery(e);this.ongoingQueries.set(r,e),i?this.useParentOngoingQuery(e,i).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,r){const n={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:r.clientRequestId},i=new au(e.query);r.unsubscribeBlockerCount.next(r.unsubscribeBlockerCount.value+1);try{await(0,t.firstValueFrom)(r.queryRegistered.pipe(cu(Boolean)))}catch(t){return this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(e.dataSubject.error(t),e.queryRegistered.error(t)),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",n).then((()=>{e.isInFlight=!1,e.queryRegistered.next(!0)})).catch((t=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,r.query,t),e.dataSubject.error(t)),e.done=!0})).finally((()=>{r.unsubscribeBlockerCount.next(r.unsubscribeBlockerCount.value-1)}));const o=(0,t.race)(e.queryRegistered.pipe(cu(Boolean),(0,t.delay)(2e3),(0,t.take)(1)),this.destructManager.observeIsDestructing().pipe((0,t.take)(1)));r.dataSubject.pipe((0,t.takeWhile)((()=>!e.done)),(0,t.takeUntil)(o),cu(Boolean),(0,t.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),L((e=>e.filter((e=>i.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(Be(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+yu:t,n={query:Object.assign(Object.assign({},e.query),{limit:r}),clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(n).then((t=>{e.isInFlight=!1,e.queryRegistered.next(!0),this.queryResultsSubject.next(t)})).catch((t=>{e.isInFlight=!1,this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(Se.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0}))}refreshOngoingQueries(){for(const e of this.ongoingQueries.values())this.sendQueryToServerOrUseParentQuery(e)}migrateDocIds(e){const t=Object.keys(e);for(const r of this.clientRequestIdToLocalDocuments.values())t.forEach((t=>{r.has(t)&&(r.delete(t),r.add(e[t]))}));t.forEach((t=>{oe(this.localDocumentToClientRequestIds,t,e[t])}))}}function gu(e,t){var r;for(const n of e.fields){const e=null!==(r=te(t,n.fieldName))&&void 0!==r?r:null;if(Ze(n.value,e,n.operator))return!0;if(Ze(n.value,e,"!="))return!1}return!1}class _u{constructor(){this.stateService=new du.TrieStore({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch((()=>{let r=0;const n=new Set;for(const i of e.conditions){if(xe(i)&&["=="].includes(i.operator)){const e=be(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];pu(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)||[]];pu(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)||[]];vu(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)||[]];vu(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,pe(r))];var r}}class Ou{constructor(){this.locks={}}async lock(...e){if(this.canGetLock(...e))return void this.lockSync(...e);const r=Object.entries(this.locks).filter((([t])=>e.includes(t))).map((([,e])=>e));await(0,t.lastValueFrom)((0,t.combineLatest)(r).pipe((0,t.filter)((e=>!e.includes(!0))),(0,t.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=(0,B.truthy)(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some((e=>{var t;return null===(t=this.locks[e])||void 0===t?void 0:t.value}))}lockSync(...e){(0,B.assertTruthy)(this.canGetLock(...e),"Cannot acquire lock sync");for(const r of e)this.locks[r]=new t.BehaviorSubject(!0)}}class Su{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 Eu(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 wu="subscriptionMutex";class Eu{constructor(e,r,n){this.integrationId=e,this.topicName=r,this.rpcManager=n,this.messagesSubject=new t.Subject,this.subscriberCount=0,this.lockManager=new Ou}async produce(e){await this.lockManager.lock(wu);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(wu)}}consume(){return(0,t.defer)((()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,t.finalize)((()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))))}async performSubscribe(){await this.lockManager.lock(wu);try{await this.rpcManager.post("queue/subscribe",{integrationId:this.integrationId,topicName:this.topicName})}catch(e){this.messagesSubject.error(e),this.messagesSubject.complete(),this.subscriberCount=0,this.messagesSubject=new t.Subject}finally{this.lockManager.release(wu)}}async performUnsubscribe(){await this.lockManager.lock(wu);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(wu)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class Tu{constructor(e,t){this.capacity=e,this.seconds=t,this.tokens=e,this.refillRatePerMs=e/(1e3*t),this.lastRefillTimestamp=Date.now()}async consume(){this.attemptConsume()||await(0,t.firstValueFrom)((0,t.interval)(10).pipe((0,t.filter)((()=>this.attemptConsume())),(0,t.first)()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}class Iu 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 Au(e){const t=await async function({headers:e,files:t,filesFieldName:r,message:n,url:i,extractErrorMessage:o}){const s=new Headers(e),a={method:"POST",headers:s,body:void 0};if(t.length){const e=new FormData;for(const n of t){const t=n instanceof Blob?n:n.blob,i=n instanceof Blob?void 0:n.name;e.append(r,t,i)}e.append("body",ve(n)),a.body=e}else s.append("Content-Type","application/json"),a.body=ve(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=Fu(r);if(!o)throw new Iu(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 Iu(e.status,e.statusText,i,t,n,s)}const r=await e.text();return Se.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Se.debug(`Unable to perform fetch request to url: ${i}`,e),e}}(e);return t.body=Fu(t.body),t}function Fu(e){if(e){try{return ye(e)}catch(e){}return e}}class Mu{constructor(e,r,n,i,o,s){this.region=e,this.appId=r,this.authManager=o,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new t.BehaviorSubject(0);for(const[e,t]of Object.entries(i))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe((e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")})),n.onDestruct((async()=>{await this.awaitAllSettled()}));const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Tu(60*a,5),ai:new Tu(20*a,5),secret:new Tu(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:r}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return r&&(n+=`; IntegrationId ${r}`),{Authorization:n}}async awaitAllSettled(){await(0,t.firstValueFrom)(this.onGoingRpcCounter.pipe((0,t.filter)((e=>0===e))))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,r=[],n="files"){return(await this.rawPost(e,t,r,n)).body}async rawPost(e,t,r=[],n="files",i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),s=Object.assign(Object.assign({},this.staticHeaders),o);Se.debug(`sending request: path: ${e} message: ${JSON.stringify(t)}`);const a=Ya(this.region,this.appId,e);return await Au({url:a,headers:s,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?(0,B.truthy)(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?(0,B.truthy)(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):(0,B.truthy)(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class ku{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 Du(this.rpcManager)}}class Du{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 ju=e=>e();var xu;function Pu(){}const Nu=null!==(xu=Oe().WebSocket)&&void 0!==xu?xu:r(5352);class Ru{constructor(e,r,n,i=ju,o,s){this.clientIdService=e,this.region=r,this.appId=n,this.messageNotificationWrapper=i,this.destructManager=o,this.authManager=s,this.webSocketObserver=new t.Subject,this.allMessagesObserver=new t.Subject,this.connectionReady=new t.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new t.Subject,this.clientTooOldThreshold=3e4,this.destructManager.onDestruct((async()=>{await this.destruct()})),this.setupMessageAcknowledgments(),this.connect(),this.lastTick=new Date,this.tickInterval=setInterval((()=>this.tick()),5e3),this.observeConnectionReady().pipe((0,t.skip)(1),(0,t.filter)((e=>!e)),(0,t.switchMap)((()=>(0,t.race)((0,t.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,t.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value?Se.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Se.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())})),this.observeConnectionReady().pipe((0,t.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}))}refreshClient(){this.destructManager.isDestructing?Se.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Se.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Se.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Se.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}tick(){Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(Se.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,t.distinctUntilChanged)())}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){var r;await(0,t.firstValueFrom)(this.connectionReady.pipe((0,t.filter)(Boolean)));const n=await this.authManager.getToken();if(this.connectionReady.value)try{(0,B.assertTruthy)(this.socket,"Socket is undefined in sendMessageAsync");const t=ve({message:e,authToken:n});Se.debug(this.clientIdService.getClientId(),"Sending message to socket: ",t),this.socket.send(t)}catch(t){(null===(r=this.socket)||void 0===r?void 0:r.connected)?console.error("Websocket message is ignored due to a non-recoverable error",t):(this.connectionReady.next(!1),await this.sendMessageAsync(e))}else await this.sendMessageAsync(e)}sendKillMessage(){var e;(null===(e=this.socket)||void 0===e?void 0:e.connected)&&this.socket.send(ve({message:{type:"kill"}}))}connect(){var e;null===(e=this.socket)||void 0===e||e.close(),this.connectionReady.value&&this.connectionReady.next(!1);const t=Ya(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),r=this.clientIdService.getClientId();Se.debug(this.clientIdService.getClientId(),"Connecting to socket at:",t);const n=`${t}?clientId=${r}`;this.socket=function(e,t={}){let r,n=0,i=1;const o={connected:!1,open(){var i;const s=null!==(i=null==Nu?void 0:Nu.WebSocket)&&void 0!==i?i:Nu;r=new s(e,t.protocols||[]),r.onmessage=t.onmessage||Pu,r.onopen=function(e){o.connected=!0,(t.onopen||Pu)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return Se.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Pu)(e),void o.reconnect(e);(t.onclose||Pu)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):(t.onerror||Pu)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout((function(){(t.onreconnect||Pu)(e),Se.debug("WebSocket trying to reconnect..."),o.open()}),t.timeout||1e3):(t.onmaximum||Pu)(e)},json(e){r.send(JSON.stringify(e))},send(e){r.send(e)},close(e=4999,t){try{o.connected=!1,clearTimeout(i),i=void 0,r.close(e,t)}catch(e){}}};return o.open(),o}(n,{timeout:5e3,onmessage:e=>this.onMessage(e.data),onopen:()=>{Se.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${t}`)},onreconnect:()=>{Se.debug(r,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===r?this.connectionReady.value&&this.connectionReady.next(!1):Se.debug(r,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Se.debug(r,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===r?this.connectionReady.value&&this.connectionReady.next(!1):Se.debug(r,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}disconnectForTest(){var e;this.connectionReady.next(!1),null===(e=this.socket)||void 0===e||e.close(4998)}onConnectionReady(){this.connectionReady.next(!0),this.sendMessage({type:"catchup"})}onMessage(e){if("connectionReady"===e)return Se.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=ye(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Se.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}setupMessageAcknowledgments(){const e=new t.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const r=[];e.pipe((0,t.tap)((e=>r.push(e))),(0,t.debounceTime)(100)).subscribe((async()=>{const e=[...r.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){var e;this.sendKillMessage(),await(0,t.firstValueFrom)((0,t.timer)(0)),this.connectionReady.next(!1),await(0,t.firstValueFrom)((0,t.timer)(0)),clearInterval(this.tickInterval),null===(e=this.socket)||void 0===e||e.close(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Cu(e,t){return`${function(e){const[t,r,n,i]=e.split("-");return(0,B.assertTruthy)(!i,"Invalid appId: "+e),{appId:t,environmentId:null!=r?r:"prod",squidDeveloperId:n}}(e).appId}${t&&"prod"!==t?`-${t}`:""}`}class qu{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 Lu{constructor(e){this.options=e,this.destructManager=new ft,(0,B.assertTruthy)(e.appId,"APP_ID_MUST_BE_PROVIDED");for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this))){const t=this[e];"function"!=typeof t||"constructor"===e||e.startsWith("_")||(this[e]=t.bind(this))}const t="prod"!==e.environmentId&&e.squidDeveloperId,r=function(e,t,r){return`${Cu(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return Wa(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new we(this.destructManager),this.authManager=new ge(e.apiKey,e.authProvider),this.socketManager=new Ru(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Mu(e.region,r,this.destructManager,n,this.authManager,this.clientIdService),this.aiClientFactory=new H(this.rpcManager,this.socketManager),this.aiClient=new J(this.aiClientFactory,this.rpcManager),this.apiClient=new Z(this.rpcManager),this.documentStore=new mt,this.lockManager=new Ou,this.distributedLockManager=new pt(this.socketManager,this.destructManager),this.documentIdentityService=new yt(this.documentStore,this.destructManager),this.documentReferenceFactory=new bt(this.documentIdentityService),this.querySender=new lu(this.rpcManager,this.destructManager),this.querySubscriptionManager=new mu(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender),this.localQueryManager=new uu(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new Ha(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new ze(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new ht(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new it(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new _e(this.clientIdService,this.rpcManager),this.nativeQueryManager=new Ka(this.rpcManager),this.apiManager=new me(this.clientIdService,this.rpcManager),this.graphqlClientFactory=new Ga(this.rpcManager,e.region,r),this.secretClient=new ku(this.rpcManager),this._connectionDetails=new ot(this.clientIdService,this.socketManager),this.queueManagerFactory=new Su(this.rpcManager,this.socketManager,this.destructManager)}static getInstance(e){const t=pe(e);let r=Lu.squidInstancesMap[t];return r||(r=new Lu(e),Lu.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(Lu.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=ke.built_in_db){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...r){return this._validateNotDestructed(),(0,t.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...r))}executeNativeRelationalQuery(e,t,r={}){const n={type:"relational",query:t,params:r};return this.nativeQueryManager.executeNativeQuery(e,n)}executeNativeMongoQuery(e,t,r){const n={type:"mongo",collectionName:t,aggregationPipeline:r};return this.nativeQueryManager.executeNativeQuery(e,n)}callApi(e,r,n={},i,o){return this._validateNotDestructed(),(0,t.firstValueFrom)(this.apiManager.callApiAndSubscribe(e,r,n,i||{},o))}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 qu(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=ke.built_in_queue){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally((()=>{const e=Object.entries(Lu.squidInstancesMap).find((([,e])=>e===this));e&&delete Lu.squidInstancesMap[e[0]]}))}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}_validateNotDestructed(){(0,B.assertTruthy)(!this.destructManager.isDestructing,"The client was already destructed.")}}Lu.squidInstancesMap={}})();var i=exports;for(var o in n)i[o]=n[o];n.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})();
|
|
5
|
+
`})).data}}class Ga{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 $a(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class Ha{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySender=r}async sendMutations(e,t){const r=ct(e),n=r.map((e=>`sendMutation_${Be(e.squidDocIdObj)}`));await this.lockManager.lock(...n),await this.querySender.waitForAllQueriesToFinish();try{const e={mutations:r,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}catch(e){throw Se.debug("Error while sending mutations",{error:e,mutations:JSON.stringify(r,null,2)}),e}finally{this.lockManager.release(...n)}}}class Ka{constructor(e){this.rpcManager=e}async executeNativeQuery(e){return this.rpcManager.post("native-query/execute",e)}}function Ja(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=Xa(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=Xa(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=Xa(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}=Za(r[0]),o=r.map((t=>Ja(e,t)));return e.collection(n,i).or(...o)}(e,t)}}function Xa(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 Za(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 Za(e.queries[0])}}const eu={"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)=>tu(e.toLowerCase(),t.toLowerCase()),"like_cs:like":(e,t)=>tu(e.toLowerCase(),t.toLowerCase()),"like:like_cs":(e,t)=>tu(e,t)&&nu(t),"like_cs:like_cs":(e,t)=>tu(e,t),"like:not like":(e,t)=>!ru(e.toLowerCase(),t.toLowerCase()),"like_cs:not like":(e,t)=>!ru(e.toLowerCase(),t.toLowerCase()),"like:not like_cs":(e,t)=>!ru(e.toLowerCase(),t.toLowerCase()),"like_cs:not like_cs":(e,t)=>!ru(e,t),"not like:like":(e,t)=>ou(e,t),"not like_cs:like":(e,t)=>ou(e,t),"not like:like_cs":(e,t)=>ou(e,t),"not like_cs:like_cs":(e,t)=>ou(e,t),"not like:not like":(e,t)=>tu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like":(e,t)=>tu(t,e)&&nu(e),"not like:not like_cs":(e,t)=>tu(t.toLowerCase(),e.toLowerCase()),"not like_cs:not like_cs":(e,t)=>tu(t,e),"in:like":(e,t)=>e.every((e=>Ze(t,e,"like"))),"in:like_cs":(e,t)=>e.every((e=>Ze(t,e,"like_cs"))),"in:not like":(e,t)=>e.every((e=>Ze(t,e,"not like"))),"in:not like_cs":(e,t)=>e.every((e=>Ze(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&&iu(e)||su(e)&&t.includes(""),"not like_cs:in":(e,t)=>e.length>0&&iu(e)||su(e)&&t.includes(""),"not in:like":(e,t)=>t.length>0&&iu(t)||su(t)&&e.includes(""),"not in:like_cs":(e,t)=>t.length>0&&iu(t)||su(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=>Ze(e,t,"not like"))),"like_cs:not in":(e,t)=>t.every((t=>Ze(e,t,"not like_cs"))),"not like:not in":(e,t)=>t.every((t=>Ze(e,t,"like"))),"not like_cs:not in":(e,t)=>t.every((t=>Ze(e,t,"like_cs")))};function tu(e,t,r=0,n=0){if(n>=t.length)return r>=e.length;if(r>=e.length)return iu(t.substring(n));const i=e[r],o=t[n];return"%"===i&&"%"===o?tu(e,t,r+1,n+1)||tu(e,t,r+1,n):"%"!==i&&("%"===o?tu(e,t,r,n+1)||tu(e,t,r+1,n):(i===o||"_"===o)&&tu(e,t,r+1,n+1))}function ru(e,t,r=0,n=0){if(r>=e.length&&n>=t.length)return!0;if(r>=e.length)return iu(t.substring(n));if(n>=t.length)return iu(e.substring(r));const i=r<e.length?e[r]:"",o=n<t.length?t[n]:"";return"%"===i&&"%"===o?ru(e,t,r+1,n+1)||ru(e,t,r,n+1)||ru(e,t,r+1,n):"%"===i||"%"===o?ru(e,t,r,n+1)||ru(e,t,r+1,n):(i===o||"_"===i||"_"===o)&&ru(e,t,r+1,n+1)}function nu(e){return!/[a-zA-Z]/.test(e)}function iu(e){return e.split("").every((e=>"%"===e))}function ou(e,t){return e.length>0&&iu(e)||t.length>0&&iu(t)||su(e)&&0===t.length}function su(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 au{constructor(e){this.query=e,this.query=e,this.parsedConditions=this.parseConditions(this.query.conditions.filter(xe))}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!ae(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(xe),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=te(e,r);if("in"===n){if(t.value.includes(i))continue;return!1}if("not in"!==n){if(!Ze(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=eu[`${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&&ae(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 uu{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 au(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[Be(e.__docId__,r,t)]))}}function cu(e,t){return o((function(r,n){var i=0;r.subscribe(C(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}class lu{constructor(e,r){this.rpcManager=e,this.destructManager=r,this.pendingQueryRequests=[],this.safeToSendQueriesToServer=new t.BehaviorSubject(!0),this.inflightQueriesCount=new t.BehaviorSubject(0),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}async sendQuery(e){const r=new t.Subject,n=(0,t.firstValueFrom)(r);return this.pendingQueryRequests.push({queryRequest:e,responseSubject:r}),this.pendingQueryBatchTimeout&&(clearTimeout(this.pendingQueryBatchTimeout),this.pendingQueryBatchTimeout=void 0),this.pendingQueryRequests.length>=10?(this.processQueryBatch(),n):(this.pendingQueryBatchTimeout=setTimeout((()=>{this.safeToSendQueriesToServer.pipe(cu(Boolean),(0,t.take)(1)).subscribe((()=>{this.processQueryBatch()}))}),0),n)}async processQueryBatch(){const e=this.pendingQueryRequests.splice(0);if(!e.length)return;const t=e.map((({queryRequest:e})=>e)),r=e.map((({responseSubject:e})=>e));this.inflightQueriesCount.next(this.inflightQueriesCount.value+t.length);try{const r=await this.rpcManager.post("query/batchQueries",t);for(const{queryRequest:t,responseSubject:n}of e){const e=t.clientRequestId,i=r.errors[e],o=r.results[e];i?n.error(i):n.next(o)}}catch(e){r.forEach((t=>t.error(e)))}finally{this.inflightQueriesCount.next(this.inflightQueriesCount.value-t.length)}}async waitForAllQueriesToFinish(){return(0,t.firstValueFrom)(this.inflightQueriesCount.pipe(cu((e=>0===e)))).then((()=>{}))}preDestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete()}}var hu,du=r(511);function fu(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?fu(e,t,r,o+1,i):fu(e,t,r,n,o-1)}function pu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){if(-1!==fu(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 vu(e,t,r=((e,t)=>e>t?1:e<t?-1:0)){const n=fu(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"}(hu||(hu={}));const yu=100,bu=20;class mu{constructor(e,r,n,i,o,s){this.rpcManager=e,this.clientIdService=r,this.documentStore=n,this.destructManager=i,this.documentIdentityService=o,this.querySender=s,this.onOrphanDocuments=new t.Subject,this.ongoingQueries=new Map,this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new _u,this.queryResultsSubject=new t.Subject,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe((()=>{this.refreshOngoingQueries()})),this.destructManager.onPreDestruct((()=>{this.preDestruct()}))}observeQueryResults(){return this.queryResultsSubject.asObservable()}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return(0,B.truthy)(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);(null==t?void 0:t.gotInitialResponse)&&this.removeClientRequestIdMapping(e),t&&(t.gotInitialResponse=!0,t.isInFlight=!1)}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=Le(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=ye(n);let s;if(xe(e)){const n=null!==(r=te(t,e.fieldName))&&void 0!==r?r:null;s=Ze(e.value,n,e.operator)}else s=gu(e,t);if(s)for(const e of o)i.set(e,(i.get(e)||0)+1)}for(const[t,r]of i.entries())r>=e.queriesMetadata[t].condCount&&n.push(t);return n}(i,e):[]}setClientRequestIdsForLocalDoc(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set,n=new Set(t?this.findQueriesForDocument(t,e).map((e=>function(e){const t=e.split("_");return{clientId:t[0],clientRequestId:t[1]}}(e).clientRequestId)):[]),i=new Set([...r,...n]);for(const t of[...r]){if(n.has(t))continue;r.delete(t);const i=this.clientRequestIdToLocalDocuments.get(t);i&&(i.delete(e),i.size||this.clientRequestIdToLocalDocuments.delete(t)),r.size||this.localDocumentToClientRequestIds.delete(e)}for(const t of n){let r=this.localDocumentToClientRequestIds.get(e);r||(r=new Set,this.localDocumentToClientRequestIds.set(e,r)),r.add(t);let n=this.clientRequestIdToLocalDocuments.get(t);n||(n=new Set,this.clientRequestIdToLocalDocuments.set(t,n)),n.add(e)}return[...i]}errorOutAllQueries(e,t){const r=this.localDocumentToClientRequestIds.get(e)||new Set;for(const e of r){const r=this.ongoingQueries.get(e);r&&(this.destructManager.isDestructing?r.dataSubject.complete():r.dataSubject.error(t),r.done=!0)}}notifyAllSubscriptions(e){const t=new Set;for(const r of e){const e=this.ongoingQueries.get(r);if(!e)continue;if(!e.gotInitialResponse||!e.activated||e.isInFlight)continue;const n=this.clientRequestIdToLocalDocuments.get(r)||new Set,i=this.documentStore.sortAndLimitDocs(n,e.query),o=e.supportedQueries.map((e=>this.updateOngoingQueryWithNewDataFromSupportingQuery(i,e))).some(Boolean);let s=e;for(;!s.allObservables;)s=(0,B.truthy)(null==s?void 0:s.supportingOngoingQuery);if(o&&t.add(s),e.query.limit>0)switch(e.limitUnderflowState){case hu.UNKNOWN:e.limitUnderflowState=n.size===e.query.limit+yu?hu.ENABLED:hu.DISABLED;break;case hu.DISABLED:break;case hu.ENABLED:if(n.size<e.query.limit+bu){e.limitUnderflowState=hu.UNKNOWN,this.sendQueryToServerOrUseParentQuery(e);continue}}e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);(0,B.truthy)(e.allObservables).next(t)}}isValidParent(e){if(!e.activated||e.isInFlight||e.isEmptyForJoin||e.done||!e.subscribe||!e.gotInitialResponse||!e.dataSubject.value)return!1;const t=-1===e.query.limit?1e3:e.query.limit;return e.dataSubject.value.length<t}findValidParentOfOngoingQuery(e){if(e.forceFetchFromServer)return;const t=new au(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 au(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,r,n,i,o,s){return(0,t.defer)((()=>{const a=this.createOngoingQueryGraph(e,r,n,i,o,!0);s&&(a.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(a),a.allObservables=new t.ReplaySubject(1);const u=a.allObservables.pipe((0,t.switchMap)((e=>(0,t.combineLatest)(e).pipe(L((e=>this.joinResults(e,i,a)))))),cu((()=>this.allOngoingQueriesGotInitialResult(a))),(0,t.startWith)(void 0),(0,t.pairwise)(),cu((([e,t])=>!ae(e,t))),L((([,e])=>e)),o?(0,t.tap)():(0,t.take)(1),(0,t.finalize)((()=>{var e;a.dataSubject.complete(),a.done=!0,this.completeAllSupportedQueries(a).then(),null===(e=a.allObservables)||void 0===e||e.complete()}))),c=this.collectAllObservables(a);return a.allObservables.next(c),u})).pipe((0,t.share)())}hasOngoingQueryForDocId(e){const t=this.localDocumentToClientRequestIds.get(e);return!!t&&!!t.size}removeClientRequestIdMapping(e){const t=this.clientRequestIdToLocalDocuments.get(e);if(!t)return;this.clientRequestIdToLocalDocuments.delete(e);const r=[];for(const n of t){const t=(0,B.truthy)(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r)}registerQueryFinalizer(e){const r=e.clientRequestId,n=tt(this.clientIdService.getClientId(),r);e.dataSubject.pipe((0,t.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,t.firstValueFrom)((0,t.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe(cu((e=>0===e))))),this.queryMappingManager.removeQuery(n).then(),this.ongoingQueries.delete(r),e.subscribe&&!e.isEmptyForJoin&&e.activated){const t={clientRequestId:r};this.rpcManager.post("query/unsubscribe",t).catch((t=>{this.destructManager.isDestructing||console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestIdMapping(r),this.ongoingQueries.delete(r)})),cu(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,r,n,i,o,s,a={}){if(a[r])return a[r];const u=Q(),c=[],l={clientRequestId:u,activated:s,alias:r,query:e,subscribe:o,dataSubject:new t.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,canExpandForJoin:!0,unsubscribeBlockerCount:new t.BehaviorSubject(0),queryRegistered:new t.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1,limitUnderflowState:o?hu.UNKNOWN:hu.DISABLED};this.registerQueryFinalizer(l),this.ongoingQueries.set(u,l),a[r]=l;for(const[e,t]of Object.entries(i)){const s=t.leftAlias;if(s!==r&&e!==r)continue;const u=s===r?e:s;if(s===r){const e=this.createOngoingQueryGraph(n[u],u,n,i,o,!1,a);e.joinCondition=t,c.push(e)}else l.supportingOngoingQuery=this.createOngoingQueryGraph(n[u],u,n,i,o,!1,a)}return l}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe(cu(Boolean),L((e=>({docs:e,alias:r})))));for(const r of e.supportedQueries)this.collectAllObservables(r,t);return t}joinResults(e,t,r){const n=e.reduce(((e,t)=>(e[t.alias]?e[t.alias].push(...t.docs):e[t.alias]=[...t.docs],e)),{});let i=n[r.alias].map((e=>({[r.alias]:e})));const o=this.getOngoingQueriesBfs(r),s=new Set;for(let e=1;e<o.length;e++){const r=o[e].alias;s.has(r)||(s.add(r),i=this.join(i,r,n[r],t[r]))}return i}join(e,t,r,n){if(!e.length)return e;const i=Object.keys(e[0]);if(!n||!i.includes(n.leftAlias))throw new Error("No join condition found for alias "+t);const o=new Map;return(r||[]).forEach((e=>{const t=e[n.right];o.has(t)||o.set(t,[]),(0,B.truthy)(o.get(t)).push(e)})),e.flatMap((e=>{var r;const i=o.get(null===(r=e[n.leftAlias])||void 0===r?void 0:r[n.left])||[];return i.length?i.map((r=>Object.assign(Object.assign({},e),{[t]:r}))):n.isInner?[]:[Object.assign(Object.assign({},e),{[t]:void 0})]}))}getOngoingQueriesBfs(e){const t=[],r=[e];for(;r.length;){const e=(0,B.truthy)(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,r){var n;const i=(0,B.truthy)(r.joinCondition),o=r.query;if(r.activated){if(!r.canExpandForJoin)return!1;const s=(0,B.truthy)(null===(n=r.supportingOngoingQuery)||void 0===n?void 0:n.supportedQueries).filter((e=>e.alias===r.alias)),a=new Set(e.map((e=>{var t;return null!==(t=e[i.left])&&void 0!==t?t:null})));for(const e of s)e.query.conditions.filter(xe).filter((e=>e.fieldName===i.right)).forEach((e=>{a.delete(e.value)}));if(0===a.size)return!1;const u=ce(o);u.conditions=u.conditions.filter((e=>!xe(e)||e.fieldName!==i.right)),[...a].forEach((e=>{u.conditions.push({fieldName:i.right,operator:"==",value:e})}));const c=Object.assign(Object.assign({},r),{query:u,activated:!0,gotInitialResponse:!1,dataSubject:new t.BehaviorSubject(null),clientRequestId:Q(),isEmptyForJoin:!1});return this.registerQueryFinalizer(c),this.ongoingQueries.set(c.clientRequestId,c),(0,B.truthy)(r.supportingOngoingQuery).supportedQueries.push(c),this.sendQueryToServerOrUseParentQuery(c),!0}{if(r.activated=!0,o.conditions.filter(xe).filter((e=>e.fieldName===i.right&&"=="===e.operator)).map((e=>e.value)).length)return this.sendQueryToServerOrUseParentQuery(r),r.canExpandForJoin=!1,!0;const t=e.map((e=>{var t;return null!==(t=e[i.left])&&void 0!==t?t:null})).map((e=>({fieldName:i.right,operator:"==",value:e})));return t.length?(o.conditions.push(...t),this.sendQueryToServerOrUseParentQuery(r)):r.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotInitialResult(e))))}async completeAllSupportedQueries(e){const r=[...e.supportedQueries||[]];for(;r.length;){const e=(0,B.truthy)(r.shift());r.push(...e.supportedQueries||[]),await(0,t.firstValueFrom)(e.unsubscribeBlockerCount.pipe(cu((e=>0===e)))),e.dataSubject.complete()}}preDestruct(){this.unsubscribe()}unsubscribe(){var e;const t=[...this.ongoingQueries.values()];for(const r of t)r.dataSubject.complete(),null===(e=r.allObservables)||void 0===e||e.complete()}hasSubscription(e){var t;return!!(null===(t=this.ongoingQueries.get(e))||void 0===t?void 0:t.subscribe)}sendQueryToServerOrUseParentQuery(e){if(this.destructManager.isDestructing)return;const t=e.query,r=e.clientRequestId,n=tt(this.clientIdService.getClientId(),r);this.queryMappingManager.addQuery(t,n);const i=this.findValidParentOfOngoingQuery(e);this.ongoingQueries.set(r,e),i?this.useParentOngoingQuery(e,i).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,r){const n={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:r.clientRequestId},i=new au(e.query);r.unsubscribeBlockerCount.next(r.unsubscribeBlockerCount.value+1);try{await(0,t.firstValueFrom)(r.queryRegistered.pipe(cu(Boolean)))}catch(t){return this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(e.dataSubject.error(t),e.queryRegistered.error(t)),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",n).then((()=>{e.isInFlight=!1,e.queryRegistered.next(!0)})).catch((t=>{e.isInFlight=!1,this.destructManager.isDestructing?e.dataSubject.complete():(console.error("Query error",e.query,r.query,t),e.dataSubject.error(t)),e.done=!0})).finally((()=>{r.unsubscribeBlockerCount.next(r.unsubscribeBlockerCount.value-1)}));const o=(0,t.race)(e.queryRegistered.pipe(cu(Boolean),(0,t.delay)(2e3),(0,t.take)(1)),this.destructManager.observeIsDestructing().pipe((0,t.take)(1)));r.dataSubject.pipe((0,t.takeWhile)((()=>!e.done)),(0,t.takeUntil)(o),cu(Boolean),(0,t.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),L((e=>e.filter((e=>i.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(Be(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+yu:t,n={query:Object.assign(Object.assign({},e.query),{limit:r}),clientRequestId:e.clientRequestId,subscribe:e.subscribe};e.isInFlight=!0,this.querySender.sendQuery(n).then((t=>{e.isInFlight=!1,e.queryRegistered.next(!0),this.queryResultsSubject.next(t)})).catch((t=>{e.isInFlight=!1,this.destructManager.isDestructing?(e.dataSubject.complete(),e.queryRegistered.complete()):(Se.debug("Query error",e.query,t),e.dataSubject.error(t),e.queryRegistered.error("query failed")),e.done=!0}))}refreshOngoingQueries(){for(const e of this.ongoingQueries.values())this.sendQueryToServerOrUseParentQuery(e)}migrateDocIds(e){const t=Object.keys(e);for(const r of this.clientRequestIdToLocalDocuments.values())t.forEach((t=>{r.has(t)&&(r.delete(t),r.add(e[t]))}));t.forEach((t=>{oe(this.localDocumentToClientRequestIds,t,e[t])}))}}function gu(e,t){var r;for(const n of e.fields){const e=null!==(r=te(t,n.fieldName))&&void 0!==r?r:null;if(Ze(n.value,e,n.operator))return!0;if(Ze(n.value,e,"!="))return!1}return!1}class _u{constructor(){this.stateService=new du.TrieStore({}),this.querySubscriptionIdToQuery={}}addQuery(e,t){this.stateService.runInBatch((()=>{let r=0;const n=new Set;for(const i of e.conditions){if(xe(i)&&["=="].includes(i.operator)){const e=be(i.fieldName);n.has(e)||(r++,n.add(e))}else r++;const o=this.getConditionStatePath(e,i),s=[...this.stateService.get(o)||[]];pu(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)||[]];pu(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)||[]];vu(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)||[]];vu(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,pe(r))];var r}}class Ou{constructor(){this.locks={}}async lock(...e){if(this.canGetLock(...e))return void this.lockSync(...e);const r=Object.entries(this.locks).filter((([t])=>e.includes(t))).map((([,e])=>e));await(0,t.lastValueFrom)((0,t.combineLatest)(r).pipe((0,t.filter)((e=>!e.includes(!0))),(0,t.take)(1))),await this.lock(...e)}release(...e){for(const t of e){const e=(0,B.truthy)(this.locks[t]);e.next(!1),e.complete(),delete this.locks[t]}}canGetLock(...e){return!e.some((e=>{var t;return null===(t=this.locks[e])||void 0===t?void 0:t.value}))}lockSync(...e){(0,B.assertTruthy)(this.canGetLock(...e),"Cannot acquire lock sync");for(const r of e)this.locks[r]=new t.BehaviorSubject(!0)}}class Su{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 Eu(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 wu="subscriptionMutex";class Eu{constructor(e,r,n){this.integrationId=e,this.topicName=r,this.rpcManager=n,this.messagesSubject=new t.Subject,this.subscriberCount=0,this.lockManager=new Ou}async produce(e){await this.lockManager.lock(wu);try{await this.rpcManager.post("queue/produceMessages",{integrationId:this.integrationId,topicName:this.topicName,messages:e})}finally{this.lockManager.release(wu)}}consume(){return(0,t.defer)((()=>(this.subscriberCount++,1===this.subscriberCount&&this.performSubscribe(),this.messagesSubject.asObservable().pipe((0,t.finalize)((()=>{this.subscriberCount--,0===this.subscriberCount&&this.performUnsubscribe()}))))))}async performSubscribe(){await this.lockManager.lock(wu);try{await this.rpcManager.post("queue/subscribe",{integrationId:this.integrationId,topicName:this.topicName})}catch(e){this.messagesSubject.error(e),this.messagesSubject.complete(),this.subscriberCount=0,this.messagesSubject=new t.Subject}finally{this.lockManager.release(wu)}}async performUnsubscribe(){await this.lockManager.lock(wu);try{await this.rpcManager.post("queue/unsubscribe",{integrationId:this.integrationId,topicName:this.topicName})}finally{this.lockManager.release(wu)}}onMessages(e){for(const t of e)this.messagesSubject.next(t)}destruct(){this.messagesSubject.complete()}}class Tu{constructor(e,t){this.capacity=e,this.seconds=t,this.tokens=e,this.refillRatePerMs=e/(1e3*t),this.lastRefillTimestamp=Date.now()}async consume(){this.attemptConsume()||await(0,t.firstValueFrom)((0,t.interval)(10).pipe((0,t.filter)((()=>this.attemptConsume())),(0,t.first)()))}attemptConsume(){return this.refill(),this.tokens>=1&&(this.tokens-=1,!0)}refill(){const e=Date.now(),t=(e-this.lastRefillTimestamp)*this.refillRatePerMs;this.tokens=Math.min(this.tokens+t,this.capacity),this.lastRefillTimestamp=e}}class Iu 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 Au(e){const t=await async function({headers:e,files:t,filesFieldName:r,message:n,url:i,extractErrorMessage:o}){const s=new Headers(e),a={method:"POST",headers:s,body:void 0};if(t.length){const e=new FormData;for(const n of t){const t=n instanceof Blob?n:n.blob,i=n instanceof Blob?void 0:n.name;e.append(r,t,i)}e.append("body",ve(n)),a.body=e}else s.append("Content-Type","application/json"),a.body=ve(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=Fu(r);if(!o)throw new Iu(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 Iu(e.status,e.statusText,i,t,n,s)}const r=await e.text();return Se.debug(`received response from url ${i}: ${JSON.stringify(r)}`),{body:r,headers:t,status:e.status,statusText:e.statusText}}catch(e){throw Se.debug(`Unable to perform fetch request to url: ${i}`,e),e}}(e);return t.body=Fu(t.body),t}function Fu(e){if(e){try{return ye(e)}catch(e){}return e}}class Mu{constructor(e,r,n,i,o,s){this.region=e,this.appId=r,this.authManager=o,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new t.BehaviorSubject(0);for(const[e,t]of Object.entries(i))this.setStaticHeader(e,t);this.clientIdService.observeClientId().subscribe((e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")})),n.onDestruct((async()=>{await this.awaitAllSettled()}));const a=this.authManager.getApiKey()?5:1;this.rateLimiters={default:new Tu(60*a,5),ai:new Tu(20*a,5),secret:new Tu(20*a,5)}}async getAuthHeaders(){const e=this.authManager.getApiKey();if(e)return{Authorization:`ApiKey ${e}`};const{token:t,integrationId:r}=await this.authManager.getAuthData();if(!t)return{};let n=`Bearer ${t}`;return r&&(n+=`; IntegrationId ${r}`),{Authorization:n}}async awaitAllSettled(){await(0,t.firstValueFrom)(this.onGoingRpcCounter.pipe((0,t.filter)((e=>0===e))))}setStaticHeader(e,t){this.staticHeaders[e]=t}deleteStaticHeader(e){delete this.staticHeaders[e]}getStaticHeaders(){return this.staticHeaders}async post(e,t,r=[],n="files"){return(await this.rawPost(e,t,r,n)).body}async rawPost(e,t,r=[],n="files",i=!0){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await this.getRateLimiterBucket(e).consume();const o=await this.getAuthHeaders(),s=Object.assign(Object.assign({},this.staticHeaders),o);Se.debug(`sending request: path: ${e} message: ${JSON.stringify(t)}`);const a=Ya(this.region,this.appId,e);return await Au({url:a,headers:s,message:t,files:r,filesFieldName:n,extractErrorMessage:i})}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}getRateLimiterBucket(e){return e.startsWith("ai/chatbot")?(0,B.truthy)(this.rateLimiters.ai,"MISSING_RATE_LIMITER_AI"):e.startsWith("secret/")?(0,B.truthy)(this.rateLimiters.secret,"MISSING_RATE_LIMITER_SECRETS"):(0,B.truthy)(this.rateLimiters.default,"MISSING_RATE_LIMITER_DEFAULT")}}class ku{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 Du(this.rpcManager)}}class Du{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 ju=e=>e();var xu;function Pu(){}const Nu=null!==(xu=Oe().WebSocket)&&void 0!==xu?xu:r(5352);class Ru{constructor(e,r,n,i=ju,o,s){this.clientIdService=e,this.region=r,this.appId=n,this.messageNotificationWrapper=i,this.destructManager=o,this.authManager=s,this.webSocketObserver=new t.Subject,this.allMessagesObserver=new t.Subject,this.connectionReady=new t.BehaviorSubject(!1),this.seenMessageIds=new Set,this.destructSubject=new t.Subject,this.clientTooOldThreshold=3e4,this.destructManager.onDestruct((async()=>{await this.destruct()})),this.setupMessageAcknowledgments(),this.connect(),this.lastTick=new Date,this.tickInterval=setInterval((()=>this.tick()),5e3),this.observeConnectionReady().pipe((0,t.skip)(1),(0,t.filter)((e=>!e)),(0,t.switchMap)((()=>(0,t.race)((0,t.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,t.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value?Se.debug(this.clientIdService.getClientId(),"Client reconnected before becoming too old. Ignoring..."):this.destructManager.isDestructing||(Se.debug(this.clientIdService.getClientId(),"Client disconnected for a long period - refreshing"),this.refreshClient())})),this.observeConnectionReady().pipe((0,t.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientNotTooOld()}))}refreshClient(){this.destructManager.isDestructing?Se.debug(this.clientIdService.getClientId(),"Client too old but is destructed. Ignoring..."):this.clientIdService.isClientTooOld()?Se.debug(this.clientIdService.getClientId(),"Client is already marked as too old. Ignoring..."):(Se.debug(this.clientIdService.getClientId(),"Notifying client too old"),this.clientIdService.notifyClientTooOld(),Se.debug(this.clientIdService.getClientId(),"Client too old. Reconnecting..."),this.connect())}tick(){Math.abs(Date.now()-this.lastTick.getTime())>this.clientTooOldThreshold&&(Se.debug(this.clientIdService.getClientId(),"Tick: Client not responding for a long time. Refreshing..."),this.refreshClient()),this.lastTick=new Date}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,t.distinctUntilChanged)())}sendMessage(e){this.sendMessageAsync(e).then()}async sendMessageAsync(e){var r;await(0,t.firstValueFrom)(this.connectionReady.pipe((0,t.filter)(Boolean)));const n=await this.authManager.getToken();if(this.connectionReady.value)try{(0,B.assertTruthy)(this.socket,"Socket is undefined in sendMessageAsync");const t=ve({message:e,authToken:n});Se.debug(this.clientIdService.getClientId(),"Sending message to socket: ",t),this.socket.send(t)}catch(t){(null===(r=this.socket)||void 0===r?void 0:r.connected)?console.error("Websocket message is ignored due to a non-recoverable error",t):(this.connectionReady.next(!1),await this.sendMessageAsync(e))}else await this.sendMessageAsync(e)}sendKillMessage(){var e;(null===(e=this.socket)||void 0===e?void 0:e.connected)&&this.socket.send(ve({message:{type:"kill"}}))}connect(){var e;null===(e=this.socket)||void 0===e||e.close(),this.connectionReady.value&&this.connectionReady.next(!1);const t=Ya(this.region,this.appId,"ws/general").replace("https","wss").replace("http","ws"),r=this.clientIdService.getClientId();Se.debug(this.clientIdService.getClientId(),"Connecting to socket at:",t);const n=`${t}?clientId=${r}`;this.socket=function(e,t={}){let r,n=0,i=1;const o={connected:!1,open(){var i;const s=null!==(i=null==Nu?void 0:Nu.WebSocket)&&void 0!==i?i:Nu;r=new s(e,t.protocols||[]),r.onmessage=t.onmessage||Pu,r.onopen=function(e){o.connected=!0,(t.onopen||Pu)(e),n=0},r.onclose=function(e){if(o.connected=!1,4999!==e.code&&4001!==e.code)return Se.debug("WebSocket closed. Reconnecting. Close code: ",e.code),(t.onclose||Pu)(e),void o.reconnect(e);(t.onclose||Pu)(e)},r.onerror=function(e){o.connected=!1,e&&"ECONNREFUSED"===e.code?o.reconnect(e):(t.onerror||Pu)(e)}},reconnect(e){const r=void 0!==t.maxAttempts?t.maxAttempts:1/0;i&&n++<r?i=setTimeout((function(){(t.onreconnect||Pu)(e),Se.debug("WebSocket trying to reconnect..."),o.open()}),t.timeout||1e3):(t.onmaximum||Pu)(e)},json(e){r.send(JSON.stringify(e))},send(e){r.send(e)},close(e=4999,t){try{o.connected=!1,clearTimeout(i),i=void 0,r.close(e,t)}catch(e){}}};return o.open(),o}(n,{timeout:5e3,onmessage:e=>this.onMessage(e.data),onopen:()=>{Se.debug(this.clientIdService.getClientId(),`Connection to socket established. Endpoint: ${t}`)},onreconnect:()=>{Se.debug(r,"WebSocket reconnect event triggered"),this.clientIdService.getClientId()===r?this.connectionReady.value&&this.connectionReady.next(!1):Se.debug(r,`WebSocket reconnect event triggered - ignored because the client id changed. Old: ${this.clientIdService.getClientId()}`)},onclose:()=>{Se.debug(r,"WebSocket onclose event triggered"),this.clientIdService.getClientId()===r?this.connectionReady.value&&this.connectionReady.next(!1):Se.debug(r,`WebSocket onclose event triggered - ignored because the client id changed. new: ${this.clientIdService.getClientId()}`)},onerror:e=>console.error("WebSocket error:",e)})}disconnectForTest(){var e;this.connectionReady.next(!1),null===(e=this.socket)||void 0===e||e.close(4998)}onConnectionReady(){this.connectionReady.next(!0),this.sendMessage({type:"catchup"})}onMessage(e){if("connectionReady"===e)return Se.debug(this.clientIdService.getClientId(),"Got socket message: connectionReady"),void this.onConnectionReady();const t=ye(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),Se.debug(this.clientIdService.getClientId(),new Date,"Got socket message",JSON.stringify(e,null,2)),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}setupMessageAcknowledgments(){const e=new t.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const r=[];e.pipe((0,t.tap)((e=>r.push(e))),(0,t.debounceTime)(100)).subscribe((async()=>{const e=[...r.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){var e;this.sendKillMessage(),await(0,t.firstValueFrom)((0,t.timer)(0)),this.connectionReady.next(!1),await(0,t.firstValueFrom)((0,t.timer)(0)),clearInterval(this.tickInterval),null===(e=this.socket)||void 0===e||e.close(),this.webSocketObserver.complete(),this.allMessagesObserver.complete(),this.destructSubject.next()}}function Cu(e,t){return`${function(e){const[t,r,n,i]=e.split("-");return(0,B.assertTruthy)(!i,"Invalid appId: "+e),{appId:t,environmentId:null!=r?r:"prod",squidDeveloperId:n}}(e).appId}${t&&"prod"!==t?`-${t}`:""}`}class qu{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 Lu{constructor(e){this.options=e,this.destructManager=new ft,(0,B.assertTruthy)(e.appId,"APP_ID_MUST_BE_PROVIDED");for(const e of Object.getOwnPropertyNames(Object.getPrototypeOf(this))){const t=this[e];"function"!=typeof t||"constructor"===e||e.startsWith("_")||(this[e]=t.bind(this))}const t="prod"!==e.environmentId&&e.squidDeveloperId,r=function(e,t,r){return`${Cu(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return Wa(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new we(this.destructManager),this.authManager=new ge(e.apiKey,e.authProvider),this.socketManager=new Ru(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,this.authManager),this.rpcManager=new Mu(e.region,r,this.destructManager,n,this.authManager,this.clientIdService),this.aiClientFactory=new H(this.rpcManager,this.socketManager),this.aiClient=new J(this.aiClientFactory,this.rpcManager),this.apiClient=new Z(this.rpcManager),this.documentStore=new mt,this.lockManager=new Ou,this.distributedLockManager=new pt(this.socketManager,this.destructManager),this.documentIdentityService=new yt(this.documentStore,this.destructManager),this.documentReferenceFactory=new bt(this.documentIdentityService),this.querySender=new lu(this.rpcManager,this.destructManager),this.querySubscriptionManager=new mu(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService,this.querySender),this.localQueryManager=new uu(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const i=new Ha(this.rpcManager,this.lockManager,this.querySender);this.queryBuilderFactory=new ze(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.dataManager=new ht(this.documentStore,i,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService,this.querySender),this.collectionReferenceFactory=new it(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager,this.dataManager),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new _e(this.clientIdService,this.rpcManager),this.nativeQueryManager=new Ka(this.rpcManager),this.apiManager=new me(this.clientIdService,this.rpcManager),this.graphqlClientFactory=new Ga(this.rpcManager,e.region,r),this.secretClient=new ku(this.rpcManager),this._connectionDetails=new ot(this.clientIdService,this.socketManager),this.queueManagerFactory=new Su(this.rpcManager,this.socketManager,this.destructManager)}static getInstance(e){const t=pe(e);let r=Lu.squidInstancesMap[t];return r||(r=new Lu(e),Lu.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(Lu.squidInstancesMap)}setAuthProvider(e){this.authManager.setAuthProvider(e)}collection(e,t=ke.built_in_db){return this._validateNotDestructed(),this.collectionReferenceFactory.get(e,t)}runInTransaction(e){return this._validateNotDestructed(),this.dataManager.runInTransaction(e)}executeFunction(e,...r){return this._validateNotDestructed(),(0,t.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...r))}executeNativeRelationalQuery(e,t,r={}){const n={type:"relational",query:t,params:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}executeNativeMongoQuery(e,t,r){const n={type:"mongo",collectionName:t,aggregationPipeline:r,integrationId:e};return this.nativeQueryManager.executeNativeQuery(n)}callApi(e,r,n={},i,o){return this._validateNotDestructed(),(0,t.firstValueFrom)(this.apiManager.callApiAndSubscribe(e,r,n,i||{},o))}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 qu(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=ke.built_in_queue){return this._validateNotDestructed(),this.queueManagerFactory.get(t,e)}async destruct(){return this.destructManager.destruct().finally((()=>{const e=Object.entries(Lu.squidInstancesMap).find((([,e])=>e===this));e&&delete Lu.squidInstancesMap[e[0]]}))}connectionDetails(){return this._validateNotDestructed(),this._connectionDetails}async _unsubscribe(){this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()}_validateNotDestructed(){(0,B.assertTruthy)(!this.destructManager.isDestructing,"The client was already destructed.")}}Lu.squidInstancesMap={}})();var i=exports;for(var o in n)i[o]=n[o];n.__esModule&&Object.defineProperty(i,"__esModule",{value:!0})})();
|
|
@@ -7,11 +7,11 @@ import { DocumentData } from '../public-types/document.public-types';
|
|
|
7
7
|
import { MutationType } from '../public-types/mutation.public-types';
|
|
8
8
|
import { ClientId, SquidDocId } from '../public-types/communication.public-types';
|
|
9
9
|
import { TopicReadContext, TopicWriteContext } from './topic.public-context';
|
|
10
|
-
import { NativeQueryContext } from './native-query.public-context';
|
|
11
10
|
import { DistributedLockContext } from './distributed-lock.public-context';
|
|
12
11
|
import { GraphqlContext } from './graphql.public-context';
|
|
13
12
|
import { AiChatbotChatContext, AiChatbotMutationContext } from './ai-chatbot.public-context';
|
|
14
13
|
import { StorageContext } from '../public-types/storage.types';
|
|
14
|
+
import { NativeQueryContext } from './native-query.public-context';
|
|
15
15
|
export type SecureDatabaseAction<T extends DatabaseActionType> = T extends 'all' ? () => boolean | Promise<boolean> : T extends 'read' ? ((context: QueryContext) => boolean | Promise<boolean>) | (() => boolean | Promise<boolean>) : ((context: MutationContext) => boolean | Promise<boolean>) | (() => boolean | Promise<boolean>);
|
|
16
16
|
export type SecureStorageAction<T extends StorageActionType> = T extends 'all' ? () => boolean | Promise<boolean> : (context: StorageContext) => boolean | Promise<boolean>;
|
|
17
17
|
export type SecureTopicAction<T extends TopicActionType> = T extends 'all' ? () => boolean | Promise<boolean> : T extends 'read' ? ((context: TopicReadContext) => boolean | Promise<boolean>) | (() => boolean | Promise<boolean>) : ((context: TopicWriteContext<T>) => boolean | Promise<boolean>) | (() => boolean | Promise<boolean>);
|
|
@@ -1,7 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
readonly clientId: ClientId;
|
|
1
|
+
import { IntegrationId } from '../public-types/communication.public-types';
|
|
2
|
+
export type NativeQueryRequestType = 'relational' | 'mongo';
|
|
3
|
+
interface BaseNativeQueryRequest {
|
|
4
|
+
type: NativeQueryRequestType;
|
|
5
|
+
integrationId: IntegrationId;
|
|
7
6
|
}
|
|
7
|
+
export interface RelationalNativeQueryRequest extends BaseNativeQueryRequest {
|
|
8
|
+
type: 'relational';
|
|
9
|
+
query: string;
|
|
10
|
+
params: Record<string, any>;
|
|
11
|
+
}
|
|
12
|
+
export interface MongoNativeQueryRequest extends BaseNativeQueryRequest {
|
|
13
|
+
type: 'mongo';
|
|
14
|
+
collectionName: string;
|
|
15
|
+
aggregationPipeline: Array<any | undefined>;
|
|
16
|
+
}
|
|
17
|
+
export type NativeQueryContext = RelationalNativeQueryRequest | MongoNativeQueryRequest;
|
|
18
|
+
export {};
|
|
@@ -3,7 +3,6 @@ import { AiChatbotChatContext as AiChatbotChatContextDeprecated, AiChatbotContex
|
|
|
3
3
|
import { ApiCallContext as ApiCallContextDeprecated, ApiHeaders as ApiHeadersDeprecated, ApiOptions as ApiOptionsDeprecated, CallApiRequest as CallApiRequestDeprecated } from '../../internal-common/src/public-types-backend/api-call.public-context';
|
|
4
4
|
import { DistributedLockContext as DistributedLockContextDeprecated } from '../../internal-common/src/public-types-backend/distributed-lock.public-context';
|
|
5
5
|
import { GraphqlContext as GraphqlContextDeprecated } from '../../internal-common/src/public-types-backend/graphql.public-context';
|
|
6
|
-
import { NativeQueryContext as NativeQueryContextDeprecated } from '../../internal-common/src/public-types-backend/native-query.public-context';
|
|
7
6
|
import { ContextConditions as ContextConditionsDeprecated, QueryContext as QueryContextDeprecated } from '../../internal-common/src/public-types-backend/query.public-context';
|
|
8
7
|
import { TopicReadContext as TopicReadContextDeprecated, TopicWriteContext as TopicWriteContextDeprecated } from '../../internal-common/src/public-types-backend/topic.public-context';
|
|
9
8
|
import { DocumentData } from '../../internal-common/src/public-types/document.public-types';
|
|
@@ -41,8 +40,6 @@ export type DistributedLockContext = DistributedLockContextDeprecated;
|
|
|
41
40
|
/** @deprecated. Use import from @squidcloud/backend. */
|
|
42
41
|
export type GraphqlContext = GraphqlContextDeprecated;
|
|
43
42
|
/** @deprecated. Use import from @squidcloud/backend. */
|
|
44
|
-
export type NativeQueryContext = NativeQueryContextDeprecated;
|
|
45
|
-
/** @deprecated. Use import from @squidcloud/backend. */
|
|
46
43
|
export type QueryContext<T extends DocumentData = any> = QueryContextDeprecated<T>;
|
|
47
44
|
/** @deprecated. Use import from @squidcloud/backend. */
|
|
48
45
|
export type ContextConditions<Doc extends DocumentData = any, F extends Paths<Doc> = Paths<Doc>> = ContextConditionsDeprecated<Doc, F>;
|
|
@@ -11,7 +11,7 @@ export * from '../../internal-common/src/public-types/integration.public-types';
|
|
|
11
11
|
export * from '../../internal-common/src/public-types/integrations/ai_chatbot.public-types';
|
|
12
12
|
export * from '../../internal-common/src/public-types/integrations/api.public-types';
|
|
13
13
|
export * from '../../internal-common/src/public-types/mutation.public-types';
|
|
14
|
-
export * from '../../internal-common/src/public-types/native-query.public-
|
|
14
|
+
export * from '../../internal-common/src/public-types-backend/native-query.public-context';
|
|
15
15
|
export * from '../../internal-common/src/public-types/openapi.public-types';
|
|
16
16
|
export * from '../../internal-common/src/public-types/query.public-types';
|
|
17
17
|
export * from '../../internal-common/src/public-types/regions.public-types';
|
package/package.json
CHANGED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
export type NativeQueryRequestType = 'relational' | 'mongo';
|
|
2
|
-
interface BaseNativeQueryRequest {
|
|
3
|
-
type: NativeQueryRequestType;
|
|
4
|
-
}
|
|
5
|
-
export interface RelationalNativeQueryRequest extends BaseNativeQueryRequest {
|
|
6
|
-
type: 'relational';
|
|
7
|
-
query: string;
|
|
8
|
-
params: Record<string, any>;
|
|
9
|
-
}
|
|
10
|
-
export interface MongoNativeQueryRequest extends BaseNativeQueryRequest {
|
|
11
|
-
type: 'mongo';
|
|
12
|
-
collectionName: string;
|
|
13
|
-
aggregationPipeline: Array<any | undefined>;
|
|
14
|
-
}
|
|
15
|
-
export type NativeQueryRequest = RelationalNativeQueryRequest | MongoNativeQueryRequest;
|
|
16
|
-
export {};
|