aws-appsync-subscription-link 3.0.8 → 3.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,38 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ <a name="3.0.11"></a>
7
+ ## [3.0.11](https://github.com/awslabs/aws-mobile-appsync-sdk-js/compare/aws-appsync-subscription-link@3.0.10...aws-appsync-subscription-link@3.0.11) (2022-05-02)
8
+
9
+
10
+
11
+
12
+ **Note:** Version bump only for package aws-appsync-subscription-link
13
+
14
+ <a name="3.0.10"></a>
15
+ ## [3.0.10](https://github.com/awslabs/aws-mobile-appsync-sdk-js/compare/aws-appsync-subscription-link@3.0.9...aws-appsync-subscription-link@3.0.10) (2022-03-04)
16
+
17
+
18
+ ### Bug Fixes
19
+
20
+ * Port over Amplify fix for subscription race conditions ([#509](https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/509)) ([#704](https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/704)) ([92b50c4](https://github.com/awslabs/aws-mobile-appsync-sdk-js/commit/92b50c4))
21
+
22
+
23
+
24
+
25
+ <a name="3.0.9"></a>
26
+ ## [3.0.9](https://github.com/awslabs/aws-mobile-appsync-sdk-js/compare/aws-appsync-subscription-link@3.0.8...aws-appsync-subscription-link@3.0.9) (2021-09-24)
27
+
28
+
29
+ ### Bug Fixes
30
+
31
+ * add type fix to subscription link to fix 'prepare' script ([#669](https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/669)) ([c5202dc](https://github.com/awslabs/aws-mobile-appsync-sdk-js/commit/c5202dc))
32
+ * **aws-appsync-subscription-link:** graphql header refactor to fix IAM-based auth ([#619](https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/619)) ([#671](https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/671)) ([dbf4959](https://github.com/awslabs/aws-mobile-appsync-sdk-js/commit/dbf4959))
33
+ * remove aws-sdk V2; import aws-sdk V3 packages ([#637](https://github.com/awslabs/aws-mobile-appsync-sdk-js/issues/637)); refactor auth-link, signer, and types ([0996740](https://github.com/awslabs/aws-mobile-appsync-sdk-js/commit/0996740))
34
+
35
+
36
+
37
+
6
38
  <a name="3.0.8"></a>
7
39
  ## [3.0.8](https://github.com/awslabs/aws-mobile-appsync-sdk-js/compare/aws-appsync-subscription-link@3.0.7...aws-appsync-subscription-link@3.0.8) (2021-07-28)
8
40
 
@@ -6,7 +6,8 @@ import { AppSyncRealTimeSubscriptionHandshakeLink } from '../../src/realtime-sub
6
6
  const query = gql`subscription { someSubscription { aField } }`
7
7
 
8
8
  class myWebSocket implements WebSocket {
9
- binaryType: BinaryType; bufferedAmount: number;
9
+ binaryType: BinaryType;
10
+ bufferedAmount: number;
10
11
  extensions: string;
11
12
  onclose: (this: WebSocket, ev: CloseEvent) => any;
12
13
  onerror: (this: WebSocket, ev: Event) => any;
@@ -49,8 +50,22 @@ describe("RealTime subscription link", () => {
49
50
  type: AUTH_TYPE.API_KEY,
50
51
  apiKey: 'xxxxx'
51
52
  },
52
- region: 'us-east-1',
53
- url: 'https://xxxxx.appsync-api.amazonaws.com/graphql'
53
+ region: 'us-west-2',
54
+ url: 'https://firsttesturl12345678901234.appsync-api.us-west-2.amazonaws.com/graphql'
55
+ });
56
+
57
+ expect(link).toBeInstanceOf(AppSyncRealTimeSubscriptionHandshakeLink);
58
+ });
59
+
60
+ test("Can instantiate link with custom domain", () => {
61
+ expect.assertions(1);
62
+ const link = new AppSyncRealTimeSubscriptionHandshakeLink({
63
+ auth: {
64
+ type: AUTH_TYPE.API_KEY,
65
+ apiKey: 'xxxxx'
66
+ },
67
+ region: 'us-west-2',
68
+ url: 'https://test1.testcustomdomain.com/graphql'
54
69
  });
55
70
 
56
71
  expect(link).toBeInstanceOf(AppSyncRealTimeSubscriptionHandshakeLink);
@@ -62,7 +77,7 @@ describe("RealTime subscription link", () => {
62
77
  return "2019-11-13T18:47:04.733Z";
63
78
  }));
64
79
  AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = jest.fn((url, protocol) => {
65
- expect(url).toBe('wss://xxxxx.appsync-realtime-api.amazonaws.com/graphql?header=eyJob3N0IjoieHh4eHguYXBwc3luYy1hcGkuYW1hem9uYXdzLmNvbSIsIngtYW16LWRhdGUiOiIyMDE5MTExM1QxODQ3MDRaIiwieC1hcGkta2V5IjoieHh4eHgifQ==&payload=e30=');
80
+ expect(url).toBe('wss://apikeytesturl1234567890123.appsync-realtime-api.us-west-2.amazonaws.com/graphql?header=eyJob3N0IjoiYXBpa2V5dGVzdHVybDEyMzQ1Njc4OTAxMjMuYXBwc3luYy1hcGkudXMtd2VzdC0yLmFtYXpvbmF3cy5jb20iLCJ4LWFtei1kYXRlIjoiMjAxOTExMTNUMTg0NzA0WiIsIngtYXBpLWtleSI6Inh4eHh4In0=&payload=e30=');
66
81
  expect(protocol).toBe('graphql-ws');
67
82
  done();
68
83
  return new myWebSocket();
@@ -72,13 +87,50 @@ describe("RealTime subscription link", () => {
72
87
  type: AUTH_TYPE.API_KEY,
73
88
  apiKey: 'xxxxx'
74
89
  },
75
- region: 'us-east-1',
76
- url: 'https://xxxxx.appsync-api.amazonaws.com/graphql'
90
+ region: 'us-west-2',
91
+ url: 'https://apikeytesturl1234567890123.appsync-api.us-west-2.amazonaws.com/graphql'
77
92
  });
78
93
 
79
94
  execute(link, { query }).subscribe({
80
95
  error: (err) => {
81
- console.log({ err });
96
+ console.log(JSON.stringify(err));
97
+ fail;
98
+ },
99
+ next: (data) => {
100
+ console.log({ data });
101
+ done();
102
+ },
103
+ complete: () => {
104
+ console.log('done with this');
105
+ done();
106
+ }
107
+
108
+ });
109
+ });
110
+
111
+ test("Initialize WebSocket correctly for API KEY with custom domain", (done) => {
112
+ expect.assertions(2);
113
+ jest.spyOn(Date.prototype, 'toISOString').mockImplementation(jest.fn(() => {
114
+ return "2019-11-13T18:47:04.733Z";
115
+ }));
116
+ AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = jest.fn((url, protocol) => {
117
+ expect(url).toBe('wss://apikeytest.testcustomdomain.com/graphql/realtime?header=eyJob3N0IjoiYXBpa2V5dGVzdC50ZXN0Y3VzdG9tZG9tYWluLmNvbSIsIngtYW16LWRhdGUiOiIyMDE5MTExM1QxODQ3MDRaIiwieC1hcGkta2V5IjoieHh4eHgifQ==&payload=e30=');
118
+ expect(protocol).toBe('graphql-ws');
119
+ done();
120
+ return new myWebSocket();
121
+ });
122
+ const link = new AppSyncRealTimeSubscriptionHandshakeLink({
123
+ auth: {
124
+ type: AUTH_TYPE.API_KEY,
125
+ apiKey: 'xxxxx'
126
+ },
127
+ region: 'us-west-2',
128
+ url: 'https://apikeytest.testcustomdomain.com/graphql'
129
+ });
130
+
131
+ execute(link, { query }).subscribe({
132
+ error: (err) => {
133
+ console.log(JSON.stringify(err));
82
134
  fail;
83
135
  },
84
136
  next: (data) => {
@@ -99,7 +151,7 @@ describe("RealTime subscription link", () => {
99
151
  return "2019-11-13T18:47:04.733Z";
100
152
  }));
101
153
  AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = jest.fn((url, protocol) => {
102
- expect(url).toBe('wss://xxxxx.appsync-realtime-api.amazonaws.com/graphql?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0IjoieHh4eHguYXBwc3luYy1hcGkuYW1hem9uYXdzLmNvbSJ9&payload=e30=');
154
+ expect(url).toBe('wss://cognitouserpooltesturl1234.appsync-realtime-api.us-west-2.amazonaws.com/graphql?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0IjoiY29nbml0b3VzZXJwb29sdGVzdHVybDEyMzQuYXBwc3luYy1hcGkudXMtd2VzdC0yLmFtYXpvbmF3cy5jb20ifQ==&payload=e30=');
103
155
  expect(protocol).toBe('graphql-ws');
104
156
  done();
105
157
  return new myWebSocket();
@@ -109,13 +161,50 @@ describe("RealTime subscription link", () => {
109
161
  type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
110
162
  jwtToken: 'token'
111
163
  },
112
- region: 'us-east-1',
113
- url: 'https://xxxxx.appsync-api.amazonaws.com/graphql'
164
+ region: 'us-west-2',
165
+ url: 'https://cognitouserpooltesturl1234.appsync-api.us-west-2.amazonaws.com/graphql'
114
166
  });
115
167
 
116
168
  execute(link, { query }).subscribe({
117
169
  error: (err) => {
118
- console.log({ err });
170
+ console.log(JSON.stringify(err));
171
+ fail;
172
+ },
173
+ next: (data) => {
174
+ console.log({ data });
175
+ done();
176
+ },
177
+ complete: () => {
178
+ console.log('done with this');
179
+ done();
180
+ }
181
+
182
+ });
183
+ });
184
+
185
+ test("Initialize WebSocket correctly for COGNITO USER POOLS with custom domain", (done) => {
186
+ expect.assertions(2);
187
+ jest.spyOn(Date.prototype, 'toISOString').mockImplementation(jest.fn(() => {
188
+ return "2019-11-13T18:47:04.733Z";
189
+ }));
190
+ AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = jest.fn((url, protocol) => {
191
+ expect(url).toBe('wss://cognitouserpools.testcustomdomain.com/graphql/realtime?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0IjoiY29nbml0b3VzZXJwb29scy50ZXN0Y3VzdG9tZG9tYWluLmNvbSJ9&payload=e30=');
192
+ expect(protocol).toBe('graphql-ws');
193
+ done();
194
+ return new myWebSocket();
195
+ });
196
+ const link = new AppSyncRealTimeSubscriptionHandshakeLink({
197
+ auth: {
198
+ type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS,
199
+ jwtToken: 'token'
200
+ },
201
+ region: 'us-west-2',
202
+ url: 'https://cognitouserpools.testcustomdomain.com/graphql'
203
+ });
204
+
205
+ execute(link, { query }).subscribe({
206
+ error: (err) => {
207
+ console.log(JSON.stringify(err));
119
208
  fail;
120
209
  },
121
210
  next: (data) => {
@@ -136,7 +225,44 @@ describe("RealTime subscription link", () => {
136
225
  return "2019-11-13T18:47:04.733Z";
137
226
  }));
138
227
  AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = jest.fn((url, protocol) => {
139
- expect(url).toBe('wss://xxxxx.appsync-realtime-api.amazonaws.com/graphql?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0IjoieHh4eHguYXBwc3luYy1hcGkuYW1hem9uYXdzLmNvbSJ9&payload=e30=');
228
+ expect(url).toBe('wss://openidconnecttesturl123456.appsync-realtime-api.us-west-2.amazonaws.com/graphql?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0Ijoib3BlbmlkY29ubmVjdHRlc3R1cmwxMjM0NTYuYXBwc3luYy1hcGkudXMtd2VzdC0yLmFtYXpvbmF3cy5jb20ifQ==&payload=e30=');
229
+ expect(protocol).toBe('graphql-ws');
230
+ done();
231
+ return new myWebSocket();
232
+ });
233
+ const link = new AppSyncRealTimeSubscriptionHandshakeLink({
234
+ auth: {
235
+ type: AUTH_TYPE.OPENID_CONNECT,
236
+ jwtToken: 'token'
237
+ },
238
+ region: 'us-west-2',
239
+ url: 'https://openidconnecttesturl123456.appsync-api.us-west-2.amazonaws.com/graphql'
240
+ });
241
+
242
+ execute(link, { query }).subscribe({
243
+ error: (err) => {
244
+ console.log(JSON.stringify(err));
245
+ fail;
246
+ },
247
+ next: (data) => {
248
+ console.log({ data });
249
+ done();
250
+ },
251
+ complete: () => {
252
+ console.log('done with this');
253
+ done();
254
+ }
255
+
256
+ });
257
+ });
258
+
259
+ test("Initialize WebSocket correctly for OPENID_CONNECT with custom domain", (done) => {
260
+ expect.assertions(2);
261
+ jest.spyOn(Date.prototype, 'toISOString').mockImplementation(jest.fn(() => {
262
+ return "2019-11-13T18:47:04.733Z";
263
+ }));
264
+ AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = jest.fn((url, protocol) => {
265
+ expect(url).toBe('wss://openidconnecttesturl.testcustomdomain.com/graphql/realtime?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0Ijoib3BlbmlkY29ubmVjdHRlc3R1cmwudGVzdGN1c3RvbWRvbWFpbi5jb20ifQ==&payload=e30=');
140
266
  expect(protocol).toBe('graphql-ws');
141
267
  done();
142
268
  return new myWebSocket();
@@ -146,13 +272,13 @@ describe("RealTime subscription link", () => {
146
272
  type: AUTH_TYPE.OPENID_CONNECT,
147
273
  jwtToken: 'token'
148
274
  },
149
- region: 'us-east-1',
150
- url: 'https://xxxxx.appsync-api.amazonaws.com/graphql'
275
+ region: 'us-west-2',
276
+ url: 'https://openidconnecttesturl.testcustomdomain.com/graphql'
151
277
  });
152
278
 
153
279
  execute(link, { query }).subscribe({
154
280
  error: (err) => {
155
- console.log({ err });
281
+ console.log(JSON.stringify(err));
156
282
  fail;
157
283
  },
158
284
  next: (data) => {
@@ -173,7 +299,41 @@ describe("RealTime subscription link", () => {
173
299
  return "2019-11-13T18:47:04.733Z";
174
300
  }));
175
301
  AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = jest.fn((url, protocol) => {
176
- expect(url).toBe('wss://xxxxx.appsync-realtime-api.amazonaws.com/graphql?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0IjoieHh4eHguYXBwc3luYy1hcGkuYW1hem9uYXdzLmNvbSJ9&payload=e30=');
302
+ expect(url).toBe('wss://awslambdatesturl1234567890.appsync-realtime-api.us-west-2.amazonaws.com/graphql?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0IjoiYXdzbGFtYmRhdGVzdHVybDEyMzQ1Njc4OTAuYXBwc3luYy1hcGkudXMtd2VzdC0yLmFtYXpvbmF3cy5jb20ifQ==&payload=e30=');
303
+ expect(protocol).toBe('graphql-ws');
304
+ done();
305
+ return new myWebSocket();
306
+ });
307
+ const link = new AppSyncRealTimeSubscriptionHandshakeLink({
308
+ auth: {
309
+ type: AUTH_TYPE.AWS_LAMBDA,
310
+ token: 'token'
311
+ },
312
+ region: 'us-west-2',
313
+ url: 'https://awslambdatesturl1234567890.appsync-api.us-west-2.amazonaws.com/graphql'
314
+ });
315
+
316
+ execute(link, { query }).subscribe({
317
+ error: (err) => {
318
+ fail;
319
+ },
320
+ next: (data) => {
321
+ done();
322
+ },
323
+ complete: () => {
324
+ done();
325
+ }
326
+
327
+ });
328
+ })
329
+
330
+ test('Initialize WebSocket correctly for AWS_LAMBDA with custom domain', (done) => {
331
+ expect.assertions(2);
332
+ jest.spyOn(Date.prototype, 'toISOString').mockImplementation(jest.fn(() => {
333
+ return "2019-11-13T18:47:04.733Z";
334
+ }));
335
+ AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = jest.fn((url, protocol) => {
336
+ expect(url).toBe('wss://awslambdatesturl.testcustomdomain.com/graphql/realtime?header=eyJBdXRob3JpemF0aW9uIjoidG9rZW4iLCJob3N0IjoiYXdzbGFtYmRhdGVzdHVybC50ZXN0Y3VzdG9tZG9tYWluLmNvbSJ9&payload=e30=');
177
337
  expect(protocol).toBe('graphql-ws');
178
338
  done();
179
339
  return new myWebSocket();
@@ -183,8 +343,8 @@ describe("RealTime subscription link", () => {
183
343
  type: AUTH_TYPE.AWS_LAMBDA,
184
344
  token: 'token'
185
345
  },
186
- region: 'us-east-1',
187
- url: 'https://xxxxx.appsync-api.amazonaws.com/graphql'
346
+ region: 'us-west-2',
347
+ url: 'https://awslambdatesturl.testcustomdomain.com/graphql'
188
348
  });
189
349
 
190
350
  execute(link, { query }).subscribe({
package/lib/index.js CHANGED
@@ -28,7 +28,7 @@ function createSubscriptionHandshakeLink(infoOrUrl, theResultsFetcherLink) {
28
28
  link: new core_1.ApolloLink(function (operation, _forward) {
29
29
  return new core_1.Observable(function (observer) {
30
30
  var _a;
31
- var _b = operation.variables, _c = subscription_handshake_link_1.CONTROL_EVENTS_KEY, controlEvents = _b[_c], variables = __rest(_b, [typeof _c === "symbol" ? _c : _c + ""]);
31
+ var _b = operation, _c = _b.variables, _d = subscription_handshake_link_1.CONTROL_EVENTS_KEY, controlEvents = _c[_d], variables = __rest(_c, [typeof _d === "symbol" ? _d : _d + ""]);
32
32
  if (typeof controlEvents !== "undefined") {
33
33
  operation.variables = variables;
34
34
  }
@@ -2,12 +2,14 @@
2
2
  * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import { ApolloLink, NextLink } from '@apollo/client/core';
5
+ import { ApolloLink } from '@apollo/client/core';
6
+ import type { NextLink, FetchResult } from '@apollo/client/core';
7
+ import type { Observable } from 'zen-observable-ts';
6
8
  export declare class NonTerminatingLink extends ApolloLink {
7
9
  private contextKey;
8
10
  private link;
9
11
  constructor(contextKey: string, { link }: {
10
12
  link: ApolloLink;
11
13
  });
12
- request(operation: any, forward?: NextLink): any;
14
+ request(operation: any, forward?: NextLink): Observable<FetchResult>;
13
15
  }
@@ -77,7 +77,7 @@ var NonTerminatingLink = /** @class */ (function (_super) {
77
77
  }
78
78
  NonTerminatingLink.prototype.request = function (operation, forward) {
79
79
  var _this = this;
80
- return context_1.setContext(function (_request, prevContext) { return __awaiter(_this, void 0, void 0, function () {
80
+ return (context_1.setContext(function (_request, prevContext) { return __awaiter(_this, void 0, void 0, function () {
81
81
  var result;
82
82
  var _a;
83
83
  var _this = this;
@@ -94,7 +94,7 @@ var NonTerminatingLink = /** @class */ (function (_super) {
94
94
  return [2 /*return*/, __assign(__assign({}, prevContext), (_a = {}, _a[this.contextKey] = result, _a))];
95
95
  }
96
96
  });
97
- }); }).request(operation, forward);
97
+ }); })).request(operation, forward);
98
98
  };
99
99
  return NonTerminatingLink;
100
100
  }(core_1.ApolloLink));
@@ -1,8 +1,8 @@
1
1
  /*!
2
- * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ * Copyright 2017-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import { ApolloLink, Operation } from "@apollo/client/core";
5
+ import { ApolloLink, Observable, Operation, FetchResult } from "@apollo/client/core";
6
6
  import { UrlInfo } from "./types";
7
7
  export declare const CONTROL_EVENTS_KEY = "@@controlEvents";
8
8
  export declare class AppSyncRealTimeSubscriptionHandshakeLink extends ApolloLink {
@@ -16,11 +16,12 @@ export declare class AppSyncRealTimeSubscriptionHandshakeLink extends ApolloLink
16
16
  private subscriptionObserverMap;
17
17
  private promiseArray;
18
18
  constructor({ url: theUrl, region: theRegion, auth: theAuth }: UrlInfo);
19
- request(operation: Operation): any;
19
+ private isCustomDomain;
20
+ request(operation: Operation): Observable<FetchResult<Record<string, any>, Record<string, any>, Record<string, any>>>;
20
21
  private _verifySubscriptionAlreadyStarted;
21
22
  private _sendUnsubscriptionMessage;
22
23
  private _removeSubscriptionObserver;
23
- private _closeSocketWhenFlushed;
24
+ private _closeSocketIfRequired;
24
25
  private _startSubscriptionWithAWSAppSyncRealTime;
25
26
  private _initializeWebSocketConnection;
26
27
  private _awsRealTimeHeaderBasedAuth;
@@ -33,5 +34,4 @@ export declare class AppSyncRealTimeSubscriptionHandshakeLink extends ApolloLink
33
34
  private _errorDisconnect;
34
35
  private _timeoutStartSubscriptionAck;
35
36
  static createWebSocket(awsRealTimeUrl: string, protocol: string): WebSocket;
36
- private static _discoverAppSyncRealTimeEndpoint;
37
37
  }
@@ -61,7 +61,7 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
61
61
  };
62
62
  Object.defineProperty(exports, "__esModule", { value: true });
63
63
  /*!
64
- * Copyright 2017-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
64
+ * Copyright 2017-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
65
65
  * SPDX-License-Identifier: Apache-2.0
66
66
  */
67
67
  var core_1 = require("@apollo/client/core");
@@ -93,6 +93,8 @@ var START_ACK_TIMEOUT = 15000;
93
93
  * Default Time in milliseconds to wait for GQL_CONNECTION_KEEP_ALIVE message
94
94
  */
95
95
  var DEFAULT_KEEP_ALIVE_TIMEOUT = 5 * 60 * 1000;
96
+ var standardDomainPattern = /^https:\/\/\w{26}\.appsync\-api\.\w{2}(?:(?:\-\w{2,})+)\-\d\.amazonaws.com\/graphql$/i;
97
+ var customDomainPath = '/realtime';
96
98
  var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super) {
97
99
  __extends(AppSyncRealTimeSubscriptionHandshakeLink, _super);
98
100
  function AppSyncRealTimeSubscriptionHandshakeLink(_a) {
@@ -107,6 +109,10 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
107
109
  _this.auth = theAuth;
108
110
  return _this;
109
111
  }
112
+ // Check if url matches standard domain pattern
113
+ AppSyncRealTimeSubscriptionHandshakeLink.prototype.isCustomDomain = function (url) {
114
+ return url.match(standardDomainPattern) === null;
115
+ };
110
116
  AppSyncRealTimeSubscriptionHandshakeLink.prototype.request = function (operation) {
111
117
  var _a;
112
118
  var _this = this;
@@ -220,22 +226,25 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
220
226
  };
221
227
  AppSyncRealTimeSubscriptionHandshakeLink.prototype._removeSubscriptionObserver = function (subscriptionId) {
222
228
  this.subscriptionObserverMap.delete(subscriptionId);
223
- if (this.subscriptionObserverMap.size === 0) {
224
- // Socket could be sending data to unsubscribe so is required to wait until is flushed
225
- this._closeSocketWhenFlushed();
226
- }
229
+ // Verifying for 1000ms after removing subscription in case there are new subscriptions on mount / unmount
230
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
227
231
  };
228
- AppSyncRealTimeSubscriptionHandshakeLink.prototype._closeSocketWhenFlushed = function () {
229
- logger("closing WebSocket...");
230
- clearTimeout(this.keepAliveTimeoutId);
232
+ AppSyncRealTimeSubscriptionHandshakeLink.prototype._closeSocketIfRequired = function () {
233
+ if (this.subscriptionObserverMap.size > 0) {
234
+ // There are active subscriptions on the WebSocket
235
+ return;
236
+ }
231
237
  if (!this.awsRealTimeSocket) {
232
238
  this.socketStatus = types_1.SOCKET_STATUS.CLOSED;
233
239
  return;
234
240
  }
235
241
  if (this.awsRealTimeSocket.bufferedAmount > 0) {
236
- setTimeout(this._closeSocketWhenFlushed.bind(this), 1000);
242
+ // There is still data on the WebSocket
243
+ setTimeout(this._closeSocketIfRequired.bind(this), 1000);
237
244
  }
238
245
  else {
246
+ logger("closing WebSocket...");
247
+ clearTimeout(this.keepAliveTimeoutId);
239
248
  var tempSocket = this.awsRealTimeSocket;
240
249
  tempSocket.close(1000);
241
250
  this.awsRealTimeSocket = null;
@@ -245,11 +254,11 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
245
254
  AppSyncRealTimeSubscriptionHandshakeLink.prototype._startSubscriptionWithAWSAppSyncRealTime = function (_a) {
246
255
  var options = _a.options, observer = _a.observer, subscriptionId = _a.subscriptionId;
247
256
  return __awaiter(this, void 0, void 0, function () {
248
- var appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, _b, graphql_headers, credentials, token, subscriptionState, data, dataString, headerObj, _c, _d, subscriptionMessage, stringToAWSRealTime, err_1, _e, message, subscriptionFailedCallback_1, _f, subscriptionFailedCallback, subscriptionReadyCallback;
249
- var _g;
257
+ var appSyncGraphqlEndpoint, authenticationType, query, variables, apiKey, region, _b, graphql_headers, credentials, token, subscriptionState, data, dataString, headerObj, _c, subscriptionMessage, stringToAWSRealTime, err_1, _d, message, subscriptionFailedCallback_1, _e, subscriptionFailedCallback, subscriptionReadyCallback;
258
+ var _f;
250
259
  var _this = this;
251
- return __generator(this, function (_h) {
252
- switch (_h.label) {
260
+ return __generator(this, function (_g) {
261
+ switch (_g.label) {
253
262
  case 0:
254
263
  appSyncGraphqlEndpoint = options.appSyncGraphqlEndpoint, authenticationType = options.authenticationType, query = options.query, variables = options.variables, apiKey = options.apiKey, region = options.region, _b = options.graphql_headers, graphql_headers = _b === void 0 ? function () { return ({}); } : _b, credentials = options.credentials, token = options.token;
255
264
  subscriptionState = types_1.SUBSCRIPTION_STATUS.PENDING;
@@ -275,13 +284,11 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
275
284
  canonicalUri: "",
276
285
  region: region,
277
286
  credentials: credentials,
278
- token: token
287
+ token: token,
288
+ graphql_headers: graphql_headers
279
289
  })];
280
290
  case 1:
281
- _d = [__assign.apply(void 0, _c.concat([(_h.sent())]))];
282
- return [4 /*yield*/, graphql_headers()];
283
- case 2:
284
- headerObj = __assign.apply(void 0, [__assign.apply(void 0, _d.concat([(_h.sent())])), (_g = {}, _g[aws_appsync_auth_link_1.USER_AGENT_HEADER] = aws_appsync_auth_link_1.USER_AGENT, _g)]);
291
+ headerObj = __assign.apply(void 0, [__assign.apply(void 0, _c.concat([(_g.sent())])), (_f = {}, _f[aws_appsync_auth_link_1.USER_AGENT_HEADER] = aws_appsync_auth_link_1.USER_AGENT, _f)]);
285
292
  subscriptionMessage = {
286
293
  id: subscriptionId,
287
294
  payload: {
@@ -293,9 +300,9 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
293
300
  type: types_1.MESSAGE_TYPES.GQL_START
294
301
  };
295
302
  stringToAWSRealTime = JSON.stringify(subscriptionMessage);
296
- _h.label = 3;
297
- case 3:
298
- _h.trys.push([3, 5, , 6]);
303
+ _g.label = 2;
304
+ case 2:
305
+ _g.trys.push([2, 4, , 5]);
299
306
  return [4 /*yield*/, this._initializeWebSocketConnection({
300
307
  apiKey: apiKey,
301
308
  appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
@@ -304,12 +311,12 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
304
311
  credentials: credentials,
305
312
  token: token
306
313
  })];
314
+ case 3:
315
+ _g.sent();
316
+ return [3 /*break*/, 5];
307
317
  case 4:
308
- _h.sent();
309
- return [3 /*break*/, 6];
310
- case 5:
311
- err_1 = _h.sent();
312
- _e = err_1.message, message = _e === void 0 ? "" : _e;
318
+ err_1 = _g.sent();
319
+ _d = err_1.message, message = _d === void 0 ? "" : _d;
313
320
  observer.error({
314
321
  errors: [
315
322
  __assign({}, new graphql_1.GraphQLError("Connection failed: " + message))
@@ -322,8 +329,8 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
322
329
  subscriptionFailedCallback_1();
323
330
  }
324
331
  return [2 /*return*/];
325
- case 6:
326
- _f = this.subscriptionObserverMap.get(subscriptionId), subscriptionFailedCallback = _f.subscriptionFailedCallback, subscriptionReadyCallback = _f.subscriptionReadyCallback;
332
+ case 5:
333
+ _e = this.subscriptionObserverMap.get(subscriptionId), subscriptionFailedCallback = _e.subscriptionFailedCallback, subscriptionReadyCallback = _e.subscriptionReadyCallback;
327
334
  // This must be done before sending the message in order to be listening immediately
328
335
  this.subscriptionObserverMap.set(subscriptionId, {
329
336
  observer: observer,
@@ -351,7 +358,7 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
351
358
  return;
352
359
  }
353
360
  return new Promise(function (res, rej) { return __awaiter(_this, void 0, void 0, function () {
354
- var discoverableEndpoint, payloadString, headerString, _a, _b, headerQs, payloadQs, awsRealTimeUrl, err_2;
361
+ var payloadString, headerString, _a, _b, headerQs, payloadQs, discoverableEndpoint, awsRealTimeUrl, err_2;
355
362
  return __generator(this, function (_c) {
356
363
  switch (_c.label) {
357
364
  case 0:
@@ -361,7 +368,6 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
361
368
  case 1:
362
369
  _c.trys.push([1, 4, , 5]);
363
370
  this.socketStatus = types_1.SOCKET_STATUS.CONNECTING;
364
- discoverableEndpoint = AppSyncRealTimeSubscriptionHandshakeLink._discoverAppSyncRealTimeEndpoint(this.url);
365
371
  payloadString = "{}";
366
372
  _b = (_a = JSON).stringify;
367
373
  return [4 /*yield*/, this._awsRealTimeHeaderBasedAuth({
@@ -372,12 +378,23 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
372
378
  appSyncGraphqlEndpoint: appSyncGraphqlEndpoint,
373
379
  region: region,
374
380
  credentials: credentials,
375
- token: token
381
+ token: token,
382
+ graphql_headers: function () { }
376
383
  })];
377
384
  case 2:
378
385
  headerString = _b.apply(_a, [_c.sent()]);
379
386
  headerQs = Buffer.from(headerString).toString("base64");
380
387
  payloadQs = Buffer.from(payloadString).toString("base64");
388
+ discoverableEndpoint = appSyncGraphqlEndpoint;
389
+ if (this.isCustomDomain(discoverableEndpoint)) {
390
+ discoverableEndpoint = discoverableEndpoint.concat(customDomainPath);
391
+ }
392
+ else {
393
+ discoverableEndpoint = discoverableEndpoint.replace('appsync-api', 'appsync-realtime-api').replace('gogi-beta', 'grt-beta');
394
+ }
395
+ discoverableEndpoint = discoverableEndpoint
396
+ .replace("https://", "wss://")
397
+ .replace('http://', 'ws://');
381
398
  awsRealTimeUrl = discoverableEndpoint + "?header=" + headerQs + "&payload=" + payloadQs;
382
399
  return [4 /*yield*/, this._initializeRetryableHandshake({ awsRealTimeUrl: awsRealTimeUrl })];
383
400
  case 3:
@@ -410,7 +427,7 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
410
427
  }); });
411
428
  };
412
429
  AppSyncRealTimeSubscriptionHandshakeLink.prototype._awsRealTimeHeaderBasedAuth = function (_a) {
413
- var authenticationType = _a.authenticationType, payload = _a.payload, canonicalUri = _a.canonicalUri, appSyncGraphqlEndpoint = _a.appSyncGraphqlEndpoint, apiKey = _a.apiKey, region = _a.region, credentials = _a.credentials, token = _a.token;
430
+ var authenticationType = _a.authenticationType, payload = _a.payload, canonicalUri = _a.canonicalUri, appSyncGraphqlEndpoint = _a.appSyncGraphqlEndpoint, apiKey = _a.apiKey, region = _a.region, credentials = _a.credentials, token = _a.token, graphql_headers = _a.graphql_headers;
414
431
  return __awaiter(this, void 0, void 0, function () {
415
432
  var headerHandler, handler, host, result;
416
433
  return __generator(this, function (_b) {
@@ -437,7 +454,8 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
437
454
  region: region,
438
455
  host: host,
439
456
  credentials: credentials,
440
- token: token
457
+ token: token,
458
+ graphql_headers: graphql_headers
441
459
  })];
442
460
  case 1:
443
461
  result = _b.sent();
@@ -447,41 +465,43 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
447
465
  });
448
466
  };
449
467
  AppSyncRealTimeSubscriptionHandshakeLink.prototype._awsRealTimeAuthorizationHeader = function (_a) {
450
- var host = _a.host, token = _a.token;
468
+ var host = _a.host, token = _a.token, graphql_headers = _a.graphql_headers;
451
469
  return __awaiter(this, void 0, void 0, function () {
452
- var _b, _c;
453
- return __generator(this, function (_d) {
454
- switch (_d.label) {
470
+ var _b, _c, _d;
471
+ return __generator(this, function (_e) {
472
+ switch (_e.label) {
455
473
  case 0:
456
474
  _b = {};
457
475
  if (!(typeof token === "function")) return [3 /*break*/, 2];
458
476
  return [4 /*yield*/, token.call(undefined)];
459
477
  case 1:
460
- _c = _d.sent();
478
+ _c = _e.sent();
461
479
  return [3 /*break*/, 4];
462
480
  case 2: return [4 /*yield*/, token];
463
481
  case 3:
464
- _c = _d.sent();
465
- _d.label = 4;
466
- case 4: return [2 /*return*/, (_b.Authorization = _c,
467
- _b.host = host,
468
- _b)];
482
+ _c = _e.sent();
483
+ _e.label = 4;
484
+ case 4:
485
+ _d = [(_b.Authorization = _c, _b.host = host, _b)];
486
+ return [4 /*yield*/, graphql_headers()];
487
+ case 5: return [2 /*return*/, __assign.apply(void 0, _d.concat([(_e.sent())]))];
469
488
  }
470
489
  });
471
490
  });
472
491
  };
473
492
  AppSyncRealTimeSubscriptionHandshakeLink.prototype._awsRealTimeApiKeyHeader = function (_a) {
474
- var apiKey = _a.apiKey, host = _a.host;
493
+ var apiKey = _a.apiKey, host = _a.host, graphql_headers = _a.graphql_headers;
475
494
  return __awaiter(this, void 0, void 0, function () {
476
- var dt, dtStr;
477
- return __generator(this, function (_b) {
478
- dt = new Date();
479
- dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, "");
480
- return [2 /*return*/, {
481
- host: host,
482
- "x-amz-date": dtStr,
483
- "x-api-key": apiKey
484
- }];
495
+ var dt, dtStr, _b;
496
+ return __generator(this, function (_c) {
497
+ switch (_c.label) {
498
+ case 0:
499
+ dt = new Date();
500
+ dtStr = dt.toISOString().replace(/[:\-]|\.\d{3}/g, "");
501
+ _b = [{ host: host, "x-amz-date": dtStr, "x-api-key": apiKey }];
502
+ return [4 /*yield*/, graphql_headers()];
503
+ case 1: return [2 /*return*/, __assign.apply(void 0, _b.concat([(_c.sent())]))];
504
+ }
485
505
  });
486
506
  });
487
507
  };
@@ -755,13 +775,6 @@ var AppSyncRealTimeSubscriptionHandshakeLink = /** @class */ (function (_super)
755
775
  AppSyncRealTimeSubscriptionHandshakeLink.createWebSocket = function (awsRealTimeUrl, protocol) {
756
776
  return new WebSocket(awsRealTimeUrl, protocol);
757
777
  };
758
- AppSyncRealTimeSubscriptionHandshakeLink._discoverAppSyncRealTimeEndpoint = function (url) {
759
- return url
760
- .replace("https://", "wss://")
761
- .replace('http://', 'ws://')
762
- .replace("appsync-api", "appsync-realtime-api")
763
- .replace("gogi-beta", "grt-beta");
764
- };
765
778
  return AppSyncRealTimeSubscriptionHandshakeLink;
766
779
  }(core_1.ApolloLink));
767
780
  exports.AppSyncRealTimeSubscriptionHandshakeLink = AppSyncRealTimeSubscriptionHandshakeLink;
@@ -2,7 +2,7 @@
2
2
  * Copyright 2017-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3
3
  * SPDX-License-Identifier: Apache-2.0
4
4
  */
5
- import { ApolloLink, Operation, FetchResult } from "@apollo/client/core";
5
+ import { ApolloLink, Observable, Operation, FetchResult } from "@apollo/client/core";
6
6
  declare type MqttConnectionInfo = {
7
7
  client: string;
8
8
  url: string;
@@ -14,7 +14,7 @@ export declare class SubscriptionHandshakeLink extends ApolloLink {
14
14
  private topicObservers;
15
15
  private clientObservers;
16
16
  constructor(subsInfoContextKey: any);
17
- request(operation: Operation): any;
17
+ request(operation: Operation): Observable<unknown>;
18
18
  connectNewClients(connectionInfo: MqttConnectionInfo[], observer: ZenObservable.Observer<FetchResult>, operation: Operation): Promise<any[]>;
19
19
  connectNewClient(connectionInfo: MqttConnectionInfo, observer: ZenObservable.Observer<FetchResult>, selectionNames: string[]): Promise<any>;
20
20
  subscribeToTopics<T>(client: any, topics: string[], observer: ZenObservable.Observer<T>): Promise<unknown[]>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aws-appsync-subscription-link",
3
- "version": "3.0.8",
3
+ "version": "3.0.11",
4
4
  "main": "lib/index.js",
5
5
  "license": "Apache-2.0",
6
6
  "description": "AWS Mobile AppSync SDK for JavaScript",
@@ -19,7 +19,7 @@
19
19
  "test-watch": "jest --watch"
20
20
  },
21
21
  "dependencies": {
22
- "aws-appsync-auth-link": "^3.0.6",
22
+ "aws-appsync-auth-link": "^3.0.7",
23
23
  "debug": "2.6.9",
24
24
  "url": "^0.11.0"
25
25
  },