@aws-amplify/datastore 4.7.6-api-v6-models.b3abc9b.0 → 5.0.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 (187) hide show
  1. package/README.md +4 -0
  2. package/lib/authModeStrategies/defaultAuthStrategy.js +3 -2
  3. package/lib/authModeStrategies/index.js +3 -3
  4. package/lib/authModeStrategies/multiAuthStrategy.js +38 -53
  5. package/lib/datastore/datastore.d.ts +4 -5
  6. package/lib/datastore/datastore.js +929 -1284
  7. package/lib/index.d.ts +1 -1
  8. package/lib/index.js +26 -13
  9. package/lib/predicates/index.js +54 -69
  10. package/lib/predicates/next.d.ts +2 -2
  11. package/lib/predicates/next.js +313 -462
  12. package/lib/predicates/sort.js +24 -28
  13. package/lib/ssr/index.js +2 -2
  14. package/lib/storage/adapter/AsyncStorageAdapter.js +120 -342
  15. package/lib/storage/adapter/AsyncStorageDatabase.js +217 -421
  16. package/lib/storage/adapter/InMemoryStore.js +28 -51
  17. package/lib/storage/adapter/InMemoryStore.native.js +5 -3
  18. package/lib/storage/adapter/IndexedDBAdapter.js +466 -871
  19. package/lib/storage/adapter/StorageAdapterBase.js +180 -330
  20. package/lib/storage/adapter/getDefaultAdapter/index.js +8 -10
  21. package/lib/storage/adapter/getDefaultAdapter/index.native.js +5 -4
  22. package/lib/storage/adapter/index.js +0 -1
  23. package/lib/storage/relationship.js +177 -253
  24. package/lib/storage/storage.d.ts +4 -4
  25. package/lib/storage/storage.js +255 -433
  26. package/lib/sync/datastoreConnectivity.d.ts +2 -2
  27. package/lib/sync/datastoreConnectivity.js +29 -39
  28. package/lib/sync/datastoreReachability/index.d.ts +1 -3
  29. package/lib/sync/datastoreReachability/index.js +3 -3
  30. package/lib/sync/datastoreReachability/index.native.d.ts +1 -3
  31. package/lib/sync/datastoreReachability/index.native.js +4 -5
  32. package/lib/sync/index.d.ts +2 -2
  33. package/lib/sync/index.js +522 -827
  34. package/lib/sync/merger.js +31 -63
  35. package/lib/sync/outbox.js +148 -232
  36. package/lib/sync/processors/errorMaps.d.ts +1 -1
  37. package/lib/sync/processors/errorMaps.js +30 -47
  38. package/lib/sync/processors/mutation.d.ts +2 -2
  39. package/lib/sync/processors/mutation.js +343 -502
  40. package/lib/sync/processors/subscription.d.ts +5 -2
  41. package/lib/sync/processors/subscription.js +283 -437
  42. package/lib/sync/processors/sync.d.ts +2 -2
  43. package/lib/sync/processors/sync.js +279 -404
  44. package/lib/sync/utils.d.ts +5 -4
  45. package/lib/sync/utils.js +267 -320
  46. package/lib/tsconfig.tsbuildinfo +1 -0
  47. package/lib/types.d.ts +138 -140
  48. package/lib/types.js +17 -24
  49. package/lib/util.d.ts +9 -17
  50. package/lib/util.js +387 -511
  51. package/lib-esm/authModeStrategies/defaultAuthStrategy.js +1 -2
  52. package/lib-esm/authModeStrategies/index.js +0 -1
  53. package/lib-esm/authModeStrategies/multiAuthStrategy.js +35 -52
  54. package/lib-esm/datastore/datastore.d.ts +4 -5
  55. package/lib-esm/datastore/datastore.js +888 -1247
  56. package/lib-esm/index.d.ts +1 -1
  57. package/lib-esm/index.js +6 -7
  58. package/lib-esm/predicates/index.js +53 -70
  59. package/lib-esm/predicates/next.d.ts +2 -2
  60. package/lib-esm/predicates/next.js +306 -459
  61. package/lib-esm/predicates/sort.js +23 -28
  62. package/lib-esm/ssr/index.js +1 -2
  63. package/lib-esm/storage/adapter/AsyncStorageAdapter.js +111 -338
  64. package/lib-esm/storage/adapter/AsyncStorageDatabase.js +212 -416
  65. package/lib-esm/storage/adapter/InMemoryStore.js +27 -52
  66. package/lib-esm/storage/adapter/InMemoryStore.native.js +0 -1
  67. package/lib-esm/storage/adapter/IndexedDBAdapter.js +438 -866
  68. package/lib-esm/storage/adapter/StorageAdapterBase.js +173 -325
  69. package/lib-esm/storage/adapter/getDefaultAdapter/index.js +2 -6
  70. package/lib-esm/storage/adapter/getDefaultAdapter/index.native.js +1 -2
  71. package/lib-esm/storage/adapter/index.js +1 -1
  72. package/lib-esm/storage/relationship.js +173 -251
  73. package/lib-esm/storage/storage.d.ts +4 -4
  74. package/lib-esm/storage/storage.js +242 -424
  75. package/lib-esm/sync/datastoreConnectivity.d.ts +2 -2
  76. package/lib-esm/sync/datastoreConnectivity.js +28 -39
  77. package/lib-esm/sync/datastoreReachability/index.d.ts +1 -3
  78. package/lib-esm/sync/datastoreReachability/index.js +2 -3
  79. package/lib-esm/sync/datastoreReachability/index.native.d.ts +1 -3
  80. package/lib-esm/sync/datastoreReachability/index.native.js +3 -4
  81. package/lib-esm/sync/index.d.ts +2 -2
  82. package/lib-esm/sync/index.js +502 -812
  83. package/lib-esm/sync/merger.js +28 -61
  84. package/lib-esm/sync/outbox.js +143 -228
  85. package/lib-esm/sync/processors/errorMaps.d.ts +1 -1
  86. package/lib-esm/sync/processors/errorMaps.js +32 -50
  87. package/lib-esm/sync/processors/mutation.d.ts +2 -2
  88. package/lib-esm/sync/processors/mutation.js +329 -490
  89. package/lib-esm/sync/processors/subscription.d.ts +5 -2
  90. package/lib-esm/sync/processors/subscription.js +266 -421
  91. package/lib-esm/sync/processors/sync.d.ts +2 -2
  92. package/lib-esm/sync/processors/sync.js +271 -397
  93. package/lib-esm/sync/utils.d.ts +5 -4
  94. package/lib-esm/sync/utils.js +252 -307
  95. package/lib-esm/tsconfig.tsbuildinfo +1 -0
  96. package/lib-esm/types.d.ts +138 -140
  97. package/lib-esm/types.js +16 -25
  98. package/lib-esm/util.d.ts +9 -17
  99. package/lib-esm/util.js +335 -497
  100. package/package.json +31 -26
  101. package/src/authModeStrategies/multiAuthStrategy.ts +15 -12
  102. package/src/datastore/datastore.ts +36 -35
  103. package/src/predicates/sort.ts +3 -1
  104. package/src/storage/adapter/InMemoryStore.ts +1 -1
  105. package/src/storage/adapter/IndexedDBAdapter.ts +2 -2
  106. package/src/storage/adapter/StorageAdapterBase.ts +2 -2
  107. package/src/storage/adapter/getDefaultAdapter/index.ts +1 -4
  108. package/src/storage/storage.ts +29 -24
  109. package/src/sync/datastoreConnectivity.ts +6 -6
  110. package/src/sync/datastoreReachability/index.native.ts +5 -3
  111. package/src/sync/datastoreReachability/index.ts +1 -1
  112. package/src/sync/index.ts +79 -89
  113. package/src/sync/processors/errorMaps.ts +7 -7
  114. package/src/sync/processors/mutation.ts +19 -13
  115. package/src/sync/processors/subscription.ts +221 -295
  116. package/src/sync/processors/sync.ts +11 -8
  117. package/src/sync/utils.ts +30 -15
  118. package/src/types.ts +4 -8
  119. package/src/util.ts +46 -9
  120. package/lib/.tsbuildinfo +0 -3
  121. package/lib/authModeStrategies/defaultAuthStrategy.js.map +0 -1
  122. package/lib/authModeStrategies/index.js.map +0 -1
  123. package/lib/authModeStrategies/multiAuthStrategy.js.map +0 -1
  124. package/lib/datastore/datastore.js.map +0 -1
  125. package/lib/index.js.map +0 -1
  126. package/lib/predicates/index.js.map +0 -1
  127. package/lib/predicates/next.js.map +0 -1
  128. package/lib/predicates/sort.js.map +0 -1
  129. package/lib/ssr/index.js.map +0 -1
  130. package/lib/storage/adapter/AsyncStorageAdapter.js.map +0 -1
  131. package/lib/storage/adapter/AsyncStorageDatabase.js.map +0 -1
  132. package/lib/storage/adapter/InMemoryStore.js.map +0 -1
  133. package/lib/storage/adapter/InMemoryStore.native.js.map +0 -1
  134. package/lib/storage/adapter/IndexedDBAdapter.js.map +0 -1
  135. package/lib/storage/adapter/StorageAdapterBase.js.map +0 -1
  136. package/lib/storage/adapter/getDefaultAdapter/index.js.map +0 -1
  137. package/lib/storage/adapter/getDefaultAdapter/index.native.js.map +0 -1
  138. package/lib/storage/adapter/index.js.map +0 -1
  139. package/lib/storage/relationship.js.map +0 -1
  140. package/lib/storage/storage.js.map +0 -1
  141. package/lib/sync/datastoreConnectivity.js.map +0 -1
  142. package/lib/sync/datastoreReachability/index.js.map +0 -1
  143. package/lib/sync/datastoreReachability/index.native.js.map +0 -1
  144. package/lib/sync/index.js.map +0 -1
  145. package/lib/sync/merger.js.map +0 -1
  146. package/lib/sync/outbox.js.map +0 -1
  147. package/lib/sync/processors/errorMaps.js.map +0 -1
  148. package/lib/sync/processors/mutation.js.map +0 -1
  149. package/lib/sync/processors/subscription.js.map +0 -1
  150. package/lib/sync/processors/sync.js.map +0 -1
  151. package/lib/sync/utils.js.map +0 -1
  152. package/lib/types.js.map +0 -1
  153. package/lib/util.js.map +0 -1
  154. package/lib-esm/.tsbuildinfo +0 -3
  155. package/lib-esm/authModeStrategies/defaultAuthStrategy.js.map +0 -1
  156. package/lib-esm/authModeStrategies/index.js.map +0 -1
  157. package/lib-esm/authModeStrategies/multiAuthStrategy.js.map +0 -1
  158. package/lib-esm/datastore/datastore.js.map +0 -1
  159. package/lib-esm/index.js.map +0 -1
  160. package/lib-esm/predicates/index.js.map +0 -1
  161. package/lib-esm/predicates/next.js.map +0 -1
  162. package/lib-esm/predicates/sort.js.map +0 -1
  163. package/lib-esm/ssr/index.js.map +0 -1
  164. package/lib-esm/storage/adapter/AsyncStorageAdapter.js.map +0 -1
  165. package/lib-esm/storage/adapter/AsyncStorageDatabase.js.map +0 -1
  166. package/lib-esm/storage/adapter/InMemoryStore.js.map +0 -1
  167. package/lib-esm/storage/adapter/InMemoryStore.native.js.map +0 -1
  168. package/lib-esm/storage/adapter/IndexedDBAdapter.js.map +0 -1
  169. package/lib-esm/storage/adapter/StorageAdapterBase.js.map +0 -1
  170. package/lib-esm/storage/adapter/getDefaultAdapter/index.js.map +0 -1
  171. package/lib-esm/storage/adapter/getDefaultAdapter/index.native.js.map +0 -1
  172. package/lib-esm/storage/adapter/index.js.map +0 -1
  173. package/lib-esm/storage/relationship.js.map +0 -1
  174. package/lib-esm/storage/storage.js.map +0 -1
  175. package/lib-esm/sync/datastoreConnectivity.js.map +0 -1
  176. package/lib-esm/sync/datastoreReachability/index.js.map +0 -1
  177. package/lib-esm/sync/datastoreReachability/index.native.js.map +0 -1
  178. package/lib-esm/sync/index.js.map +0 -1
  179. package/lib-esm/sync/merger.js.map +0 -1
  180. package/lib-esm/sync/outbox.js.map +0 -1
  181. package/lib-esm/sync/processors/errorMaps.js.map +0 -1
  182. package/lib-esm/sync/processors/mutation.js.map +0 -1
  183. package/lib-esm/sync/processors/subscription.js.map +0 -1
  184. package/lib-esm/sync/processors/sync.js.map +0 -1
  185. package/lib-esm/sync/utils.js.map +0 -1
  186. package/lib-esm/types.js.map +0 -1
  187. package/lib-esm/util.js.map +0 -1
