@aws-amplify/api-graphql 4.0.1-console-preview.d745d43.0 → 4.0.1-mjs-test.20ead30.0

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 (155) hide show
  1. package/dist/cjs/GraphQLAPI.js +52 -0
  2. package/dist/cjs/GraphQLAPI.js.map +1 -0
  3. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js +693 -0
  4. package/dist/cjs/Providers/AWSAppSyncRealTimeProvider/index.js.map +1 -0
  5. package/{lib → dist/cjs}/Providers/constants.js +8 -8
  6. package/dist/cjs/Providers/constants.js.map +1 -0
  7. package/dist/cjs/index.js +15 -0
  8. package/dist/cjs/index.js.map +1 -0
  9. package/dist/cjs/internals/InternalGraphQLAPI.js +274 -0
  10. package/dist/cjs/internals/InternalGraphQLAPI.js.map +1 -0
  11. package/dist/cjs/internals/index.js +14 -0
  12. package/dist/cjs/internals/index.js.map +1 -0
  13. package/{lib → dist/cjs}/internals/v6.js +7 -4
  14. package/dist/cjs/internals/v6.js.map +1 -0
  15. package/{lib → dist/cjs}/types/PubSub.js +6 -6
  16. package/dist/cjs/types/PubSub.js.map +1 -0
  17. package/{lib → dist/cjs}/types/index.js +7 -5
  18. package/dist/cjs/types/index.js.map +1 -0
  19. package/dist/cjs/utils/ConnectionStateMonitor.js +134 -0
  20. package/dist/cjs/utils/ConnectionStateMonitor.js.map +1 -0
  21. package/dist/cjs/utils/ReachabilityMonitor/index.js +10 -0
  22. package/dist/cjs/utils/ReachabilityMonitor/index.js.map +1 -0
  23. package/dist/cjs/utils/ReachabilityMonitor/index.native.js +12 -0
  24. package/dist/cjs/utils/ReachabilityMonitor/index.native.js.map +1 -0
  25. package/{lib → dist/cjs}/utils/ReconnectionMonitor.js +24 -25
  26. package/dist/cjs/utils/ReconnectionMonitor.js.map +1 -0
  27. package/dist/cjs/utils/errors/APIError.js +21 -0
  28. package/dist/cjs/utils/errors/APIError.js.map +1 -0
  29. package/dist/cjs/utils/errors/assertValidationError.js +19 -0
  30. package/dist/cjs/utils/errors/assertValidationError.js.map +1 -0
  31. package/dist/cjs/utils/errors/index.js +14 -0
  32. package/dist/cjs/utils/errors/index.js.map +1 -0
  33. package/{lib → dist/cjs}/utils/errors/validation.js +9 -7
  34. package/dist/cjs/utils/errors/validation.js.map +1 -0
  35. package/dist/cjs/utils/index.js +11 -0
  36. package/dist/cjs/utils/index.js.map +1 -0
  37. package/dist/cjs/utils/resolveConfig.js +26 -0
  38. package/dist/cjs/utils/resolveConfig.js.map +1 -0
  39. package/dist/cjs/utils/resolveLibraryOptions.js +16 -0
  40. package/dist/cjs/utils/resolveLibraryOptions.js.map +1 -0
  41. package/{lib-esm → dist/esm}/GraphQLAPI.d.ts +2 -2
  42. package/dist/esm/GraphQLAPI.mjs +50 -0
  43. package/dist/esm/GraphQLAPI.mjs.map +1 -0
  44. package/{lib → dist/esm}/Providers/AWSAppSyncRealTimeProvider/index.d.ts +1 -1
  45. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs +691 -0
  46. package/dist/esm/Providers/AWSAppSyncRealTimeProvider/index.mjs.map +1 -0
  47. package/{lib-esm/Providers/constants.js → dist/esm/Providers/constants.mjs} +18 -14
  48. package/dist/esm/Providers/constants.mjs.map +1 -0
  49. package/dist/esm/index.mjs +5 -0
  50. package/dist/esm/index.mjs.map +1 -0
  51. package/{lib → dist/esm}/internals/InternalGraphQLAPI.d.ts +2 -2
  52. package/dist/esm/internals/InternalGraphQLAPI.mjs +272 -0
  53. package/dist/esm/internals/InternalGraphQLAPI.mjs.map +1 -0
  54. package/dist/esm/internals/index.mjs +3 -0
  55. package/dist/esm/internals/index.mjs.map +1 -0
  56. package/{lib-esm/internals/v6.js → dist/esm/internals/v6.mjs} +10 -6
  57. package/dist/esm/internals/v6.mjs.map +1 -0
  58. package/{lib → dist/esm}/types/PubSub.d.ts +2 -2
  59. package/{lib-esm/types/PubSub.js → dist/esm/types/PubSub.mjs} +5 -2
  60. package/dist/esm/types/PubSub.mjs.map +1 -0
  61. package/{lib-esm → dist/esm}/types/index.d.ts +45 -25
  62. package/{lib-esm/types/index.js → dist/esm/types/index.mjs} +7 -3
  63. package/dist/esm/types/index.mjs.map +1 -0
  64. package/{lib-esm → dist/esm}/utils/ConnectionStateMonitor.d.ts +3 -3
  65. package/{lib-esm/utils/ConnectionStateMonitor.js → dist/esm/utils/ConnectionStateMonitor.mjs} +56 -66
  66. package/dist/esm/utils/ConnectionStateMonitor.mjs.map +1 -0
  67. package/dist/esm/utils/ReachabilityMonitor/index.d.ts +1 -0
  68. package/{lib-esm/utils/ReachabilityMonitor/index.js → dist/esm/utils/ReachabilityMonitor/index.mjs} +6 -2
  69. package/dist/esm/utils/ReachabilityMonitor/index.mjs.map +1 -0
  70. package/dist/esm/utils/ReachabilityMonitor/index.native.d.ts +1 -0
  71. package/dist/esm/utils/ReachabilityMonitor/index.native.mjs +9 -0
  72. package/dist/esm/utils/ReachabilityMonitor/index.native.mjs.map +1 -0
  73. package/{lib-esm/utils/ReconnectionMonitor.js → dist/esm/utils/ReconnectionMonitor.mjs} +25 -26
  74. package/dist/esm/utils/ReconnectionMonitor.mjs.map +1 -0
  75. package/dist/esm/utils/errors/APIError.mjs +19 -0
  76. package/dist/esm/utils/errors/APIError.mjs.map +1 -0
  77. package/dist/esm/utils/errors/assertValidationError.mjs +17 -0
  78. package/dist/esm/utils/errors/assertValidationError.mjs.map +1 -0
  79. package/dist/esm/utils/errors/index.mjs +4 -0
  80. package/dist/esm/utils/errors/index.mjs.map +1 -0
  81. package/{lib-esm/utils/errors/validation.js → dist/esm/utils/errors/validation.mjs} +9 -7
  82. package/dist/esm/utils/errors/validation.mjs.map +1 -0
  83. package/dist/esm/utils/index.mjs +3 -0
  84. package/dist/esm/utils/index.mjs.map +1 -0
  85. package/{lib → dist/esm}/utils/resolveConfig.d.ts +1 -1
  86. package/dist/esm/utils/resolveConfig.mjs +26 -0
  87. package/dist/esm/utils/resolveConfig.mjs.map +1 -0
  88. package/{lib-esm → dist/esm}/utils/resolveLibraryOptions.d.ts +2 -2
  89. package/dist/esm/utils/resolveLibraryOptions.mjs +13 -0
  90. package/dist/esm/utils/resolveLibraryOptions.mjs.map +1 -0
  91. package/internals/package.json +4 -4
  92. package/package.json +48 -26
  93. package/src/GraphQLAPI.ts +2 -2
  94. package/src/internals/InternalGraphQLAPI.ts +35 -10
  95. package/src/types/index.ts +51 -9
  96. package/lib/GraphQLAPI.d.ts +0 -38
  97. package/lib/GraphQLAPI.js +0 -57
  98. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +0 -805
  99. package/lib/Providers/constants.d.ts +0 -95
  100. package/lib/index.d.ts +0 -3
  101. package/lib/index.js +0 -12
  102. package/lib/internals/InternalGraphQLAPI.js +0 -316
  103. package/lib/internals/index.d.ts +0 -2
  104. package/lib/internals/index.js +0 -11
  105. package/lib/internals/v6.d.ts +0 -101
  106. package/lib/tsconfig.tsbuildinfo +0 -6638
  107. package/lib/types/index.d.ts +0 -289
  108. package/lib/utils/ConnectionStateMonitor.d.ts +0 -41
  109. package/lib/utils/ConnectionStateMonitor.js +0 -144
  110. package/lib/utils/ReachabilityMonitor/index.d.ts +0 -1
  111. package/lib/utils/ReachabilityMonitor/index.js +0 -6
  112. package/lib/utils/ReachabilityMonitor/index.native.d.ts +0 -1
  113. package/lib/utils/ReachabilityMonitor/index.native.js +0 -10
  114. package/lib/utils/ReconnectionMonitor.d.ts +0 -29
  115. package/lib/utils/errors/APIError.d.ts +0 -7
  116. package/lib/utils/errors/APIError.js +0 -22
  117. package/lib/utils/errors/assertValidationError.d.ts +0 -5
  118. package/lib/utils/errors/assertValidationError.js +0 -16
  119. package/lib/utils/errors/index.d.ts +0 -3
  120. package/lib/utils/errors/index.js +0 -11
  121. package/lib/utils/errors/validation.d.ts +0 -7
  122. package/lib/utils/index.d.ts +0 -2
  123. package/lib/utils/index.js +0 -8
  124. package/lib/utils/resolveConfig.js +0 -23
  125. package/lib/utils/resolveLibraryOptions.d.ts +0 -11
  126. package/lib/utils/resolveLibraryOptions.js +0 -13
  127. package/lib-esm/GraphQLAPI.js +0 -55
  128. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +0 -64
  129. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +0 -803
  130. package/lib-esm/index.js +0 -5
  131. package/lib-esm/internals/InternalGraphQLAPI.d.ts +0 -58
  132. package/lib-esm/internals/InternalGraphQLAPI.js +0 -314
  133. package/lib-esm/internals/index.js +0 -4
  134. package/lib-esm/tsconfig.tsbuildinfo +0 -6638
  135. package/lib-esm/types/PubSub.d.ts +0 -27
  136. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +0 -1
  137. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +0 -1
  138. package/lib-esm/utils/ReachabilityMonitor/index.native.js +0 -7
  139. package/lib-esm/utils/errors/APIError.js +0 -20
  140. package/lib-esm/utils/errors/assertValidationError.js +0 -13
  141. package/lib-esm/utils/errors/index.js +0 -5
  142. package/lib-esm/utils/index.js +0 -4
  143. package/lib-esm/utils/resolveConfig.d.ts +0 -12
  144. package/lib-esm/utils/resolveConfig.js +0 -21
  145. package/lib-esm/utils/resolveLibraryOptions.js +0 -11
  146. /package/{lib-esm → dist/esm}/Providers/constants.d.ts +0 -0
  147. /package/{lib-esm → dist/esm}/index.d.ts +0 -0
  148. /package/{lib-esm → dist/esm}/internals/index.d.ts +0 -0
  149. /package/{lib-esm → dist/esm}/internals/v6.d.ts +0 -0
  150. /package/{lib-esm → dist/esm}/utils/ReconnectionMonitor.d.ts +0 -0
  151. /package/{lib-esm → dist/esm}/utils/errors/APIError.d.ts +0 -0
  152. /package/{lib-esm → dist/esm}/utils/errors/assertValidationError.d.ts +0 -0
  153. /package/{lib-esm → dist/esm}/utils/errors/index.d.ts +0 -0
  154. /package/{lib-esm → dist/esm}/utils/errors/validation.d.ts +0 -0
  155. /package/{lib-esm → dist/esm}/utils/index.d.ts +0 -0
