@aws-amplify/pubsub 5.5.6-api-v6-models.b3abc9b.0 → 6.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 (150) hide show
  1. package/iot/packages.json +7 -0
  2. package/lib/Providers/AWSIot.d.ts +10 -0
  3. package/lib/Providers/AWSIot.js +34 -0
  4. package/lib/Providers/{MqttOverWSProvider.d.ts → MqttOverWS.d.ts} +16 -16
  5. package/lib/Providers/MqttOverWS.js +274 -0
  6. package/lib/Providers/PubSub.d.ts +11 -0
  7. package/lib/Providers/PubSub.js +19 -0
  8. package/lib/Providers/constants.d.ts +1 -1
  9. package/lib/Providers/constants.js +3 -4
  10. package/lib/Providers/index.d.ts +3 -4
  11. package/lib/Providers/index.js +8 -10
  12. package/lib/clients/iot.d.ts +1 -0
  13. package/lib/clients/iot.js +7 -0
  14. package/lib/clients/mqtt.d.ts +1 -0
  15. package/lib/clients/mqtt.js +7 -0
  16. package/lib/index.d.ts +2 -2
  17. package/lib/index.js +7 -11
  18. package/lib/tsconfig.tsbuildinfo +1 -0
  19. package/lib/types/PubSub.d.ts +21 -3
  20. package/lib/types/PubSub.js +1 -1
  21. package/lib/types/index.d.ts +0 -1
  22. package/lib/types/index.js +5 -3
  23. package/lib/utils/ConnectionStateMonitor.d.ts +5 -5
  24. package/lib/utils/ConnectionStateMonitor.js +52 -64
  25. package/lib/utils/ReachabilityMonitor/index.d.ts +1 -3
  26. package/lib/utils/ReachabilityMonitor/index.js +4 -3
  27. package/lib/utils/ReachabilityMonitor/index.native.d.ts +1 -3
  28. package/lib/utils/ReachabilityMonitor/index.native.js +7 -8
  29. package/lib/utils/ReconnectionMonitor.d.ts +1 -1
  30. package/lib/utils/ReconnectionMonitor.js +21 -25
  31. package/lib-esm/Providers/AWSIot.d.ts +10 -0
  32. package/lib-esm/Providers/AWSIot.js +30 -0
  33. package/lib-esm/Providers/{MqttOverWSProvider.d.ts → MqttOverWS.d.ts} +16 -16
  34. package/lib-esm/Providers/MqttOverWS.js +268 -0
  35. package/lib-esm/Providers/PubSub.d.ts +11 -0
  36. package/lib-esm/Providers/PubSub.js +15 -0
  37. package/lib-esm/Providers/constants.d.ts +1 -1
  38. package/lib-esm/Providers/constants.js +11 -14
  39. package/lib-esm/Providers/index.d.ts +3 -4
  40. package/lib-esm/Providers/index.js +3 -5
  41. package/lib-esm/clients/iot.d.ts +1 -0
  42. package/{src/internals/index.ts → lib-esm/clients/iot.js} +1 -1
  43. package/lib-esm/clients/mqtt.d.ts +1 -0
  44. package/lib-esm/{internals/index.js → clients/mqtt.js} +1 -2
  45. package/lib-esm/index.d.ts +2 -2
  46. package/lib-esm/index.js +2 -3
  47. package/lib-esm/tsconfig.tsbuildinfo +1 -0
  48. package/lib-esm/types/PubSub.d.ts +21 -3
  49. package/lib-esm/types/PubSub.js +0 -1
  50. package/lib-esm/types/index.d.ts +0 -1
  51. package/lib-esm/types/index.js +2 -1
  52. package/lib-esm/utils/ConnectionStateMonitor.d.ts +5 -5
  53. package/lib-esm/utils/ConnectionStateMonitor.js +50 -64
  54. package/lib-esm/utils/ReachabilityMonitor/index.d.ts +1 -3
  55. package/lib-esm/utils/ReachabilityMonitor/index.js +2 -3
  56. package/lib-esm/utils/ReachabilityMonitor/index.native.d.ts +1 -3
  57. package/lib-esm/utils/ReachabilityMonitor/index.native.js +2 -5
  58. package/lib-esm/utils/ReconnectionMonitor.d.ts +1 -1
  59. package/lib-esm/utils/ReconnectionMonitor.js +19 -25
  60. package/mqtt/packages.json +7 -0
  61. package/package.json +146 -126
  62. package/src/Providers/{AWSIotProvider.ts → AWSIot.ts} +17 -15
  63. package/src/Providers/{MqttOverWSProvider.ts → MqttOverWS.ts} +38 -50
  64. package/src/Providers/PubSub.ts +40 -0
  65. package/src/Providers/constants.ts +2 -6
  66. package/src/Providers/index.ts +3 -12
  67. package/src/clients/iot.ts +4 -0
  68. package/src/clients/mqtt.ts +7 -0
  69. package/src/index.ts +3 -12
  70. package/src/types/PubSub.ts +28 -5
  71. package/src/types/index.ts +0 -1
  72. package/src/utils/ConnectionStateMonitor.ts +17 -13
  73. package/src/utils/ReachabilityMonitor/index.native.ts +2 -1
  74. package/src/utils/ReachabilityMonitor/index.ts +1 -1
  75. package/src/utils/ReconnectionMonitor.ts +1 -1
  76. package/internals/package.json +0 -8
  77. package/lib/.tsbuildinfo +0 -3
  78. package/lib/Providers/AWSAppSyncRealTimeProvider/index.d.ts +0 -77
  79. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js +0 -856
  80. package/lib/Providers/AWSAppSyncRealTimeProvider/index.js.map +0 -1
  81. package/lib/Providers/AWSIotProvider.d.ts +0 -11
  82. package/lib/Providers/AWSIotProvider.js +0 -53
  83. package/lib/Providers/AWSIotProvider.js.map +0 -1
  84. package/lib/Providers/MqttOverWSProvider.js +0 -396
  85. package/lib/Providers/MqttOverWSProvider.js.map +0 -1
  86. package/lib/Providers/PubSubProvider.d.ts +0 -15
  87. package/lib/Providers/PubSubProvider.js +0 -28
  88. package/lib/Providers/PubSubProvider.js.map +0 -1
  89. package/lib/Providers/constants.js.map +0 -1
  90. package/lib/Providers/index.js.map +0 -1
  91. package/lib/PubSub.d.ts +0 -13
  92. package/lib/PubSub.js +0 -22
  93. package/lib/PubSub.js.map +0 -1
  94. package/lib/index.js.map +0 -1
  95. package/lib/internals/InternalPubSub.d.ts +0 -50
  96. package/lib/internals/InternalPubSub.js +0 -136
  97. package/lib/internals/InternalPubSub.js.map +0 -1
  98. package/lib/internals/index.d.ts +0 -1
  99. package/lib/internals/index.js +0 -8
  100. package/lib/internals/index.js.map +0 -1
  101. package/lib/types/Provider.d.ts +0 -18
  102. package/lib/types/Provider.js +0 -3
  103. package/lib/types/Provider.js.map +0 -1
  104. package/lib/types/PubSub.js.map +0 -1
  105. package/lib/types/index.js.map +0 -1
  106. package/lib/utils/ConnectionStateMonitor.js.map +0 -1
  107. package/lib/utils/ReachabilityMonitor/index.js.map +0 -1
  108. package/lib/utils/ReachabilityMonitor/index.native.js.map +0 -1
  109. package/lib/utils/ReconnectionMonitor.js.map +0 -1
  110. package/lib/vendor/paho-mqtt.d.ts +0 -2
  111. package/lib/vendor/paho-mqtt.js.map +0 -1
  112. package/lib-esm/.tsbuildinfo +0 -3
  113. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.d.ts +0 -77
  114. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js +0 -854
  115. package/lib-esm/Providers/AWSAppSyncRealTimeProvider/index.js.map +0 -1
  116. package/lib-esm/Providers/AWSIotProvider.d.ts +0 -11
  117. package/lib-esm/Providers/AWSIotProvider.js +0 -51
  118. package/lib-esm/Providers/AWSIotProvider.js.map +0 -1
  119. package/lib-esm/Providers/MqttOverWSProvider.js +0 -393
  120. package/lib-esm/Providers/MqttOverWSProvider.js.map +0 -1
  121. package/lib-esm/Providers/PubSubProvider.d.ts +0 -15
  122. package/lib-esm/Providers/PubSubProvider.js +0 -26
  123. package/lib-esm/Providers/PubSubProvider.js.map +0 -1
  124. package/lib-esm/Providers/constants.js.map +0 -1
  125. package/lib-esm/Providers/index.js.map +0 -1
  126. package/lib-esm/PubSub.d.ts +0 -13
  127. package/lib-esm/PubSub.js +0 -20
  128. package/lib-esm/PubSub.js.map +0 -1
  129. package/lib-esm/index.js.map +0 -1
  130. package/lib-esm/internals/InternalPubSub.d.ts +0 -50
  131. package/lib-esm/internals/InternalPubSub.js +0 -134
  132. package/lib-esm/internals/InternalPubSub.js.map +0 -1
  133. package/lib-esm/internals/index.d.ts +0 -1
  134. package/lib-esm/internals/index.js.map +0 -1
  135. package/lib-esm/types/Provider.d.ts +0 -18
  136. package/lib-esm/types/Provider.js +0 -1
  137. package/lib-esm/types/Provider.js.map +0 -1
  138. package/lib-esm/types/PubSub.js.map +0 -1
  139. package/lib-esm/types/index.js.map +0 -1
  140. package/lib-esm/utils/ConnectionStateMonitor.js.map +0 -1
  141. package/lib-esm/utils/ReachabilityMonitor/index.js.map +0 -1
  142. package/lib-esm/utils/ReachabilityMonitor/index.native.js.map +0 -1
  143. package/lib-esm/utils/ReconnectionMonitor.js.map +0 -1
  144. package/lib-esm/vendor/paho-mqtt.d.ts +0 -2
  145. package/lib-esm/vendor/paho-mqtt.js.map +0 -1
  146. package/src/Providers/AWSAppSyncRealTimeProvider/index.ts +0 -1049
  147. package/src/Providers/PubSubProvider.ts +0 -53
  148. package/src/PubSub.ts +0 -33
  149. package/src/internals/InternalPubSub.ts +0 -185
  150. package/src/types/Provider.ts +0 -37
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- var constants_1 = require("../Providers/constants");
3
+ exports.ReconnectionMonitor = exports.ReconnectEvent = void 0;
4
+ const constants_1 = require("../Providers/constants");
4
5
  var ReconnectEvent;
