@squidcloud/client 1.0.98 → 1.0.99

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.
Files changed (103) hide show
  1. package/dist/cjs/index.js +1 -1
  2. package/dist/common/src/ai-assistant.context.d.ts +12 -12
  3. package/dist/common/src/ai-assistant.schemas.d.ts +1 -1
  4. package/dist/common/src/ai-assistant.types.d.ts +12 -12
  5. package/dist/common/src/api-call.context.d.ts +13 -13
  6. package/dist/common/src/api.types.d.ts +4 -4
  7. package/dist/common/src/application.schemas.d.ts +1 -1
  8. package/dist/common/src/application.types.d.ts +184 -184
  9. package/dist/common/src/backend-function.schemas.d.ts +1 -1
  10. package/dist/common/src/backend-function.types.d.ts +1 -1
  11. package/dist/common/src/backend-run.types.d.ts +2 -2
  12. package/dist/common/src/bundle-api.types.d.ts +36 -36
  13. package/dist/common/src/bundle-data.types.d.ts +4 -4
  14. package/dist/common/src/communication.types.d.ts +12 -12
  15. package/dist/common/src/context.types.d.ts +40 -40
  16. package/dist/common/src/distributed-lock.context.d.ts +5 -5
  17. package/dist/common/src/document.types.d.ts +22 -22
  18. package/dist/common/src/graphql.context.d.ts +7 -7
  19. package/dist/common/src/graphql.types.d.ts +9 -9
  20. package/dist/common/src/heartbeat.types.d.ts +1 -1
  21. package/dist/common/src/http-status.enum.d.ts +50 -50
  22. package/dist/common/src/index.d.ts +53 -53
  23. package/dist/common/src/integrations/ai_assistant.types.d.ts +30 -30
  24. package/dist/common/src/integrations/api.types.d.ts +80 -80
  25. package/dist/common/src/integrations/auth.types.d.ts +39 -39
  26. package/dist/common/src/integrations/database.types.d.ts +236 -236
  27. package/dist/common/src/integrations/index.d.ts +101 -101
  28. package/dist/common/src/integrations/observability.types.d.ts +23 -23
  29. package/dist/common/src/logger.types.d.ts +21 -21
  30. package/dist/common/src/metrics.types.d.ts +1 -1
  31. package/dist/common/src/mutation.context.d.ts +14 -14
  32. package/dist/common/src/mutation.schemas.d.ts +1 -1
  33. package/dist/common/src/mutation.types.d.ts +53 -53
  34. package/dist/common/src/named-query.context.d.ts +4 -4
  35. package/dist/common/src/named-query.schemas.d.ts +1 -1
  36. package/dist/common/src/named-query.types.d.ts +1 -1
  37. package/dist/common/src/query/base-query-builder.d.ts +196 -196
  38. package/dist/common/src/query/index.d.ts +3 -3
  39. package/dist/common/src/query/query-context.d.ts +137 -137
  40. package/dist/common/src/query/serialized-query.types.d.ts +24 -24
  41. package/dist/common/src/query.types.d.ts +59 -59
  42. package/dist/common/src/regions.d.ts +1 -1
  43. package/dist/common/src/schema/schema.types.d.ts +54 -54
  44. package/dist/common/src/secret.schemas.d.ts +1 -1
  45. package/dist/common/src/secret.types.d.ts +8 -8
  46. package/dist/common/src/security.types.d.ts +1 -1
  47. package/dist/common/src/socket.schemas.d.ts +1 -1
  48. package/dist/common/src/socket.types.d.ts +1 -1
  49. package/dist/common/src/time-units.d.ts +1 -1
  50. package/dist/common/src/trigger.types.d.ts +1 -1
  51. package/dist/common/src/types.d.ts +14 -14
  52. package/dist/common/src/utils/array.d.ts +1 -1
  53. package/dist/common/src/utils/assert.d.ts +1 -1
  54. package/dist/common/src/utils/error.d.ts +4 -4
  55. package/dist/common/src/utils/http.d.ts +2 -2
  56. package/dist/common/src/utils/id.d.ts +2 -2
  57. package/dist/common/src/utils/lock.manager.d.ts +14 -14
  58. package/dist/common/src/utils/nullish.d.ts +2 -2
  59. package/dist/common/src/utils/object.d.ts +5 -5
  60. package/dist/common/src/utils/serialization.d.ts +6 -6
  61. package/dist/common/src/utils/transforms.d.ts +18 -18
  62. package/dist/common/src/utils/url.d.ts +1 -1
  63. package/dist/common/src/utils/validation.d.ts +30 -30
  64. package/dist/common/src/webhook-response.d.ts +1 -1
  65. package/dist/esm/index.js +1 -1
  66. package/dist/node_modules/json-schema-typed/draft-2020-12.d.ts +1239 -1239
  67. package/dist/typescript-client/src/ai-assistant-client.d.ts +167 -167
  68. package/dist/typescript-client/src/ai-client.factory.d.ts +11 -11
  69. package/dist/typescript-client/src/api.manager.d.ts +15 -15
  70. package/dist/typescript-client/src/auth.manager.d.ts +23 -23
  71. package/dist/typescript-client/src/backend-function.manager.d.ts +13 -13
  72. package/dist/typescript-client/src/client-id.service.d.ts +25 -25
  73. package/dist/typescript-client/src/collection-reference.d.ts +81 -81
  74. package/dist/typescript-client/src/collection-reference.factory.d.ts +13 -13
  75. package/dist/typescript-client/src/connection-details.d.ts +23 -23
  76. package/dist/typescript-client/src/data.manager.d.ts +172 -172
  77. package/dist/typescript-client/src/destruct.manager.d.ts +12 -12
  78. package/dist/typescript-client/src/distributed-lock.manager.d.ts +19 -19
  79. package/dist/typescript-client/src/document-identity.service.d.ts +12 -12
  80. package/dist/typescript-client/src/document-reference.d.ts +140 -140
  81. package/dist/typescript-client/src/document-reference.factory.d.ts +13 -13
  82. package/dist/typescript-client/src/document-store.d.ts +11 -11
  83. package/dist/typescript-client/src/graphql-client.d.ts +14 -14
  84. package/dist/typescript-client/src/graphql-client.factory.d.ts +11 -11
  85. package/dist/typescript-client/src/index.d.ts +8 -8
  86. package/dist/typescript-client/src/mutation/mutation-sender.d.ts +10 -10
  87. package/dist/typescript-client/src/named-query.manager.d.ts +12 -12
  88. package/dist/typescript-client/src/query/deserializer.d.ts +3 -3
  89. package/dist/typescript-client/src/query/join-query-builder.factory.d.ts +161 -161
  90. package/dist/typescript-client/src/query/local-query-manager.d.ts +9 -9
  91. package/dist/typescript-client/src/query/query-builder.factory.d.ts +76 -76
  92. package/dist/typescript-client/src/query/query-subscription.manager.d.ts +170 -170
  93. package/dist/typescript-client/src/rpc.manager.d.ts +29 -29
  94. package/dist/typescript-client/src/socket.manager.d.ts +33 -33
  95. package/dist/typescript-client/src/squid.d.ts +218 -218
  96. package/dist/typescript-client/src/state/action.applier.d.ts +7 -7
  97. package/dist/typescript-client/src/state/actions.d.ts +29 -29
  98. package/dist/typescript-client/src/state/path_trie.d.ts +27 -27
  99. package/dist/typescript-client/src/state/state.service.d.ts +22 -22
  100. package/dist/typescript-client/src/state/state.service.spec.d.ts +1 -1
  101. package/dist/typescript-client/src/testing/setup-tests.d.ts +1 -1
  102. package/dist/typescript-client/src/types.d.ts +2 -2
  103. package/package.json +1 -1