@@ -0,0 +1,691 @@
1
+ import { Observable } from 'rxjs';
2
+ import { GraphQLError } from 'graphql';
3
+ import { ConsoleLogger, fetchAuthSession, Hub } from '@aws-amplify/core';
4
+ import { signRequest } from '@aws-amplify/core/internals/aws-client-utils';
5
+ import { amplifyUuid, USER_AGENT_HEADER, getAmplifyUserAgent, isNonRetryableError, base64Encoder, jitteredExponentialRetry, NonRetryableError, AmplifyUrl, AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';
6
+ import { ConnectionState, CONTROL_MSG } from '../../types/PubSub.mjs';
7
+ import { SOCKET_STATUS, DEFAULT_KEEP_ALIVE_TIMEOUT, SUBSCRIPTION_STATUS, MESSAGE_TYPES, START_ACK_TIMEOUT, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT, MAX_DELAY_MS, CONNECTION_INIT_TIMEOUT, NON_RETRYABLE_CODES, AWS_APPSYNC_REALTIME_HEADERS, CONNECTION_STATE_CHANGE } from '../constants.mjs';
8
+ import { ConnectionStateMonitor, CONNECTION_CHANGE } from '../../utils/ConnectionStateMonitor.mjs';
9
+ import { ReconnectionMonitor, ReconnectEvent } from '../../utils/ReconnectionMonitor.mjs';
10
+
11
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
12
+ // SPDX-License-Identifier: Apache-2.0
13
+ const logger = new ConsoleLogger('AWSAppSyncRealTimeProvider');
14
+ const dispatchApiEvent = payload => {
15
+ Hub.dispatch('api', payload, 'PubSub', AMPLIFY_SYMBOL);
16
+ };
17
+ const standardDomainPattern = /^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com(?:\.cn)?\/graphql$/i;
18
+ const customDomainPath = '/realtime';
19
+ class AWSAppSyncRealTimeProvider {
20
+ constructor(options = {}) {
21
+ this.socketStatus = SOCKET_STATUS.CLOSED;
22
+ this.keepAliveTimeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
23
+ this.subscriptionObserverMap = new Map();
24
+ this.promiseArray = [];
25
+ this.connectionStateMonitor = new ConnectionStateMonitor();
26
+ this.reconnectionMonitor = new ReconnectionMonitor();
27
+ // Monitor the connection state and pass changes along to Hub
28
+ this.connectionStateMonitorSubscription =
29
+ this.connectionStateMonitor.connectionStateObservable.subscribe(connectionState => {
30
+ dispatchApiEvent({
31
+ event: CONNECTION_STATE_CHANGE,
32
+ data: {
33
+ provider: this,
34
+ connectionState,
35
+ },
36
+ message: `Connection state is ${connectionState}`,
37
+ });
38
+ this.connectionState = connectionState;
39
+ // Trigger START_RECONNECT when the connection is disrupted
40
+ if (connectionState === ConnectionState.ConnectionDisrupted) {
41
+ this.reconnectionMonitor.record(ReconnectEvent.START_RECONNECT);
42
+ }
43
+ // Trigger HALT_RECONNECT to halt reconnection attempts when the state is anything other than
44
+ // ConnectionDisrupted or Connecting
45
+ if ([
46
+ ConnectionState.Connected,
47
+ ConnectionState.ConnectedPendingDisconnect,
48
+ ConnectionState.ConnectedPendingKeepAlive,
49
+ ConnectionState.ConnectedPendingNetwork,
50
+ ConnectionState.ConnectionDisruptedPendingNetwork,
51
+ ConnectionState.Disconnected,
52
+ ].includes(connectionState)) {
53
+ this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT);
54
+ }
55
+ });
56
+ }
57
+ /**
58
+ * Mark the socket closed and release all active listeners
59
+ */
60
+ close() {
61
+ // Mark the socket closed both in status and the connection monitor
62
+ this.socketStatus = SOCKET_STATUS.CLOSED;
63
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
64
+ // Turn off the subscription monitor Hub publishing
65
+ this.connectionStateMonitorSubscription.unsubscribe();
66
+ // Complete all reconnect observers
67
+ this.reconnectionMonitor.close();
68
+ }
69
+ getNewWebSocket(url, protocol) {
70
+ return new WebSocket(url, protocol);
71
+ }
72
+ getProviderName() {
73
+ return 'AWSAppSyncRealTimeProvider';
74
+ }
75
+ // Check if url matches standard domain pattern
76
+ isCustomDomain(url) {
77
+ return url.match(standardDomainPattern) === null;
78
+ }
79
+ subscribe(options, customUserAgentDetails) {
80
+ const { appSyncGraphqlEndpoint, region, query, variables, authenticationType, additionalHeaders, apiKey, } = options || {};
81
+ return new Observable(observer => {
82
+ if (!options || !appSyncGraphqlEndpoint) {
83
+ observer.error({
84
+ errors: [
85
+ {
86
+ ...new GraphQLError(`Subscribe only available for AWS AppSync endpoint`),
87
+ },
88
+ ],
89
+ });
90
+ observer.complete();
91
+ }
92
+ else {
93
+ let subscriptionStartActive = false;
94
+ const subscriptionId = amplifyUuid();
95
+ const startSubscription = () => {
96
+ if (!subscriptionStartActive) {
97
+ subscriptionStartActive = true;
98
+ const startSubscriptionPromise = this._startSubscriptionWithAWSAppSyncRealTime({
99
+ options: {
100
+ query,
101
+ variables,
102
+ region,
103
+ authenticationType,
104
+ appSyncGraphqlEndpoint,
105
+ additionalHeaders,
106
+ apiKey,
107
+ },
108
+ observer,
109
+ subscriptionId,
110
+ customUserAgentDetails,
111
+ }).catch(err => {
112
+ logger.debug(`${CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR}: ${err}`);
113
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
114
+ });
115
+ startSubscriptionPromise.finally(() => {
116
+ subscriptionStartActive = false;
117
+ });
118
+ }
119
+ };
120
+ let reconnectSubscription;
121
+ // Add an observable to the reconnection list to manage reconnection for this subscription
122
+ reconnectSubscription = new Observable(observer => {
123
+ this.reconnectionMonitor.addObserver(observer);
124
+ }).subscribe(() => {
125
+ startSubscription();
126
+ });
127
+ startSubscription();
128
+ return async () => {
129
+ // Cleanup reconnection subscription
130
+ reconnectSubscription?.unsubscribe();
131
+ // Cleanup after unsubscribing or observer.complete was called after _startSubscriptionWithAWSAppSyncRealTime
132
+ try {
133
+ // Waiting that subscription has been connected before trying to unsubscribe
134
+ await this._waitForSubscriptionToBeConnected(subscriptionId);
135
+ const { subscriptionState } = this.subscriptionObserverMap.get(subscriptionId) || {};
136
+ if (!subscriptionState) {
137
+ // subscription already unsubscribed
138
+ return;
139
+ }
140
+ if (subscriptionState === SUBSCRIPTION_STATUS.CONNECTED) {
141
+ this._sendUnsubscriptionMessage(subscriptionId);
142
+ }
143
+ else {
144
+ throw new Error('Subscription never connected');
145
+ }
146
+ }
147
+ catch (err) {
148
+ logger.debug(`Error while unsubscribing ${err}`);
149
+ }
150
+ finally {
151
+ this._removeSubscriptionObserver(subscriptionId);
152
+ }
153
+ };
154
+ }
155
+ });
156
+ }
157
+ async _startSubscriptionWithAWSAppSyncRealTime({ options, observer, subscriptionId, customUserAgentDetails, }) {
158
+ const { appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, graphql_headers = () => ({}), additionalHeaders = {}, } = options;
159
+ const subscriptionState = SUBSCRIPTION_STATUS.PENDING;
160
+ const data = {
161
+ query,
162
+ variables,
163
+ };
164
+ // Having a subscription id map will make it simple to forward messages received
165
+ this.subscriptionObserverMap.set(subscriptionId, {
166
+ observer,
167
+ query: query ?? '',
168
+ variables: variables ?? {},
169
+ subscriptionState,
170
+ startAckTimeoutId: undefined,
171
+ });
172
+ // Preparing payload for subscription message
173
+ const dataString = JSON.stringify(data);
174
+ const headerObj = {
175
+ ...(await this._awsRealTimeHeaderBasedAuth({
176
+ apiKey,
177
+ appSyncGraphqlEndpoint,
178
+ authenticationType,
179
+ payload: dataString,
180
+ canonicalUri: '',
181
+ region,
182
+ additionalHeaders,
183
+ })),
184
+ ...(await graphql_headers()),
185
+ ...additionalHeaders,
186
+ [USER_AGENT_HEADER]: getAmplifyUserAgent(customUserAgentDetails),
187
+ };
188
+ const subscriptionMessage = {
189
+ id: subscriptionId,
190
+ payload: {
191
+ data: dataString,
192
+ extensions: {
193
+ authorization: {
194
+ ...headerObj,
195
+ },
196
+ },
197
+ },
198
+ type: MESSAGE_TYPES.GQL_START,
199
+ };
200
+ const stringToAWSRealTime = JSON.stringify(subscriptionMessage);
201
+ try {
202
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
203
+ await this._initializeWebSocketConnection({
204
+ apiKey,
205
+ appSyncGraphqlEndpoint,
206
+ authenticationType,
207
+ region,
208
+ additionalHeaders,
209
+ });
210
+ }
211
+ catch (err) {
212
+ this._logStartSubscriptionError(subscriptionId, observer, err);
213
+ return;
214
+ }
215
+ // Potential race condition can occur when unsubscribe is called during _initializeWebSocketConnection.
216
+ // E.g.unsubscribe gets invoked prior to finishing WebSocket handshake or START_ACK.
217
+ // Both subscriptionFailedCallback and subscriptionReadyCallback are used to synchronized this.
218
+ const { subscriptionFailedCallback, subscriptionReadyCallback } = this.subscriptionObserverMap.get(subscriptionId) ?? {};
219
+ // This must be done before sending the message in order to be listening immediately
220
+ this.subscriptionObserverMap.set(subscriptionId, {
221
+ observer,
222
+ subscriptionState,
223
+ query: query ?? '',
224
+ variables: variables ?? {},
225
+ subscriptionReadyCallback,
226
+ subscriptionFailedCallback,
227
+ startAckTimeoutId: setTimeout(() => {
228
+ this._timeoutStartSubscriptionAck.call(this, subscriptionId);
229
+ }, START_ACK_TIMEOUT),
230
+ });
231
+ if (this.awsRealTimeSocket) {
232
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
233
+ }
234
+ }
235
+ // Log logic for start subscription failures
236
+ _logStartSubscriptionError(subscriptionId, observer, err) {
237
+ logger.debug({ err });
238
+ const message = String(err.message ?? '');
239
+ // Resolving to give the state observer time to propogate the update
240
+ Promise.resolve(this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED));
241
+ // Capture the error only when the network didn't cause disruption
242
+ if (this.connectionState !== ConnectionState.ConnectionDisruptedPendingNetwork) {
243
+ // When the error is non-retriable, error out the observable
244
+ if (isNonRetryableError(err)) {
245
+ observer.error({
246
+ errors: [
247
+ {
248
+ ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`),
249
+ },
250
+ ],
251
+ });
252
+ }
253
+ else {
254
+ logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${message}`);
255
+ }
256
+ const { subscriptionFailedCallback } = this.subscriptionObserverMap.get(subscriptionId) || {};
257
+ // Notify concurrent unsubscription
258
+ if (typeof subscriptionFailedCallback === 'function') {
259
+ subscriptionFailedCallback();
260
+ }
261
+ }
262
+ }
263
+ // Waiting that subscription has been connected before trying to unsubscribe
264
+ async _waitForSubscriptionToBeConnected(subscriptionId) {
265
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
266
+ if (subscriptionObserver) {
267
+ const { subscriptionState } = subscriptionObserver;
268
+ // This in case unsubscribe is invoked before sending start subscription message
269
+ if (subscriptionState === SUBSCRIPTION_STATUS.PENDING) {
270
+ return new Promise((res, rej) => {
271
+ const { observer, subscriptionState, variables, query } = subscriptionObserver;
272
+ this.subscriptionObserverMap.set(subscriptionId, {
273
+ observer,
274
+ subscriptionState,
275
+ variables,
276
+ query,
277
+ subscriptionReadyCallback: res,
278
+ subscriptionFailedCallback: rej,
279
+ });
280
+ });
281
+ }
282
+ }
283
+ }
284
+ _sendUnsubscriptionMessage(subscriptionId) {
285
+ try {
286
+ if (this.awsRealTimeSocket &&
287
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN &&
288
+ this.socketStatus === SOCKET_STATUS.READY) {
289
+ // Preparing unsubscribe message to stop receiving messages for that subscription
290
+ const unsubscribeMessage = {
291
+ id: subscriptionId,
292
+ type: MESSAGE_TYPES.GQL_STOP,
293
+ };
294
+ const stringToAWSRealTime = JSON.stringify(unsubscribeMessage);
295
+ this.awsRealTimeSocket.send(stringToAWSRealTime);
296
+ }
297
+ }
298
+ catch (err) {
299
+ // If GQL_STOP is not sent because of disconnection issue, then there is nothing the client can do
300
+ logger.debug({ err });
301
+ }
302
+ }
303
+ _removeSubscriptionObserver(subscriptionId) {
304
+ this.subscriptionObserverMap.delete(subscriptionId);
305
+ // Verifying 1000ms after removing subscription in case there are new subscription unmount/mount
306
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
307
+ }
308
+ _closeSocketIfRequired() {
309
+ if (this.subscriptionObserverMap.size > 0) {
310
+ // Active subscriptions on the WebSocket
311
+ return;
312
+ }
313
+ if (!this.awsRealTimeSocket) {
314
+ this.socketStatus = SOCKET_STATUS.CLOSED;
315
+ return;
316
+ }
317
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
318
+ if (this.awsRealTimeSocket.bufferedAmount > 0) {
319
+ // Still data on the WebSocket
320
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
321
+ }
322
+ else {
323
+ logger.debug('closing WebSocket...');
324
+ if (this.keepAliveTimeoutId) {
325
+ clearTimeout(this.keepAliveTimeoutId);
326
+ }
327
+ if (this.keepAliveAlertTimeoutId) {
328
+ clearTimeout(this.keepAliveAlertTimeoutId);
329
+ }
330
+ const tempSocket = this.awsRealTimeSocket;
331
+ // Cleaning callbacks to avoid race condition, socket still exists
332
+ tempSocket.onclose = null;
333
+ tempSocket.onerror = null;
334
+ tempSocket.close(1000);
335
+ this.awsRealTimeSocket = undefined;
336
+ this.socketStatus = SOCKET_STATUS.CLOSED;
337
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
338
+ }
339
+ }
340
+ _handleIncomingSubscriptionMessage(message) {
341
+ if (typeof message.data !== 'string') {
342
+ return;
343
+ }
344
+ logger.debug(`subscription message from AWS AppSync RealTime: ${message.data}`);
345
+ const { id = '', payload, type, } = JSON.parse(String(message.data));
346
+ const { observer = null, query = '', variables = {}, startAckTimeoutId, subscriptionReadyCallback, subscriptionFailedCallback, } = this.subscriptionObserverMap.get(id) || {};
347
+ logger.debug({ id, observer, query, variables });
348
+ if (type === MESSAGE_TYPES.GQL_DATA && payload && payload.data) {
349
+ if (observer) {
350
+ observer.next(payload);
351
+ }
352
+ else {
353
+ logger.debug(`observer not found for id: ${id}`);
354
+ }
355
+ return;
356
+ }
357
+ if (type === MESSAGE_TYPES.GQL_START_ACK) {
358
+ logger.debug(`subscription ready for ${JSON.stringify({ query, variables })}`);
359
+ if (typeof subscriptionReadyCallback === 'function') {
360
+ subscriptionReadyCallback();
361
+ }
362
+ if (startAckTimeoutId)
363
+ clearTimeout(startAckTimeoutId);
364
+ dispatchApiEvent({
365
+ event: CONTROL_MSG.SUBSCRIPTION_ACK,
366
+ data: { query, variables },
367
+ message: 'Connection established for subscription',
368
+ });
369
+ const subscriptionState = SUBSCRIPTION_STATUS.CONNECTED;
370
+ if (observer) {
371
+ this.subscriptionObserverMap.set(id, {
372
+ observer,
373
+ query,
374
+ variables,
375
+ startAckTimeoutId: undefined,
376
+ subscriptionState,
377
+ subscriptionReadyCallback,
378
+ subscriptionFailedCallback,
379
+ });
380
+ }
381
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
382
+ return;
383
+ }
384
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_KEEP_ALIVE) {
385
+ if (this.keepAliveTimeoutId)
386
+ clearTimeout(this.keepAliveTimeoutId);
387
+ if (this.keepAliveAlertTimeoutId)
388
+ clearTimeout(this.keepAliveAlertTimeoutId);
389
+ this.keepAliveTimeoutId = setTimeout(() => this._errorDisconnect(CONTROL_MSG.TIMEOUT_DISCONNECT), this.keepAliveTimeout);
390
+ this.keepAliveAlertTimeoutId = setTimeout(() => {
391
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE_MISSED);
392
+ }, DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT);
393
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.KEEP_ALIVE);
394
+ return;
395
+ }
396
+ if (type === MESSAGE_TYPES.GQL_ERROR) {
397
+ const subscriptionState = SUBSCRIPTION_STATUS.FAILED;
398
+ if (observer) {
399
+ this.subscriptionObserverMap.set(id, {
400
+ observer,
401
+ query,
402
+ variables,
403
+ startAckTimeoutId,
404
+ subscriptionReadyCallback,
405
+ subscriptionFailedCallback,
406
+ subscriptionState,
407
+ });
408
+ logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`);
409
+ observer.error({
410
+ errors: [
411
+ {
412
+ ...new GraphQLError(`${CONTROL_MSG.CONNECTION_FAILED}: ${JSON.stringify(payload)}`),
413
+ },
414
+ ],
415
+ });
416
+ if (startAckTimeoutId)
417
+ clearTimeout(startAckTimeoutId);
418
+ if (typeof subscriptionFailedCallback === 'function') {
419
+ subscriptionFailedCallback();
420
+ }
421
+ }
422
+ }
423
+ }
424
+ _errorDisconnect(msg) {
425
+ logger.debug(`Disconnect error: ${msg}`);
426
+ if (this.awsRealTimeSocket) {
427
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
428
+ this.awsRealTimeSocket.close();
429
+ }
430
+ this.socketStatus = SOCKET_STATUS.CLOSED;
431
+ }
432
+ _timeoutStartSubscriptionAck(subscriptionId) {
433
+ const subscriptionObserver = this.subscriptionObserverMap.get(subscriptionId);
434
+ if (subscriptionObserver) {
435
+ const { observer, query, variables } = subscriptionObserver;
436
+ if (!observer) {
437
+ return;
438
+ }
439
+ this.subscriptionObserverMap.set(subscriptionId, {
440
+ observer,
441
+ query,
442
+ variables,
443
+ subscriptionState: SUBSCRIPTION_STATUS.FAILED,
444
+ });
445
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
446
+ logger.debug('timeoutStartSubscription', JSON.stringify({ query, variables }));
447
+ }
448
+ }
449
+ _initializeWebSocketConnection({ appSyncGraphqlEndpoint, authenticationType, apiKey, region, additionalHeaders, }) {
450
+ if (this.socketStatus === SOCKET_STATUS.READY) {
451
+ return;
452
+ }
453
+ return new Promise(async (res, rej) => {
454
+ this.promiseArray.push({ res, rej });
455
+ if (this.socketStatus === SOCKET_STATUS.CLOSED) {
456
+ try {
457
+ this.socketStatus = SOCKET_STATUS.CONNECTING;
458
+ const payloadString = '{}';
459
+ const authHeader = await this._awsRealTimeHeaderBasedAuth({
460
+ authenticationType,
461
+ payload: payloadString,
462
+ canonicalUri: '/connect',
463
+ apiKey,
464
+ appSyncGraphqlEndpoint,
465
+ region,
466
+ additionalHeaders,
467
+ });
468
+ const headerString = authHeader ? JSON.stringify(authHeader) : '';
469
+ const headerQs = base64Encoder.convert(headerString);
470
+ const payloadQs = base64Encoder.convert(payloadString);
471
+ let discoverableEndpoint = appSyncGraphqlEndpoint ?? '';
472
+ if (this.isCustomDomain(discoverableEndpoint)) {
473
+ discoverableEndpoint =
474
+ discoverableEndpoint.concat(customDomainPath);
475
+ }
476
+ else {
477
+ discoverableEndpoint = discoverableEndpoint
478
+ .replace('appsync-api', 'appsync-realtime-api')
479
+ .replace('gogi-beta', 'grt-beta');
480
+ }
481
+ // Creating websocket url with required query strings
482
+ const protocol = 'wss://';
483
+ discoverableEndpoint = discoverableEndpoint
484
+ .replace('https://', protocol)
485
+ .replace('http://', protocol);
486
+ const awsRealTimeUrl = `${discoverableEndpoint}?header=${headerQs}&payload=${payloadQs}`;
487
+ await this._initializeRetryableHandshake(awsRealTimeUrl);
488
+ this.promiseArray.forEach(({ res }) => {
489
+ logger.debug('Notifying connection successful');
490
+ res();
491
+ });
492
+ this.socketStatus = SOCKET_STATUS.READY;
493
+ this.promiseArray = [];
494
+ }
495
+ catch (err) {
496
+ logger.debug('Connection exited with', err);
497
+ this.promiseArray.forEach(({ rej }) => rej(err));
498
+ this.promiseArray = [];
499
+ if (this.awsRealTimeSocket &&
500
+ this.awsRealTimeSocket.readyState === WebSocket.OPEN) {
501
+ this.awsRealTimeSocket.close(3001);
502
+ }
503
+ this.awsRealTimeSocket = undefined;
504
+ this.socketStatus = SOCKET_STATUS.CLOSED;
505
+ }
506
+ }
507
+ });
508
+ }
509
+ async _initializeRetryableHandshake(awsRealTimeUrl) {
510
+ logger.debug(`Initializaling retryable Handshake`);
511
+ await jitteredExponentialRetry(this._initializeHandshake.bind(this), [awsRealTimeUrl], MAX_DELAY_MS);
512
+ }
513
+ async _initializeHandshake(awsRealTimeUrl) {
514
+ logger.debug(`Initializing handshake ${awsRealTimeUrl}`);
515
+ // Because connecting the socket is async, is waiting until connection is open
516
+ // Step 1: connect websocket
517
+ try {
518
+ await (() => {
519
+ return new Promise((res, rej) => {
520
+ const newSocket = this.getNewWebSocket(awsRealTimeUrl, 'graphql-ws');
521
+ newSocket.onerror = () => {
522
+ logger.debug(`WebSocket connection error`);
523
+ };
524
+ newSocket.onclose = () => {
525
+ rej(new Error('Connection handshake error'));
526
+ };
527
+ newSocket.onopen = () => {
528
+ this.awsRealTimeSocket = newSocket;
529
+ return res();
530
+ };
531
+ });
532
+ })();
533
+ // Step 2: wait for ack from AWS AppSyncReaTime after sending init
534
+ await (() => {
535
+ return new Promise((res, rej) => {
536
+ if (this.awsRealTimeSocket) {
537
+ let ackOk = false;
538
+ this.awsRealTimeSocket.onerror = error => {
539
+ logger.debug(`WebSocket error ${JSON.stringify(error)}`);
540
+ };
541
+ this.awsRealTimeSocket.onclose = event => {
542
+ logger.debug(`WebSocket closed ${event.reason}`);
543
+ rej(new Error(JSON.stringify(event)));
544
+ };
545
+ this.awsRealTimeSocket.onmessage = (message) => {
546
+ if (typeof message.data !== 'string') {
547
+ return;
548
+ }
549
+ logger.debug(`subscription message from AWS AppSyncRealTime: ${message.data} `);
550
+ const data = JSON.parse(message.data);
551
+ const { type, payload: { connectionTimeoutMs = DEFAULT_KEEP_ALIVE_TIMEOUT, } = {}, } = data;
552
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ACK) {
553
+ ackOk = true;
554
+ if (this.awsRealTimeSocket) {
555
+ this.keepAliveTimeout = connectionTimeoutMs;
556
+ this.awsRealTimeSocket.onmessage =
557
+ this._handleIncomingSubscriptionMessage.bind(this);
558
+ this.awsRealTimeSocket.onerror = err => {
559
+ logger.debug(err);
560
+ this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
561
+ };
562
+ this.awsRealTimeSocket.onclose = event => {
563
+ logger.debug(`WebSocket closed ${event.reason}`);
564
+ this._errorDisconnect(CONTROL_MSG.CONNECTION_CLOSED);
565
+ };
566
+ }
567
+ res('Cool, connected to AWS AppSyncRealTime');
568
+ return;
569
+ }
570
+ if (type === MESSAGE_TYPES.GQL_CONNECTION_ERROR) {
571
+ const { payload: { errors: [{ errorType = '', errorCode = 0 } = {}] = [], } = {}, } = data;
572
+ rej({ errorType, errorCode });
573
+ }
574
+ };
575
+ const gqlInit = {
576
+ type: MESSAGE_TYPES.GQL_CONNECTION_INIT,
577
+ };
578
+ this.awsRealTimeSocket.send(JSON.stringify(gqlInit));
579
+ const checkAckOk = (ackOk) => {
580
+ if (!ackOk) {
581
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_FAILED);
582
+ rej(new Error(`Connection timeout: ack from AWSAppSyncRealTime was not received after ${CONNECTION_INIT_TIMEOUT} ms`));
583
+ }
584
+ };
585
+ setTimeout(() => checkAckOk(ackOk), CONNECTION_INIT_TIMEOUT);
586
+ }
587
+ });
588
+ })();
589
+ }
590
+ catch (err) {
591
+ const { errorType, errorCode } = err;
592
+ if (NON_RETRYABLE_CODES.includes(errorCode)) {
593
+ throw new NonRetryableError(errorType);
594
+ }
595
+ else if (errorType) {
596
+ throw new Error(errorType);
597
+ }
598
+ else {
599
+ throw err;
600
+ }
601
+ }
602
+ }
603
+ async _awsRealTimeHeaderBasedAuth({ apiKey, authenticationType, payload, canonicalUri, appSyncGraphqlEndpoint, region, additionalHeaders, }) {
604
+ const headerHandler = {
605
+ apiKey: this._awsRealTimeApiKeyHeader.bind(this),
606
+ iam: this._awsRealTimeIAMHeader.bind(this),
607
+ oidc: this._awsAuthTokenHeader.bind(this),
608
+ userPool: this._awsAuthTokenHeader.bind(this),
609
+ lambda: this._customAuthHeader,
610
+ none: this._customAuthHeader,
611
+ };
612
+ if (!authenticationType || !headerHandler[authenticationType]) {
613
+ logger.debug(`Authentication type ${authenticationType} not supported`);
614
+ return undefined;
615
+ }
616
+ else {
617
+ const handler = headerHandler[authenticationType];
618
+ const host = appSyncGraphqlEndpoint
619
+ ? new AmplifyUrl(appSyncGraphqlEndpoint).host
620
+ : undefined;
621
+ logger.debug(`Authenticating with ${JSON.stringify(authenticationType)}`);
622
+ let resolvedApiKey;
623
+ if (authenticationType === 'apiKey') {
624
+ resolvedApiKey = apiKey;
625
+ }
626
+ const result = await handler({
627
+ payload,
628
+ canonicalUri,
629
+ appSyncGraphqlEndpoint,
630
+ apiKey: resolvedApiKey,
631
+ region,
632
+ host,
633
+ additionalHeaders,
634
+ });
635
+ return result;
636
+ }
637
+ }
638
+ async _awsAuthTokenHeader({ host }) {
639
+ const session = await fetchAuthSession();
640
+ return {
641
+ Authorization: session?.tokens?.accessToken?.toString(),
642
+ host,
643
+ };
644
+ }
645
+ async _awsRealTimeApiKeyHeader({ apiKey, host, }) {
646
+ const dt = new Date();
647
+ const dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, '');
648
+ return {
649
+ host,
650
+ 'x-amz-date': dtStr,
651
+ 'x-api-key': apiKey,
652
+ };
653
+ }
654
+ async _awsRealTimeIAMHeader({ payload, canonicalUri, appSyncGraphqlEndpoint, region, }) {
655
+ const endpointInfo = {
656
+ region,
657
+ service: 'appsync',
658
+ };
659
+ const creds = (await fetchAuthSession()).credentials;
660
+ const request = {
661
+ url: `${appSyncGraphqlEndpoint}${canonicalUri}`,
662
+ data: payload,
663
+ method: 'POST',
664
+ headers: { ...AWS_APPSYNC_REALTIME_HEADERS },
665
+ };
666
+ const signed_params = signRequest({
667
+ headers: request.headers,
668
+ method: request.method,
669
+ url: new AmplifyUrl(request.url),
670
+ body: request.data,
671
+ }, {
672
+ // TODO: What do we need to do to remove these !'s?
673
+ credentials: creds,
674
+ signingRegion: endpointInfo.region,
675
+ signingService: endpointInfo.service,
676
+ });
677
+ return signed_params.headers;
678
+ }
679
+ _customAuthHeader({ host, additionalHeaders, }) {
680
+ if (!additionalHeaders?.['Authorization']) {
681
+ throw new Error('No auth token specified');
682
+ }
683
+ return {
684
+ Authorization: additionalHeaders.Authorization,
685
+ host,
686
+ };
687
+ }
688
+ }
689
+
690
+ export { AWSAppSyncRealTimeProvider };
691
+ //# sourceMappingURL=index.mjs.map