5
6
  (function (ReconnectEvent) {
6
7
  ReconnectEvent["START_RECONNECT"] = "START_RECONNECT";
@@ -12,31 +13,30 @@ var ReconnectEvent;
12
13
  * Attempting to reconnect only once creates unrecoverable states when the network state isn't
13
14
  * supported by the browser, so this keeps retrying every minute until halted.
14
15
  */
15
- var ReconnectionMonitor = /** @class */ (function () {
16
- function ReconnectionMonitor() {
16
+ class ReconnectionMonitor {
17
+ constructor() {
17
18
  this.reconnectObservers = [];
18
19
  }
19
20
  /**
20
21
  * Add reconnect observer to the list of observers to alert on reconnect
21
22
  */
22
- ReconnectionMonitor.prototype.addObserver = function (reconnectObserver) {
23
+ addObserver(reconnectObserver) {
23
24
  this.reconnectObservers.push(reconnectObserver);
24
- };
25
+ }
25
26
  /**
26
27
  * Given a reconnect event, start the appropriate behavior
27
28
  */
28
- ReconnectionMonitor.prototype.record = function (event) {
29
- var _this = this;
29
+ record(event) {
30
30
  if (event === ReconnectEvent.START_RECONNECT) {
31
31
  // If the reconnection hasn't been started
32
32
  if (this.reconnectSetTimeoutId === undefined &&
33
33
  this.reconnectIntervalId === undefined) {
34
- this.reconnectSetTimeoutId = setTimeout(function () {
34
+ this.reconnectSetTimeoutId = setTimeout(() => {
35
35
  // Reconnect now
36
- _this._triggerReconnect();
36
+ this._triggerReconnect();
37
37
  // Retry reconnect every periodically until it works
38
- _this.reconnectIntervalId = setInterval(function () {
39
- _this._triggerReconnect();
38
+ this.reconnectIntervalId = setInterval(() => {
39
+ this._triggerReconnect();
40
40
  }, constants_1.RECONNECT_INTERVAL);
41
41
  }, constants_1.RECONNECT_DELAY);
42
42
  }
@@ -51,23 +51,19 @@ var ReconnectionMonitor = /** @class */ (function () {
51
51
  this.reconnectSetTimeoutId = undefined;
52
52
  }
53
53
  }
54
- };
54
+ }
55
55
  /**
56
56
  * Complete all reconnect observers
57
57
  */
58
- ReconnectionMonitor.prototype.close = function () {
59
- this.reconnectObservers.forEach(function (reconnectObserver) {
60
- var _a;
61
- (_a = reconnectObserver.complete) === null || _a === void 0 ? void 0 : _a.call(reconnectObserver);
58
+ close() {
59
+ this.reconnectObservers.forEach(reconnectObserver => {
60
+ reconnectObserver.complete?.();
62
61
  });
63
- };
64
- ReconnectionMonitor.prototype._triggerReconnect = function () {
65
- this.reconnectObservers.forEach(function (reconnectObserver) {
66
- var _a;
67
- (_a = reconnectObserver.next) === null || _a === void 0 ? void 0 : _a.call(reconnectObserver);
62
+ }
63
+ _triggerReconnect() {
64
+ this.reconnectObservers.forEach(reconnectObserver => {
65
+ reconnectObserver.next?.();
68
66
  });
69
- };
70
- return ReconnectionMonitor;
71
- }());
67
+ }
68
+ }
72
69
  exports.ReconnectionMonitor = ReconnectionMonitor;
73
- //# sourceMappingURL=ReconnectionMonitor.js.map
@@ -0,0 +1,10 @@
1
+ import { MqttOverWS, MqttOptions } from './MqttOverWS';
2
+ export interface AWSIoTOptions extends MqttOptions {
3
+ region?: string;
4
+ endpoint?: string;
5
+ }
6
+ export declare class AWSIoT extends MqttOverWS {
7
+ constructor(options?: AWSIoTOptions);
8
+ protected get region(): string | undefined;
9
+ protected get endpoint(): Promise<string>;
10
+ }
@@ -0,0 +1,30 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { MqttOverWS } from './MqttOverWS';
4
+ import { Signer } from '@aws-amplify/core/internals/utils';
5
+ import { fetchAuthSession } from '@aws-amplify/core';
6
+ const SERVICE_NAME = 'iotdevicegateway';
7
+ export class AWSIoT extends MqttOverWS {
8
+ constructor(options = {}) {
9
+ super(options);
10
+ }
11
+ get region() {
12
+ return this.options?.region;
13
+ }
14
+ get endpoint() {
15
+ return (async () => {
16
+ const endpoint = this.options.endpoint;
17
+ const serviceInfo = {
18
+ service: SERVICE_NAME,
19
+ region: this.region,
20
+ };
21
+ const session = await fetchAuthSession();
22
+ if (!session.credentials) {
23
+ throw new Error('No auth session credentials');
24
+ }
25
+ const { accessKeyId: access_key, secretAccessKey: secret_key, sessionToken: session_token, } = session.credentials;
26
+ const result = Signer.signUrl(endpoint, { access_key, secret_key, session_token }, serviceInfo);
27
+ return result;
28
+ })();
29
+ }
30
+ }
@@ -1,12 +1,11 @@
1
- import Observable from 'zen-observable-ts';
2
- import { AbstractPubSubProvider } from './PubSubProvider';
3
- import { PubSubContentObserver, PubSubContent } from '../types/PubSub';
4
- import { ProviderOptions } from '../types/Provider';
1
+ import { Observable } from 'rxjs';
2
+ import { AbstractPubSub } from './PubSub';
3
+ import { PubSubContentObserver, PubSubContent, PubSubOptions, PublishInput, SubscribeInput } from '../types/PubSub';
5
4
  export declare function mqttTopicMatch(filter: string, topic: string): boolean;
6
- export interface MqttProviderOptions extends ProviderOptions {
5
+ export interface MqttOptions extends PubSubOptions {
7
6
  clientId?: string;
8
7
  url?: string;
9
- aws_pubsub_endpoint?: string;
8
+ endpoint?: string;
10
9
  }
11
10
  interface PahoClient {
12
11
  onMessageArrived: (params: {
@@ -23,36 +22,37 @@ interface PahoClient {
23
22
  isConnected: () => boolean;
24
23
  subscribe: (topic: string) => void;
25
24
  unsubscribe: (topic: string) => void;
26
- send(topic: string, message: string): any;
25
+ send(topic: string, message: string): void;
27
26
  }
28
27
  declare class ClientsQueue {
29
28
  private promises;
30
- get(clientId: string, clientFactory?: (input: string) => Promise<PahoClient | undefined>): Promise<PahoClient>;
29
+ get(clientId: string, clientFactory?: (input: string) => Promise<PahoClient | undefined>): Promise<PahoClient | undefined>;
31
30
  get allClients(): string[];
32
31
  remove(clientId: string): void;
33
32
  }
34
- export declare class MqttOverWSProvider extends AbstractPubSubProvider<MqttProviderOptions> {
33
+ export declare class MqttOverWS extends AbstractPubSub<MqttOptions> {
35
34
  private _clientsQueue;
36
- private connectionState;
35
+ private connectionState?;
37
36
  private readonly connectionStateMonitor;
38
37
  private readonly reconnectionMonitor;
39
- constructor(options?: MqttProviderOptions);
38
+ constructor(options?: MqttOptions);
40
39
  protected get clientId(): string;
41
40
  protected get endpoint(): Promise<string | undefined>;
42
41
  protected get clientsQueue(): ClientsQueue;
43
42
  protected get isSSLEnabled(): boolean;
44
- getProviderName(): string;
45
43
  onDisconnect({ clientId, errorCode, ...args }: {
46
44
  clientId?: string;
47
45
  errorCode?: number;
48
46
  }): void;
49
- newClient({ url, clientId, }: MqttProviderOptions): Promise<PahoClient>;
50
- protected connect(clientId: string, options?: MqttProviderOptions): Promise<PahoClient | undefined>;
47
+ newClient({ url, clientId }: MqttOptions): Promise<PahoClient>;
48
+ protected connect(clientId: string, options?: MqttOptions): Promise<PahoClient | undefined>;
51
49
  protected disconnect(clientId: string): Promise<void>;
52
- publish(topics: string[] | string, msg: PubSubContent): Promise<void>;
50
+ publish({ topics, message }: PublishInput): Promise<void>;
53
51
  protected _topicObservers: Map<string, Set<PubSubContentObserver>>;
54
52
  protected _clientIdObservers: Map<string, Set<PubSubContentObserver>>;
55
53
  private _onMessage;
56
- subscribe(topics: string[] | string, options?: MqttProviderOptions): Observable<PubSubContent>;
54
+ subscribe({ topics, options, }: SubscribeInput & {
55
+ options?: MqttOptions;
56
+ }): Observable<PubSubContent>;
57
57
  }
58
58
  export {};
@@ -0,0 +1,268 @@
1
+ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // @ts-ignore
4
+ import * as Paho from '../vendor/paho-mqtt';
5
+ import { Observable } from 'rxjs';
6
+ import { AbstractPubSub } from './PubSub';
7
+ import { ConnectionState, } from '../types/PubSub';
8
+ import { Hub, ConsoleLogger as Logger } from '@aws-amplify/core';
9
+ import { amplifyUuid } from '@aws-amplify/core/internals/utils';
10
+ import { ConnectionStateMonitor, CONNECTION_CHANGE, } from '../utils/ConnectionStateMonitor';
11
+ import { ReconnectEvent, ReconnectionMonitor, } from '../utils/ReconnectionMonitor';
12
+ import { AMPLIFY_SYMBOL, CONNECTION_STATE_CHANGE } from './constants';
13
+ const logger = new Logger('MqttOverWS');
14
+ export function mqttTopicMatch(filter, topic) {
15
+ const filterArray = filter.split('/');
16
+ const length = filterArray.length;
17
+ const topicArray = topic.split('/');
18
+ for (let i = 0; i < length; ++i) {
19
+ const left = filterArray[i];
20
+ const right = topicArray[i];
21
+ if (left === '#')
22
+ return topicArray.length >= length;
23
+ if (left !== '+' && left !== right)
24
+ return false;
25
+ }
26
+ return length === topicArray.length;
27
+ }
28
+ class ClientsQueue {
29
+ constructor() {
30
+ this.promises = new Map();
31
+ }
32
+ async get(clientId, clientFactory) {
33
+ const cachedPromise = this.promises.get(clientId);
34
+ if (cachedPromise)
35
+ return cachedPromise;
36
+ if (clientFactory) {
37
+ const newPromise = clientFactory(clientId);
38
+ this.promises.set(clientId, newPromise);
39
+ newPromise.catch(() => this.promises.delete(clientId));
40
+ return newPromise;
41
+ }
42
+ return undefined;
43
+ }
44
+ get allClients() {
45
+ return Array.from(this.promises.keys());
46
+ }
47
+ remove(clientId) {
48
+ this.promises.delete(clientId);
49
+ }
50
+ }
51
+ const dispatchPubSubEvent = (payload) => {
52
+ Hub.dispatch('pubsub', payload, 'PubSub', AMPLIFY_SYMBOL);
53
+ };
54
+ const topicSymbol = typeof Symbol !== 'undefined' ? Symbol('topic') : '@@topic';
55
+ export class MqttOverWS extends AbstractPubSub {
56
+ constructor(options = {}) {
57
+ super({ ...options, clientId: options.clientId || amplifyUuid() });
58
+ this._clientsQueue = new ClientsQueue();
59
+ this.connectionStateMonitor = new ConnectionStateMonitor();
60
+ this.reconnectionMonitor = new ReconnectionMonitor();
61
+ this._topicObservers = new Map();
62
+ this._clientIdObservers = new Map();
63
+ // Monitor the connection health state and pass changes along to Hub
64
+ this.connectionStateMonitor.connectionStateObservable.subscribe(connectionStateChange => {
65
+ dispatchPubSubEvent({
66
+ event: CONNECTION_STATE_CHANGE,
67
+ data: {
68
+ provider: this,
69
+ connectionState: connectionStateChange,
70
+ },
71
+ message: `Connection state is ${connectionStateChange}`,
72
+ });
73
+ this.connectionState = connectionStateChange;
74
+ // Trigger reconnection when the connection is disrupted
75
+ if (connectionStateChange === ConnectionState.ConnectionDisrupted) {
76
+ this.reconnectionMonitor.record(ReconnectEvent.START_RECONNECT);
77
+ }
78
+ else if (connectionStateChange !== ConnectionState.Connecting) {
79
+ // Trigger connected to halt reconnection attempts
80
+ this.reconnectionMonitor.record(ReconnectEvent.HALT_RECONNECT);
81
+ }
82
+ });
83
+ }
84
+ get clientId() {
85
+ return this.options.clientId;
86
+ }
87
+ get endpoint() {
88
+ return Promise.resolve(this.options.endpoint);
89
+ }
90
+ get clientsQueue() {
91
+ return this._clientsQueue;
92
+ }
93
+ get isSSLEnabled() {
94
+ return !this.options['aws_appsync_dangerously_connect_to_http_endpoint_for_testing'];
95
+ }
96
+ onDisconnect({ clientId, errorCode, ...args }) {
97
+ if (errorCode !== 0) {
98
+ logger.warn(clientId, JSON.stringify({ errorCode, ...args }, null, 2));
99
+ if (!clientId) {
100
+ return;
101
+ }
102
+ const clientIdObservers = this._clientIdObservers.get(clientId);
103
+ if (!clientIdObservers) {
104
+ return;
105
+ }
106
+ this.disconnect(clientId);
107
+ }
108
+ }
109
+ async newClient({ url, clientId }) {
110
+ logger.debug('Creating new MQTT client', clientId);
111
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.OPENING_CONNECTION);
112
+ // @ts-ignore
113
+ const client = new Paho.Client(url, clientId);
114
+ client.onMessageArrived = ({ destinationName: topic, payloadString: msg, }) => {
115
+ this._onMessage(topic, msg);
116
+ };
117
+ client.onConnectionLost = ({ errorCode, ...args }) => {
118
+ this.onDisconnect({ clientId, errorCode, ...args });
119
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
120
+ };
121
+ const connected = await new Promise((resolve, reject) => {
122
+ client.connect({
123
+ useSSL: this.isSSLEnabled,
124
+ mqttVersion: 3,
125
+ onSuccess: () => resolve(true),
126
+ onFailure: () => {
127
+ if (clientId)
128
+ this._clientsQueue.remove(clientId);
129
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
130
+ resolve(false);
131
+ },
132
+ });
133
+ });
134
+ if (connected) {
135
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CONNECTION_ESTABLISHED);
136
+ }
137
+ return client;
138
+ }
139
+ async connect(clientId, options = {}) {
140
+ return await this.clientsQueue.get(clientId, async (clientId) => {
141
+ const client = await this.newClient({ ...options, clientId });
142
+ if (client) {
143
+ // Once connected, subscribe to all topics registered observers
144
+ this._topicObservers.forEach((_value, key) => {
145
+ client.subscribe(key);
146
+ });
147
+ }
148
+ return client;
149
+ });
150
+ }
151
+ async disconnect(clientId) {
152
+ const client = await this.clientsQueue.get(clientId);
153
+ if (client && client.isConnected()) {
154
+ client.disconnect();
155
+ }
156
+ this.clientsQueue.remove(clientId);
157
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSED);
158
+ }
159
+ async publish({ topics, message }) {
160
+ const targetTopics = [].concat(topics);
161
+ const msg = JSON.stringify(message);
162
+ const client = await this.clientsQueue.get(this.clientId);
163
+ if (client) {
164
+ logger.debug('Publishing to topic(s)', targetTopics.join(','), message);
165
+ targetTopics.forEach(topic => client.send(topic, msg));
166
+ }
167
+ else {
168
+ logger.debug('Publishing to topic(s) failed', targetTopics.join(','), message);
169
+ }
170
+ }
171
+ _onMessage(topic, msg) {
172
+ try {
173
+ const matchedTopicObservers = [];
174
+ this._topicObservers.forEach((observerForTopic, observerTopic) => {
175
+ if (mqttTopicMatch(observerTopic, topic)) {
176
+ matchedTopicObservers.push(observerForTopic);
177
+ }
178
+ });
179
+ const parsedMessage = JSON.parse(msg);
180
+ if (typeof parsedMessage === 'object') {
181
+ // @ts-ignore
182
+ parsedMessage[topicSymbol] = topic;
183
+ }
184
+ matchedTopicObservers.forEach(observersForTopic => {
185
+ observersForTopic.forEach(observer => observer.next(parsedMessage));
186
+ });
187
+ }
188
+ catch (error) {
189
+ logger.warn('Error handling message', error, msg);
190
+ }
191
+ }
192
+ subscribe({ topics, options = {}, }) {
193
+ const targetTopics = [].concat(topics);
194
+ logger.debug('Subscribing to topic(s)', targetTopics.join(','));
195
+ let reconnectSubscription;
196
+ return new Observable(observer => {
197
+ targetTopics.forEach(topic => {
198
+ // this._topicObservers is used to notify the observers according to the topic received on the message
199
+ let observersForTopic = this._topicObservers.get(topic);
200
+ if (!observersForTopic) {
201
+ observersForTopic = new Set();
202
+ this._topicObservers.set(topic, observersForTopic);
203
+ }
204
+ observersForTopic.add(observer);
205
+ });
206
+ const { clientId = this.clientId } = options;
207
+ // this._clientIdObservers is used to close observers when client gets disconnected
208
+ let observersForClientId = this._clientIdObservers.get(clientId);
209
+ if (!observersForClientId) {
210
+ observersForClientId = new Set();
211
+ }
212
+ if (observersForClientId) {
213
+ observersForClientId.add(observer);
214
+ this._clientIdObservers.set(clientId, observersForClientId);
215
+ }
216
+ (async () => {
217
+ const getClient = async () => {
218
+ try {
219
+ const { url = await this.endpoint } = options;
220
+ const client = await this.connect(clientId, { url });
221
+ if (client !== undefined) {
222
+ targetTopics.forEach(topic => {
223
+ client.subscribe(topic);
224
+ });
225
+ }
226
+ }
227
+ catch (e) {
228
+ logger.debug('Error forming connection', e);
229
+ }
230
+ };
231
+ // Establish the initial connection
232
+ await getClient();
233
+ // Add an observable to the reconnection list to manage reconnection for this subscription
234
+ reconnectSubscription = new Observable(observer => {
235
+ this.reconnectionMonitor.addObserver(observer);
236
+ }).subscribe(() => {
237
+ getClient();
238
+ });
239
+ })();
240
+ return async () => {
241
+ const client = await this.clientsQueue.get(clientId);
242
+ reconnectSubscription?.unsubscribe();
243
+ if (client) {
244
+ this._clientIdObservers.get(clientId)?.delete(observer);
245
+ // No more observers per client => client not needed anymore
246
+ if (this._clientIdObservers.get(clientId)?.size === 0) {
247
+ this.disconnect(clientId);
248
+ this.connectionStateMonitor.record(CONNECTION_CHANGE.CLOSING_CONNECTION);
249
+ this._clientIdObservers.delete(clientId);
250
+ }
251
+ targetTopics.forEach(topic => {
252
+ const observersForTopic = this._topicObservers.get(topic) ||
253
+ new Set();
254
+ observersForTopic.delete(observer);
255
+ // if no observers exists for the topic, topic should be removed
256
+ if (observersForTopic.size === 0) {
257
+ this._topicObservers.delete(topic);
258
+ if (client.isConnected()) {
259
+ client.unsubscribe(topic);
260
+ }
261
+ }
262
+ });
263
+ }
264
+ return null;
265
+ };
266
+ });
267
+ }
268
+ }
@@ -0,0 +1,11 @@
1
+ import { Observable } from 'rxjs';
2
+ import { PubSubBase, PubSubOptions, PubSubContent, PublishInput, SubscribeInput } from '../types/PubSub';
3
+ export declare abstract class AbstractPubSub<T extends PubSubOptions> implements PubSubBase {
4
+ private _config;
5
+ constructor(options: T);
6
+ configure(config: T): T;
7
+ protected get options(): T;
8
+ abstract newClient(clientOptions: T): Promise<any>;
9
+ abstract publish(input: PublishInput): void;
10
+ abstract subscribe(input: SubscribeInput): Observable<PubSubContent>;
11
+ }
@@ -0,0 +1,15 @@
1
+ import { ConsoleLogger as Logger } from '@aws-amplify/core';
2
+ const logger = new Logger('AbstractPubSubProvider');
3
+ export class AbstractPubSub {
4
+ constructor(options) {
5
+ this._config = options;
6
+ }
7
+ configure(config) {
8
+ this._config = { ...config, ...this._config };
9
+ logger.debug(`configure`, this._config);
10
+ return this.options;
11
+ }
12
+ get options() {
13
+ return { ...this._config };
14
+ }
15
+ }
@@ -1,3 +1,4 @@
1
+ export { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';
1
2
  export declare const MAX_DELAY_MS = 5000;
2
3
  export declare const NON_RETRYABLE_CODES: number[];
3
4
  export declare const CONNECTION_STATE_CHANGE = "ConnectionStateChange";
@@ -63,7 +64,6 @@ export declare enum SOCKET_STATUS {
63
64
  READY = 1,
64
65
  CONNECTING = 2
65
66
  }
66
- export declare const AMPLIFY_SYMBOL: Symbol;
67
67
  export declare const AWS_APPSYNC_REALTIME_HEADERS: {
68
68
  accept: string;
69
69
  'content-encoding': string;
@@ -1,8 +1,9 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- export var MAX_DELAY_MS = 5000;
4
- export var NON_RETRYABLE_CODES = [400, 401, 403];
5
- export var CONNECTION_STATE_CHANGE = 'ConnectionStateChange';
3
+ export { AMPLIFY_SYMBOL } from '@aws-amplify/core/internals/utils';
4
+ export const MAX_DELAY_MS = 5000;
5
+ export const NON_RETRYABLE_CODES = [400, 401, 403];
6
+ export const CONNECTION_STATE_CHANGE = 'ConnectionStateChange';
6
7
  export var MESSAGE_TYPES;
7
8
  (function (MESSAGE_TYPES) {
8
9
  /**
@@ -68,10 +69,7 @@ export var SOCKET_STATUS;
68
69
  SOCKET_STATUS[SOCKET_STATUS["READY"] = 1] = "READY";
69
70
  SOCKET_STATUS[SOCKET_STATUS["CONNECTING"] = 2] = "CONNECTING";
70
71
  })(SOCKET_STATUS || (SOCKET_STATUS = {}));
71
- export var AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'
72
- ? Symbol.for('amplify_default')
73
- : '@@amplify_default');
74
- export var AWS_APPSYNC_REALTIME_HEADERS = {
72
+ export const AWS_APPSYNC_REALTIME_HEADERS = {
75
73
  accept: 'application/json, text/javascript',
76
74
  'content-encoding': 'amz-1.0',
77
75
  'content-type': 'application/json; charset=UTF-8',
@@ -79,25 +77,24 @@ export var AWS_APPSYNC_REALTIME_HEADERS = {
79
77
  /**
80
78
  * Time in milleseconds to wait for GQL_CONNECTION_INIT message
81
79
  */
82
- export var CONNECTION_INIT_TIMEOUT = 15000;
80
+ export const CONNECTION_INIT_TIMEOUT = 15000;
83
81
  /**
84
82
  * Time in milleseconds to wait for GQL_START_ACK message
85
83
  */
86
- export var START_ACK_TIMEOUT = 15000;
84
+ export const START_ACK_TIMEOUT = 15000;
87
85
  /**
88
86
  * Default Time in milleseconds to wait for GQL_CONNECTION_KEEP_ALIVE message
89
87
  */
90
- export var DEFAULT_KEEP_ALIVE_TIMEOUT = 5 * 60 * 1000;
88
+ export const DEFAULT_KEEP_ALIVE_TIMEOUT = 5 * 60 * 1000;
91
89
  /**
92
90
  * Default Time in milleseconds to alert for missed GQL_CONNECTION_KEEP_ALIVE message
93
91
  */
94
- export var DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT = 65 * 1000;
92
+ export const DEFAULT_KEEP_ALIVE_ALERT_TIMEOUT = 65 * 1000;
95
93
  /**
96
94
  * Default delay time in milleseconds between when reconnect is triggered vs when it is attempted
97
95
  */
98
- export var RECONNECT_DELAY = 5 * 1000;
96
+ export const RECONNECT_DELAY = 5 * 1000;
99
97
  /**
100
98
  * Default interval time in milleseconds between when reconnect is re-attempted
101
99
  */
102
- export var RECONNECT_INTERVAL = 60 * 1000;
103
- //# sourceMappingURL=constants.js.map
100
+ export const RECONNECT_INTERVAL = 60 * 1000;
@@ -1,4 +1,3 @@
1
- export { AbstractPubSubProvider } from './PubSubProvider';
2
- export { AWSAppSyncRealTimeProvider, AWSAppSyncRealTimeProviderOptions, ObserverQuery, } from './AWSAppSyncRealTimeProvider';
3
- export { AWSIoTProvider, AWSIoTProviderOptions } from './AWSIotProvider';
4
- export { MqttProviderOptions, MqttOverWSProvider, mqttTopicMatch, } from './MqttOverWSProvider';
1
+ export { AbstractPubSub } from './PubSub';
2
+ export { AWSIoT, AWSIoTOptions } from './AWSIot';
3
+ export { MqttOptions, MqttOverWS, mqttTopicMatch } from './MqttOverWS';
@@ -1,7 +1,5 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- export { AbstractPubSubProvider } from './PubSubProvider';
4
- export { AWSAppSyncRealTimeProvider, } from './AWSAppSyncRealTimeProvider';
5
- export { AWSIoTProvider } from './AWSIotProvider';
6
- export { MqttOverWSProvider, mqttTopicMatch, } from './MqttOverWSProvider';
7
- //# sourceMappingURL=index.js.map
3
+ export { AbstractPubSub } from './PubSub';
4
+ export { AWSIoT } from './AWSIot';
5
+ export { MqttOverWS, mqttTopicMatch } from './MqttOverWS';
@@ -0,0 +1 @@
1
+ export { AWSIoT as PubSub, AWSIoTOptions as PubSubOptions } from '../Providers';
@@ -1,3 +1,3 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- export { InternalPubSub, InternalPubSubClass } from './InternalPubSub';
3
+ export { AWSIoT as PubSub } from '../Providers';
@@ -0,0 +1 @@
1
+ export { MqttOverWS as PubSub, MqttOptions as PubSubOptions, } from '../Providers';
@@ -1,4 +1,3 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- export { InternalPubSub, InternalPubSubClass } from './InternalPubSub';
4
- //# sourceMappingURL=index.js.map
3
+ export { MqttOverWS as PubSub, } from '../Providers';
@@ -1,4 +1,4 @@
1
- export { PubSub } from './PubSub';
2
1
  export { CONNECTION_STATE_CHANGE } from './Providers/constants';
3
2
  export { ConnectionState, CONTROL_MSG } from './types';
4
- export { AWSAppSyncRealTimeProvider, AWSAppSyncRealTimeProviderOptions, AWSIoTProvider, AWSIoTProviderOptions, AbstractPubSubProvider, MqttOverWSProvider, MqttProviderOptions, ObserverQuery, mqttTopicMatch, } from './Providers';
3
+ export { mqttTopicMatch } from './Providers';
4
+ export { PubSub, PubSubOptions } from './clients/iot';
package/lib-esm/index.js CHANGED
@@ -1,7 +1,6 @@
1
1
  // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- export { PubSub } from './PubSub';
4
3
  export { CONNECTION_STATE_CHANGE } from './Providers/constants';
5
4
  export { ConnectionState, CONTROL_MSG } from './types';
6
- export { AWSAppSyncRealTimeProvider, AWSIoTProvider, AbstractPubSubProvider, MqttOverWSProvider, mqttTopicMatch, } from './Providers';
7
- //# sourceMappingURL=index.js.map
5
+ export { mqttTopicMatch } from './Providers';
6
+ export { PubSub } from './clients/iot';