@@ -1 +1 @@
1
- export {};
1
+ export {};
@@ -1,4 +1,4 @@
1
- export declare class CodeExecutionError extends Error {
2
- readonly details?: string | undefined;
3
- constructor(error: string, details?: string | undefined);
4
- }
1
+ export declare class CodeExecutionError extends Error {
2
+ readonly details?: string | undefined;
3
+ constructor(error: string, details?: string | undefined);
4
+ }
@@ -1,2 +1,2 @@
1
- export declare function getApplicationUrl(regionPrefix: string, appId: string, path: string): string;
2
- export declare function getApplicationHttpHeaders(regionPrefix: string, appId: string): Record<string, string>;
1
+ export declare function getApplicationUrl(regionPrefix: string, appId: string, path: string): string;
2
+ export declare function getApplicationHttpHeaders(regionPrefix: string, appId: string): Record<string, string>;
@@ -1,2 +1,2 @@
1
- export declare function generateId(): string;
2
- export declare function generateShortId(length?: number): string;
1
+ export declare function generateId(): string;
2
+ export declare function generateShortId(length?: number): string;
@@ -1,14 +1,14 @@
1
- type LockMutex = string;
2
- /**
3
- * A simple lock manager that locks a list of mutexes.
4
- * When locking a list of mutexes, the lock will start only when all the mutexes are available - preventing partial lock
5
- * and potential deadlocks.
6
- */
7
- export declare class LockManager {
8
- private readonly locks;
9
- lock(...mutexes: LockMutex[]): Promise<void>;
10
- release(...mutexes: LockMutex[]): void;
11
- canGetLock(...mutexes: LockMutex[]): boolean;
12
- lockSync(...mutexes: LockMutex[]): void;
13
- }
14
- export {};
1
+ type LockMutex = string;
2
+ /**
3
+ * A simple lock manager that locks a list of mutexes.
4
+ * When locking a list of mutexes, the lock will start only when all the mutexes are available - preventing partial lock
5
+ * and potential deadlocks.
6
+ */
7
+ export declare class LockManager {
8
+ private readonly locks;
9
+ lock(...mutexes: LockMutex[]): Promise<void>;
10
+ release(...mutexes: LockMutex[]): void;
11
+ canGetLock(...mutexes: LockMutex[]): boolean;
12
+ lockSync(...mutexes: LockMutex[]): void;
13
+ }
14
+ export {};
@@ -1,2 +1,2 @@
1
- export declare function isNotNullish<T>(t: T | undefined | null): t is T;
2
- export declare function isString(t: unknown): t is string;
1
+ export declare function isNotNullish<T>(t: T | undefined | null): t is T;
2
+ export declare function isString(t: unknown): t is string;
@@ -1,5 +1,5 @@
1
- export declare function getInPath(obj: any, path: string, delimiter?: string): any;
2
- export declare function setInPath(obj: any, path: string, value: any, delimiter?: string): void;
3
- export declare function deleteInPath(obj: any, path: string, delimiter?: string): void;
4
- export declare function replaceKeyInMap<K, T>(map: Map<K, T | undefined>, a: K, b: K): void;
5
- export declare function replaceKeyInRecord<K extends keyof any, T>(record: Record<K, T>, a: K, b: K): void;
1
+ export declare function getInPath(obj: any, path: string, delimiter?: string): any;
2
+ export declare function setInPath(obj: any, path: string, value: any, delimiter?: string): void;
3
+ export declare function deleteInPath(obj: any, path: string, delimiter?: string): void;
4
+ export declare function replaceKeyInMap<K, T>(map: Map<K, T | undefined>, a: K, b: K): void;
5
+ export declare function replaceKeyInRecord<K extends keyof any, T>(record: Record<K, T>, a: K, b: K): void;
@@ -1,6 +1,6 @@
1
- export declare function normalizeJsonAsString(json: any): string;
2
- export declare function serializeObj(obj: any): string;
3
- export declare function deserializeObj<T = any>(str: string): T;
4
- export declare function encodeValueForMapping(value: any): string;
5
- export declare function decodeValueForMapping(encodedString: string): any;
6
- export declare function recodeValue(value: any): any;
1
+ export declare function normalizeJsonAsString(json: any): string;
2
+ export declare function serializeObj(obj: any): string;
3
+ export declare function deserializeObj<T = any>(str: string): T;
4
+ export declare function encodeValueForMapping(value: any): string;
5
+ export declare function decodeValueForMapping(encodedString: string): any;
6
+ export declare function recodeValue(value: any): any;
@@ -1,18 +1,18 @@
1
- export declare function unchanged(any: any): any;
2
- export declare function booleanToInt(boolean: boolean): number;
3
- export declare function intToBoolean(int: number): boolean;
4
- export declare function stringToNumber(string: string): number;
5
- export declare function numberToString(number: number): string;
6
- export declare function bufferToString(buffer: ArrayBuffer): string;
7
- export declare function stringToBuffer(string: string): ArrayBuffer;
8
- export declare function stringToJSON(string: string): JSON;
9
- export declare function JSONToString(json: JSON): string;
10
- export declare function moneyStringToNumber(money: string): number;
11
- export declare function daysPastEpochToDate(days: number): Date;
12
- export declare function msToDate(ms: number): Date;
13
- export declare function isoStringToDate(string: string): Date;
14
- export declare function base64ToString(string: string): string;
15
- export declare function base64ToBinary(string: string): string;
16
- export declare function kafkaConnectStringToInterval(string: string): Record<string, number>;
17
- export declare function msPastMidnightToTimeString(ms: number): string;
18
- export declare function dateToTimeString(date: Date): string;
1
+ export declare function unchanged(any: any): any;
2
+ export declare function booleanToInt(boolean: boolean): number;
3
+ export declare function intToBoolean(int: number): boolean;
4
+ export declare function stringToNumber(string: string): number;
5
+ export declare function numberToString(number: number): string;
6
+ export declare function bufferToString(buffer: ArrayBuffer): string;
7
+ export declare function stringToBuffer(string: string): ArrayBuffer;
8
+ export declare function stringToJSON(string: string): JSON;
9
+ export declare function JSONToString(json: JSON): string;
10
+ export declare function moneyStringToNumber(money: string): number;
11
+ export declare function daysPastEpochToDate(days: number): Date;
12
+ export declare function msToDate(ms: number): Date;
13
+ export declare function isoStringToDate(string: string): Date;
14
+ export declare function base64ToString(string: string): string;
15
+ export declare function base64ToBinary(string: string): string;
16
+ export declare function kafkaConnectStringToInterval(string: string): Record<string, number>;
17
+ export declare function msPastMidnightToTimeString(ms: number): string;
18
+ export declare function dateToTimeString(date: Date): string;
@@ -1 +1 @@
1
- export declare function appendQueryParams(url: string, queryParams: Record<string, any>): string;
1
+ export declare function appendQueryParams(url: string, queryParams: Record<string, any>): string;
@@ -1,30 +1,30 @@
1
- /**
2
- * This file contains general validators for the different objects being received from the client. The parameters are
3
- * usually of type 'any' to make sure there are no assumptions that the object has the correct type.
4
- * Also, this file should avoid importing from other files that are not for validation to avoid circular deps.
5
- */
6
- import { OpenIdProvider } from '../application.types';
7
- import { HttpStatus } from '../http-status.enum';
8
- export type StatusCode = HttpStatus.BAD_REQUEST | HttpStatus.NOT_FOUND | HttpStatus.FORBIDDEN | HttpStatus.UNAUTHORIZED | HttpStatus.CONFLICT;
9
- export declare class ValidationError extends Error {
10
- readonly statusCode: StatusCode;
11
- readonly details?: any;
12
- constructor(error: string, statusCode: StatusCode, details?: Record<string, any>);
13
- }
14
- export declare function validateFieldSort(fieldSort: any): void;
15
- export declare function validateOpenIdProvider(openIdProvider: OpenIdProvider | undefined): OpenIdProvider;
16
- export declare function validateOpenIdProviderType(providerType: any): void;
17
- export declare function validateMutations(mutations: any): void;
18
- export declare function validateQueryLimit(limit: any): void;
19
- /** Returns true if the value is not an empty string (undefined/null are considered empty). */
20
- export declare function isNotEmpty(value: string | undefined | null): value is string;
21
- /**
22
- * All type names returned by 'typeof' supported by JavaScript:
23
- * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof}.
24
- * and a few other supported types.
25
- */
26
- export type JavascriptTypeName = 'undefined' | 'object' | 'boolean' | 'number' | 'bigint' | 'string' | 'symbol' | 'function';
27
- /** Returns true if 'typeof' of the 'value' is 'type' or 'type[]'. */
28
- export declare function isRightType(value: unknown, type: JavascriptTypeName): boolean;
29
- /** Returns true if 'obj' has only keys listed in the 'keys'. Object can't be an array. */
30
- export declare function hasOnlyKeys(obj: object, keys: string[]): boolean;
1
+ /**
2
+ * This file contains general validators for the different objects being received from the client. The parameters are
3
+ * usually of type 'any' to make sure there are no assumptions that the object has the correct type.
4
+ * Also, this file should avoid importing from other files that are not for validation to avoid circular deps.
5
+ */
6
+ import { OpenIdProvider } from '../application.types';
7
+ import { HttpStatus } from '../http-status.enum';
8
+ export type StatusCode = HttpStatus.BAD_REQUEST | HttpStatus.NOT_FOUND | HttpStatus.FORBIDDEN | HttpStatus.UNAUTHORIZED | HttpStatus.CONFLICT;
9
+ export declare class ValidationError extends Error {
10
+ readonly statusCode: StatusCode;
11
+ readonly details?: any;
12
+ constructor(error: string, statusCode: StatusCode, details?: Record<string, any>);
13
+ }
14
+ export declare function validateFieldSort(fieldSort: any): void;
15
+ export declare function validateOpenIdProvider(openIdProvider: OpenIdProvider | undefined): OpenIdProvider;
16
+ export declare function validateOpenIdProviderType(providerType: any): void;
17
+ export declare function validateMutations(mutations: any): void;
18
+ export declare function validateQueryLimit(limit: any): void;
19
+ /** Returns true if the value is not an empty string (undefined/null are considered empty). */
20
+ export declare function isNotEmpty(value: string | undefined | null): value is string;
21
+ /**
22
+ * All type names returned by 'typeof' supported by JavaScript:
23
+ * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof}.
24
+ * and a few other supported types.
25
+ */
26
+ export type JavascriptTypeName = 'undefined' | 'object' | 'boolean' | 'number' | 'bigint' | 'string' | 'symbol' | 'function';
27
+ /** Returns true if 'typeof' of the 'value' is 'type' or 'type[]'. */
28
+ export declare function isRightType(value: unknown, type: JavascriptTypeName): boolean;
29
+ /** Returns true if 'obj' has only keys listed in the 'keys'. Object can't be an array. */
30
+ export declare function hasOnlyKeys(obj: object, keys: string[]): boolean;
@@ -1 +1 @@
1
- export {};
1
+ export {};
package/dist/esm/index.js CHANGED
@@ -9,4 +9,4 @@ import*as e from"rxjs";import*as t from"cross-fetch";import*as r from"socket.io-
9
9
  ${e.query}
10
10
  `,variables:e.variables})).data}async mutate(e){return(await this.client.mutate({mutation:ka`
11
11
  ${e.query}