@@ -1,20 +1,24 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { GraphQLResult, GRAPHQL_AUTH_MODE } from '@aws-amplify/api';
3
+ import { GraphQLResult } from '@aws-amplify/api';
4
4
  import { InternalAPI } from '@aws-amplify/api/internals';
5
- import { Auth } from '@aws-amplify/auth';
6
- import { Cache } from '@aws-amplify/cache';
5
+ import {
6
+ Hub,
7
+ HubCapsule,
8
+ fetchAuthSession,
9
+ ConsoleLogger,
10
+ } from '@aws-amplify/core';
7
11
  import {
8
12
  Category,
9
- ConsoleLogger as Logger,
10
13
  CustomUserAgentDetails,
11
14
  DataStoreAction,
12
- Hub,
13
- HubCapsule,
14
15
  BackgroundProcessManager,
15
- } from '@aws-amplify/core';
16
- import { CONTROL_MSG as PUBSUB_CONTROL_MSG } from '@aws-amplify/pubsub';
17
- import Observable, { ZenObservable } from 'zen-observable-ts';
16
+ GraphQLAuthMode,
17
+ AmplifyError,
18
+ JwtPayload,
19
+ } from '@aws-amplify/core/internals/utils';
20
+
21
+ import { Observable, Observer, SubscriptionLike } from 'rxjs';
18
22
  import {
19
23
  InternalSchema,
20
24
  PersistentModel,
@@ -45,8 +49,9 @@ import {
45
49
  import { ModelPredicateCreator } from '../../predicates';
46
50
  import { validatePredicate } from '../../util';
47
51
  import { getSubscriptionErrorType } from './errorMaps';
52
+ import { CONTROL_MSG as PUBSUB_CONTROL_MSG } from '@aws-amplify/api-graphql';
48
53
 
49
- const logger = new Logger('DataStore');
54
+ const logger = new ConsoleLogger('DataStore');
50
55
 
51
56
  export enum CONTROL_MSG {
52
57
  CONNECTED = 'CONNECTED',
@@ -59,7 +64,7 @@ export enum USER_CREDENTIALS {
59
64
  }
60
65
 
61
66
  type AuthorizationInfo = {
62
- authMode: GRAPHQL_AUTH_MODE;
67
+ authMode: GraphQLAuthMode;
63
68
  isOwner: boolean;
64
69
  ownerField?: string;
65
70
  ownerValue?: string;
@@ -72,7 +77,7 @@ class SubscriptionProcessor {
72
77
  >();
73
78
  private buffer: [TransformerMutationType, SchemaModel, PersistentModel][] =
74
79
  [];
75
- private dataObserver!: ZenObservable.Observer<any>;
80
+ private dataObserver!: Observer<any>;
76
81
 
77
82
  private runningProcesses = new BackgroundProcessManager();
78
83
 
@@ -86,9 +91,7 @@ class SubscriptionProcessor {
86
91
  private readonly authModeStrategy: AuthModeStrategy,
87
92
  private readonly errorHandler: ErrorHandler,
88
93
  private readonly amplifyContext: AmplifyContext = {
89
- Auth,
90
94
  InternalAPI,
91
- Cache,
92
95
  }
93
96
  ) {}
94
97
 
@@ -97,15 +100,14 @@ class SubscriptionProcessor {
97
100
  model: SchemaModel,
98
101
  transformerMutationType: TransformerMutationType,
99
102
  userCredentials: USER_CREDENTIALS,
100
- cognitoTokenPayload: { [field: string]: any } | undefined,
101
- oidcTokenPayload: { [field: string]: any } | undefined,
102
- authMode: GRAPHQL_AUTH_MODE,
103
+ oidcTokenPayload: JwtPayload | undefined,
104
+ authMode: GraphQLAuthMode,
103
105
  filterArg: boolean = false
104
106
  ): {
105
107
  opType: TransformerMutationType;
106
108
  opName: string;
107
109
  query: string;
108
- authMode: GRAPHQL_AUTH_MODE;
110
+ authMode: GraphQLAuthMode;
109
111
  isOwner: boolean;
110
112
  ownerField?: string;
111
113
  ownerValue?: string;
@@ -116,7 +118,6 @@ class SubscriptionProcessor {
116
118
  model,
117
119
  userCredentials,
118
120
  aws_appsync_authenticationType,
119
- cognitoTokenPayload,
120
121
  oidcTokenPayload,
121
122
  authMode
122
123
  ) || {};
@@ -135,16 +136,14 @@ class SubscriptionProcessor {
135
136
  private getAuthorizationInfo(
136
137
  model: SchemaModel,
137
138
  userCredentials: USER_CREDENTIALS,
138
- defaultAuthType: GRAPHQL_AUTH_MODE,
139
- cognitoTokenPayload: { [field: string]: any } = {},
140
- oidcTokenPayload: { [field: string]: any } = {},
141
- authMode: GRAPHQL_AUTH_MODE
139
+ defaultAuthType: GraphQLAuthMode,
140
+ oidcTokenPayload: JwtPayload | undefined,
141
+ authMode: GraphQLAuthMode
142
142
  ): AuthorizationInfo {
143
143
  const rules = getAuthorizationRules(model);
144
-
145
144
  // Return null if user doesn't have proper credentials for private API with IAM auth
146
145
  const iamPrivateAuth =
147
- authMode === GRAPHQL_AUTH_MODE.AWS_IAM &&
146
+ authMode === 'iam' &&
148
147
  rules.find(
149
148
  rule => rule.authStrategy === 'private' && rule.provider === 'iam'
150
149
  );
@@ -164,22 +163,19 @@ class SubscriptionProcessor {
164
163
  );
165
164
 
166
165
  const validGroup =
167
- (authMode === GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS ||
168
- authMode === GRAPHQL_AUTH_MODE.OPENID_CONNECT) &&
166
+ (authMode === 'oidc' || authMode === 'userPool') &&
169
167
  groupAuthRules.find(groupAuthRule => {
170
168
  // validate token against groupClaim
171
- const cognitoUserGroups = getUserGroupsFromToken(
172
- cognitoTokenPayload,
173
- groupAuthRule
174
- );
175
- const oidcUserGroups = getUserGroupsFromToken(
176
- oidcTokenPayload,
177
- groupAuthRule
178
- );
179
-
180
- return [...cognitoUserGroups, ...oidcUserGroups].find(userGroup => {
181
- return groupAuthRule.groups.find(group => group === userGroup);
182
- });
169
+ if (oidcTokenPayload) {
170
+ const oidcUserGroups = getUserGroupsFromToken(
171
+ oidcTokenPayload,
172
+ groupAuthRule
173
+ );
174
+
175
+ return [...oidcUserGroups].find(userGroup => {
176
+ return groupAuthRule.groups.find(group => group === userGroup);
177
+ });
178
+ }
183
179
  });
184
180
 
185
181
  if (validGroup) {
@@ -189,38 +185,7 @@ class SubscriptionProcessor {
189
185
  };
190
186
  }
191
187
 
192
- // Owner auth needs additional values to be returned in order to create the subscription with
193
- // the correct parameters so we are getting the owner value from the Cognito token via the
194
- // identityClaim from the auth rule.
195
- const cognitoOwnerAuthRules =
196
- authMode === GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS
197
- ? rules.filter(
198
- rule =>
199
- rule.authStrategy === 'owner' && rule.provider === 'userPools'
200
- )
201
- : [];
202
-
203
188
  let ownerAuthInfo: AuthorizationInfo;
204
- cognitoOwnerAuthRules.forEach(ownerAuthRule => {
205
- const ownerValue = cognitoTokenPayload[ownerAuthRule.identityClaim];
206
-
207
- // AuthZ for "list of owners" is handled dynamically in the subscription auth request
208
- // resolver. It doesn't rely on a subscription arg.
209
- // Only pass a subscription arg for single owner auth
210
- const singleOwner =
211
- model.fields[ownerAuthRule.ownerField]?.isArray !== true;
212
- const isOwnerArgRequired =
213
- singleOwner && !ownerAuthRule.areSubscriptionsPublic;
214
-
215
- if (ownerValue) {
216
- ownerAuthInfo = {
217
- authMode: GRAPHQL_AUTH_MODE.AMAZON_COGNITO_USER_POOLS,
218
- isOwner: isOwnerArgRequired,
219
- ownerField: ownerAuthRule.ownerField,
220
- ownerValue,
221
- };
222
- }
223
- });
224
189
 
225
190
  if (ownerAuthInfo!) {
226
191
  return ownerAuthInfo!;
@@ -229,16 +194,18 @@ class SubscriptionProcessor {
229
194
  // Owner auth needs additional values to be returned in order to create the subscription with
230
195
  // the correct parameters so we are getting the owner value from the OIDC token via the
231
196
  // identityClaim from the auth rule.
197
+
232
198
  const oidcOwnerAuthRules =
233
- authMode === GRAPHQL_AUTH_MODE.OPENID_CONNECT
199
+ authMode === 'oidc' || authMode === 'userPool'
234
200
  ? rules.filter(
235
- rule => rule.authStrategy === 'owner' && rule.provider === 'oidc'
201
+ rule =>
202
+ rule.authStrategy === 'owner' &&
203
+ (rule.provider === 'oidc' || rule.provider === 'userPools')
236
204
  )
237
205
  : [];
238
206
 
239
207
  oidcOwnerAuthRules.forEach(ownerAuthRule => {
240
208
  const ownerValue = oidcTokenPayload[ownerAuthRule.identityClaim];
241
-
242
209
  const singleOwner =
243
210
  model.fields[ownerAuthRule.ownerField]?.isArray !== true;
244
211
  const isOwnerArgRequired =
@@ -246,10 +213,10 @@ class SubscriptionProcessor {
246
213
 
247
214
  if (ownerValue) {
248
215
  ownerAuthInfo = {
249
- authMode: GRAPHQL_AUTH_MODE.OPENID_CONNECT,
216
+ authMode,
250
217
  isOwner: isOwnerArgRequired,
251
218
  ownerField: ownerAuthRule.ownerField,
252
- ownerValue,
219
+ ownerValue: String(ownerValue),
253
220
  };
254
221
  }
255
222
  });
@@ -265,7 +232,10 @@ class SubscriptionProcessor {
265
232
  };
266
233
  }
267
234
 
268
- private hubQueryCompletionListener(completed: Function, capsule: HubCapsule) {
235
+ private hubQueryCompletionListener(
236
+ completed: Function,
237
+ capsule: HubCapsule<'datastore', { event: string }>
238
+ ) {
269
239
  const {
270
240
  payload: { event },
271
241
  } = capsule;
@@ -289,20 +259,18 @@ class SubscriptionProcessor {
289
259
  // independently, since the auth retry behavior is asynchronous.
290
260
  let subscriptions: {
291
261
  [modelName: string]: {
292
- [TransformerMutationType.CREATE]: ZenObservable.Subscription[];
293
- [TransformerMutationType.UPDATE]: ZenObservable.Subscription[];
294
- [TransformerMutationType.DELETE]: ZenObservable.Subscription[];
262
+ [TransformerMutationType.CREATE]: SubscriptionLike[];
263
+ [TransformerMutationType.UPDATE]: SubscriptionLike[];
264
+ [TransformerMutationType.DELETE]: SubscriptionLike[];
295
265
  };
296
266
  } = {};
297
- let cognitoTokenPayload: { [field: string]: any },
298
- oidcTokenPayload: { [field: string]: any };
267
+ let oidcTokenPayload: JwtPayload | undefined;
299
268
  let userCredentials = USER_CREDENTIALS.none;
300
269
  this.runningProcesses.add(async () => {
301
270
  try {
302
271
  // retrieving current AWS Credentials
303
- const credentials =
304
- await this.amplifyContext.Auth.currentCredentials();
305
- userCredentials = credentials.authenticated
272
+ const credentials = (await fetchAuthSession()).tokens?.accessToken;
273
+ userCredentials = credentials
306
274
  ? USER_CREDENTIALS.auth
307
275
  : USER_CREDENTIALS.unauth;
308
276
  } catch (err) {
@@ -311,47 +279,12 @@ class SubscriptionProcessor {
311
279
 
312
280
  try {
313
281
  // retrieving current token info from Cognito UserPools
314
- const session = await this.amplifyContext.Auth.currentSession();
315
- cognitoTokenPayload = session.getIdToken().decodePayload();
282
+ const session = await await fetchAuthSession();
283
+ oidcTokenPayload = session.tokens?.idToken?.payload;
316
284
  } catch (err) {
317
285
  // best effort to get jwt from Cognito
318
286
  }
319
287
 
320
- try {
321
- // Checking for the Cognito region in config to see if Auth is configured
322
- // before attempting to get federated token. We're using the Cognito region
323
- // because it will be there regardless of user/identity pool being present.
324
- const { aws_cognito_region, Auth: AuthConfig } = this.amplifyConfig;
325
- if (!aws_cognito_region || (AuthConfig && !AuthConfig.region)) {
326
- throw 'Auth is not configured';
327
- }
328
-
329
- let token;
330
- // backwards compatibility
331
- const federatedInfo = await this.amplifyContext.Cache.getItem(
332
- 'federatedInfo'
333
- );
334
- if (federatedInfo) {
335
- token = federatedInfo.token;
336
- } else {
337
- const currentUser =
338
- await this.amplifyContext.Auth.currentAuthenticatedUser();
339
- if (currentUser) {
340
- token = currentUser.token;
341
- }
342
- }
343
-
344
- if (token) {
345
- const payload = token.split('.')[1];
346
- oidcTokenPayload = JSON.parse(
347
- Buffer.from(payload, 'base64').toString('utf8')
348
- );
349
- }
350
- } catch (err) {
351
- logger.debug('error getting OIDC JWT', err);
352
- // best effort to get oidc jwt
353
- }
354
-
355
288
  Object.values(this.schema.namespaces).forEach(namespace => {
356
289
  Object.values(namespace.models)
357
290
  .filter(({ syncable }) => syncable)
@@ -418,7 +351,6 @@ class SubscriptionProcessor {
418
351
  modelDefinition,
419
352
  operation,
420
353
  userCredentials,
421
- cognitoTokenPayload,
422
354
  oidcTokenPayload,
423
355
  readAuthModes[operationAuthModeAttempts[operation]],
424
356
  addFilter
@@ -459,9 +391,7 @@ class SubscriptionProcessor {
459
391
  );
460
392
 
461
393
  const queryObservable = <
462
- Observable<{
463
- value: GraphQLResult<Record<string, PersistentModel>>;
464
- }>
394
+ Observable<GraphQLResult<Record<string, PersistentModel>>>
465
395
  >(<unknown>this.amplifyContext.InternalAPI.graphql(
466
396
  {
467
397
  query,
@@ -473,202 +403,198 @@ class SubscriptionProcessor {
473
403
  customUserAgentDetails
474
404
  ));
475
405
 
476
- let subscriptionReadyCallback: () => void;
406
+ let subscriptionReadyCallback: (param?: unknown) => void;
477
407
 
478
408
  // TODO: consider onTerminate.then(() => API.cancel(...))
479
409
 
480
410
  subscriptions[modelDefinition.name][
481
411
  transformerMutationType
482
412
  ].push(
483
- queryObservable
484
- .map(({ value }) => {
485
- return value;
486
- })
487
- .subscribe({
488
- next: ({ data, errors }) => {
489
- if (Array.isArray(errors) && errors.length > 0) {
490
- const messages = (<
491
- {
492
- message: string;
493
- }[]
494
- >errors).map(({ message }) => message);
495
-
496
- logger.warn(
497
- `Skipping incoming subscription. Messages: ${messages.join(
498
- '\n'
499
- )}`
500
- );
501
-
502
- this.drainBuffer();
503
- return;
504
- }
413
+ queryObservable.subscribe({
414
+ next: result => {
415
+ const { data, errors } = result;
416
+ if (Array.isArray(errors) && errors.length > 0) {
417
+ const messages = (<
418
+ {
419
+ message: string;
420
+ }[]
421
+ >errors).map(({ message }) => message);
422
+
423
+ logger.warn(
424
+ `Skipping incoming subscription. Messages: ${messages.join(
425
+ '\n'
426
+ )}`
427
+ );
505
428
 
506
- const predicatesGroup =
507
- ModelPredicateCreator.getPredicates(
508
- this.syncPredicates.get(modelDefinition)!,
509
- false
510
- );
511
-
512
- // @ts-ignore
513
- const { [opName]: record } = data;
514
-
515
- // checking incoming subscription against syncPredicate.
516
- // once AppSync implements filters on subscriptions, we'll be
517
- // able to set these when establishing the subscription instead.
518
- // Until then, we'll need to filter inbound
519
- if (
520
- this.passesPredicateValidation(
521
- record,
522
- predicatesGroup!
523
- )
524
- ) {
525
- this.pushToBuffer(
526
- transformerMutationType,
527
- modelDefinition,
528
- record
529
- );
530
- }
531
429
  this.drainBuffer();
532
- },
533
- error: async subscriptionError => {
534
- const {
535
- error: { errors: [{ message = '' } = {}] } = {
536
- errors: [],
537
- },
538
- } = subscriptionError;
539
-
540
- const isRTFError =
541
- // only attempt catch if a filter variable was added to the subscription query
542
- addFilter &&
543
- this.catchRTFError(
544
- message,
545
- modelDefinition,
546
- predicatesGroup
547
- );
548
-
549
- // Catch RTF errors
550
- if (isRTFError) {
551
- // Unsubscribe and clear subscription array for model/operation
552
- subscriptions[modelDefinition.name][
553
- transformerMutationType
554
- ].forEach(subscription =>
555
- subscription.unsubscribe()
556
- );
557
-
558
- subscriptions[modelDefinition.name][
559
- transformerMutationType
560
- ] = [];
561
-
562
- // retry subscription connection without filter
563
- subscriptionRetry(operation, false);
564
- return;
565
- }
566
-
430
+ return;
431
+ }
432
+
433
+ const predicatesGroup =
434
+ ModelPredicateCreator.getPredicates(
435
+ this.syncPredicates.get(modelDefinition)!,
436
+ false
437
+ );
438
+
439
+ // @ts-ignore
440
+ const { [opName]: record } = data;
441
+
442
+ // checking incoming subscription against syncPredicate.
443
+ // once AppSync implements filters on subscriptions, we'll be
444
+ // able to set these when establishing the subscription instead.
445
+ // Until then, we'll need to filter inbound
446
+ if (
447
+ this.passesPredicateValidation(
448
+ record,
449
+ predicatesGroup!
450
+ )
451
+ ) {
452
+ this.pushToBuffer(
453
+ transformerMutationType,
454
+ modelDefinition,
455
+ record
456
+ );
457
+ }
458
+ this.drainBuffer();
459
+ },
460
+ error: async subscriptionError => {
461
+ const {
462
+ errors: [{ message = '' } = {}],
463
+ } = ({
464
+ errors: [],
465
+ } = subscriptionError);
466
+
467
+ const isRTFError =
468
+ // only attempt catch if a filter variable was added to the subscription query
469
+ addFilter &&
470
+ this.catchRTFError(
471
+ message,
472
+ modelDefinition,
473
+ predicatesGroup
474
+ );
475
+
476
+ // Catch RTF errors
477
+ if (isRTFError) {
478
+ // Unsubscribe and clear subscription array for model/operation
479
+ subscriptions[modelDefinition.name][
480
+ transformerMutationType
481
+ ].forEach(subscription =>
482
+ subscription.unsubscribe()
483
+ );
484
+
485
+ subscriptions[modelDefinition.name][
486
+ transformerMutationType
487
+ ] = [];
488
+
489
+ // retry subscription connection without filter
490
+ subscriptionRetry(operation, false);
491
+ return;
492
+ }
493
+
494
+ if (
495
+ message.includes(
496
+ PUBSUB_CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR
497
+ ) ||
498
+ message.includes(
499
+ PUBSUB_CONTROL_MSG.CONNECTION_FAILED
500
+ )
501
+ ) {
502
+ // Unsubscribe and clear subscription array for model/operation
503
+ subscriptions[modelDefinition.name][
504
+ transformerMutationType
505
+ ].forEach(subscription =>
506
+ subscription.unsubscribe()
507
+ );
508
+ subscriptions[modelDefinition.name][
509
+ transformerMutationType
510
+ ] = [];
511
+
512
+ operationAuthModeAttempts[operation]++;
567
513
  if (
568
- message.includes(
569
- PUBSUB_CONTROL_MSG.REALTIME_SUBSCRIPTION_INIT_ERROR
570
- ) ||
571
- message.includes(
572
- PUBSUB_CONTROL_MSG.CONNECTION_FAILED
573
- )
514
+ operationAuthModeAttempts[operation] >=
515
+ readAuthModes.length
574
516
  ) {
575
- // Unsubscribe and clear subscription array for model/operation
576
- subscriptions[modelDefinition.name][
577
- transformerMutationType
578
- ].forEach(subscription =>
579
- subscription.unsubscribe()
517
+ // last auth mode retry. Continue with error
518
+ logger.debug(
519
+ `${operation} subscription failed with authMode: ${
520
+ readAuthModes[
521
+ operationAuthModeAttempts[operation] - 1
522
+ ]
523
+ }`
580
524
  );
581
- subscriptions[modelDefinition.name][
582
- transformerMutationType
583
- ] = [];
584
-
585
- operationAuthModeAttempts[operation]++;
586
- if (
587
- operationAuthModeAttempts[operation] >=
588
- readAuthModes.length
589
- ) {
590
- // last auth mode retry. Continue with error
591
- logger.debug(
592
- `${operation} subscription failed with authMode: ${
593
- readAuthModes[
594
- operationAuthModeAttempts[operation] - 1
595
- ]
596
- }`
597
- );
598
- } else {
599
- // retry with different auth mode. Do not trigger
600
- // observer error or error handler
601
- logger.debug(
602
- `${operation} subscription failed with authMode: ${
603
- readAuthModes[
604
- operationAuthModeAttempts[operation] - 1
605
- ]
606
- }. Retrying with authMode: ${
607
- readAuthModes[
608
- operationAuthModeAttempts[operation]
609
- ]
610
- }`
611
- );
612
- subscriptionRetry(operation);
613
- return;
614
- }
615
- }
616
-
617
- logger.warn('subscriptionError', message);
618
-
619
- try {
620
- await this.errorHandler({
621
- recoverySuggestion:
622
- 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',
623
- localModel: null!,
624
- message,
625
- model: modelDefinition.name,
626
- operation,
627
- errorType:
628
- getSubscriptionErrorType(subscriptionError),
629
- process: ProcessName.subscribe,
630
- remoteModel: null!,
631
- cause: subscriptionError,
632
- });
633
- } catch (e) {
634
- logger.error(
635
- 'Subscription error handler failed with:',
636
- e
525
+ } else {
526
+ // retry with different auth mode. Do not trigger
527
+ // observer error or error handler
528
+ logger.debug(
529
+ `${operation} subscription failed with authMode: ${
530
+ readAuthModes[
531
+ operationAuthModeAttempts[operation] - 1
532
+ ]
533
+ }. Retrying with authMode: ${
534
+ readAuthModes[
535
+ operationAuthModeAttempts[operation]
536
+ ]
537
+ }`
637
538
  );
638
- }
639
-
640
- if (
641
- typeof subscriptionReadyCallback === 'function'
642
- ) {
643
- subscriptionReadyCallback();
644
- }
645
-
646
- if (
647
- message.includes('"errorType":"Unauthorized"') ||
648
- message.includes(
649
- '"errorType":"OperationDisabled"'
650
- )
651
- ) {
539
+ subscriptionRetry(operation);
652
540
  return;
653
541
  }
654
- observer.error(message);
655
- },
656
- })
542
+ }
543
+
544
+ logger.warn('subscriptionError', message);
545
+
546
+ try {
547
+ await this.errorHandler({
548
+ recoverySuggestion:
549
+ 'Ensure app code is up to date, auth directives exist and are correct on each model, and that server-side data has not been invalidated by a schema change. If the problem persists, search for or create an issue: https://github.com/aws-amplify/amplify-js/issues',
550
+ localModel: null!,
551
+ message,
552
+ model: modelDefinition.name,
553
+ operation,
554
+ errorType:
555
+ getSubscriptionErrorType(subscriptionError),
556
+ process: ProcessName.subscribe,
557
+ remoteModel: null!,
558
+ cause: subscriptionError,
559
+ });
560
+ } catch (e) {
561
+ logger.error(
562
+ 'Subscription error handler failed with:',
563
+ e
564
+ );
565
+ }
566
+
567
+ if (typeof subscriptionReadyCallback === 'function') {
568
+ subscriptionReadyCallback();
569
+ }
570
+
571
+ if (
572
+ message.includes('"errorType":"Unauthorized"') ||
573
+ message.includes('"errorType":"OperationDisabled"')
574
+ ) {
575
+ return;
576
+ }
577
+ observer.error(message);
578
+ },
579
+ })
657
580
  );
658
581
 
659
582
  promises.push(
660
583
  (async () => {
661
584
  let boundFunction: any;
662
-
585
+ let removeBoundFunctionListener: () => void;
663
586
  await new Promise(res => {
664
587
  subscriptionReadyCallback = res;
665
588
  boundFunction = this.hubQueryCompletionListener.bind(
666
589
  this,
667
590
  res
668
591
  );
669
- Hub.listen('api', boundFunction);
592
+ removeBoundFunctionListener = Hub.listen(
593
+ 'api',
594
+ boundFunction
595
+ );
670
596
  });
671
- Hub.remove('api', boundFunction);
597
+ removeBoundFunctionListener();
672
598
  })()
673
599
  );
674
600
  };