UNPKG

7.76 kBJavaScriptView Raw
1// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2// SPDX-License-Identifier: Apache-2.0
3var __assign = (this && this.__assign) || function () {
4 __assign = Object.assign || function(t) {
5 for (var s, i = 1, n = arguments.length; i < n; i++) {
6 s = arguments[i];
7 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
8 t[p] = s[p];
9 }
10 return t;
11 };
12 return __assign.apply(this, arguments);
13};
14var __read = (this && this.__read) || function (o, n) {
15 var m = typeof Symbol === "function" && o[Symbol.iterator];
16 if (!m) return o;
17 var i = m.call(o), r, ar = [], e;
18 try {
19 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
20 }
21 catch (error) { e = { error: error }; }
22 finally {
23 try {
24 if (r && !r.done && (m = i["return"])) m.call(i);
25 }
26 finally { if (e) throw e.error; }
27 }
28 return ar;
29};
30var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
31 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
32 if (ar || !(i in from)) {
33 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
34 ar[i] = from[i];
35 }
36 }
37 return to.concat(ar || Array.prototype.slice.call(from));
38};
39import { ConsoleLogger as Logger } from './Logger';
40var logger = new Logger('Hub');
41var AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'
42 ? Symbol.for('amplify_default')
43 : '@@amplify_default');
44function isLegacyCallback(callback) {
45 return callback.onHubCapsule !== undefined;
46}
47var HubClass = /** @class */ (function () {
48 function HubClass(name) {
49 this.listeners = [];
50 this.patterns = [];
51 this.protectedChannels = [
52 'core',
53 'auth',
54 'api',
55 'analytics',
56 'interactions',
57 'pubsub',
58 'storage',
59 'ui',
60 'xr',
61 ];
62 this.name = name;
63 }
64 /**
65 * Used internally to remove a Hub listener.
66 *
67 * @remarks
68 * This private method is for internal use only. Instead of calling Hub.remove, call the result of Hub.listen.
69 */
70 HubClass.prototype._remove = function (channel, listener) {
71 if (channel instanceof RegExp) {
72 var pattern_1 = this.patterns.find(function (_a) {
73 var pattern = _a.pattern;
74 return pattern.source === channel.source;
75 });
76 if (!pattern_1) {
77 logger.warn("No listeners for ".concat(channel));
78 return;
79 }
80 this.patterns = __spreadArray([], __read(this.patterns.filter(function (x) { return x !== pattern_1; })), false);
81 }
82 else {
83 var holder = this.listeners[channel];
84 if (!holder) {
85 logger.warn("No listeners for ".concat(channel));
86 return;
87 }
88 this.listeners[channel] = __spreadArray([], __read(holder.filter(function (_a) {
89 var callback = _a.callback;
90 return callback !== listener;
91 })), false);
92 }
93 };
94 /**
95 * @deprecated Instead of calling Hub.remove, call the result of Hub.listen.
96 */
97 HubClass.prototype.remove = function (channel, listener) {
98 this._remove(channel, listener);
99 };
100 /**
101 * Used to send a Hub event.
102 *
103 * @param channel - The channel on which the event will be broadcast
104 * @param payload - The HubPayload
105 * @param source - The source of the event; defaults to ''
106 * @param ampSymbol - Symbol used to determine if the event is dispatched internally on a protected channel
107 *
108 */
109 HubClass.prototype.dispatch = function (channel, payload, source, ampSymbol) {
110 if (source === void 0) { source = ''; }
111 if (this.protectedChannels.indexOf(channel) > -1) {
112 var hasAccess = ampSymbol === AMPLIFY_SYMBOL;
113 if (!hasAccess) {
114 logger.warn("WARNING: ".concat(channel, " is protected and dispatching on it can have unintended consequences"));
115 }
116 }
117 var capsule = {
118 channel: channel,
119 payload: __assign({}, payload),
120 source: source,
121 patternInfo: [],
122 };
123 try {
124 this._toListeners(capsule);
125 }
126 catch (e) {
127 logger.error(e);
128 }
129 };
130 /**
131 * Used to listen for Hub events.
132 *
133 * @param channel - The channel on which to listen
134 * @param callback - The callback to execute when an event is received on the specified channel
135 * @param listenerName - The name of the listener; defaults to 'noname'
136 * @returns A function which can be called to cancel the listener.
137 *
138 */
139 HubClass.prototype.listen = function (channel, callback, listenerName) {
140 var _this = this;
141 if (listenerName === void 0) { listenerName = 'noname'; }
142 var cb;
143 // Check for legacy onHubCapsule callback for backwards compatability
144 if (isLegacyCallback(callback)) {
145 logger.warn("WARNING onHubCapsule is Deprecated. Please pass in a callback.");
146 cb = callback.onHubCapsule.bind(callback);
147 }
148 else if (typeof callback !== 'function') {
149 throw new Error('No callback supplied to Hub');
150 }
151 else {
152 cb = callback;
153 }
154 if (channel instanceof RegExp) {
155 this.patterns.push({
156 pattern: channel,
157 callback: cb,
158 });
159 }
160 else {
161 var holder = this.listeners[channel];
162 if (!holder) {
163 holder = [];
164 this.listeners[channel] = holder;
165 }
166 holder.push({
167 name: listenerName,
168 callback: cb,
169 });
170 }
171 return function () {
172 _this._remove(channel, cb);
173 };
174 };
175 HubClass.prototype._toListeners = function (capsule) {
176 var channel = capsule.channel, payload = capsule.payload;
177 var holder = this.listeners[channel];
178 if (holder) {
179 holder.forEach(function (listener) {
180 logger.debug("Dispatching to ".concat(channel, " with "), payload);
181 try {
182 listener.callback(capsule);
183 }
184 catch (e) {
185 logger.error(e);
186 }
187 });
188 }
189 if (this.patterns.length > 0) {
190 if (!payload.message) {
191 logger.warn("Cannot perform pattern matching without a message key");
192 return;
193 }
194 var payloadStr_1 = payload.message;
195 this.patterns.forEach(function (pattern) {
196 var match = payloadStr_1.match(pattern.pattern);
197 if (match) {
198 var _a = __read(match), groups = _a.slice(1);
199 var dispatchingCapsule = __assign(__assign({}, capsule), { patternInfo: groups });
200 try {
201 pattern.callback(dispatchingCapsule);
202 }
203 catch (e) {
204 logger.error(e);
205 }
206 }
207 });
208 }
209 };
210 return HubClass;
211}());
212export { HubClass };
213/*We export a __default__ instance of HubClass to use it as a
214pseudo Singleton for the main messaging bus, however you can still create
215your own instance of HubClass() for a separate "private bus" of events.*/
216export var Hub = new HubClass('__default__');