12
- `})).data}}class Ra{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 Aa(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class Pa{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySubscriptionManager=r}async sendMutations(e,t){const r=W(e),n=r.map((e=>`sendMutation_${U(e.squidDocIdObj)}`));await this.lockManager.lock(...n),await this.querySubscriptionManager.waitForAllQueriesToFinish();try{const e={mutations:r,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}finally{this.lockManager.release(...n)}}}class ja{constructor(e,t){this.rpcManager=e,this.socketManager=t,this.ongoingNamedQueryExecutions={},t.observeNotifications().pipe((0,E.filter)((e=>"namedQuery"===e.type)),Ue((e=>e))).subscribe((e=>{this.handleNamedQueryResponse(e.clientRequestId,e.payload)}))}executeNamedQueryAndSubscribe(e,t,r){const n=se(),i=new E.Subject;this.ongoingNamedQueryExecutions[n]=i;const o={integrationId:e,queryName:t,paramsRecordStr:f(r),clientRequestId:n};return this.rpcManager.post("named-query/execute",o).catch((r=>{console.error("Got error while executing named query",t,"for integration",e,r),i.error(r),i.complete()})),i.pipe((0,E.finalize)((()=>{delete this.ongoingNamedQueryExecutions[n]})),(0,E.share)())}handleNamedQueryResponse(e,t){const r=this.ongoingNamedQueryExecutions[e];if(!r)return;const n=d(t);n.success?r.next(n.result):(r.error(new Error(n.result)),r.complete())}}class Ca{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 w(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[U(e.__docId__,r,t)]))}}function $a(e,t){return le((function(r,n){var i=0;r.subscribe(Ve(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}var Ma;function Fa(e){return[Ma.SET_PATH,Ma.DELETE_PATH].includes(e.type)}function qa(e){return e.type===Ma.BATCH_ACTION}function La(e){const t=[];if(Fa(e))t.push(e);else if(qa(e))for(const r of e.payload)t.push(...La(r));return t}function Va(e,t){return Ua(e,t)}function Qa(e){return"object"==typeof e}function Ua(e,t){let r=e;if(Fa(t))r=function(e,t,r=[]){switch(t.type){case Ma.DELETE_PATH:return Ba(e,t.path);case Ma.SET_PATH:const n=t;return function(e,t,r,n){return za(e,t,r,n)}(e,t.path,r,n.payload);case Ma.BATCH_ACTION:throw new Error("Unsupported")}}(e,t,[]);else{if(!qa(t))throw new Error(`Invalid action type: ${t.type}`);r=t.payload.reduce(((e,t)=>Ua(e,t)),e)}return r}function Ba(e,t){if(!t.length)throw new Error("can not delete an empty path");const r=t[0];if(1===t.length)return function(e,t){if(e instanceof Array)throw new Error("Cannot remove an item from an array");const r=Object.assign({},e);return delete r[t],r}(e,r);const n=t.slice(1),i=Wa(e,r);if(!i)return e;if(!Qa(i))throw new Error("Cannot delete from a non object state.");const o=Ba(i,n);return o===i?e:Ya(e,r,o)}function za(e,t,r,n){if(!t.length){if(Qa(n))return n;throw new Error("Relative path cannot be of length 0 when the new value is not an object.")}const i=t[0],o=[...r,i];if(1===t.length)return Ya(e,i,n);const s=t.slice(1),a=Wa(e,i);return void 0!==a&&Qa(a)?Ya(e,i,za(a,s,o,n)):za(e=Ya(e,i,{}),t,r,n)}function Ya(e,t,r){return(e=Object.assign({},e))[t]=r,e}function Wa(e,t){return e instanceof Array?e[function(e){const t=Number(e);if(isNaN(t))throw new Error(`The value is not a number: Actual: ${e}`);return Math.floor(t)}(t)]:e[t]}!function(e){e.DELETE_PATH="DELETE_PATH",e.SET_PATH="SET_PATH",e.BATCH_ACTION="BATCH_ACTION"}(Ma||(Ma={}));class Ka{constructor(){this.root=new Ha}getOrCreatePathTrieNode(e,t){let r=this.root;for(const t of e)r.children.get(t)||r.children.set(t,new Ha),r=r.children.get(t);return void 0!==t&&(r.nodeData=t),r}getPathTrieNode(e){let t=this.root;for(const r of e){if(!t)return;t=t.children.get(r)}return t}getPathTrie(e){let t=this.root;for(const r of e){if(!t)return;t=t.children.get(r)}if(t){const e=new Ka;return e.root=t,e}}iterateBfs(e){this.iterateInternal(this.root,e,[])}removeNode(e){e.length||(this.root=new Ha);const t=[this.root];for(const r of e){const e=t[t.length-1].children.get(r);if(!e)throw new Error("Node does not exist");t.push(e)}for(let r=t.length-1;r>0;r--){const n=t[r],i=e[r-1];if((n.nodeData||n.children.size)&&r!==t.length-1)break;t[r-1].children.delete(i)}}clearNodeData(e){const t=this.getPathTrieNode(e);t&&(t.nodeData=void 0,t.children.size||this.removeNode(e))}getNodeList(e){const t=[];let r=this.root;for(const n of e){if(!r)return t;t.push(r),r=r.children.get(n)}return t}iterateInternal(e,t,r){if(!1!==t(e.nodeData,r))for(const[n,i]of e.children)this.iterateInternal(i,t,r.concat(n))}}class Ha{constructor(){this.children=new Map([])}}class Ga{constructor(){this.subscriptionsTree=new Ka,this.state={},this.batchCount=0,this.batchedActions=[]}dispatch(e){this.batchCount>0&&this.batchedActions.push(e),this.state=Va(this.state,e),0===this.batchCount&&this.dispatchSubscriptions(e)}runInBatch(e){this.batchCount++;try{e()}finally{if(this.batchCount--,0===this.batchCount&&this.batchedActions.length){const e={type:Ma.BATCH_ACTION,payload:[...this.batchedActions]};this.batchedActions.splice(0),this.dispatch(e)}}}observePath(e,t){return new E.Observable((r=>{const n=this.getOrCreateSubjectForPath(e);r.next(this.getStateInPath(e));const i=n.pipe($a((e=>{if(!t)return!0;const r=new Ka,n=t();for(const e of n)r.getOrCreatePathTrieNode(e,!0);const i=La(e.action).map((e=>e.path));let o=!1;for(const e of i)if(0===r.getNodeList(e).length){o=!0;break}return o})),Ue((e=>e.data))).subscribe(r);return()=>{i.unsubscribe(),n.observed||(n.complete(),this.subscriptionsTree.clearNodeData(e))}}))}setKeyInPath(e,t,r,n=!1){this.setInPath([...e,t],r,n)}setPartial(e,t,r=!1){let n=this.getStateInPath(e);n||(n={}),this.setInPath(e,Object.assign(Object.assign({},n),t),r)}setInPath(e,t,r=!1){if(r&&this.getStateInPath(e)===t)return;const n={type:Ma.SET_PATH,path:e,payload:t};this.dispatch(n)}pushToArray(e,t){let r=this.getStateInPath(e);r=r?[...r]:[],r.push(t),this.setInPath(e,r)}deletePath(e){const t={type:Ma.DELETE_PATH,path:e};this.dispatch(t)}getState(){return this.state}getStateInPath(e){return Ja(this.state,e)}destroy(){this.subscriptionsTree.iterateBfs((e=>{e&&e.subject&&e.subject.complete()}))}getOrCreateSubjectForPath(e){const t=this.subscriptionsTree.getOrCreatePathTrieNode(e);t.nodeData||(t.nodeData=new Za);const r=t.nodeData;return r.subject||(r.subject=new E.Subject),r.subject}dispatchSubscriptions(e){const t=function(e,t){const r=new Ka;for(const n of La(e)){let e=r.getOrCreatePathTrieNode(n.path);if(!t||e.nodeData)continue;let i=t.getPathTrieNode(n.path);if(i){const t=[[e,i]];for(;t.length;){const r=t.shift();if(e=r[0],i=r[1],!e.nodeData){for(const[r,n]of i.children)e.children.get(r)||e.children.set(r,new Ha),t.push([e.children.get(r),n]);e.nodeData=!0}}}}return r}(e,this.subscriptionsTree);t.iterateBfs(((t,r)=>{const n=this.subscriptionsTree.getPathTrieNode(r);n&&n.nodeData&&n.nodeData.subject.next({action:e,data:Ja(this.getState(),r)})}))}}function Ja(e,t){let r=e;for(const e of t){if(null==r)return;if(!Qa(r))throw new Error("result must be a state object");r=r[e]}return r}class Za{}const Xa="client";class ec{constructor(e,t,r,n,i){this.rpcManager=e,this.clientIdService=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.safeToSendQueriesToServer=new E.BehaviorSubject(!0),this.onOrphanDocuments=new E.Subject,this.ongoingQueries=new Map,this.inflightQueriesCount=new E.BehaviorSubject(0),this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new rc,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe((()=>{this.refreshOngoingQueries()})),this.destructManager.onPreDestruct((()=>{this.predestruct()}))}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return A(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=A(this.ongoingQueries.get(e));t.gotInitialResponse?this.removeClientRequestIdMapping(e):t.gotInitialResponse=!0}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=Q(t),i=this.queryMappingManager.getMapping(Xa,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=d(n);let s;if(m(e)){const n=null!==(r=R(t,e.fieldName))&&void 0!==r?r:null;s=v(e.value,n,e.operator)}else s=tc(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&&(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)continue;const n=this.clientRequestIdToLocalDocuments.get(r),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=A(null==s?void 0:s.supportingOngoingQuery);o&&t.add(s),e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);A(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 w(e.query);for(const r of this.ongoingQueries.values())if(e!==r&&this.isValidParent(r)&&t.isSubqueryOfQuery(r.query))return r}findValidParentOfQuery(e){const t=new w(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,r,n,i,o){return(0,E.defer)((()=>{const s=this.createOngoingQueryGraph(e,t,r,n,i,!0);o&&(s.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(s),s.allObservables=new E.ReplaySubject(1);const a=s.allObservables.pipe((0,E.switchMap)((e=>(0,E.combineLatest)(e).pipe(Ue((e=>this.joinResults(e,n,s)))))),$a((()=>this.allOngoingQueriesGotInitialResult(s))),(0,E.startWith)(void 0),(0,E.pairwise)(),$a((([e,t])=>!c.isEqual(e,t))),Ue((([e,t])=>t)),i?(0,E.tap)():(0,E.take)(1),(0,E.finalize)((()=>{var e;s.dataSubject.complete(),s.done=!0,this.completeAllSupportedQueries(s).then(),null===(e=s.allObservables)||void 0===e||e.complete()}))),u=this.collectAllObservables(s);return s.allObservables.next(u),a})).pipe((0,E.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=A(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r)}async waitForAllQueriesToFinish(){return(0,E.firstValueFrom)(this.inflightQueriesCount.pipe($a((e=>0===e)))).then((()=>{}))}registerQueryFinalizer(e){const t=e.clientRequestId,r=b(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,E.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,E.firstValueFrom)((0,E.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe($a((e=>0===e))))),this.queryMappingManager.removeQuery(t,r).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const r={clientRequestId:t};this.rpcManager.post("query/unsubscribe",r).catch((t=>{console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)})),$a(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,o,s={}){if(s[t])return s[t];const a=se(),c=[],u={clientRequestId:a,activated:o,alias:t,query:e,subscribe:i,dataSubject:new E.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,unsubscribeBlockerCount:new E.BehaviorSubject(0),queryRegistered:new E.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1};this.registerQueryFinalizer(u),this.ongoingQueries.set(a,u),s[t]=u;for(const[e,o]of Object.entries(n)){const a=o.leftAlias;if(a!==t&&e!==t)continue;const l=a===t?e:a;if(a===t){const e=this.createOngoingQueryGraph(r[l],l,r,n,i,!1,s);e.joinCondition=o,c.push(e)}else u.supportingOngoingQuery=this.createOngoingQueryGraph(r[l],l,r,n,i,!1,s)}return u}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe($a(Boolean),Ue((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,[]),A(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=A(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=A(t.joinCondition),i=t.query;if(t.activated){const o=A(null===(r=t.supportingOngoingQuery)||void 0===r?void 0:r.supportedQueries).filter((e=>e.alias===t.alias)),s=new Set(e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})));for(const e of o)e.query.conditions.filter(m).filter((e=>e.fieldName===n.right)).forEach((e=>{s.delete(e.value)}));if(0===s.size)return!1;const a=c.cloneDeep(i);a.conditions=a.conditions.filter((e=>!m(e)||e.fieldName!==n.right)),[...s].forEach((e=>{a.conditions.push({fieldName:n.right,operator:"==",value:e})}));const u=Object.assign(Object.assign({},t),{query:a,activated:!0,gotInitialResponse:!1,dataSubject:new E.BehaviorSubject(null),clientRequestId:se(),isEmptyForJoin:!1});return this.registerQueryFinalizer(u),this.ongoingQueries.set(u.clientRequestId,u),A(t.supportingOngoingQuery).supportedQueries.push(u),this.sendQueryToServerOrUseParentQuery(u),!0}{const r=e.map((e=>{var t;return{fieldName:n.right,operator:"==",value:null!==(t=e[n.left])&&void 0!==t?t:null}}));return t.activated=!0,r.length?(i.conditions.push(...r),this.sendQueryToServerOrUseParentQuery(t)):t.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotInitialResult(e))))}async completeAllSupportedQueries(e){const t=[...e.supportedQueries||[]];for(;t.length;){const e=A(t.shift());t.push(...e.supportedQueries||[]),await(0,E.firstValueFrom)(e.unsubscribeBlockerCount.pipe($a((e=>0===e)))),e.dataSubject.complete()}}predestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete(),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=b(this.clientIdService.getClientId(),r);this.queryMappingManager.addQuery(Xa,t,n),this.ongoingQueries.set(r,e);const i=this.findValidParentOfOngoingQuery(e);i?this.useParentOngoingQuery(e,i).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const r={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new w(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,E.firstValueFrom)(t.queryRegistered.pipe($a(Boolean)))}catch(t){return e.dataSubject.error(t),e.queryRegistered.error(t),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",r).then((()=>{e.queryRegistered.next(!0)})).catch((r=>{console.error("Query error",e.query,t.query,r),e.dataSubject.error(r),e.done=!0})).finally((()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1),e.isInFlight=!1}));const i=(0,E.race)(e.queryRegistered.pipe($a(Boolean),(0,E.delay)(2e3),(0,E.take)(1)),this.destructManager.observeIsDestructing().pipe((0,E.take)(1)));t.dataSubject.pipe((0,E.takeWhile)((()=>!e.done)),(0,E.takeUntil)(i),$a(Boolean),(0,E.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),Ue((e=>e.filter((e=>n.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(U(r.__docId__,e.query.collectionName,e.query.integrationId),r);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>e.dataSubject.error(t)})}sendQueryToServer(e){const t={query:e.query,clientRequestId:e.clientRequestId,subscribe:e.subscribe};this.safeToSendQueriesToServer.pipe($a(Boolean),(0,E.take)(1)).subscribe((()=>{e.done||(this.inflightQueriesCount.next(this.inflightQueriesCount.value+1),e.isInFlight=!0,this.rpcManager.post("query/query",t).catch((t=>{e.dataSubject.error(t),e.done=!0,e.queryRegistered.error("query failed")})).then((()=>{e.queryRegistered.next(!0)})).finally((()=>{this.inflightQueriesCount.next(this.inflightQueriesCount.value-1),e.isInFlight=!1})))}))}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=>{$(this.localDocumentToClientRequestIds,t,e[t])}))}}function tc(e,t){var r;for(const n of e.fields){const e=null!==(r=R(t,n.fieldName))&&void 0!==r?r:null;if(v(n.value,e,n.operator))return!0;if(v(n.value,e,"!="))return!1}return!1}class rc{constructor(){this.stateService=new Ga,this.querySubscriptionIdToQuery={}}addQuery(e,t,r){this.stateService.runInBatch((()=>{let e=0;const n=new Set;for(const i of t.conditions){if(m(i)&&["=="].includes(i.operator)){const t=p(i.fieldName);n.has(t)||(e++,n.add(t))}else e++;const o=this.getConditionStatePath(t,i),s=[...this.stateService.getStateInPath(o)||[]];ee(s,r),this.stateService.setInPath(o,s)}if(!t.conditions.length){const e=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.getStateInPath(e)||[]];ee(n,r),this.stateService.setInPath(e,n)}this.stateService.setInPath([...this.getQueryMetadataStatePath(t,r),"condCount"],e)})),this.querySubscriptionIdToQuery[r]=t}async removeQuery(e,t){const r=this.querySubscriptionIdToQuery[t];if(r)return this.stateService.runInBatch((()=>{for(const e of r.conditions){const n=this.getConditionStatePath(r,e),i=[...this.stateService.getStateInPath(n)||[]];te(i,t),i.length?this.stateService.setInPath(n,i):this.stateService.deletePath(n)}if(!r.conditions.length){const e=["queryMapping",r.collectionName,r.integrationId,"mapping","unconditional"],n=[...this.stateService.getStateInPath(e)||[]];te(n,t),this.stateService.setInPath(e,n)}this.stateService.deletePath(this.getQueryMetadataStatePath(r,t))})),r}getMapping(e,t,r){return this.stateService.getStateInPath(["queryMapping",t,r,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",y(t)]}}class nc{constructor(e,t,r,n,i={},o,s){this.region=e,this.appId=t,this.socketManager=r,this.destructManager=n,this.headers=i,this.authManager=o,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new E.BehaviorSubject(0);for(const[e,t]of Object.entries(i))this.setStaticHeader(e,t);const a=this.authManager.getApiKey();a&&this.setStaticHeader("Authorization",`ApiKey ${a}`),this.clientIdService.observeClientId().subscribe((e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")})),this.authManager.observeAuthIdToken().subscribe((e=>{if(e.token){let t=`Bearer ${e.token}`;e.integrationId&&(t+=`; IntegrationId ${e.integrationId}`),this.setStaticHeader("Authorization",t)}else this.deleteStaticHeader("Authorization")})),n.onDestruct((async()=>{await this.awaitAllSettled()}))}async awaitAllSettled(){await(0,E.firstValueFrom)(this.onGoingRpcCounter.pipe((0,E.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){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await(0,E.firstValueFrom)((0,E.race)(this.socketManager.observeConnectionReady().pipe((0,E.filter)(Boolean)),this.destructManager.observeIsDestructing())),await this.authManager.waitForReadyState();let r={"Content-Type":"application/json"};Object.keys(this.staticHeaders)&&(r=Object.assign(Object.assign({},r),this.staticHeaders));const n=ie(this.region,this.appId,e),i=await(0,xa.default)(n,{method:"POST",body:f(t),headers:r});let o,s;try{o=await i.text();try{s=JSON.parse(o)}catch(e){}}catch(e){o="Cannot read body"}if(!i.ok)throw new ic(i.status,i.statusText,i.headers,i.url,null==s?void 0:s.message);return s||o}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}}class ic extends Error{constructor(e,t,r,n,i){super(i||`RPC error ${e} ${t} calling ${n}`),this.statusCode=e,this.statusText=t,this.headers=r,this.url=n}}const oc=(e=>{var t={};return o.d(t,e),t})({io:()=>r.io}),sc=e=>e();class ac{constructor(e,t,r,n=sc,i,o={},s){this.clientIdService=e,this.region=t,this.appId=r,this.messageNotificationWrapper=n,this.destructManager=i,this.authManager=s,this.webSocketObserver=new E.Subject,this.allMessagesObserver=new E.Subject,this.connectionReady=new E.BehaviorSubject(!1),this.seenMessageIds=new Set,this.firstConnection=!0,this.clientTooOldThreshold=3e5,this.destructManager.onDestruct((async()=>{await this.destruct()})),this.setupMessageAcknowledgments(),this.connect(Object.assign({},o)),this.connectionReady.pipe((0,E.skip)(1),(0,E.filter)((e=>!e)),(0,E.switchMap)((()=>(0,E.race)((0,E.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,E.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value||this.destructManager.isDestructing||(this.clientIdService.notifyClientTooOld(),this.connect(Object.assign({},o)))})),this.connectionReady.pipe((0,E.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientReadyToBeRegenerated()}))}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,E.distinctUntilChanged)())}sendMessage(e){this.authManager.waitForReadyState().then((()=>{(0,E.firstValueFrom)(this.connectionReady.pipe((0,E.filter)(Boolean))).then((()=>{const t=this.authManager.getAuthToken();A(this.socket).emit("message",Object.assign(Object.assign({},e),{authToken:t}))}))}))}connect(e){const t=ie(this.region,this.appId,""),r={clientId:this.clientIdService.getClientId()};this.socket=(0,oc.io)(t,{query:r,reconnectionDelay:5e3,transports:["websocket"],extraHeaders:e}),this.socket.on("connect",(()=>{})),this.socket.on("disconnect",((e,t)=>{this.connectionReady.next(!1)})),this.socket.on("connectionReady",(()=>{this.connectionReady.next(!0),this.firstConnection||this.sendMessage({type:"catchup"}),this.firstConnection=!1})),this.socket.on("message",(e=>{const t=d(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}))}setupMessageAcknowledgments(){const e=new E.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,E.tap)((e=>t.push(e))),(0,E.debounceTime)(100)).subscribe((async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){var e;this.sendMessage({type:"kill"}),this.connectionReady.next(!1),await(0,E.firstValueFrom)((0,E.timer)(0)),null===(e=this.socket)||void 0===e||e.disconnect(),this.webSocketObserver.complete(),this.allMessagesObserver.complete()}}class cc{constructor(e){this.destructManager=new gt,this.setAuthIdToken=(e,t)=>{this.authManager.setAuthIdToken(e,t)},this.collection=(e,t=i.built_in_db)=>(this.validateNotDestructed(),this.collectionReferenceFactory.get(e,t)),this.runInTransaction=e=>(this.validateNotDestructed(),this.dataManager.runInTransaction(e)),this.executeFunction=(e,...t)=>(this.validateNotDestructed(),(0,E.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...t))),this.executeNamedQuery=(e,t,r)=>(this.validateNotDestructed(),(0,E.firstValueFrom)(this.namedQueryManager.executeNamedQueryAndSubscribe(e,t,r))),this.callApi=(e,t,r={})=>(this.validateNotDestructed(),(0,E.firstValueFrom)(this.apiManager.callApiAndSubscribe(e,t,r))),this.graphql=e=>(this.validateNotDestructed(),this.graphqlClientFactory.get(e)),this.ai=()=>(this.validateNotDestructed(),{assistant:e=>this.aiClientFactory.getAssistant(e)}),this.acquireLock=(e,t=!0)=>(this.validateNotDestructed(),this.distributedLockManager.lock(e,t)),this.destruct=async()=>{if(!this.destructManager.isDestructing)return this.destructManager.destruct().finally((()=>{const e=Object.entries(cc.squidInstancesMap).find((([,e])=>e===this));e&&delete cc.squidInstancesMap[e[0]]}))},this.connectionDetails=()=>(this.validateNotDestructed(),this._connectionDetails),this.unsubscribe=async()=>{this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()},x(e.appId,"APP_ID_MUST_BE_PROVIDED");const t="prod"!==e.environmentId&&e.squidDeveloperId,r=function(e,t,r){return`${L(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return oe(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new ft(this.destructManager),this.authManager=new lt(this.destructManager,e.apiKey),this.socketManager=new ac(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,n,this.authManager),this.rpcManager=new nc(e.region,r,this.socketManager,this.destructManager,n,this.authManager,this.clientIdService),this.documentStore=new St,this.lockManager=new ae,this.distributedLockManager=new bt(this.socketManager,this.destructManager),this.documentIdentityService=new wt(this.documentStore,this.destructManager),this.documentReferenceFactory=new Et(this.documentIdentityService),this.querySubscriptionManager=new ec(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService),this.localQueryManager=new Ca(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const o=new Pa(this.rpcManager,this.lockManager,this.querySubscriptionManager);this.queryBuilderFactory=new Je(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.collectionReferenceFactory=new dt(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager),this.dataManager=new vt(this.documentStore,o,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new ht(this.clientIdService,this.rpcManager,this.socketManager),this.namedQueryManager=new ja(this.rpcManager,this.socketManager),this.apiManager=new ut(this.clientIdService,this.rpcManager,this.socketManager,e.apiServerUrlOverrideMapping),this.graphqlClientFactory=new Ra(this.rpcManager,e.region,r),this.aiClientFactory=new ct(this.rpcManager,this.socketManager),this._connectionDetails=new pt(this.clientIdService,this.socketManager)}static getInstance(e){const t=h(e);let r=cc.squidInstancesMap[t];return r||(r=new cc(e),cc.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(cc.squidInstancesMap)}validateNotDestructed(){x(!this.destructManager.isDestructing,"The client was already destructed.")}}cc.squidInstancesMap={}})();var a=s.Jk,c=s.hx,u=s.my,l=s.g6,h=s.jP,f=s.zk,d=s.VE,p=s.Rx;export{a as Changes,c as CollectionReference,u as DocumentReference,l as GraphQLClient,h as JoinQueryBuilder,f as QueryBuilder,d as Squid,p as deserializeQuery};
12
+ `})).data}}class Ra{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 Aa(this.rpcManager,e,this.region,this.appId),this.clientsMap.set(e,t),t)}}class Pa{constructor(e,t,r){this.rpcManager=e,this.lockManager=t,this.querySubscriptionManager=r}async sendMutations(e,t){const r=W(e),n=r.map((e=>`sendMutation_${U(e.squidDocIdObj)}`));await this.lockManager.lock(...n),await this.querySubscriptionManager.waitForAllQueriesToFinish();try{const e={mutations:r,integrationId:t};return await this.rpcManager.post("mutation/mutate",e)}finally{this.lockManager.release(...n)}}}class ja{constructor(e,t){this.rpcManager=e,this.socketManager=t,this.ongoingNamedQueryExecutions={},t.observeNotifications().pipe((0,E.filter)((e=>"namedQuery"===e.type)),Ue((e=>e))).subscribe((e=>{this.handleNamedQueryResponse(e.clientRequestId,e.payload)}))}executeNamedQueryAndSubscribe(e,t,r){const n=se(),i=new E.Subject;this.ongoingNamedQueryExecutions[n]=i;const o={integrationId:e,queryName:t,paramsRecordStr:f(r),clientRequestId:n};return this.rpcManager.post("named-query/execute",o).catch((r=>{console.error("Got error while executing named query",t,"for integration",e,r),i.error(r),i.complete()})),i.pipe((0,E.finalize)((()=>{delete this.ongoingNamedQueryExecutions[n]})),(0,E.share)())}handleNamedQueryResponse(e,t){const r=this.ongoingNamedQueryExecutions[e];if(!r)return;const n=d(t);n.success?r.next(n.result):(r.error(new Error(n.result)),r.complete())}}class Ca{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 w(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[U(e.__docId__,r,t)]))}}function $a(e,t){return le((function(r,n){var i=0;r.subscribe(Ve(n,(function(r){return e.call(t,r,i++)&&n.next(r)})))}))}var Ma;function Fa(e){return[Ma.SET_PATH,Ma.DELETE_PATH].includes(e.type)}function qa(e){return e.type===Ma.BATCH_ACTION}function La(e){const t=[];if(Fa(e))t.push(e);else if(qa(e))for(const r of e.payload)t.push(...La(r));return t}function Va(e,t){return Ua(e,t)}function Qa(e){return"object"==typeof e}function Ua(e,t){let r=e;if(Fa(t))r=function(e,t,r=[]){switch(t.type){case Ma.DELETE_PATH:return Ba(e,t.path);case Ma.SET_PATH:const n=t;return function(e,t,r,n){return za(e,t,r,n)}(e,t.path,r,n.payload);case Ma.BATCH_ACTION:throw new Error("Unsupported")}}(e,t,[]);else{if(!qa(t))throw new Error(`Invalid action type: ${t.type}`);r=t.payload.reduce(((e,t)=>Ua(e,t)),e)}return r}function Ba(e,t){if(!t.length)throw new Error("can not delete an empty path");const r=t[0];if(1===t.length)return function(e,t){if(e instanceof Array)throw new Error("Cannot remove an item from an array");const r=Object.assign({},e);return delete r[t],r}(e,r);const n=t.slice(1),i=Wa(e,r);if(!i)return e;if(!Qa(i))throw new Error("Cannot delete from a non object state.");const o=Ba(i,n);return o===i?e:Ya(e,r,o)}function za(e,t,r,n){if(!t.length){if(Qa(n))return n;throw new Error("Relative path cannot be of length 0 when the new value is not an object.")}const i=t[0],o=[...r,i];if(1===t.length)return Ya(e,i,n);const s=t.slice(1),a=Wa(e,i);return void 0!==a&&Qa(a)?Ya(e,i,za(a,s,o,n)):za(e=Ya(e,i,{}),t,r,n)}function Ya(e,t,r){return(e=Object.assign({},e))[t]=r,e}function Wa(e,t){return e instanceof Array?e[function(e){const t=Number(e);if(isNaN(t))throw new Error(`The value is not a number: Actual: ${e}`);return Math.floor(t)}(t)]:e[t]}!function(e){e.DELETE_PATH="DELETE_PATH",e.SET_PATH="SET_PATH",e.BATCH_ACTION="BATCH_ACTION"}(Ma||(Ma={}));class Ka{constructor(){this.root=new Ha}getOrCreatePathTrieNode(e,t){let r=this.root;for(const t of e)r.children.get(t)||r.children.set(t,new Ha),r=r.children.get(t);return void 0!==t&&(r.nodeData=t),r}getPathTrieNode(e){let t=this.root;for(const r of e){if(!t)return;t=t.children.get(r)}return t}getPathTrie(e){let t=this.root;for(const r of e){if(!t)return;t=t.children.get(r)}if(t){const e=new Ka;return e.root=t,e}}iterateBfs(e){this.iterateInternal(this.root,e,[])}removeNode(e){e.length||(this.root=new Ha);const t=[this.root];for(const r of e){const e=t[t.length-1].children.get(r);if(!e)throw new Error("Node does not exist");t.push(e)}for(let r=t.length-1;r>0;r--){const n=t[r],i=e[r-1];if((n.nodeData||n.children.size)&&r!==t.length-1)break;t[r-1].children.delete(i)}}clearNodeData(e){const t=this.getPathTrieNode(e);t&&(t.nodeData=void 0,t.children.size||this.removeNode(e))}getNodeList(e){const t=[];let r=this.root;for(const n of e){if(!r)return t;t.push(r),r=r.children.get(n)}return t}iterateInternal(e,t,r){if(!1!==t(e.nodeData,r))for(const[n,i]of e.children)this.iterateInternal(i,t,r.concat(n))}}class Ha{constructor(){this.children=new Map([])}}class Ga{constructor(){this.subscriptionsTree=new Ka,this.state={},this.batchCount=0,this.batchedActions=[]}dispatch(e){this.batchCount>0&&this.batchedActions.push(e),this.state=Va(this.state,e),0===this.batchCount&&this.dispatchSubscriptions(e)}runInBatch(e){this.batchCount++;try{e()}finally{if(this.batchCount--,0===this.batchCount&&this.batchedActions.length){const e={type:Ma.BATCH_ACTION,payload:[...this.batchedActions]};this.batchedActions.splice(0),this.dispatch(e)}}}observePath(e,t){return new E.Observable((r=>{const n=this.getOrCreateSubjectForPath(e);r.next(this.getStateInPath(e));const i=n.pipe($a((e=>{if(!t)return!0;const r=new Ka,n=t();for(const e of n)r.getOrCreatePathTrieNode(e,!0);const i=La(e.action).map((e=>e.path));let o=!1;for(const e of i)if(0===r.getNodeList(e).length){o=!0;break}return o})),Ue((e=>e.data))).subscribe(r);return()=>{i.unsubscribe(),n.observed||(n.complete(),this.subscriptionsTree.clearNodeData(e))}}))}setKeyInPath(e,t,r,n=!1){this.setInPath([...e,t],r,n)}setPartial(e,t,r=!1){let n=this.getStateInPath(e);n||(n={}),this.setInPath(e,Object.assign(Object.assign({},n),t),r)}setInPath(e,t,r=!1){if(r&&this.getStateInPath(e)===t)return;const n={type:Ma.SET_PATH,path:e,payload:t};this.dispatch(n)}pushToArray(e,t){let r=this.getStateInPath(e);r=r?[...r]:[],r.push(t),this.setInPath(e,r)}deletePath(e){const t={type:Ma.DELETE_PATH,path:e};this.dispatch(t)}getState(){return this.state}getStateInPath(e){return Ja(this.state,e)}destroy(){this.subscriptionsTree.iterateBfs((e=>{e&&e.subject&&e.subject.complete()}))}getOrCreateSubjectForPath(e){const t=this.subscriptionsTree.getOrCreatePathTrieNode(e);t.nodeData||(t.nodeData=new Za);const r=t.nodeData;return r.subject||(r.subject=new E.Subject),r.subject}dispatchSubscriptions(e){const t=function(e,t){const r=new Ka;for(const n of La(e)){let e=r.getOrCreatePathTrieNode(n.path);if(!t||e.nodeData)continue;let i=t.getPathTrieNode(n.path);if(i){const t=[[e,i]];for(;t.length;){const r=t.shift();if(e=r[0],i=r[1],!e.nodeData){for(const[r,n]of i.children)e.children.get(r)||e.children.set(r,new Ha),t.push([e.children.get(r),n]);e.nodeData=!0}}}}return r}(e,this.subscriptionsTree);t.iterateBfs(((t,r)=>{const n=this.subscriptionsTree.getPathTrieNode(r);n&&n.nodeData&&n.nodeData.subject.next({action:e,data:Ja(this.getState(),r)})}))}}function Ja(e,t){let r=e;for(const e of t){if(null==r)return;if(!Qa(r))throw new Error("result must be a state object");r=r[e]}return r}class Za{}const Xa="client";class ec{constructor(e,t,r,n,i){this.rpcManager=e,this.clientIdService=t,this.documentStore=r,this.destructManager=n,this.documentIdentityService=i,this.safeToSendQueriesToServer=new E.BehaviorSubject(!0),this.onOrphanDocuments=new E.Subject,this.ongoingQueries=new Map,this.inflightQueriesCount=new E.BehaviorSubject(0),this.clientRequestIdToLocalDocuments=new Map,this.localDocumentToClientRequestIds=new Map,this.queryMappingManager=new rc,this.documentIdentityService.observeChanges().subscribe(this.migrateDocIds.bind(this)),this.clientIdService.observeClientReadyToBeRegenerated().subscribe((()=>{this.refreshOngoingQueries()})),this.destructManager.onPreDestruct((()=>{this.predestruct()}))}hasOngoingQuery(e){return this.ongoingQueries.has(e)}getQuery(e){return A(this.ongoingQueries.get(e),"UNKNOWN_QUERY").query}setGotInitialResult(e){const t=this.ongoingQueries.get(e);t&&!t.gotInitialResponse?t.gotInitialResponse=!0:this.removeClientRequestIdMapping(e)}findQueriesForDocument(e,t){const{collectionName:r,integrationId:n}=Q(t),i=this.queryMappingManager.getMapping(Xa,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=d(n);let s;if(m(e)){const n=null!==(r=R(t,e.fieldName))&&void 0!==r?r:null;s=v(e.value,n,e.operator)}else s=tc(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&&(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)continue;const n=this.clientRequestIdToLocalDocuments.get(r),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=A(null==s?void 0:s.supportingOngoingQuery);o&&t.add(s),e.dataSubject.next(i)}for(const e of t){const t=this.collectAllObservables(e);A(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 w(e.query);for(const r of this.ongoingQueries.values())if(e!==r&&this.isValidParent(r)&&t.isSubqueryOfQuery(r.query))return r}findValidParentOfQuery(e){const t=new w(e);for(const e of this.ongoingQueries.values())if(this.isValidParent(e)&&t.isSubqueryOfQuery(e.query))return e}processQuery(e,t,r,n,i,o){return(0,E.defer)((()=>{const s=this.createOngoingQueryGraph(e,t,r,n,i,!0);o&&(s.forceFetchFromServer=!0),this.sendQueryToServerOrUseParentQuery(s),s.allObservables=new E.ReplaySubject(1);const a=s.allObservables.pipe((0,E.switchMap)((e=>(0,E.combineLatest)(e).pipe(Ue((e=>this.joinResults(e,n,s)))))),$a((()=>this.allOngoingQueriesGotInitialResult(s))),(0,E.startWith)(void 0),(0,E.pairwise)(),$a((([e,t])=>!c.isEqual(e,t))),Ue((([e,t])=>t)),i?(0,E.tap)():(0,E.take)(1),(0,E.finalize)((()=>{var e;s.dataSubject.complete(),s.done=!0,this.completeAllSupportedQueries(s).then(),null===(e=s.allObservables)||void 0===e||e.complete()}))),u=this.collectAllObservables(s);return s.allObservables.next(u),a})).pipe((0,E.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=A(this.localDocumentToClientRequestIds.get(n));t.delete(e),t.size||(this.localDocumentToClientRequestIds.delete(n),r.push(n))}r.length&&this.onOrphanDocuments.next(r)}async waitForAllQueriesToFinish(){return(0,E.firstValueFrom)(this.inflightQueriesCount.pipe($a((e=>0===e)))).then((()=>{}))}registerQueryFinalizer(e){const t=e.clientRequestId,r=b(this.clientIdService.getClientId(),t);e.dataSubject.pipe((0,E.finalize)((async()=>{if(e.unsubscribeBlockerCount.value>0&&await(0,E.firstValueFrom)((0,E.race)(this.destructManager.observeIsDestructing(),e.unsubscribeBlockerCount.pipe($a((e=>0===e))))),this.queryMappingManager.removeQuery(t,r).then(),this.ongoingQueries.delete(t),e.subscribe&&!e.isEmptyForJoin&&e.activated){const r={clientRequestId:t};this.rpcManager.post("query/unsubscribe",r).catch((t=>{console.error("Got error while unsubscribing from query",e.query,t)}))}this.removeClientRequestIdMapping(t),this.ongoingQueries.delete(t)})),$a(Boolean)).subscribe({error:()=>{}})}createOngoingQueryGraph(e,t,r,n,i,o,s={}){if(s[t])return s[t];const a=se(),c=[],u={clientRequestId:a,activated:o,alias:t,query:e,subscribe:i,dataSubject:new E.BehaviorSubject(null),supportedQueries:c,supportingOngoingQuery:void 0,joinCondition:void 0,gotInitialResponse:!1,isEmptyForJoin:!1,unsubscribeBlockerCount:new E.BehaviorSubject(0),queryRegistered:new E.BehaviorSubject(!1),done:!1,isInFlight:!1,forceFetchFromServer:!1};this.registerQueryFinalizer(u),this.ongoingQueries.set(a,u),s[t]=u;for(const[e,o]of Object.entries(n)){const a=o.leftAlias;if(a!==t&&e!==t)continue;const l=a===t?e:a;if(a===t){const e=this.createOngoingQueryGraph(r[l],l,r,n,i,!1,s);e.joinCondition=o,c.push(e)}else u.supportingOngoingQuery=this.createOngoingQueryGraph(r[l],l,r,n,i,!1,s)}return u}collectAllObservables(e,t=[]){if(e.isEmptyForJoin)return t;const r=e.alias;t.push(e.dataSubject.pipe($a(Boolean),Ue((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,[]),A(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=A(r.shift());e.isEmptyForJoin||(t.push(e),r.push(...e.supportedQueries))}return t}updateOngoingQueryWithNewDataFromSupportingQuery(e,t){var r;const n=A(t.joinCondition),i=t.query;if(t.activated){const o=A(null===(r=t.supportingOngoingQuery)||void 0===r?void 0:r.supportedQueries).filter((e=>e.alias===t.alias)),s=new Set(e.map((e=>{var t;return null!==(t=e[n.left])&&void 0!==t?t:null})));for(const e of o)e.query.conditions.filter(m).filter((e=>e.fieldName===n.right)).forEach((e=>{s.delete(e.value)}));if(0===s.size)return!1;const a=c.cloneDeep(i);a.conditions=a.conditions.filter((e=>!m(e)||e.fieldName!==n.right)),[...s].forEach((e=>{a.conditions.push({fieldName:n.right,operator:"==",value:e})}));const u=Object.assign(Object.assign({},t),{query:a,activated:!0,gotInitialResponse:!1,dataSubject:new E.BehaviorSubject(null),clientRequestId:se(),isEmptyForJoin:!1});return this.registerQueryFinalizer(u),this.ongoingQueries.set(u.clientRequestId,u),A(t.supportingOngoingQuery).supportedQueries.push(u),this.sendQueryToServerOrUseParentQuery(u),!0}{const r=e.map((e=>{var t;return{fieldName:n.right,operator:"==",value:null!==(t=e[n.left])&&void 0!==t?t:null}}));return t.activated=!0,r.length?(i.conditions.push(...r),this.sendQueryToServerOrUseParentQuery(t)):t.isEmptyForJoin=!0,!0}}allOngoingQueriesGotInitialResult(e){return!!e.isEmptyForJoin||!!e.gotInitialResponse&&(!e.supportedQueries.length||e.supportedQueries.every((e=>this.allOngoingQueriesGotInitialResult(e))))}async completeAllSupportedQueries(e){const t=[...e.supportedQueries||[]];for(;t.length;){const e=A(t.shift());t.push(...e.supportedQueries||[]),await(0,E.firstValueFrom)(e.unsubscribeBlockerCount.pipe($a((e=>0===e)))),e.dataSubject.complete()}}predestruct(){this.safeToSendQueriesToServer.next(!1),this.safeToSendQueriesToServer.complete(),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=b(this.clientIdService.getClientId(),r);this.queryMappingManager.addQuery(Xa,t,n),this.ongoingQueries.set(r,e);const i=this.findValidParentOfOngoingQuery(e);i?this.useParentOngoingQuery(e,i).then():this.sendQueryToServer(e)}async useParentOngoingQuery(e,t){const r={clientRequestId:e.clientRequestId,query:e.query,parentClientRequestId:t.clientRequestId},n=new w(e.query);t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value+1);try{await(0,E.firstValueFrom)(t.queryRegistered.pipe($a(Boolean)))}catch(t){return e.dataSubject.error(t),e.queryRegistered.error(t),void(e.done=!0)}if(this.destructManager.isDestructing)return;if(e.done)return;this.rpcManager.post("query/register",r).then((()=>{e.queryRegistered.next(!0)})).catch((r=>{console.error("Query error",e.query,t.query,r),e.dataSubject.error(r),e.done=!0})).finally((()=>{t.unsubscribeBlockerCount.next(t.unsubscribeBlockerCount.value-1),e.isInFlight=!1}));const i=(0,E.race)(e.queryRegistered.pipe($a(Boolean),(0,E.delay)(2e3),(0,E.take)(1)),this.destructManager.observeIsDestructing().pipe((0,E.take)(1)));t.dataSubject.pipe((0,E.takeWhile)((()=>!e.done)),(0,E.takeUntil)(i),$a(Boolean),(0,E.tap)((()=>{e.gotInitialResponse||this.setGotInitialResult(e.clientRequestId)})),Ue((e=>e.filter((e=>n.documentMatchesQuery(e)))))).subscribe({next:t=>{for(const r of t)this.setClientRequestIdsForLocalDoc(U(r.__docId__,e.query.collectionName,e.query.integrationId),r);this.notifyAllSubscriptions([e.clientRequestId])},error:t=>e.dataSubject.error(t)})}sendQueryToServer(e){const t={query:e.query,clientRequestId:e.clientRequestId,subscribe:e.subscribe};this.safeToSendQueriesToServer.pipe($a(Boolean),(0,E.take)(1)).subscribe((()=>{e.done||(this.inflightQueriesCount.next(this.inflightQueriesCount.value+1),e.isInFlight=!0,this.rpcManager.post("query/query",t).catch((t=>{e.dataSubject.error(t),e.done=!0,e.queryRegistered.error("query failed")})).then((()=>{e.queryRegistered.next(!0)})).finally((()=>{this.inflightQueriesCount.next(this.inflightQueriesCount.value-1),e.isInFlight=!1})))}))}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=>{$(this.localDocumentToClientRequestIds,t,e[t])}))}}function tc(e,t){var r;for(const n of e.fields){const e=null!==(r=R(t,n.fieldName))&&void 0!==r?r:null;if(v(n.value,e,n.operator))return!0;if(v(n.value,e,"!="))return!1}return!1}class rc{constructor(){this.stateService=new Ga,this.querySubscriptionIdToQuery={}}addQuery(e,t,r){this.stateService.runInBatch((()=>{let e=0;const n=new Set;for(const i of t.conditions){if(m(i)&&["=="].includes(i.operator)){const t=p(i.fieldName);n.has(t)||(e++,n.add(t))}else e++;const o=this.getConditionStatePath(t,i),s=[...this.stateService.getStateInPath(o)||[]];ee(s,r),this.stateService.setInPath(o,s)}if(!t.conditions.length){const e=["queryMapping",t.collectionName,t.integrationId,"mapping","unconditional"],n=[...this.stateService.getStateInPath(e)||[]];ee(n,r),this.stateService.setInPath(e,n)}this.stateService.setInPath([...this.getQueryMetadataStatePath(t,r),"condCount"],e)})),this.querySubscriptionIdToQuery[r]=t}async removeQuery(e,t){const r=this.querySubscriptionIdToQuery[t];if(r)return this.stateService.runInBatch((()=>{for(const e of r.conditions){const n=this.getConditionStatePath(r,e),i=[...this.stateService.getStateInPath(n)||[]];te(i,t),i.length?this.stateService.setInPath(n,i):this.stateService.deletePath(n)}if(!r.conditions.length){const e=["queryMapping",r.collectionName,r.integrationId,"mapping","unconditional"],n=[...this.stateService.getStateInPath(e)||[]];te(n,t),this.stateService.setInPath(e,n)}this.stateService.deletePath(this.getQueryMetadataStatePath(r,t))})),r}getMapping(e,t,r){return this.stateService.getStateInPath(["queryMapping",t,r,"mapping"])}getQueryMetadataStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","queriesMetadata",`${t}`]}getConditionStatePath(e,t){return["queryMapping",e.collectionName,e.integrationId,"mapping","conditional",y(t)]}}class nc{constructor(e,t,r,n,i={},o,s){this.region=e,this.appId=t,this.socketManager=r,this.destructManager=n,this.headers=i,this.authManager=o,this.clientIdService=s,this.staticHeaders={},this.onGoingRpcCounter=new E.BehaviorSubject(0);for(const[e,t]of Object.entries(i))this.setStaticHeader(e,t);const a=this.authManager.getApiKey();a&&this.setStaticHeader("Authorization",`ApiKey ${a}`),this.clientIdService.observeClientId().subscribe((e=>{e?this.setStaticHeader("x-squid-clientid",e):this.deleteStaticHeader("x-squid-clientid")})),this.authManager.observeAuthIdToken().subscribe((e=>{if(e.token){let t=`Bearer ${e.token}`;e.integrationId&&(t+=`; IntegrationId ${e.integrationId}`),this.setStaticHeader("Authorization",t)}else this.deleteStaticHeader("Authorization")})),n.onDestruct((async()=>{await this.awaitAllSettled()}))}async awaitAllSettled(){await(0,E.firstValueFrom)(this.onGoingRpcCounter.pipe((0,E.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){this.onGoingRpcCounter.next(this.onGoingRpcCounter.value+1);try{await(0,E.firstValueFrom)((0,E.race)(this.socketManager.observeConnectionReady().pipe((0,E.filter)(Boolean)),this.destructManager.observeIsDestructing())),await this.authManager.waitForReadyState();let r={"Content-Type":"application/json"};Object.keys(this.staticHeaders)&&(r=Object.assign(Object.assign({},r),this.staticHeaders));const n=ie(this.region,this.appId,e),i=await(0,xa.default)(n,{method:"POST",body:f(t),headers:r});let o,s;try{o=await i.text();try{s=JSON.parse(o)}catch(e){}}catch(e){o="Cannot read body"}if(!i.ok)throw new ic(i.status,i.statusText,i.headers,i.url,null==s?void 0:s.message);return s||o}finally{this.onGoingRpcCounter.next(this.onGoingRpcCounter.value-1)}}}class ic extends Error{constructor(e,t,r,n,i){super(i||`RPC error ${e} ${t} calling ${n}`),this.statusCode=e,this.statusText=t,this.headers=r,this.url=n}}const oc=(e=>{var t={};return o.d(t,e),t})({io:()=>r.io}),sc=e=>e();class ac{constructor(e,t,r,n=sc,i,o={},s){this.clientIdService=e,this.region=t,this.appId=r,this.messageNotificationWrapper=n,this.destructManager=i,this.authManager=s,this.webSocketObserver=new E.Subject,this.allMessagesObserver=new E.Subject,this.connectionReady=new E.BehaviorSubject(!1),this.seenMessageIds=new Set,this.firstConnection=!0,this.clientTooOldThreshold=3e5,this.destructManager.onDestruct((async()=>{await this.destruct()})),this.setupMessageAcknowledgments(),this.connect(Object.assign({},o)),this.connectionReady.pipe((0,E.skip)(1),(0,E.filter)((e=>!e)),(0,E.switchMap)((()=>(0,E.race)((0,E.timer)(this.clientTooOldThreshold),this.connectionReady.pipe((0,E.filter)(Boolean)),this.destructManager.observeIsDestructing())))).subscribe((()=>{this.connectionReady.value||this.destructManager.isDestructing||(this.clientIdService.notifyClientTooOld(),this.connect(Object.assign({},o)))})),this.connectionReady.pipe((0,E.filter)(Boolean)).subscribe((()=>{this.clientIdService.isClientTooOld()&&this.clientIdService.notifyClientReadyToBeRegenerated()}))}observeNotifications(){return this.webSocketObserver.asObservable()}observeConnectionReady(){return this.connectionReady.asObservable().pipe((0,E.distinctUntilChanged)())}sendMessage(e){this.authManager.waitForReadyState().then((()=>{(0,E.firstValueFrom)(this.connectionReady.pipe((0,E.filter)(Boolean))).then((()=>{const t=this.authManager.getAuthToken();A(this.socket).emit("message",Object.assign(Object.assign({},e),{authToken:t}))}))}))}connect(e){const t=ie(this.region,this.appId,""),r={clientId:this.clientIdService.getClientId()};this.socket=(0,oc.io)(t,{query:r,reconnectionDelay:5e3,transports:["websocket"],extraHeaders:e}),this.socket.on("connect",(()=>{})),this.socket.on("disconnect",((e,t)=>{this.connectionReady.next(!1)})),this.socket.on("connectionReady",(()=>{this.connectionReady.next(!0),this.firstConnection||this.sendMessage({type:"catchup"}),this.firstConnection=!1})),this.socket.on("message",(e=>{const t=d(e);for(const e of t)this.allMessagesObserver.next(e),this.seenMessageIds.has(e.messageId)||(this.seenMessageIds.add(e.messageId),this.messageNotificationWrapper((()=>{this.webSocketObserver.next(e)})))}))}setupMessageAcknowledgments(){const e=new E.Subject;this.allMessagesObserver.subscribe((t=>{(null==t?void 0:t.messageId)&&e.next(t.messageId)}));const t=[];e.pipe((0,E.tap)((e=>t.push(e))),(0,E.debounceTime)(100)).subscribe((async()=>{const e=[...t.splice(0)];this.sendMessage({type:"acknowledge",payload:e})}))}async destruct(){var e;this.sendMessage({type:"kill"}),this.connectionReady.next(!1),await(0,E.firstValueFrom)((0,E.timer)(0)),null===(e=this.socket)||void 0===e||e.disconnect(),this.webSocketObserver.complete(),this.allMessagesObserver.complete()}}class cc{constructor(e){this.destructManager=new gt,this.setAuthIdToken=(e,t)=>{this.authManager.setAuthIdToken(e,t)},this.collection=(e,t=i.built_in_db)=>(this.validateNotDestructed(),this.collectionReferenceFactory.get(e,t)),this.runInTransaction=e=>(this.validateNotDestructed(),this.dataManager.runInTransaction(e)),this.executeFunction=(e,...t)=>(this.validateNotDestructed(),(0,E.firstValueFrom)(this.backendFunctionManager.executeFunctionAndSubscribe(e,...t))),this.executeNamedQuery=(e,t,r)=>(this.validateNotDestructed(),(0,E.firstValueFrom)(this.namedQueryManager.executeNamedQueryAndSubscribe(e,t,r))),this.callApi=(e,t,r={})=>(this.validateNotDestructed(),(0,E.firstValueFrom)(this.apiManager.callApiAndSubscribe(e,t,r))),this.graphql=e=>(this.validateNotDestructed(),this.graphqlClientFactory.get(e)),this.ai=()=>(this.validateNotDestructed(),{assistant:e=>this.aiClientFactory.getAssistant(e)}),this.acquireLock=(e,t=!0)=>(this.validateNotDestructed(),this.distributedLockManager.lock(e,t)),this.destruct=async()=>{if(!this.destructManager.isDestructing)return this.destructManager.destruct().finally((()=>{const e=Object.entries(cc.squidInstancesMap).find((([,e])=>e===this));e&&delete cc.squidInstancesMap[e[0]]}))},this.connectionDetails=()=>(this.validateNotDestructed(),this._connectionDetails),this.unsubscribe=async()=>{this.querySubscriptionManager.unsubscribe(),await this.rpcManager.awaitAllSettled()},x(e.appId,"APP_ID_MUST_BE_PROVIDED");const t="prod"!==e.environmentId&&e.squidDeveloperId,r=function(e,t,r){return`${L(e,t)}${r?`-${r}`:""}`}(e.appId,e.environmentId,t?e.squidDeveloperId:void 0),n=function(e,t){const r={};return oe(e)&&(r["x-squid-appid"]=t),r}(e.region,r);this.clientIdService=new ft(this.destructManager),this.authManager=new lt(this.destructManager,e.apiKey),this.socketManager=new ac(this.clientIdService,e.region,r,e.messageNotificationWrapper,this.destructManager,n,this.authManager),this.rpcManager=new nc(e.region,r,this.socketManager,this.destructManager,n,this.authManager,this.clientIdService),this.documentStore=new St,this.lockManager=new ae,this.distributedLockManager=new bt(this.socketManager,this.destructManager),this.documentIdentityService=new wt(this.documentStore,this.destructManager),this.documentReferenceFactory=new Et(this.documentIdentityService),this.querySubscriptionManager=new ec(this.rpcManager,this.clientIdService,this.documentStore,this.destructManager,this.documentIdentityService),this.localQueryManager=new Ca(this.documentStore,this.documentReferenceFactory,this.querySubscriptionManager);const o=new Pa(this.rpcManager,this.lockManager,this.querySubscriptionManager);this.queryBuilderFactory=new Je(this.querySubscriptionManager,this.localQueryManager,this.documentReferenceFactory,this.documentIdentityService),this.collectionReferenceFactory=new dt(this.documentReferenceFactory,this.queryBuilderFactory,this.querySubscriptionManager),this.dataManager=new vt(this.documentStore,o,this.socketManager,this.querySubscriptionManager,this.queryBuilderFactory,this.lockManager,this.destructManager,this.documentIdentityService),this.documentReferenceFactory.setDataManager(this.dataManager),this.backendFunctionManager=new ht(this.clientIdService,this.rpcManager,this.socketManager),this.namedQueryManager=new ja(this.rpcManager,this.socketManager),this.apiManager=new ut(this.clientIdService,this.rpcManager,this.socketManager,e.apiServerUrlOverrideMapping),this.graphqlClientFactory=new Ra(this.rpcManager,e.region,r),this.aiClientFactory=new ct(this.rpcManager,this.socketManager),this._connectionDetails=new pt(this.clientIdService,this.socketManager)}static getInstance(e){const t=h(e);let r=cc.squidInstancesMap[t];return r||(r=new cc(e),cc.squidInstancesMap[t]=r,r)}static getInstances(){return Object.values(cc.squidInstancesMap)}validateNotDestructed(){x(!this.destructManager.isDestructing,"The client was already destructed.")}}cc.squidInstancesMap={}})();var a=s.Jk,c=s.hx,u=s.my,l=s.g6,h=s.jP,f=s.zk,d=s.VE,p=s.Rx;export{a as Changes,c as CollectionReference,u as DocumentReference,l as GraphQLClient,h as JoinQueryBuilder,f as QueryBuilder,d as Squid,p as deserializeQuery};