@interopio/fdc3 2.1.0 → 2.1.2

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.
@@ -124,17 +124,95 @@
124
124
  const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
125
125
  const defaultContextProps = ["type"];
126
126
  const defaultGlue42APIs = ["contexts", "channels", "interop", "intents", "appManager", "windows"];
127
- const responseInteropMethodPrefix = "T42.FDC3.Open.Listener.Response";
128
127
  const glueChannelNamePrefix = "___channel___";
129
128
  const fdc3NothingContextType = "fdc3.nothing";
130
129
  const Glue42EnterpriseNoAppWindow = "no-app-window";
131
130
  const RaiseTimeoutMs = 75 * 1000;
132
- const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
131
+ const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
132
+ const Fdc3SupportedIntentTypes = {
133
+ "CreateInteraction": [
134
+ "fdc3.contactList",
135
+ "fdc3.interaction"
136
+ ],
137
+ "StartCall": [
138
+ "fdc3.contact",
139
+ "fdc3.contactList"
140
+ ],
141
+ "StartChat": [
142
+ "fdc3.contact",
143
+ "fdc3.contactList",
144
+ "fdc3.chat.initSettings"
145
+ ],
146
+ "StartEmail": [
147
+ "fdc3.email"
148
+ ],
149
+ "SendChatMessage": [
150
+ "fdc3.chat.message"
151
+ ],
152
+ "ViewAnalysis": [
153
+ "fdc3.instrument",
154
+ "fdc3.organization",
155
+ "fdc3.portfolio"
156
+ ],
157
+ "ViewChat": [
158
+ "fdc3.chat.room",
159
+ "fdc3.contact",
160
+ "fdc3.contactList"
161
+ ],
162
+ "ViewChart": [
163
+ "fdc3.chart",
164
+ "fdc3.instrument",
165
+ "fdc3.instrumentList",
166
+ "fdc3.portfolio",
167
+ "fdc3.position"
168
+ ],
169
+ "ViewHoldings": [
170
+ "fdc3.instrument",
171
+ "fdc3.instrumentList",
172
+ "fdc3.organization"
173
+ ],
174
+ "ViewInstrument": [
175
+ "fdc3.instrument"
176
+ ],
177
+ "ViewInteractions": [
178
+ "fdc3.contact",
179
+ "fdc3.instrument",
180
+ "fdc3.organization"
181
+ ],
182
+ "ViewMessages": [
183
+ "fdc3.chat.searchCriteria"
184
+ ],
185
+ "ViewNews": [
186
+ "fdc3.country",
187
+ "fdc3.instrument",
188
+ "fdc3.instrumentList",
189
+ "fdc3.organization",
190
+ "fdc3.portfolio"
191
+ ],
192
+ "ViewOrders": [
193
+ "fdc3.contact",
194
+ "fdc3.instrument",
195
+ "fdc3.organization"
196
+ ],
197
+ "ViewProfile": [
198
+ "fdc3.contact",
199
+ "fdc3.organization"
200
+ ],
201
+ "ViewQuote": [
202
+ "fdc3.instrument"
203
+ ],
204
+ "ViewResearch": [
205
+ "fdc3.contact",
206
+ "fdc3.instrument",
207
+ "fdc3.organization"
208
+ ]
209
+ };
133
210
 
134
- const Glue42FDC3SystemMethod = "T42.FDC3.Client.Control";
211
+ const ioConnectFDC3SystemMethod = "FDC3.Collaborate";
135
212
  const PrivateChannelPrefix = "___privateFDC3Channel___";
136
213
  var PrivateChannelEventMethods;
137
214
  (function (PrivateChannelEventMethods) {
215
+ PrivateChannelEventMethods["ListenerAdded"] = "listenerAdded";
138
216
  PrivateChannelEventMethods["OnAddContextListener"] = "onAddContextListener";
139
217
  PrivateChannelEventMethods["OnUnsubscribe"] = "onUnsubscribe";
140
218
  PrivateChannelEventMethods["OnDisconnect"] = "onDisconnect";
@@ -887,7 +965,7 @@
887
965
  /** See `Decoder.number` */
888
966
  var number = Decoder.number;
889
967
  /** See `Decoder.boolean` */
890
- var boolean = Decoder.boolean;
968
+ Decoder.boolean;
891
969
  /** See `Decoder.anyJson` */
892
970
  var anyJson = Decoder.anyJson;
893
971
  /** See `Decoder.unknownJson` */
@@ -959,31 +1037,35 @@
959
1037
  const optionalTargetApp = optional(appIdentifierDecoder);
960
1038
  const optionalAppIdentifier = optional(targetAppDecoder);
961
1039
  const optionalNonEmptyStringDecoder = optional(nonEmptyStringDecoder);
962
- const SystemMethodActionDecider = oneOf(constant(PrivateChannelEventMethods.OnAddContextListener), constant(PrivateChannelEventMethods.OnUnsubscribe), constant(PrivateChannelEventMethods.OnDisconnect));
963
- const SystemMethodEventPayloadDecoder = object({
964
- channelId: nonEmptyStringDecoder,
965
- clientId: nonEmptyStringDecoder,
966
- contextType: optional(string()),
967
- replayContextTypes: optional(array(string()))
1040
+ const SystemMethodActionDecoder = oneOf(constant("joinPrivateChannel"), constant("publishOnPrivateChannel"), constant("addedContextListenerOnPrivateChannel"), constant("removedContextListenerOnPrivateChannel"), constant("disconnectedFromPrivateChannel"), constant("startupContextOpened"));
1041
+ const CollaborationObjectDecoder = object({
1042
+ channelId: optional(nonEmptyStringDecoder),
1043
+ contextType: optional(nonEmptyStringDecoder),
1044
+ payload: optional(contextDecoder)
968
1045
  });
969
1046
  const SystemMethodInvocationArgumentDecoder = object({
970
- action: SystemMethodActionDecider,
971
- payload: SystemMethodEventPayloadDecoder
972
- });
973
- const ContextListenerResponseDecoder = object({
974
- listenerInvoked: optional(boolean())
1047
+ action: SystemMethodActionDecoder,
1048
+ correlationId: nonEmptyStringDecoder,
1049
+ collaborationObject: optional(CollaborationObjectDecoder)
975
1050
  });
976
- object({
977
- meta: object({
978
- responseMethodName: nonEmptyStringDecoder
979
- }),
980
- context: contextDecoder
1051
+ const FDC3StartupContextDecoder = object({
1052
+ fdc3: object({
1053
+ collaborationId: nonEmptyStringDecoder,
1054
+ openApp: object({
1055
+ appId: nonEmptyStringDecoder,
1056
+ instanceId: nonEmptyStringDecoder
1057
+ }),
1058
+ context: object({
1059
+ contextType: optional(string()),
1060
+ payload: contextDecoder
1061
+ })
1062
+ })
981
1063
  });
982
1064
 
983
1065
  class GlueController {
984
1066
  constructor(channelsParser) {
985
1067
  this.channelsParser = channelsParser;
986
- this.defaultGluePromiseTimeout = 120000;
1068
+ this.defaultGluePromiseTimeout = 120 * 1000;
987
1069
  }
988
1070
  get gluePromise() {
989
1071
  return this.glueInitPromise.then(this.initializeLogger.bind(this));
@@ -1039,6 +1121,15 @@
1039
1121
  return this.glue.intents.raise(request);
1040
1122
  });
1041
1123
  }
1124
+ getMyWindowContext() {
1125
+ return __awaiter(this, void 0, void 0, function* () {
1126
+ const myWin = this.getMyWindow();
1127
+ if (!myWin) {
1128
+ return;
1129
+ }
1130
+ return myWin.getContext();
1131
+ });
1132
+ }
1042
1133
  addIntentListener(intent, handler) {
1043
1134
  const registerMethodExists = this.glue.intents.register;
1044
1135
  return registerMethodExists
@@ -1060,20 +1151,15 @@
1060
1151
  }
1061
1152
  updateContextWithLatestFdc3Type(contextId, context) {
1062
1153
  return __awaiter(this, void 0, void 0, function* () {
1063
- const prevContextData = yield this.getContext(contextId);
1064
- if (!isValidNonEmptyObject(prevContextData)) {
1065
- return this.updateContext(contextId, {
1066
- data: this.channelsParser.parseFDC3ContextToGlueContexts(context),
1067
- latest_fdc3_type: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type)
1068
- });
1069
- }
1070
- return this.updateContext(contextId, Object.assign(Object.assign({}, prevContextData), { data: Object.assign(Object.assign({}, prevContextData.data), this.channelsParser.parseFDC3ContextToGlueContexts(context)), latest_fdc3_type: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type) }));
1154
+ const { path, value } = this.channelsParser.parseFDC3ContextToGlueContexts(context);
1155
+ const latestTypePathValue = { path: "latest_fdc3_type", value: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type) };
1156
+ yield this.contextsSetPaths(contextId, [{ path: `data.${path}`, value: value }, latestTypePathValue]);
1071
1157
  });
1072
1158
  }
1073
1159
  channelsUpdate(channelId, context) {
1074
1160
  return __awaiter(this, void 0, void 0, function* () {
1075
- const parsedData = this.channelsParser.parseFDC3ContextToGlueContexts(context);
1076
- return this.glue.channels.publish(parsedData, channelId);
1161
+ const { path, value } = this.channelsParser.parseFDC3ContextToGlueContexts(context);
1162
+ return this.glue.channels.publish({ [path]: value }, channelId);
1077
1163
  });
1078
1164
  }
1079
1165
  joinChannel(channelId) {
@@ -1111,8 +1197,8 @@
1111
1197
  const win = this.glue.windows.my();
1112
1198
  return isValidNonEmptyObject(win) ? win : undefined;
1113
1199
  }
1114
- getMyInteropInstanceId() {
1115
- return this.glue.interop.instance.instance;
1200
+ getMyInteropInstance() {
1201
+ return this.glue.interop.instance;
1116
1202
  }
1117
1203
  getGlueVersion() {
1118
1204
  var _a;
@@ -1121,21 +1207,14 @@
1121
1207
  registerOnInstanceStopped(cb) {
1122
1208
  return this.glue.appManager.onInstanceStopped(cb);
1123
1209
  }
1124
- invokeMethod(methodName, instance, argumentObj) {
1125
- return __awaiter(this, void 0, void 0, function* () {
1126
- const args = ContextListenerResponseDecoder.runWithException(argumentObj);
1127
- return this.glue.interop.invoke(methodName, args, { instance });
1128
- });
1129
- }
1130
1210
  unregisterMethod(methodName) {
1131
1211
  return __awaiter(this, void 0, void 0, function* () {
1132
1212
  return this.glue.interop.unregister(methodName);
1133
1213
  });
1134
1214
  }
1135
- invokeSystemMethod(argumentObj) {
1136
- const args = SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1137
- const target = args.payload.clientId;
1138
- return this.glue.interop.invoke(Glue42FDC3SystemMethod, args, { instance: target });
1215
+ invokeSystemMethod(argumentObj, target) {
1216
+ SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1217
+ return this.glue.interop.invoke(ioConnectFDC3SystemMethod, argumentObj, { instance: target });
1139
1218
  }
1140
1219
  registerMethod(name, handler) {
1141
1220
  return this.glue.interop.register(name, handler);
@@ -1143,22 +1222,17 @@
1143
1222
  getInteropMethods(filter) {
1144
1223
  return this.glue.interop.methods(filter);
1145
1224
  }
1146
- channelsSubscribe(callback) {
1225
+ channelsSubscribe(callback, contextType) {
1147
1226
  const didReplay = { replayed: false };
1148
- return this.glue.channels.subscribe((_, context, updaterId) => __awaiter(this, void 0, void 0, function* () {
1149
- if (this.isUpdateFromMe(updaterId) || !context) {
1150
- return;
1151
- }
1152
- const contextData = yield this.glue.contexts.get(`${glueChannelNamePrefix}${context.name}`);
1153
- if (!contextData.latest_fdc3_type) {
1227
+ return this.glue.channels.subscribe((_, contextData, updaterId) => __awaiter(this, void 0, void 0, function* () {
1228
+ if (this.isUpdateFromMe(updaterId) || !contextData || !contextData.latest_fdc3_type) {
1154
1229
  return;
1155
1230
  }
1156
- if (!didReplay.replayed) {
1157
- this.invokePreviouslyBroadcastedData(callback, contextData, this.getContextMetadata(updaterId));
1158
- didReplay.replayed = true;
1159
- return;
1231
+ if (didReplay.replayed) {
1232
+ return this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1160
1233
  }
1161
- this.parseDataAndInvokeSubscribeCallback(callback, contextData, this.getContextMetadata(updaterId));
1234
+ this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1235
+ didReplay.replayed = true;
1162
1236
  }));
1163
1237
  }
1164
1238
  contextsSubscribe(contextName, callback) {
@@ -1170,7 +1244,7 @@
1170
1244
  if (!this.checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData)) {
1171
1245
  return;
1172
1246
  }
1173
- this.parseDataAndInvokeSubscribeCallback(callback, contextData, this.getContextMetadata(extraData === null || extraData === void 0 ? void 0 : extraData.updaterId));
1247
+ this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(extraData === null || extraData === void 0 ? void 0 : extraData.updaterId) });
1174
1248
  });
1175
1249
  }
1176
1250
  getInteropServers(methodFilter) {
@@ -1179,14 +1253,12 @@
1179
1253
  initSubLogger(name) {
1180
1254
  return this.logger.subLogger(name);
1181
1255
  }
1182
- invokePreviouslyBroadcastedData(callback, contextData, metadata) {
1183
- Object.entries(contextData.data).forEach(([key, value]) => {
1184
- if (!this.channelsParser.isFdc3DataKey(key)) {
1185
- return;
1186
- }
1187
- const parsedData = Object.assign({ type: this.channelsParser.revertGlueParsedTypeToInitialFDC3Type(key) }, value);
1188
- callback(parsedData, metadata);
1189
- });
1256
+ invokePreviouslyBroadcastedData({ callback, contextData, metadata, contextType }) {
1257
+ const invokeForType = contextType || this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
1258
+ const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, invokeForType);
1259
+ if (dataForContextType) {
1260
+ callback(dataForContextType, metadata);
1261
+ }
1190
1262
  }
1191
1263
  isUpdateFromMe(updaterId) {
1192
1264
  return this.glue.interop.instance.peerId === updaterId;
@@ -1206,9 +1278,34 @@
1206
1278
  initializeLogger() {
1207
1279
  this._logger = this.glue.logger;
1208
1280
  }
1209
- parseDataAndInvokeSubscribeCallback(callback, data, metadata) {
1210
- const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data(data);
1211
- callback(parsedData, metadata);
1281
+ parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata, contextType }) {
1282
+ if (!contextType) {
1283
+ const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data({ data: contextData.data, latest_fdc3_type: contextData.latest_fdc3_type });
1284
+ callback(parsedData, metadata);
1285
+ return;
1286
+ }
1287
+ const latestPublishedType = this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
1288
+ if (latestPublishedType !== contextType) {
1289
+ return;
1290
+ }
1291
+ const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, contextType);
1292
+ if (dataForContextType) {
1293
+ callback(dataForContextType, metadata);
1294
+ }
1295
+ }
1296
+ getLatestBroadcastedDataByContextType(contextData, contextType) {
1297
+ let foundData;
1298
+ Object.entries(contextData.data).find(([key, value]) => {
1299
+ if (!this.channelsParser.isFdc3DataKey(key)) {
1300
+ return;
1301
+ }
1302
+ const parsedType = this.channelsParser.revertGlueParsedTypeToInitialFDC3Type(key);
1303
+ if (parsedType !== contextType) {
1304
+ return;
1305
+ }
1306
+ foundData = Object.assign({ type: parsedType }, value);
1307
+ });
1308
+ return foundData;
1212
1309
  }
1213
1310
  checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData) {
1214
1311
  if (!didReplay.replayed) {
@@ -1220,6 +1317,11 @@
1220
1317
  }
1221
1318
  return true;
1222
1319
  }
1320
+ contextsSetPaths(name, paths) {
1321
+ return __awaiter(this, void 0, void 0, function* () {
1322
+ yield this.glue.contexts.setPaths(name, paths);
1323
+ });
1324
+ }
1223
1325
  }
1224
1326
 
1225
1327
  const GLUE42_EVENT_NAME = "Glue42";
@@ -1255,6 +1357,7 @@
1255
1357
  }
1256
1358
  toApi() {
1257
1359
  const api = {
1360
+ getStartupContext: this.getStartupContext.bind(this),
1258
1361
  addContextListener: this.addContextListener.bind(this),
1259
1362
  addIntentListener: this.addIntentListener.bind(this),
1260
1363
  broadcast: this.broadcast.bind(this),
@@ -1367,6 +1470,11 @@
1367
1470
  return this.intentsController.addIntentListener({ commandId: generateCommandId(), intent, handler });
1368
1471
  });
1369
1472
  }
1473
+ getStartupContext() {
1474
+ return __awaiter(this, void 0, void 0, function* () {
1475
+ return this.channelsController.getStartupContext();
1476
+ });
1477
+ }
1370
1478
  getOrCreateChannel(channelId) {
1371
1479
  return __awaiter(this, void 0, void 0, function* () {
1372
1480
  nonEmptyStringDecoder.runWithException(channelId);
@@ -1472,7 +1580,7 @@
1472
1580
  parseFDC3ContextToGlueContexts(context) {
1473
1581
  const { type } = context, rest = __rest$1(context, ["type"]);
1474
1582
  const parsedType = this.mapFDC3TypeToChannelsDelimiter(type);
1475
- return { [`${this.channelsFdc3DataPrefix}${parsedType}`]: rest };
1583
+ return { path: `${this.channelsFdc3DataPrefix}${parsedType}`, value: rest };
1476
1584
  }
1477
1585
  mapFDC3TypeToChannelsDelimiter(type) {
1478
1586
  return type.split(".").join(this.fdc3Delimiter);
@@ -1489,76 +1597,60 @@
1489
1597
  * SPDX-License-Identifier: Apache-2.0
1490
1598
  * Copyright FINOS FDC3 contributors - see NOTICE file
1491
1599
  */
1492
-
1493
1600
  /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
1494
1601
  var OpenError;
1495
-
1496
1602
  (function (OpenError) {
1497
1603
  /** Returned if the specified application is not found.*/
1498
1604
  OpenError["AppNotFound"] = "AppNotFound";
1499
1605
  /** Returned if the specified application fails to launch correctly.*/
1500
-
1501
1606
  OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
1502
1607
  /** Returned if the specified application launches but fails to add a context listener in order to receive the context passed to the `fdc3.open` call.*/
1503
-
1504
1608
  OpenError["AppTimeout"] = "AppTimeout";
1505
1609
  /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1506
-
1507
1610
  OpenError["ResolverUnavailable"] = "ResolverUnavailable";
1611
+ /** Returned if a call to the `open` function is made with an invalid context argument. Contexts should be Objects with at least a `type` field that has a `string` value.*/
1612
+ OpenError["MalformedContext"] = "MalformedContext";
1508
1613
  })(OpenError || (OpenError = {}));
1509
1614
  /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
1510
-
1511
-
1512
1615
  var ResolveError;
1513
-
1514
1616
  (function (ResolveError) {
1515
1617
  /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
1516
1618
  ResolveError["NoAppsFound"] = "NoAppsFound";
1517
1619
  /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1518
-
1519
1620
  ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
1520
1621
  /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
1521
-
1522
1622
  ResolveError["UserCancelled"] = "UserCancelledResolution";
1523
1623
  /** SHOULD be returned if a timeout cancels an intent resolution that required user interaction. Please use `ResolverUnavailable` instead for situations where a resolver UI or similar fails.*/
1524
-
1525
1624
  ResolveError["ResolverTimeout"] = "ResolverTimeout";
1526
1625
  /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
1527
-
1528
1626
  ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
1529
1627
  /** Returned if a specified target application instance is not available, for example because it has been closed. */
1530
-
1531
1628
  ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
1532
1629
  /** Returned if the intent and context could not be delivered to the selected application or instance, for example because it has not added an intent handler within a timeout.*/
1533
-
1534
1630
  ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
1631
+ /** Returned if a call to one of the `raiseIntent` functions is made with an invalid context argument. Contexts should be Objects with at least a `type` field that has a `string` value.*/
1632
+ ResolveError["MalformedContext"] = "MalformedContext";
1535
1633
  })(ResolveError || (ResolveError = {}));
1536
-
1537
1634
  var ResultError;
1538
-
1539
1635
  (function (ResultError) {
1540
- /** Returned if the intent handler exited without returning a Promise or that Promise was not resolved with a Context or Channel object. */
1636
+ /** Returned if the intent handler exited without returning a valid result (a promise resolving to a Context, Channel object or void). */
1541
1637
  ResultError["NoResultReturned"] = "NoResultReturned";
1542
1638
  /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
1543
-
1544
1639
  ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
1545
1640
  })(ResultError || (ResultError = {}));
1546
-
1547
1641
  var ChannelError;
1548
-
1549
1642
  (function (ChannelError) {
1550
1643
  /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
1551
1644
  ChannelError["NoChannelFound"] = "NoChannelFound";
1552
1645
  /** SHOULD be returned when a request to join a user channel or to a retrieve a Channel object via the `joinUserChannel` or `getOrCreateChannel` methods of the DesktopAgent (`fdc3`) object is denied. */
1553
-
1554
1646
  ChannelError["AccessDenied"] = "AccessDenied";
1555
1647
  /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
1556
-
1557
1648
  ChannelError["CreationFailed"] = "CreationFailed";
1649
+ /** Returned if a call to the `broadcast` functions is made with an invalid context argument. Contexts should be Objects with at least a `type` field that has a `string` value.*/
1650
+ ChannelError["MalformedContext"] = "MalformedContext";
1558
1651
  })(ChannelError || (ChannelError = {}));
1559
1652
 
1560
1653
  var ContextTypes;
1561
-
1562
1654
  (function (ContextTypes) {
1563
1655
  ContextTypes["Chart"] = "fdc3.chart";
1564
1656
  ContextTypes["ChatInitSettings"] = "fdc3.chat.initSettings";
@@ -1579,13 +1671,13 @@
1579
1671
 
1580
1672
  // To parse this data:
1581
1673
  //
1582
- // import { Convert, Context, Chart, ChatInitSettings, Contact, ContactList, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1674
+ // import { Convert, Chart, ChatInitSettings, Contact, ContactList, Context, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1583
1675
  //
1584
- // const context = Convert.toContext(json);
1585
1676
  // const chart = Convert.toChart(json);
1586
1677
  // const chatInitSettings = Convert.toChatInitSettings(json);
1587
1678
  // const contact = Convert.toContact(json);
1588
1679
  // const contactList = Convert.toContactList(json);
1680
+ // const context = Convert.toContext(json);
1589
1681
  // const country = Convert.toCountry(json);
1590
1682
  // const currency = Convert.toCurrency(json);
1591
1683
  // const email = Convert.toEmail(json);
@@ -1601,7 +1693,6 @@
1601
1693
  // These functions will throw an error if the JSON doesn't
1602
1694
  // match the expected interface, even if the JSON is valid.
1603
1695
  var Style;
1604
-
1605
1696
  (function (Style) {
1606
1697
  Style["Bar"] = "bar";
1607
1698
  Style["Candle"] = "candle";
@@ -1613,10 +1704,9 @@
1613
1704
  Style["Pie"] = "pie";
1614
1705
  Style["Scatter"] = "scatter";
1615
1706
  Style["StackedBar"] = "stacked-bar";
1616
- })(Style || (Style = {})); // Converts JSON strings to/from your types
1707
+ })(Style || (Style = {}));
1617
1708
 
1618
1709
  var Intents;
1619
-
1620
1710
  (function (Intents) {
1621
1711
  Intents["StartCall"] = "StartCall";
1622
1712
  Intents["StartChat"] = "StartChat";
@@ -1692,15 +1782,11 @@
1692
1782
  const isContext = (data) => {
1693
1783
  return defaultContextProps.every(prop => Object.keys(data).includes(prop));
1694
1784
  };
1695
- const isChannelMetadata = (data) => {
1696
- return typeof data === "object" && data.isChannel;
1697
- };
1698
1785
  const extractChannelMetadata = (channel) => {
1699
1786
  return {
1700
1787
  id: channel.id,
1701
1788
  type: channel.type,
1702
- displayMetadata: channel.displayMetadata,
1703
- isChannel: true
1789
+ displayMetadata: channel.displayMetadata
1704
1790
  };
1705
1791
  };
1706
1792
  const parseContextHandler = (handler, contextType) => {
@@ -1717,10 +1803,11 @@
1717
1803
  };
1718
1804
 
1719
1805
  class IntentsController {
1720
- constructor(glueController, channelsController, channelsFactory) {
1806
+ constructor(glueController, channelsController, channelsFactory, glueEventsController) {
1721
1807
  this.glueController = glueController;
1722
1808
  this.channelsController = channelsController;
1723
1809
  this.channelsFactory = channelsFactory;
1810
+ this.glueEventsController = glueEventsController;
1724
1811
  }
1725
1812
  get logger() {
1726
1813
  if (!this._logger) {
@@ -1812,11 +1899,33 @@
1812
1899
  });
1813
1900
  }
1814
1901
  addIntentListener({ commandId, intent, handler }) {
1902
+ var _a, _b;
1815
1903
  return __awaiter(this, void 0, void 0, function* () {
1816
1904
  yield this.glueController.gluePromise;
1817
1905
  this.logger.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
1818
1906
  const wrappedHandler = this.getWrappedIntentHandler(handler);
1819
- return this.glueController.addIntentListener(intent, wrappedHandler);
1907
+ const myInstance = this.glueController.getMyInteropInstance();
1908
+ const myApplication = this.glueController.getApplication(myInstance.applicationName);
1909
+ let appConfigIntentDef;
1910
+ const globalBrowserNamespace = window.glue42core || window.iobrowser;
1911
+ const globalDesktopNamespace = window.glue42gd || window.iodesktop;
1912
+ if (globalBrowserNamespace) {
1913
+ appConfigIntentDef = (_a = myApplication === null || myApplication === void 0 ? void 0 : myApplication.userProperties.intents) === null || _a === void 0 ? void 0 : _a.find((appIntent) => appIntent.name === intent);
1914
+ }
1915
+ if (globalDesktopNamespace) {
1916
+ const appConfig = yield myApplication.getConfiguration();
1917
+ appConfigIntentDef = (_b = appConfig === null || appConfig === void 0 ? void 0 : appConfig.intents) === null || _b === void 0 ? void 0 : _b.find((appIntent) => appIntent.name === intent);
1918
+ }
1919
+ const intentRequest = {
1920
+ intent,
1921
+ displayName: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.displayName,
1922
+ description: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.description,
1923
+ contextTypes: (appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.contexts) || Fdc3SupportedIntentTypes[intent],
1924
+ resultType: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.resultType
1925
+ };
1926
+ Object.keys(intentRequest)
1927
+ .forEach((key) => intentRequest[key] === undefined && delete intentRequest[key]);
1928
+ return this.glueController.addIntentListener(intentRequest, wrappedHandler);
1820
1929
  });
1821
1930
  }
1822
1931
  filterGlueIntentHandlers({ commandId, intent, context, target }) {
@@ -1836,7 +1945,7 @@
1836
1945
  this.logger.info(`[${commandId}] - Checking if application with name ${appName} exists`);
1837
1946
  const app = this.glueController.getApplication(appName);
1838
1947
  const serverInstances = this.serverInstanceAsIntentHandler(intent.name);
1839
- if (!app && (typeof target === "string" || !serverInstances.length)) {
1948
+ if (!app && (typeof target === "string" || !target.instanceId || !serverInstances.length)) {
1840
1949
  throw { message: ResolveError.TargetAppUnavailable, reason: `There's no app with appId ${appName}` };
1841
1950
  }
1842
1951
  this.logger.info(`[${commandId}] - target app ${appName} found. Filtering handlers by applicationName: ${appName}`);
@@ -1882,23 +1991,33 @@
1882
1991
  if (!isValidNonEmptyObject(result)) {
1883
1992
  return;
1884
1993
  }
1885
- const isResultChannelMetadata = isChannelMetadata(result);
1886
- if (!isResultChannelMetadata) {
1994
+ if (!result.fdc3intentChannel && !result.fdc3intentContext) {
1887
1995
  return result;
1888
1996
  }
1889
- const { clientId, creatorId } = yield this.glueController.getContext(result.id);
1890
- this.logger.info(`[${commandId}] - result is a private channel with creatorId ${creatorId} and clientId ${clientId}`);
1891
- const myInteropInstanceId = this.glueController.getMyInteropInstanceId();
1892
- if ((creatorId && creatorId !== myInteropInstanceId) && (clientId && clientId !== myInteropInstanceId)) {
1893
- throw { message: ResultError.NoResultReturned, reason: "There are already two parties on this private channel" };
1894
- }
1895
- const channel = this.channelsFactory.buildModel(result);
1896
- if (myInteropInstanceId && myInteropInstanceId !== creatorId) {
1897
- this.logger.info(`[${commandId}] - the current user is the second party of the private channel. Adding my id ${myInteropInstanceId} as a clientId`);
1898
- yield this.channelsController.addClientToPrivateChannel(commandId, channel.id, myInteropInstanceId);
1899
- }
1997
+ if (result.fdc3intentContext) {
1998
+ return result.fdc3intentContext;
1999
+ }
2000
+ const { fdc3intentChannel } = result;
2001
+ if (fdc3intentChannel.type === "user") {
2002
+ const glueChannel = (yield this.glueController.listAllChannels()).find(ch => ch.name === fdc3intentChannel.displayMetadata.name);
2003
+ return this.channelsFactory.buildModel(Object.assign(Object.assign({}, fdc3intentChannel), { displayMetadata: Object.assign(Object.assign({}, fdc3intentChannel.displayMetadata), { glueChannel }) }));
2004
+ }
2005
+ if (fdc3intentChannel.type !== "private") {
2006
+ return this.channelsFactory.buildModel(fdc3intentChannel);
2007
+ }
2008
+ yield this.glueEventsController.initializeCollaborateMethod();
2009
+ const channel = this.channelsController.buildPrivateChannel(fdc3intentChannel.id, commandId, false);
2010
+ channel.setCollaborator({ appId: glueIntentResult.handler.applicationName, instanceId: glueIntentResult.handler.instanceId }, commandId);
2011
+ const joinChannelArgs = {
2012
+ action: "joinPrivateChannel",
2013
+ correlationId: channel.id,
2014
+ collaborationObject: {
2015
+ channelId: channel.id
2016
+ }
2017
+ };
2018
+ yield this.glueController.invokeSystemMethod(joinChannelArgs, glueIntentResult.handler.instanceId);
1900
2019
  this.logger.info(`[${commandId}] - returning private channel`);
1901
- return channel;
2020
+ return channel.toApi();
1902
2021
  });
1903
2022
  }
1904
2023
  convertGlue42IntentToFDC3Intent(glueIntent) {
@@ -1933,15 +2052,23 @@
1933
2052
  throw new Error("Async handler function should return a promise that resolves to a Context or Channel");
1934
2053
  }
1935
2054
  getWrappedIntentHandler(handler) {
1936
- const wrappedHandler = (glue42Context) => __awaiter(this, void 0, void 0, function* () {
1937
- const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }));
2055
+ const wrappedHandler = (glue42Context, caller) => __awaiter(this, void 0, void 0, function* () {
2056
+ const contextMetadata = caller
2057
+ ? {
2058
+ source: {
2059
+ appId: caller.application || caller.applicationName || "",
2060
+ instanceId: caller.instance
2061
+ }
2062
+ }
2063
+ : undefined;
2064
+ const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }), contextMetadata);
1938
2065
  if (!handlerResult) {
1939
2066
  return;
1940
2067
  }
1941
2068
  const handlerResultType = this.getResultType(handlerResult);
1942
2069
  return handlerResultType === IntentHandlerResultTypes.Channel
1943
- ? extractChannelMetadata(handlerResult)
1944
- : handlerResult;
2070
+ ? { fdc3intentChannel: extractChannelMetadata(handlerResult) }
2071
+ : { fdc3intentContext: handlerResult };
1945
2072
  });
1946
2073
  return wrappedHandler;
1947
2074
  }
@@ -1988,13 +2115,14 @@
1988
2115
  }
1989
2116
  }
1990
2117
 
1991
- var version = "2.1.0";
2118
+ var version = "2.1.2";
1992
2119
 
1993
2120
  class ApplicationsController {
1994
- constructor(glueController) {
2121
+ constructor(glueController, appsStateStore, glueEventsController) {
1995
2122
  this.glueController = glueController;
1996
- this.defaultContextListenerInvokedPromiseTimeout = 60000;
1997
- this.contextListenerInvokedPromises = {};
2123
+ this.appsStateStore = appsStateStore;
2124
+ this.glueEventsController = glueEventsController;
2125
+ this.defaultContextListenerInvokedPromiseTimeout = 120 * 1000;
1998
2126
  }
1999
2127
  get logger() {
2000
2128
  if (!this._logger) {
@@ -2012,6 +2140,7 @@
2012
2140
  throw { message: OpenError.AppNotFound, reason: `Cannot find targeted ${name} application` };
2013
2141
  }
2014
2142
  if (context) {
2143
+ yield this.glueEventsController.initializeCollaborateMethod();
2015
2144
  this.logger.info(`[${commandId}] - opening app ${app} with startup context`);
2016
2145
  return this.openAppWithContext(app, context);
2017
2146
  }
@@ -2066,7 +2195,7 @@
2066
2195
  this.logger.info(`${commandId} - getInfo() invoked`);
2067
2196
  const appMetadata = yield this.getCurrentAppMetadata();
2068
2197
  return {
2069
- provider: "Glue42",
2198
+ provider: "io.Connect",
2070
2199
  providerVersion: version,
2071
2200
  fdc3Version: "2.0",
2072
2201
  optionalFeatures: {
@@ -2127,41 +2256,39 @@
2127
2256
  }
2128
2257
  openAppWithContext(app, context) {
2129
2258
  return __awaiter(this, void 0, void 0, function* () {
2130
- const methodName = yield this.registerContextListenerInteropMethod();
2131
- const startContext = this.buildGlueStartContext(context, methodName);
2132
- const glueInst = yield app.start(startContext);
2133
- this.createContextListenerResponsePromise(glueInst, methodName);
2259
+ const guid = nanoid();
2260
+ const startContext = this.buildStartContext(context, guid);
2261
+ const wrappedPromise = this.createContextListenerWrappedPromise(app);
2262
+ this.appsStateStore.addOpenAppPromise(guid, wrappedPromise);
2134
2263
  try {
2135
- yield this.contextListenerInvokedPromises[glueInst.id].promise;
2136
- yield this.unregisterContextListenerPromise(glueInst.id);
2264
+ const glueInst = yield app.start(startContext);
2265
+ yield wrappedPromise.promise;
2266
+ this.appsStateStore.removeOpenAppPromise(guid);
2137
2267
  return this.parseGlueInstToAppIdentifier(glueInst);
2138
2268
  }
2139
2269
  catch (error) {
2140
- yield this.unregisterContextListenerPromise(glueInst.id);
2270
+ this.appsStateStore.removeOpenAppPromise(guid);
2141
2271
  throw { message: OpenError.AppTimeout, reason: typeof error === "string" ? error : JSON.stringify(error) };
2142
2272
  }
2143
2273
  });
2144
2274
  }
2145
- buildGlueStartContext(fdc3Context, responseMethodName) {
2275
+ buildStartContext(fdc3Context, guid) {
2276
+ const myInteropInstance = this.glueController.getMyInteropInstance();
2146
2277
  return {
2147
- meta: {
2148
- responseMethodName,
2149
- instance: this.glueController.interopInstance().instance
2150
- },
2151
- context: fdc3Context
2278
+ fdc3: {
2279
+ collaborationId: guid,
2280
+ openApp: {
2281
+ appId: myInteropInstance.application || myInteropInstance.applicationName || "",
2282
+ instanceId: myInteropInstance.instance
2283
+ },
2284
+ context: {
2285
+ contextType: fdc3Context.type,
2286
+ payload: fdc3Context
2287
+ }
2288
+ }
2152
2289
  };
2153
2290
  }
2154
- registerContextListenerInteropMethod() {
2155
- return __awaiter(this, void 0, void 0, function* () {
2156
- const methodName = this.buildInteropMethodName();
2157
- yield this.glueController.registerMethod(methodName, this.contextListenerResponseHandler.bind(this));
2158
- return methodName;
2159
- });
2160
- }
2161
- buildInteropMethodName() {
2162
- return `${responseInteropMethodPrefix}.${nanoid()}`;
2163
- }
2164
- createContextListenerResponsePromise(instance, methodName) {
2291
+ createContextListenerWrappedPromise(app) {
2165
2292
  let resolve = () => { };
2166
2293
  let reject = () => { };
2167
2294
  const promise = promisePlus(() => {
@@ -2169,50 +2296,32 @@
2169
2296
  resolve = res;
2170
2297
  reject = rej;
2171
2298
  });
2172
- }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${instance.application.name} and instanceId: ${instance.id} to register context listener`);
2173
- this.contextListenerInvokedPromises[instance.id] = { promise, resolve, reject, methodName };
2174
- }
2175
- contextListenerResponseHandler(args, callerId) {
2176
- const result = ContextListenerResponseDecoder.run(args);
2177
- if (!result.ok) {
2178
- const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2179
- if (!contextListenerPromise) {
2180
- return;
2181
- }
2182
- contextListenerPromise.reject(`Method invoked with invalid argument - ${result.error.message}`);
2183
- return;
2184
- }
2185
- const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2186
- if (!contextListenerPromise) {
2187
- return;
2188
- }
2189
- contextListenerPromise.resolve();
2190
- }
2191
- unregisterContextListenerPromise(instanceId) {
2192
- return __awaiter(this, void 0, void 0, function* () {
2193
- const { methodName } = this.contextListenerInvokedPromises[instanceId];
2194
- yield this.glueController.unregisterMethod(methodName);
2195
- delete this.contextListenerInvokedPromises[instanceId];
2196
- });
2299
+ }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${app.name} to register context listener`);
2300
+ return { promise, resolve, reject };
2197
2301
  }
2198
2302
  }
2199
2303
 
2200
2304
  class ChannelsController {
2201
- constructor(glueController, channelsStateStore, channelsParser, channelsFactory, channelsCallbackRegistry) {
2305
+ constructor(glueController, channelsStateStore, channelsParser, channelsFactory, glueEventsController) {
2202
2306
  this.glueController = glueController;
2203
2307
  this.channelsStateStore = channelsStateStore;
2204
2308
  this.channelsParser = channelsParser;
2205
2309
  this.channelsFactory = channelsFactory;
2206
- this.channelsCallbackRegistry = channelsCallbackRegistry;
2310
+ this.glueEventsController = glueEventsController;
2207
2311
  this.invokeContextHandlerWithStartupContext = true;
2208
2312
  this.initDonePromise = this.initialize();
2209
- this.initDonePromise.catch(() => { });
2313
+ this.initDonePromise.catch((err) => {
2314
+ var _a;
2315
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(err);
2316
+ });
2210
2317
  }
2211
- get logger() {
2212
- if (!this._logger) {
2213
- this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2214
- }
2215
- return this._logger;
2318
+ getStartupContext() {
2319
+ var _a, _b;
2320
+ return __awaiter(this, void 0, void 0, function* () {
2321
+ yield this.initDonePromise;
2322
+ const fdc3StartupContext = yield this.glueController.getMyWindowContext();
2323
+ return ((_b = (_a = fdc3StartupContext === null || fdc3StartupContext === void 0 ? void 0 : fdc3StartupContext.fdc3) === null || _a === void 0 ? void 0 : _a.context) === null || _b === void 0 ? void 0 : _b.payload) || null;
2324
+ });
2216
2325
  }
2217
2326
  addContextListener({ commandId, handler, contextType, channelId }) {
2218
2327
  var _a;
@@ -2250,14 +2359,14 @@
2250
2359
  return __awaiter(this, void 0, void 0, function* () {
2251
2360
  yield this.initDonePromise;
2252
2361
  this.logger.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
2253
- const isPrivateChannel = this.isPrivateChannel(channelId);
2254
- if (isPrivateChannel) {
2255
- throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2256
- }
2257
2362
  const isUserChannel = this.isUserChannel(channelId);
2258
2363
  if (isUserChannel) {
2259
2364
  throw { message: ChannelError.AccessDenied, reason: "There's an already existing system channel with passed id. Retrieve it using fdc3.getSystemChannels() or create a new app channel with a different id" };
2260
2365
  }
2366
+ const isPrivateChannel = this.channelsStateStore.getPrivateChannelById(channelId);
2367
+ if (isPrivateChannel) {
2368
+ throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2369
+ }
2261
2370
  return this.getOrCreateAppChannel(commandId, channelId);
2262
2371
  });
2263
2372
  }
@@ -2335,26 +2444,28 @@
2335
2444
  return __awaiter(this, void 0, void 0, function* () {
2336
2445
  yield this.initDonePromise;
2337
2446
  this.logger.info(`[${commandId}] - createPrivateChannel() invoked`);
2338
- const creatorId = this.glueController.getMyInteropInstanceId();
2339
- const channel = this.buildChannel(ChannelTypes.Private);
2340
- yield this.glueController.updateContext(channel.id, { creatorId });
2341
- this.logger.info(`[${commandId}] - private channel with id ${channel.id} created`);
2342
- return channel;
2447
+ const channelId = `${PrivateChannelPrefix}${nanoid()}`;
2448
+ yield this.glueEventsController.initializeCollaborateMethod();
2449
+ const pc = this.buildPrivateChannel(channelId, commandId, true);
2450
+ return pc.toApi();
2343
2451
  });
2344
2452
  }
2345
- announceDisconnect(commandId, channelId, instanceId) {
2453
+ removePrivateChannelFromStoreById(id) {
2346
2454
  return __awaiter(this, void 0, void 0, function* () {
2347
- yield this.initDonePromise;
2348
- this.logger.info(`[${commandId}] - disconnect() invoked on channel with id ${channelId}`);
2349
- yield this.glueController.updateContext(channelId, { disconnected: true });
2350
- this.logger.info(`[${commandId}] - glue context for ${channelId} updated with disconnected flag`);
2351
- const closedInstanceId = instanceId || this.glueController.getMyInteropInstanceId();
2352
- const targetInstance = yield this.getOtherInstanceIdFromClosedOne(channelId, closedInstanceId);
2353
- const replayContextTypes = yield this.getContextTypesForPrivateChannel(channelId);
2354
- this.logger.info(`[${commandId}] - invoking onDisconnect callback for instance ${targetInstance}`);
2355
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnDisconnect, { clientId: targetInstance, channelId, replayContextTypes });
2455
+ this.channelsStateStore.removePrivateChannelById(id);
2356
2456
  });
2357
2457
  }
2458
+ invokeSystemMethod(args, target) {
2459
+ return __awaiter(this, void 0, void 0, function* () {
2460
+ if (!target) {
2461
+ return;
2462
+ }
2463
+ return this.glueController.invokeSystemMethod(args, target);
2464
+ });
2465
+ }
2466
+ getMyServerInstance() {
2467
+ return this.glueController.getMyInteropInstance();
2468
+ }
2358
2469
  addClientToPrivateChannel(commandId, channelId, clientId) {
2359
2470
  return __awaiter(this, void 0, void 0, function* () {
2360
2471
  this.logger.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
@@ -2368,28 +2479,22 @@
2368
2479
  return !!context.disconnected;
2369
2480
  });
2370
2481
  }
2371
- registerOnInstanceStopped({ commandId, channelId }) {
2372
- this.logger.info(`[${commandId}] - registering onInstanceStopped callback for channel with id ${channelId}`);
2373
- const handler = (instance) => __awaiter(this, void 0, void 0, function* () {
2374
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2375
- if (instance.id !== clientId && instance.id !== creatorId) {
2376
- return;
2377
- }
2378
- this.logger.info(`[${commandId}] - calling onDisconnect callback for channel with id ${channelId}`);
2379
- yield this.announceDisconnect(commandId, channelId, instance.id);
2380
- });
2482
+ subscribeOnInstanceStop(channelId, handler, commandId) {
2483
+ this.logger.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
2381
2484
  return this.glueController.registerOnInstanceStopped(handler.bind(this));
2382
2485
  }
2383
- addPrivateChannelEvent({ commandId, action, channelId, handler }) {
2384
- return __awaiter(this, void 0, void 0, function* () {
2385
- this.logger.info(`[${commandId}] - registering callback for ${action} event in channel with id ${channelId}`);
2386
- let replayArgs;
2387
- const targetInstanceId = yield this.getTargetedInstanceId(channelId);
2388
- if (action === PrivateChannelEventMethods.OnAddContextListener && targetInstanceId) {
2389
- replayArgs = yield this.getContextTypesForPrivateChannel(channelId);
2390
- }
2391
- return this.channelsCallbackRegistry.add({ action, channelId, handler, replayArgs });
2392
- });
2486
+ buildPrivateChannel(channelId, commandId, isCreator) {
2487
+ const logger = this.glueController.initSubLogger(channelId);
2488
+ const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
2489
+ this.logger.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
2490
+ this.channelsStateStore.addPrivateChannel(channel);
2491
+ return channel;
2492
+ }
2493
+ get logger() {
2494
+ if (!this._logger) {
2495
+ this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2496
+ }
2497
+ return this._logger;
2393
2498
  }
2394
2499
  initialize() {
2395
2500
  return __awaiter(this, void 0, void 0, function* () {
@@ -2438,39 +2543,43 @@
2438
2543
  return __awaiter(this, void 0, void 0, function* () {
2439
2544
  const myWindow = this.glueController.getMyWindow();
2440
2545
  if (!myWindow) {
2441
- this.logger.log(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2546
+ this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2442
2547
  this.invokeContextHandlerWithStartupContext = false;
2443
2548
  return;
2444
2549
  }
2445
2550
  const windowContext = yield myWindow.getContext();
2446
- if (!isValidNonEmptyObject(windowContext)) {
2447
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2551
+ if (!windowContext) {
2552
+ this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2448
2553
  this.invokeContextHandlerWithStartupContext = false;
2449
2554
  return;
2450
2555
  }
2451
- const { context, meta } = windowContext;
2452
- const isSameContextType = contextType ? (context === null || context === void 0 ? void 0 : context.type) === contextType : true;
2453
- if (!isSameContextType || !meta) {
2454
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked`);
2556
+ if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
2557
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2558
+ this.invokeContextHandlerWithStartupContext = false;
2455
2559
  return;
2456
2560
  }
2457
- this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context`);
2458
- handler(context);
2459
- this.invokeContextHandlerWithStartupContext = false;
2460
- const { responseMethodName, instance } = meta;
2461
- const responseMethodExists = this.doesServerMethodExist(responseMethodName, instance);
2462
- if (!responseMethodExists) {
2463
- this.logger.info(`[${commandId}] - response method for instance ${instance} does not exist anymore. returning`);
2561
+ yield this.glueEventsController.initializeCollaborateMethod();
2562
+ FDC3StartupContextDecoder.runWithException(windowContext);
2563
+ const { fdc3 } = windowContext;
2564
+ this.logger.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
2565
+ const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
2566
+ if (!isSameContextType) {
2567
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
2464
2568
  return;
2465
2569
  }
2466
- this.logger.info(`[${commandId}] - invoking response method for instance ${instance}`);
2467
- yield this.glueController.invokeMethod(responseMethodName, instance, { listenerInvoked: true });
2570
+ this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
2571
+ try {
2572
+ handler(fdc3.context.payload, { source: fdc3.openApp });
2573
+ }
2574
+ catch (error) {
2575
+ this.logger.error(typeof error === "string" ? error : error.message ? JSON.stringify(error.message) : JSON.stringify(error));
2576
+ }
2577
+ this.invokeContextHandlerWithStartupContext = false;
2578
+ this.logger.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
2579
+ yield this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
2580
+ this.logger.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
2468
2581
  });
2469
2582
  }
2470
- doesServerMethodExist(methodName, instance) {
2471
- const serversForMethodName = this.glueController.getInteropServers({ name: methodName });
2472
- return !!serversForMethodName.find(server => server.instance === instance);
2473
- }
2474
2583
  getOrCreateAppChannel(commandId, channelId) {
2475
2584
  return __awaiter(this, void 0, void 0, function* () {
2476
2585
  const exists = this.doesAppChannelExist(channelId);
@@ -2479,7 +2588,8 @@
2479
2588
  yield this.glueController.updateContext(channelId, {});
2480
2589
  }
2481
2590
  this.logger.info(`[${commandId}] - returning app channel with id ${channelId}`);
2482
- return this.buildChannel(ChannelTypes.App, { id: channelId });
2591
+ const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
2592
+ return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
2483
2593
  });
2484
2594
  }
2485
2595
  doesAppChannelExist(name) {
@@ -2491,12 +2601,6 @@
2491
2601
  }
2492
2602
  return !!this.channelsStateStore.userChannels[channelId];
2493
2603
  }
2494
- isPrivateChannel(channelId) {
2495
- return channelId.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === channelId);
2496
- }
2497
- buildChannel(type, data) {
2498
- return this.channelsFactory.buildModel(Object.assign(Object.assign({ type }, data), { isChannel: true }));
2499
- }
2500
2604
  broadcastByChannelId(commandId, channelId, context) {
2501
2605
  return __awaiter(this, void 0, void 0, function* () {
2502
2606
  const isUserChannel = this.isUserChannel(channelId);
@@ -2514,7 +2618,7 @@
2514
2618
  const subHandler = parseContextHandler(handler, contextType);
2515
2619
  if (!channelId) {
2516
2620
  this.logger.info(`[${commandId}] - Creating a channel subscription using glue.channels.subscribe`);
2517
- const unsubscribe = this.glueController.channelsSubscribe(subHandler);
2621
+ const unsubscribe = this.glueController.channelsSubscribe(subHandler, contextType);
2518
2622
  return { unsubscribe };
2519
2623
  }
2520
2624
  const channelType = this.getChannelTypeById(channelId);
@@ -2531,25 +2635,10 @@
2531
2635
  }
2532
2636
  };
2533
2637
  }
2534
- if (channelType === ChannelTypes.Private) {
2535
- this.logger.info(`[${commandId}] - subscribing for fdc3 private channel with id ${channelId} (underlying glue context with same name)`);
2536
- const contextsUnsubscribe = yield this.glueController.contextsSubscribe(channelId, subHandler);
2537
- yield this.addContextTypeInPrivateChannelContext(channelId, contextType);
2538
- const targetInstance = yield this.getTargetedInstanceId(channelId);
2539
- const unsubscribe = () => {
2540
- this.logger.info(`[${commandId}] - unsubscribe invoked for private channel with id ${channelId}`);
2541
- contextsUnsubscribe();
2542
- this.logger.info(`[${commandId}] - invoking onUnsubscribe handler for private channel with id ${channelId}`);
2543
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnUnsubscribe, { channelId, clientId: targetInstance, contextType });
2544
- };
2545
- this.logger.info(`[${commandId}] - invoking onAddContextListener handler for private channel with id ${channelId}`);
2546
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnAddContextListener, { channelId: channelId, clientId: targetInstance, contextType });
2547
- return { unsubscribe };
2548
- }
2549
2638
  throw { message: ChannelError.AccessDenied, reason: "Cannot add a context listener on an invalid channel" };
2550
2639
  });
2551
2640
  }
2552
- addContextListenerOnUserChannel({ commandId, channelId, handler, invokedOnChannelModel }) {
2641
+ addContextListenerOnUserChannel({ commandId, channelId, handler, invokedOnChannelModel, contextType }) {
2553
2642
  return __awaiter(this, void 0, void 0, function* () {
2554
2643
  let unsubscribe;
2555
2644
  if (invokedOnChannelModel) {
@@ -2559,7 +2648,7 @@
2559
2648
  }
2560
2649
  else {
2561
2650
  this.logger.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
2562
- unsubscribe = this.glueController.channelsSubscribe(handler);
2651
+ unsubscribe = this.glueController.channelsSubscribe(handler, contextType);
2563
2652
  }
2564
2653
  return {
2565
2654
  unsubscribe: () => {
@@ -2574,56 +2663,21 @@
2574
2663
  if (isUser) {
2575
2664
  return ChannelTypes.User;
2576
2665
  }
2577
- const isPrivate = this.isPrivateChannel(channelId);
2578
- if (isPrivate) {
2579
- return ChannelTypes.Private;
2580
- }
2581
2666
  const isApp = this.doesAppChannelExist(channelId);
2582
2667
  if (isApp) {
2583
2668
  return ChannelTypes.App;
2584
2669
  }
2585
2670
  throw { message: ChannelError.NoChannelFound, reason: `Channel with id: ${channelId} does not exist` };
2586
2671
  }
2587
- getTargetedInstanceId(channelId) {
2588
- return __awaiter(this, void 0, void 0, function* () {
2589
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2590
- const myId = this.glueController.getMyInteropInstanceId();
2591
- return myId === clientId ? creatorId : clientId;
2592
- });
2593
- }
2594
- getOtherInstanceIdFromClosedOne(channelId, closedInstanceId) {
2595
- return __awaiter(this, void 0, void 0, function* () {
2596
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2597
- return closedInstanceId === clientId
2598
- ? creatorId
2599
- : clientId;
2600
- });
2601
- }
2602
- invokeSystemMethod(clientId, action, payload) {
2603
- if (clientId) {
2604
- this.glueController.invokeSystemMethod({ action, payload });
2605
- }
2606
- }
2607
- addContextTypeInPrivateChannelContext(channelId, contextType) {
2608
- return __awaiter(this, void 0, void 0, function* () {
2609
- const currentContext = yield this.glueController.getContext(channelId);
2610
- const updatedTypes = currentContext.contextListenerTypes ? [...currentContext.contextListenerTypes, contextType] : [contextType];
2611
- return this.glueController.updateContext(channelId, Object.assign(Object.assign({}, currentContext), { contextListenerTypes: updatedTypes }));
2612
- });
2613
- }
2614
- getContextTypesForPrivateChannel(channelId) {
2615
- return __awaiter(this, void 0, void 0, function* () {
2616
- const ctx = yield this.glueController.getContext(channelId);
2617
- return ctx.contextListenerTypes;
2618
- });
2672
+ buildChannel(type, data) {
2673
+ return this.channelsFactory.buildModel(Object.assign({ type }, data));
2619
2674
  }
2620
2675
  }
2621
2676
 
2622
2677
  class EventReceiver {
2623
- constructor(glueController, eventDispatcher, eventsController) {
2678
+ constructor(glueController, eventDispatcher) {
2624
2679
  this.glueController = glueController;
2625
2680
  this.eventDispatcher = eventDispatcher;
2626
- this.eventsController = eventsController;
2627
2681
  this.glueResponseReceived = false;
2628
2682
  this.glueInitialized = false;
2629
2683
  this.events = {
@@ -2669,7 +2723,6 @@
2669
2723
  }
2670
2724
  window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
2671
2725
  this.glueController.initialize(glue);
2672
- yield this.eventsController.initialize();
2673
2726
  this.eventDispatcher.fireFdc3Ready();
2674
2727
  this.glueInitialized = true;
2675
2728
  });
@@ -2681,16 +2734,17 @@
2681
2734
  this._currentChannel = null;
2682
2735
  this._userChannels = {};
2683
2736
  this._fdc3ChannelIdsToGlueChannelNames = {};
2737
+ this._privateChannels = {};
2684
2738
  }
2685
2739
  get currentChannel() {
2686
2740
  return this._currentChannel;
2687
2741
  }
2688
- get userChannels() {
2689
- return this._userChannels;
2690
- }
2691
2742
  set currentChannel(newChannelValue) {
2692
2743
  this._currentChannel = newChannelValue;
2693
2744
  }
2745
+ get userChannels() {
2746
+ return this._userChannels;
2747
+ }
2694
2748
  addUserChannel(channel) {
2695
2749
  this._userChannels[channel.id] = channel;
2696
2750
  }
@@ -2704,140 +2758,14 @@
2704
2758
  const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
2705
2759
  return key;
2706
2760
  }
2707
- }
2708
-
2709
- class PrivateChannel {
2710
- constructor(channelsController, channelId) {
2711
- this.channelsController = channelsController;
2712
- this.type = ChannelTypes.Private;
2713
- this.id = channelId || `${PrivateChannelPrefix}${nanoid()}`;
2714
- this.unsubFromInstanceStopped = this.channelsController.registerOnInstanceStopped({ commandId: generateCommandId(), channelId: this.id });
2715
- }
2716
- toApi() {
2717
- const api = {
2718
- id: this.id,
2719
- type: this.type,
2720
- displayMetadata: this.displayMetadata,
2721
- broadcast: this.broadcast.bind(this),
2722
- getCurrentContext: this.getCurrentContext.bind(this),
2723
- addContextListener: this.addContextListener.bind(this),
2724
- onAddContextListener: this.onAddContextListener.bind(this),
2725
- onUnsubscribe: this.onUnsubscribe.bind(this),
2726
- onDisconnect: this.onDisconnect.bind(this),
2727
- disconnect: this.disconnect.bind(this),
2728
- };
2729
- return api;
2761
+ addPrivateChannel(privateChannel) {
2762
+ this._privateChannels[privateChannel.id] = privateChannel;
2730
2763
  }
2731
- broadcast(context) {
2732
- return __awaiter(this, void 0, void 0, function* () {
2733
- const commandId = generateCommandId();
2734
- const isDisconnected = yield this.channelsController.isPrivateChannelDisconnected({ commandId, channelId: this.id });
2735
- if (isDisconnected) {
2736
- throw { message: ChannelError.AccessDenied, reason: "Channel has disconnected - broadcast is no longer available" };
2737
- }
2738
- contextDecoder.runWithException(context);
2739
- return this.channelsController.broadcast(commandId, context, this.id);
2740
- });
2764
+ getPrivateChannelById(id) {
2765
+ return this._privateChannels[id];
2741
2766
  }
2742
- getCurrentContext(contextType) {
2743
- return __awaiter(this, void 0, void 0, function* () {
2744
- optionalNonEmptyStringDecoder.runWithException(contextType);
2745
- return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
2746
- });
2747
- }
2748
- addContextListener(contextType, handler) {
2749
- return __awaiter(this, arguments, void 0, function* () {
2750
- if (arguments.length === 1) {
2751
- if (typeof contextType !== "function") {
2752
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2753
- }
2754
- return this.channelsController.addContextListener({ commandId: generateCommandId(), handler: contextType, channelId: this.id });
2755
- }
2756
- const contextTypeDecoder = optionalNonEmptyStringDecoder.runWithException(contextType);
2757
- if (typeof handler !== "function") {
2758
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2759
- }
2760
- return this.channelsController.addContextListener({
2761
- commandId: generateCommandId(),
2762
- contextType: contextTypeDecoder,
2763
- channelId: this.id,
2764
- handler,
2765
- });
2766
- });
2767
- }
2768
- onAddContextListener(handler) {
2769
- if (typeof handler !== "function") {
2770
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2771
- }
2772
- const unsub = this.channelsController.addPrivateChannelEvent({
2773
- commandId: generateCommandId(),
2774
- action: PrivateChannelEventMethods.OnAddContextListener,
2775
- channelId: this.id,
2776
- handler
2777
- });
2778
- return AsyncListener(unsub);
2779
- }
2780
- onUnsubscribe(handler) {
2781
- if (typeof handler !== "function") {
2782
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2783
- }
2784
- const unsub = this.channelsController.addPrivateChannelEvent({
2785
- commandId: generateCommandId(),
2786
- action: PrivateChannelEventMethods.OnUnsubscribe,
2787
- channelId: this.id,
2788
- handler
2789
- });
2790
- return AsyncListener(unsub);
2791
- }
2792
- onDisconnect(handler) {
2793
- if (typeof handler !== "function") {
2794
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2795
- }
2796
- const unsub = this.channelsController.addPrivateChannelEvent({
2797
- commandId: generateCommandId(),
2798
- action: PrivateChannelEventMethods.OnDisconnect,
2799
- channelId: this.id,
2800
- handler
2801
- });
2802
- return AsyncListener(unsub);
2803
- }
2804
- disconnect() {
2805
- return __awaiter(this, void 0, void 0, function* () {
2806
- yield this.channelsController.announceDisconnect(generateCommandId(), this.id);
2807
- this.unsubFromInstanceStopped();
2808
- });
2809
- }
2810
- }
2811
-
2812
- class ChannelsFactory {
2813
- constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
2814
- this.createUserChannelFn = createUserChannelFn;
2815
- this.createAppChannel = createAppChannel;
2816
- this.createPrivateChannel = createPrivateChannel;
2817
- }
2818
- buildModel(data) {
2819
- const { type } = data;
2820
- if (type === ChannelTypes.User) {
2821
- return this.buildUserChannel(data.displayMetadata.glueChannel);
2822
- }
2823
- else if (type === ChannelTypes.App) {
2824
- return this.buildAppChannel(data.id);
2825
- }
2826
- else if (type === ChannelTypes.Private) {
2827
- return this.buildPrivateChannel(data.id);
2828
- }
2829
- else {
2830
- throw new Error("Pass one of the supported channel types: user, app, private");
2831
- }
2832
- }
2833
- buildUserChannel(data) {
2834
- return this.createUserChannelFn(data);
2835
- }
2836
- buildAppChannel(channelId) {
2837
- return this.createAppChannel(channelId);
2838
- }
2839
- buildPrivateChannel(channelId) {
2840
- return this.createPrivateChannel(channelId);
2767
+ removePrivateChannelById(id) {
2768
+ delete this._privateChannels[id];
2841
2769
  }
2842
2770
  }
2843
2771
 
@@ -2958,36 +2886,345 @@
2958
2886
  createRegistry.default = createRegistry;
2959
2887
  var lib = createRegistry;
2960
2888
 
2961
- class ChannelsCallbackRegistry {
2962
- constructor() {
2889
+ class PrivateChannel {
2890
+ constructor(channelsController, logger, channelId, isCreator) {
2891
+ this.channelsController = channelsController;
2892
+ this.logger = logger;
2893
+ this.isCreator = isCreator;
2894
+ this.type = ChannelTypes.Private;
2895
+ this.disconnected = false;
2896
+ this.broadcastedContexts = {};
2897
+ this.collaboratorListenerTypes = [];
2898
+ this.myListenerTypesBeforeBound = [];
2963
2899
  this.registry = lib();
2900
+ this.id = channelId;
2901
+ const myServerInstance = this.channelsController.getMyServerInstance();
2902
+ this.myAppMetadata = { source: { appId: myServerInstance.applicationName, instanceId: myServerInstance.instance } };
2903
+ }
2904
+ toApi() {
2905
+ const api = {
2906
+ id: this.id,
2907
+ type: this.type,
2908
+ displayMetadata: this.displayMetadata,
2909
+ broadcast: this.broadcast.bind(this),
2910
+ getCurrentContext: this.getCurrentContext.bind(this),
2911
+ addContextListener: this.addContextListener.bind(this),
2912
+ onAddContextListener: this.onAddContextListener.bind(this),
2913
+ onUnsubscribe: this.onUnsubscribe.bind(this),
2914
+ onDisconnect: this.onDisconnect.bind(this),
2915
+ disconnect: this.disconnect.bind(this),
2916
+ };
2917
+ return api;
2918
+ }
2919
+ getCollaborator() {
2920
+ return this.collaborator;
2921
+ }
2922
+ setCollaborator(collaborator, commandId) {
2923
+ if (this.collaborator && this.collaborator.instanceId !== collaborator.instanceId) {
2924
+ throw new Error(`There's already a collaborator for private channel with id ${this.id}`);
2925
+ }
2926
+ this.collaborator = collaborator;
2927
+ this.subscribeForCollaboratorInstanceStop(commandId);
2928
+ }
2929
+ handleCollaboratorJoin(collaborator, commandId) {
2930
+ return __awaiter(this, void 0, void 0, function* () {
2931
+ this.setCollaborator(collaborator, commandId);
2932
+ yield Promise.all(this.myListenerTypesBeforeBound.map((contextType) => {
2933
+ var _a;
2934
+ const listenerAddedArgs = {
2935
+ action: "addedContextListenerOnPrivateChannel",
2936
+ correlationId: this.id,
2937
+ collaborationObject: {
2938
+ channelId: this.id,
2939
+ contextType: contextType || undefined
2940
+ }
2941
+ };
2942
+ this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
2943
+ return this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
2944
+ })).catch((err) => this.logger.error(err));
2945
+ });
2946
+ }
2947
+ handleCollaboratorBroadcast(context, metadata, commandId) {
2948
+ this.logger.trace(`[${commandId}] - heard context with type ${context.type} broadcasted on the channel`);
2949
+ this.lastBroadcastedContextType = context.type;
2950
+ this.broadcastedContexts[context.type] = { context, metadata };
2951
+ this.logger.trace(`[${commandId}] - invoking all context listeners`);
2952
+ this.registry.execute(PrivateChannelEventMethods.ListenerAdded, context, metadata);
2953
+ }
2954
+ handleCollaboratorAddContextListener(contextType, commandId) {
2955
+ this.logger.trace(`[${commandId}] - heard collaborator added context listener for type ${contextType}`);
2956
+ this.collaboratorListenerTypes.push(contextType);
2957
+ this.registry.execute(PrivateChannelEventMethods.OnAddContextListener, contextType);
2958
+ }
2959
+ handleCollaboratorRemovedListener(contextType, commandId) {
2960
+ this.logger.trace(`[${commandId}] - heard collaborator removed context listener with type ${contextType}`);
2961
+ const index = this.collaboratorListenerTypes.indexOf(contextType);
2962
+ this.collaboratorListenerTypes.splice(index, 1);
2963
+ this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType);
2964
+ }
2965
+ handleCollaboratorDisconnect() {
2966
+ this.disconnected = true;
2967
+ this.collaboratorListenerTypes.forEach((contextType) => this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType));
2968
+ this.registry.execute(PrivateChannelEventMethods.OnDisconnect);
2969
+ }
2970
+ announceJoin(targetInstance, commandId) {
2971
+ return __awaiter(this, void 0, void 0, function* () {
2972
+ const joinChannelArgs = {
2973
+ action: "joinPrivateChannel",
2974
+ correlationId: this.id,
2975
+ collaborationObject: {
2976
+ channelId: this.id
2977
+ }
2978
+ };
2979
+ this.logger.trace(`[${commandId}] - announcing ${"joinPrivateChannel"} to target instance with id ${JSON.stringify(targetInstance)}`);
2980
+ yield this.channelsController.invokeSystemMethod(joinChannelArgs, targetInstance);
2981
+ this.logger.trace(`[${commandId}] - collaborator received ${"joinPrivateChannel"} action`);
2982
+ });
2983
+ }
2984
+ broadcast(context) {
2985
+ var _a;
2986
+ return __awaiter(this, void 0, void 0, function* () {
2987
+ const commandId = generateCommandId();
2988
+ this.ensureAlive(commandId);
2989
+ this.ensureBound(commandId, "broadcast");
2990
+ contextDecoder.runWithException(context);
2991
+ this.lastBroadcastedContextType = context.type;
2992
+ this.broadcastedContexts[context.type] = { context, metadata: this.myAppMetadata };
2993
+ const broadcastArgs = {
2994
+ action: "publishOnPrivateChannel",
2995
+ correlationId: this.id,
2996
+ collaborationObject: {
2997
+ channelId: this.id,
2998
+ contextType: context.type,
2999
+ payload: context
3000
+ }
3001
+ };
3002
+ this.logger.trace(`[${commandId}] - announcing ${"publishOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3003
+ yield this.channelsController.invokeSystemMethod(broadcastArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3004
+ this.logger.trace(`[${commandId}] - collaborator received context for action ${"publishOnPrivateChannel"}`);
3005
+ });
3006
+ }
3007
+ getCurrentContext(contextType) {
3008
+ return __awaiter(this, void 0, void 0, function* () {
3009
+ const commandId = generateCommandId();
3010
+ this.ensureAlive(commandId);
3011
+ this.logger.trace(`[${commandId}] - getCurrentContext invoked ${contextType ? `with contextType ${contextType}` : ""}`);
3012
+ optionalNonEmptyStringDecoder.runWithException(contextType);
3013
+ if (!contextType && !this.lastBroadcastedContextType) {
3014
+ return null;
3015
+ }
3016
+ const searchedType = contextType || this.lastBroadcastedContextType;
3017
+ this.logger.trace(`[${commandId}] - Returning context with type ${searchedType}`);
3018
+ return this.broadcastedContexts[searchedType].context;
3019
+ });
3020
+ }
3021
+ addContextListener(contextType, handler) {
3022
+ var _a;
3023
+ return __awaiter(this, void 0, void 0, function* () {
3024
+ const commandId = generateCommandId();
3025
+ this.ensureAlive(commandId);
3026
+ optionalNonEmptyStringDecoder.runWithException(contextType);
3027
+ if (typeof handler !== "function") {
3028
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
3029
+ }
3030
+ this.logger.trace(`[${commandId}] - adding subscription for broadcasted contexts with type: ${contextType}`);
3031
+ const subHandler = (data, metadata) => {
3032
+ if (contextType) {
3033
+ if (data.type === contextType) {
3034
+ handler(data, metadata);
3035
+ }
3036
+ return;
3037
+ }
3038
+ handler(data, metadata);
3039
+ };
3040
+ const lastBroadcastedContextPerType = this.retrieveLatestBroadcastedContextPerType(contextType);
3041
+ const replayArgs = lastBroadcastedContextPerType ? [[lastBroadcastedContextPerType.context, lastBroadcastedContextPerType.metadata]] : undefined;
3042
+ const unsub = this.registry.add(PrivateChannelEventMethods.ListenerAdded, subHandler, replayArgs);
3043
+ if (this.collaborator) {
3044
+ const listenerAddedArgs = {
3045
+ action: "addedContextListenerOnPrivateChannel",
3046
+ correlationId: this.id,
3047
+ collaborationObject: {
3048
+ channelId: this.id,
3049
+ contextType: contextType || undefined
3050
+ }
3051
+ };
3052
+ this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3053
+ yield this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3054
+ this.logger.trace(`[${commandId}] - collaborator received action ${"addedContextListenerOnPrivateChannel"}`);
3055
+ }
3056
+ else {
3057
+ this.myListenerTypesBeforeBound.push(contextType);
3058
+ }
3059
+ const unsubscribe = this.getAddContextListenerUnsub(unsub, contextType, commandId);
3060
+ return AsyncListener(unsubscribe);
3061
+ });
2964
3062
  }
2965
- add({ action, channelId, handler, replayArgs }) {
2966
- return this.registry.add(`${action}-${channelId}`, handler, replayArgs);
3063
+ retrieveLatestBroadcastedContextPerType(contextType) {
3064
+ if (!contextType && !this.lastBroadcastedContextType) {
3065
+ return;
3066
+ }
3067
+ if (!contextType && this.lastBroadcastedContextType) {
3068
+ return {
3069
+ context: this.broadcastedContexts[this.lastBroadcastedContextType].context,
3070
+ metadata: this.broadcastedContexts[this.lastBroadcastedContextType].metadata
3071
+ };
3072
+ }
3073
+ return this.broadcastedContexts[contextType];
2967
3074
  }
2968
- invoke(action, argumentObj) {
2969
- const { channelId, contextType } = argumentObj;
2970
- this.registry.execute(`${action}-${channelId}`, contextType);
3075
+ getAddContextListenerUnsub(unsub, contextType, commandId) {
3076
+ return () => __awaiter(this, void 0, void 0, function* () {
3077
+ var _a;
3078
+ unsub();
3079
+ if (!this.collaborator) {
3080
+ const index = this.myListenerTypesBeforeBound.indexOf(contextType);
3081
+ this.myListenerTypesBeforeBound.splice(index, 1);
3082
+ return;
3083
+ }
3084
+ const unsubArgs = {
3085
+ action: "removedContextListenerOnPrivateChannel",
3086
+ correlationId: this.id,
3087
+ collaborationObject: {
3088
+ channelId: this.id,
3089
+ contextType: contextType || undefined
3090
+ }
3091
+ };
3092
+ this.logger.trace(`[${commandId}] - announcing unsubscribe from context listener for type ${contextType}`);
3093
+ yield this.channelsController.invokeSystemMethod(unsubArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3094
+ this.logger.trace(`[${commandId}] - collaborator heard ${"removedContextListenerOnPrivateChannel"}`);
3095
+ });
3096
+ }
3097
+ onAddContextListener(handler) {
3098
+ if (typeof handler !== "function") {
3099
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3100
+ }
3101
+ const commandId = generateCommandId();
3102
+ this.ensureAlive(commandId);
3103
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnAddContextListener, handler, this.collaboratorListenerTypes);
3104
+ return AsyncListener(unsub);
3105
+ }
3106
+ onUnsubscribe(handler) {
3107
+ if (typeof handler !== "function") {
3108
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3109
+ }
3110
+ const commandId = generateCommandId();
3111
+ this.ensureAlive(commandId);
3112
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnUnsubscribe, handler);
3113
+ return AsyncListener(unsub);
3114
+ }
3115
+ onDisconnect(handler) {
3116
+ if (typeof handler !== "function") {
3117
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3118
+ }
3119
+ const commandId = generateCommandId();
3120
+ this.ensureAlive(commandId);
3121
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnDisconnect, handler);
3122
+ return AsyncListener(unsub);
3123
+ }
3124
+ disconnect() {
3125
+ var _a;
3126
+ return __awaiter(this, void 0, void 0, function* () {
3127
+ const commandId = generateCommandId();
3128
+ if (this.isCreator && !this.collaborator) {
3129
+ this.disconnected = true;
3130
+ return;
3131
+ }
3132
+ this.ensureAlive(commandId);
3133
+ this.ensureBound(commandId, "disconnect");
3134
+ this.logger.trace(`[${commandId}] - disconnect invoked`);
3135
+ this.disconnected = true;
3136
+ this.logger.trace(`[${commandId}] - announcing ${"disconnectedFromPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3137
+ const disconnectArgs = {
3138
+ action: "disconnectedFromPrivateChannel",
3139
+ correlationId: this.id,
3140
+ collaborationObject: {
3141
+ channelId: this.id
3142
+ }
3143
+ };
3144
+ this.channelsController.removePrivateChannelFromStoreById(this.id);
3145
+ yield this.channelsController.invokeSystemMethod(disconnectArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3146
+ this.logger.trace(`[${commandId}] - collaborator received action ${"disconnectedFromPrivateChannel"}`);
3147
+ if (this.unsubFromInstanceStopped) {
3148
+ this.unsubFromInstanceStopped();
3149
+ }
3150
+ });
3151
+ }
3152
+ ensureAlive(commandId) {
3153
+ if (!this.disconnected) {
3154
+ return;
3155
+ }
3156
+ const errorMsg = "Channel is disconnected - operation is no longer available";
3157
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3158
+ throw { message: ChannelError.AccessDenied, reason: errorMsg };
3159
+ }
3160
+ ensureBound(commandId, operation) {
3161
+ if (this.collaborator) {
3162
+ return;
3163
+ }
3164
+ const errorMsg = `There's no collaborator on the other side of the channel - operation ${operation} is unavailable`;
3165
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3166
+ throw { message: ChannelError.AccessDenied, reason: errorMsg };
3167
+ }
3168
+ subscribeForCollaboratorInstanceStop(commandId) {
3169
+ const handler = (instance) => {
3170
+ var _a;
3171
+ if (instance.id !== ((_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId)) {
3172
+ return;
3173
+ }
3174
+ this.handleCollaboratorDisconnect();
3175
+ };
3176
+ this.unsubFromInstanceStopped = this.channelsController.subscribeOnInstanceStop(this.id, handler.bind(this), commandId);
3177
+ }
3178
+ }
3179
+
3180
+ class ChannelsFactory {
3181
+ constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
3182
+ this.createUserChannelFn = createUserChannelFn;
3183
+ this.createAppChannel = createAppChannel;
3184
+ this.createPrivateChannel = createPrivateChannel;
3185
+ }
3186
+ buildModel(data) {
3187
+ const { type } = data;
3188
+ const lowerType = type === null || type === void 0 ? void 0 : type.toLowerCase();
3189
+ if (lowerType === ChannelTypes.User) {
3190
+ return this.createUserChannelFn(data.displayMetadata.glueChannel);
3191
+ }
3192
+ if (lowerType === ChannelTypes.App) {
3193
+ return this.createAppChannel(data.id);
3194
+ }
3195
+ if (lowerType === ChannelTypes.Private) {
3196
+ return this.createPrivateChannel(data.logger, data.id, data.isCreator);
3197
+ }
3198
+ throw new Error("Pass one of the supported channel types: user, app, private");
2971
3199
  }
2972
3200
  }
2973
3201
 
2974
3202
  class GlueEventsController {
2975
- constructor(glueController, channelsCallbackRegistry) {
3203
+ constructor(glueController, channelsStateStore, appsStateStore) {
2976
3204
  this.glueController = glueController;
2977
- this.channelsCallbackRegistry = channelsCallbackRegistry;
3205
+ this.channelsStateStore = channelsStateStore;
3206
+ this.appsStateStore = appsStateStore;
3207
+ this.actionDictionary = {
3208
+ joinPrivateChannel: this.handleJoin.bind(this),
3209
+ publishOnPrivateChannel: this.handlePublish.bind(this),
3210
+ addedContextListenerOnPrivateChannel: this.handleContextListenerAdded.bind(this),
3211
+ removedContextListenerOnPrivateChannel: this.handleContextListenerRemoved.bind(this),
3212
+ disconnectedFromPrivateChannel: this.handleDisconnect.bind(this),
3213
+ startupContextOpened: this.handleStartupContextOpened.bind(this)
3214
+ };
2978
3215
  }
2979
- initialize() {
3216
+ initializeCollaborateMethod() {
2980
3217
  return __awaiter(this, void 0, void 0, function* () {
2981
- const isMethodRegisteredByThisApp = this.isSysMethodRegisteredByCurrentApp();
2982
- if (isMethodRegisteredByThisApp) {
3218
+ const methodRegisteredByMe = this.checkSystemMethodRegistered();
3219
+ if (methodRegisteredByMe) {
2983
3220
  return;
2984
3221
  }
2985
- yield this.glueController.registerMethod(Glue42FDC3SystemMethod, this.handleSystemMethodInvocation.bind(this));
3222
+ yield this.glueController.registerMethod(ioConnectFDC3SystemMethod, this.handleReceivedAction.bind(this));
2986
3223
  });
2987
3224
  }
2988
- isSysMethodRegisteredByCurrentApp() {
2989
- const methods = this.glueController.getInteropMethods(Glue42FDC3SystemMethod);
2990
- const myId = this.glueController.getMyInteropInstanceId();
3225
+ checkSystemMethodRegistered() {
3226
+ const methods = this.glueController.getInteropMethods(ioConnectFDC3SystemMethod);
3227
+ const myId = this.glueController.getMyInteropInstance().instance;
2991
3228
  const methodsByThisInstance = methods.filter(method => {
2992
3229
  return method.getServers().find(server => server.instance === myId)
2993
3230
  ? method
@@ -2995,29 +3232,111 @@
2995
3232
  });
2996
3233
  return !!methodsByThisInstance.length;
2997
3234
  }
2998
- handleSystemMethodInvocation(argumentObj) {
2999
- const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(argumentObj);
3000
- if (!argsDecodeResult.ok) {
3001
- throw new Error(`Interop Method ${Glue42FDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}.\n Expected ${JSON.stringify({ action: string, payload: { channelId: string, clientId: string } })}`);
3235
+ handleReceivedAction(eventArgs, instance) {
3236
+ return __awaiter(this, void 0, void 0, function* () {
3237
+ const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(eventArgs);
3238
+ if (!argsDecodeResult.ok) {
3239
+ throw new Error(`Interop Method ${ioConnectFDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}`);
3240
+ }
3241
+ const commandId = generateCommandId();
3242
+ this.logger.log(`${commandId} - received system method from instance with id ${instance.instance} for action ${eventArgs.action} with arguments: ${JSON.stringify(eventArgs)}`);
3243
+ const operation = this.actionDictionary[eventArgs.action];
3244
+ if (!operation) {
3245
+ const errorMsg = `Unsupported private channel action: ${eventArgs.action}`;
3246
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3247
+ throw new Error(errorMsg);
3248
+ }
3249
+ yield operation(eventArgs, instance, commandId);
3250
+ });
3251
+ }
3252
+ get logger() {
3253
+ if (!this._logger) {
3254
+ this._logger = this.glueController.initSubLogger("fdc3.private.channels.controller");
3255
+ }
3256
+ return this._logger;
3257
+ }
3258
+ validateAndRetrieveChannel({ action, correlationId }, instance, commandId) {
3259
+ const privateChannel = this.channelsStateStore.getPrivateChannelById(correlationId);
3260
+ if (!privateChannel) {
3261
+ const errorMsg = `There's no private channel with id ${correlationId}`;
3262
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3263
+ throw new Error(errorMsg);
3002
3264
  }
3003
- const { action, payload } = argsDecodeResult.result;
3004
- if (action === PrivateChannelEventMethods.OnDisconnect) {
3005
- return this.handleOnDisconnect(payload);
3265
+ const channelCollaborator = privateChannel.getCollaborator();
3266
+ if (action === "joinPrivateChannel") {
3267
+ return privateChannel;
3006
3268
  }
3007
- if (action === PrivateChannelEventMethods.OnAddContextListener || action === PrivateChannelEventMethods.OnUnsubscribe) {
3008
- return this.channelsCallbackRegistry.invoke(action, payload);
3269
+ if (channelCollaborator && channelCollaborator.instanceId === instance.instance) {
3270
+ this.logger.log(`[${commandId}] - request sent from correct collaborator with id ${instance.instance}. Returning channel`);
3271
+ return privateChannel;
3009
3272
  }
3273
+ const errorMsg = `Cannot proceed with action ${action} - ${channelCollaborator
3274
+ ? `private channel ${correlationId} established communication with collaborator with id ${channelCollaborator}`
3275
+ : `no collaborator joined private channel with id ${correlationId}`}`;
3276
+ this.logger.error(errorMsg);
3277
+ throw new Error(errorMsg);
3278
+ }
3279
+ handleJoin(eventArgs, instance, commandId) {
3280
+ return __awaiter(this, void 0, void 0, function* () {
3281
+ const collaborator = { appId: instance.application || instance.applicationName, instanceId: instance.instance };
3282
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3283
+ yield privateChannel.handleCollaboratorJoin(collaborator, commandId);
3284
+ this.logger.log(`[${commandId}] - collaborator ${JSON.stringify(collaborator)} set for private channel with id ${eventArgs.correlationId}`);
3285
+ });
3286
+ }
3287
+ handlePublish(eventArgs, instance, commandId) {
3288
+ var _a, _b;
3289
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, adding context with type ${(_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType} to the private channel broadcasted contexts`);
3290
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3291
+ const metadata = {
3292
+ source: {
3293
+ appId: instance.application || instance.applicationName || "",
3294
+ instanceId: instance.instance
3295
+ }
3296
+ };
3297
+ privateChannel.handleCollaboratorBroadcast((_b = eventArgs.collaborationObject) === null || _b === void 0 ? void 0 : _b.payload, metadata, commandId);
3298
+ }
3299
+ handleContextListenerAdded(eventArgs, instance, commandId) {
3300
+ var _a;
3301
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onAddContextListener' callbacks`);
3302
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3303
+ privateChannel.handleCollaboratorAddContextListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
3010
3304
  }
3011
- handleOnDisconnect(payload) {
3012
- if (payload.replayContextTypes) {
3013
- this.invokeOnUnsubscribeHandlerMultipleTimes(payload);
3305
+ handleContextListenerRemoved(eventArgs, instance, commandId) {
3306
+ var _a;
3307
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onUnsubscribe' callbacks`);
3308
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3309
+ privateChannel.handleCollaboratorRemovedListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
3310
+ }
3311
+ handleDisconnect(eventArgs, instance, commandId) {
3312
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onDisconnect' callbacks`);
3313
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3314
+ privateChannel.handleCollaboratorDisconnect();
3315
+ }
3316
+ handleStartupContextOpened(eventArgs, instance, commandId) {
3317
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} with correlationId: ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3318
+ const wrappedPromise = this.appsStateStore.getOpenAppPromise(eventArgs.correlationId);
3319
+ if (!wrappedPromise) {
3320
+ this.logger.log(`[${commandId}] - there's no open app promise related to guid ${eventArgs.correlationId}`);
3321
+ return;
3014
3322
  }
3015
- this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnDisconnect, payload);
3323
+ this.logger.log(`[${commandId}] - resolving open app promise related to guid ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3324
+ wrappedPromise.resolve();
3016
3325
  }
3017
- invokeOnUnsubscribeHandlerMultipleTimes(payload) {
3018
- payload.replayContextTypes.forEach(contextType => {
3019
- this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnUnsubscribe, { channelId: payload.channelId, clientId: payload.clientId, contextType });
3020
- });
3326
+ }
3327
+
3328
+ class ApplicationsStateStore {
3329
+ constructor() {
3330
+ this.openAppPromises = {};
3331
+ }
3332
+ addOpenAppPromise(guid, promise) {
3333
+ this.openAppPromises[guid] = promise;
3334
+ }
3335
+ getOpenAppPromise(guid) {
3336
+ return this.openAppPromises[guid];
3337
+ }
3338
+ removeOpenAppPromise(guid) {
3339
+ delete this.openAppPromises[guid];
3021
3340
  }
3022
3341
  }
3023
3342
 
@@ -3027,7 +3346,7 @@
3027
3346
  }
3028
3347
  get eventReceiver() {
3029
3348
  if (!this._eventReceiver) {
3030
- this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher, this.eventsController);
3349
+ this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher);
3031
3350
  }
3032
3351
  return this._eventReceiver;
3033
3352
  }
@@ -3061,8 +3380,8 @@
3061
3380
  createAppChannel(id) {
3062
3381
  return new AppChannel(this.channelsController, id).toApi();
3063
3382
  }
3064
- createPrivateChannel(channelId) {
3065
- return new PrivateChannel(this.channelsController, channelId).toApi();
3383
+ createPrivateChannel(logger, channelId, isCreator) {
3384
+ return new PrivateChannel(this.channelsController, logger, channelId, isCreator);
3066
3385
  }
3067
3386
  get desktopAgent() {
3068
3387
  if (!this._desktopAgent) {
@@ -3078,19 +3397,19 @@
3078
3397
  }
3079
3398
  get intentsController() {
3080
3399
  if (!this._intentsController) {
3081
- this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory);
3400
+ this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory, this.eventsController);
3082
3401
  }
3083
3402
  return this._intentsController;
3084
3403
  }
3085
3404
  get applicationController() {
3086
3405
  if (!this._applicationController) {
3087
- this._applicationController = new ApplicationsController(this.glueController);
3406
+ this._applicationController = new ApplicationsController(this.glueController, this.applicationsStateStore, this.eventsController);
3088
3407
  }
3089
3408
  return this._applicationController;
3090
3409
  }
3091
3410
  get channelsController() {
3092
3411
  if (!this._channelsController) {
3093
- this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.channelsCallbackRegistry);
3412
+ this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.eventsController);
3094
3413
  }
3095
3414
  return this._channelsController;
3096
3415
  }
@@ -3100,18 +3419,18 @@
3100
3419
  }
3101
3420
  return this._channelsStateStore;
3102
3421
  }
3103
- get channelsCallbackRegistry() {
3104
- if (!this._channelsCallbackRegistry) {
3105
- this._channelsCallbackRegistry = new ChannelsCallbackRegistry();
3106
- }
3107
- return this._channelsCallbackRegistry;
3108
- }
3109
3422
  get eventsController() {
3110
3423
  if (!this._eventsController) {
3111
- this._eventsController = new GlueEventsController(this.glueController, this.channelsCallbackRegistry);
3424
+ this._eventsController = new GlueEventsController(this.glueController, this.channelsStateStore, this.applicationsStateStore);
3112
3425
  }
3113
3426
  return this._eventsController;
3114
3427
  }
3428
+ get applicationsStateStore() {
3429
+ if (!this._applicationsStateStore) {
3430
+ this._applicationsStateStore = new ApplicationsStateStore();
3431
+ }
3432
+ return this._applicationsStateStore;
3433
+ }
3115
3434
  }
3116
3435
 
3117
3436
  const fdc3Factory = () => {