@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.
package/dist/fdc3.es.js CHANGED
@@ -107,17 +107,95 @@ const fdc3ChannelNames = ["fdc3.channel.1", "fdc3.channel.4", "fdc3.channel.6",
107
107
  const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
108
108
  const defaultContextProps = ["type"];
109
109
  const defaultGlue42APIs = ["contexts", "channels", "interop", "intents", "appManager", "windows"];
110
- const responseInteropMethodPrefix = "T42.FDC3.Open.Listener.Response";
111
110
  const glueChannelNamePrefix = "___channel___";
112
111
  const fdc3NothingContextType = "fdc3.nothing";
113
112
  const Glue42EnterpriseNoAppWindow = "no-app-window";
114
113
  const RaiseTimeoutMs = 75 * 1000;
115
- const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
114
+ const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
115
+ const Fdc3SupportedIntentTypes = {
116
+ "CreateInteraction": [
117
+ "fdc3.contactList",
118
+ "fdc3.interaction"
119
+ ],
120
+ "StartCall": [
121
+ "fdc3.contact",
122
+ "fdc3.contactList"
123
+ ],
124
+ "StartChat": [
125
+ "fdc3.contact",
126
+ "fdc3.contactList",
127
+ "fdc3.chat.initSettings"
128
+ ],
129
+ "StartEmail": [
130
+ "fdc3.email"
131
+ ],
132
+ "SendChatMessage": [
133
+ "fdc3.chat.message"
134
+ ],
135
+ "ViewAnalysis": [
136
+ "fdc3.instrument",
137
+ "fdc3.organization",
138
+ "fdc3.portfolio"
139
+ ],
140
+ "ViewChat": [
141
+ "fdc3.chat.room",
142
+ "fdc3.contact",
143
+ "fdc3.contactList"
144
+ ],
145
+ "ViewChart": [
146
+ "fdc3.chart",
147
+ "fdc3.instrument",
148
+ "fdc3.instrumentList",
149
+ "fdc3.portfolio",
150
+ "fdc3.position"
151
+ ],
152
+ "ViewHoldings": [
153
+ "fdc3.instrument",
154
+ "fdc3.instrumentList",
155
+ "fdc3.organization"
156
+ ],
157
+ "ViewInstrument": [
158
+ "fdc3.instrument"
159
+ ],
160
+ "ViewInteractions": [
161
+ "fdc3.contact",
162
+ "fdc3.instrument",
163
+ "fdc3.organization"
164
+ ],
165
+ "ViewMessages": [
166
+ "fdc3.chat.searchCriteria"
167
+ ],
168
+ "ViewNews": [
169
+ "fdc3.country",
170
+ "fdc3.instrument",
171
+ "fdc3.instrumentList",
172
+ "fdc3.organization",
173
+ "fdc3.portfolio"
174
+ ],
175
+ "ViewOrders": [
176
+ "fdc3.contact",
177
+ "fdc3.instrument",
178
+ "fdc3.organization"
179
+ ],
180
+ "ViewProfile": [
181
+ "fdc3.contact",
182
+ "fdc3.organization"
183
+ ],
184
+ "ViewQuote": [
185
+ "fdc3.instrument"
186
+ ],
187
+ "ViewResearch": [
188
+ "fdc3.contact",
189
+ "fdc3.instrument",
190
+ "fdc3.organization"
191
+ ]
192
+ };
116
193
 
117
- const Glue42FDC3SystemMethod = "T42.FDC3.Client.Control";
194
+ const ioConnectFDC3SystemMethod = "FDC3.Collaborate";
118
195
  const PrivateChannelPrefix = "___privateFDC3Channel___";
119
196
  var PrivateChannelEventMethods;
120
197
  (function (PrivateChannelEventMethods) {
198
+ PrivateChannelEventMethods["ListenerAdded"] = "listenerAdded";
121
199
  PrivateChannelEventMethods["OnAddContextListener"] = "onAddContextListener";
122
200
  PrivateChannelEventMethods["OnUnsubscribe"] = "onUnsubscribe";
123
201
  PrivateChannelEventMethods["OnDisconnect"] = "onDisconnect";
@@ -870,7 +948,7 @@ var string = Decoder.string;
870
948
  /** See `Decoder.number` */
871
949
  var number = Decoder.number;
872
950
  /** See `Decoder.boolean` */
873
- var boolean = Decoder.boolean;
951
+ Decoder.boolean;
874
952
  /** See `Decoder.anyJson` */
875
953
  var anyJson = Decoder.anyJson;
876
954
  /** See `Decoder.unknownJson` */
@@ -942,31 +1020,35 @@ const optionalContextDecoder = optional(contextDecoder);
942
1020
  const optionalTargetApp = optional(appIdentifierDecoder);
943
1021
  const optionalAppIdentifier = optional(targetAppDecoder);
944
1022
  const optionalNonEmptyStringDecoder = optional(nonEmptyStringDecoder);
945
- const SystemMethodActionDecider = oneOf(constant(PrivateChannelEventMethods.OnAddContextListener), constant(PrivateChannelEventMethods.OnUnsubscribe), constant(PrivateChannelEventMethods.OnDisconnect));
946
- const SystemMethodEventPayloadDecoder = object({
947
- channelId: nonEmptyStringDecoder,
948
- clientId: nonEmptyStringDecoder,
949
- contextType: optional(string()),
950
- replayContextTypes: optional(array(string()))
1023
+ const SystemMethodActionDecoder = oneOf(constant("joinPrivateChannel"), constant("publishOnPrivateChannel"), constant("addedContextListenerOnPrivateChannel"), constant("removedContextListenerOnPrivateChannel"), constant("disconnectedFromPrivateChannel"), constant("startupContextOpened"));
1024
+ const CollaborationObjectDecoder = object({
1025
+ channelId: optional(nonEmptyStringDecoder),
1026
+ contextType: optional(nonEmptyStringDecoder),
1027
+ payload: optional(contextDecoder)
951
1028
  });
952
1029
  const SystemMethodInvocationArgumentDecoder = object({
953
- action: SystemMethodActionDecider,
954
- payload: SystemMethodEventPayloadDecoder
955
- });
956
- const ContextListenerResponseDecoder = object({
957
- listenerInvoked: optional(boolean())
1030
+ action: SystemMethodActionDecoder,
1031
+ correlationId: nonEmptyStringDecoder,
1032
+ collaborationObject: optional(CollaborationObjectDecoder)
958
1033
  });
959
- object({
960
- meta: object({
961
- responseMethodName: nonEmptyStringDecoder
962
- }),
963
- context: contextDecoder
1034
+ const FDC3StartupContextDecoder = object({
1035
+ fdc3: object({
1036
+ collaborationId: nonEmptyStringDecoder,
1037
+ openApp: object({
1038
+ appId: nonEmptyStringDecoder,
1039
+ instanceId: nonEmptyStringDecoder
1040
+ }),
1041
+ context: object({
1042
+ contextType: optional(string()),
1043
+ payload: contextDecoder
1044
+ })
1045
+ })
964
1046
  });
965
1047
 
966
1048
  class GlueController {
967
1049
  constructor(channelsParser) {
968
1050
  this.channelsParser = channelsParser;
969
- this.defaultGluePromiseTimeout = 120000;
1051
+ this.defaultGluePromiseTimeout = 120 * 1000;
970
1052
  }
971
1053
  get gluePromise() {
972
1054
  return this.glueInitPromise.then(this.initializeLogger.bind(this));
@@ -1022,6 +1104,15 @@ class GlueController {
1022
1104
  return this.glue.intents.raise(request);
1023
1105
  });
1024
1106
  }
1107
+ getMyWindowContext() {
1108
+ return __awaiter(this, void 0, void 0, function* () {
1109
+ const myWin = this.getMyWindow();
1110
+ if (!myWin) {
1111
+ return;
1112
+ }
1113
+ return myWin.getContext();
1114
+ });
1115
+ }
1025
1116
  addIntentListener(intent, handler) {
1026
1117
  const registerMethodExists = this.glue.intents.register;
1027
1118
  return registerMethodExists
@@ -1043,20 +1134,15 @@ class GlueController {
1043
1134
  }
1044
1135
  updateContextWithLatestFdc3Type(contextId, context) {
1045
1136
  return __awaiter(this, void 0, void 0, function* () {
1046
- const prevContextData = yield this.getContext(contextId);
1047
- if (!isValidNonEmptyObject(prevContextData)) {
1048
- return this.updateContext(contextId, {
1049
- data: this.channelsParser.parseFDC3ContextToGlueContexts(context),
1050
- latest_fdc3_type: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type)
1051
- });
1052
- }
1053
- 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) }));
1137
+ const { path, value } = this.channelsParser.parseFDC3ContextToGlueContexts(context);
1138
+ const latestTypePathValue = { path: "latest_fdc3_type", value: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type) };
1139
+ yield this.contextsSetPaths(contextId, [{ path: `data.${path}`, value: value }, latestTypePathValue]);
1054
1140
  });
1055
1141
  }
1056
1142
  channelsUpdate(channelId, context) {
1057
1143
  return __awaiter(this, void 0, void 0, function* () {
1058
- const parsedData = this.channelsParser.parseFDC3ContextToGlueContexts(context);
1059
- return this.glue.channels.publish(parsedData, channelId);
1144
+ const { path, value } = this.channelsParser.parseFDC3ContextToGlueContexts(context);
1145
+ return this.glue.channels.publish({ [path]: value }, channelId);
1060
1146
  });
1061
1147
  }
1062
1148
  joinChannel(channelId) {
@@ -1094,8 +1180,8 @@ class GlueController {
1094
1180
  const win = this.glue.windows.my();
1095
1181
  return isValidNonEmptyObject(win) ? win : undefined;
1096
1182
  }
1097
- getMyInteropInstanceId() {
1098
- return this.glue.interop.instance.instance;
1183
+ getMyInteropInstance() {
1184
+ return this.glue.interop.instance;
1099
1185
  }
1100
1186
  getGlueVersion() {
1101
1187
  var _a;
@@ -1104,21 +1190,14 @@ class GlueController {
1104
1190
  registerOnInstanceStopped(cb) {
1105
1191
  return this.glue.appManager.onInstanceStopped(cb);
1106
1192
  }
1107
- invokeMethod(methodName, instance, argumentObj) {
1108
- return __awaiter(this, void 0, void 0, function* () {
1109
- const args = ContextListenerResponseDecoder.runWithException(argumentObj);
1110
- return this.glue.interop.invoke(methodName, args, { instance });
1111
- });
1112
- }
1113
1193
  unregisterMethod(methodName) {
1114
1194
  return __awaiter(this, void 0, void 0, function* () {
1115
1195
  return this.glue.interop.unregister(methodName);
1116
1196
  });
1117
1197
  }
1118
- invokeSystemMethod(argumentObj) {
1119
- const args = SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1120
- const target = args.payload.clientId;
1121
- return this.glue.interop.invoke(Glue42FDC3SystemMethod, args, { instance: target });
1198
+ invokeSystemMethod(argumentObj, target) {
1199
+ SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1200
+ return this.glue.interop.invoke(ioConnectFDC3SystemMethod, argumentObj, { instance: target });
1122
1201
  }
1123
1202
  registerMethod(name, handler) {
1124
1203
  return this.glue.interop.register(name, handler);
@@ -1126,22 +1205,17 @@ class GlueController {
1126
1205
  getInteropMethods(filter) {
1127
1206
  return this.glue.interop.methods(filter);
1128
1207
  }
1129
- channelsSubscribe(callback) {
1208
+ channelsSubscribe(callback, contextType) {
1130
1209
  const didReplay = { replayed: false };
1131
- return this.glue.channels.subscribe((_, context, updaterId) => __awaiter(this, void 0, void 0, function* () {
1132
- if (this.isUpdateFromMe(updaterId) || !context) {
1133
- return;
1134
- }
1135
- const contextData = yield this.glue.contexts.get(`${glueChannelNamePrefix}${context.name}`);
1136
- if (!contextData.latest_fdc3_type) {
1210
+ return this.glue.channels.subscribe((_, contextData, updaterId) => __awaiter(this, void 0, void 0, function* () {
1211
+ if (this.isUpdateFromMe(updaterId) || !contextData || !contextData.latest_fdc3_type) {
1137
1212
  return;
1138
1213
  }
1139
- if (!didReplay.replayed) {
1140
- this.invokePreviouslyBroadcastedData(callback, contextData, this.getContextMetadata(updaterId));
1141
- didReplay.replayed = true;
1142
- return;
1214
+ if (didReplay.replayed) {
1215
+ return this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1143
1216
  }
1144
- this.parseDataAndInvokeSubscribeCallback(callback, contextData, this.getContextMetadata(updaterId));
1217
+ this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1218
+ didReplay.replayed = true;
1145
1219
  }));
1146
1220
  }
1147
1221
  contextsSubscribe(contextName, callback) {
@@ -1153,7 +1227,7 @@ class GlueController {
1153
1227
  if (!this.checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData)) {
1154
1228
  return;
1155
1229
  }
1156
- this.parseDataAndInvokeSubscribeCallback(callback, contextData, this.getContextMetadata(extraData === null || extraData === void 0 ? void 0 : extraData.updaterId));
1230
+ this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(extraData === null || extraData === void 0 ? void 0 : extraData.updaterId) });
1157
1231
  });
1158
1232
  }
1159
1233
  getInteropServers(methodFilter) {
@@ -1162,14 +1236,12 @@ class GlueController {
1162
1236
  initSubLogger(name) {
1163
1237
  return this.logger.subLogger(name);
1164
1238
  }
1165
- invokePreviouslyBroadcastedData(callback, contextData, metadata) {
1166
- Object.entries(contextData.data).forEach(([key, value]) => {
1167
- if (!this.channelsParser.isFdc3DataKey(key)) {
1168
- return;
1169
- }
1170
- const parsedData = Object.assign({ type: this.channelsParser.revertGlueParsedTypeToInitialFDC3Type(key) }, value);
1171
- callback(parsedData, metadata);
1172
- });
1239
+ invokePreviouslyBroadcastedData({ callback, contextData, metadata, contextType }) {
1240
+ const invokeForType = contextType || this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
1241
+ const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, invokeForType);
1242
+ if (dataForContextType) {
1243
+ callback(dataForContextType, metadata);
1244
+ }
1173
1245
  }
1174
1246
  isUpdateFromMe(updaterId) {
1175
1247
  return this.glue.interop.instance.peerId === updaterId;
@@ -1189,9 +1261,34 @@ class GlueController {
1189
1261
  initializeLogger() {
1190
1262
  this._logger = this.glue.logger;
1191
1263
  }
1192
- parseDataAndInvokeSubscribeCallback(callback, data, metadata) {
1193
- const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data(data);
1194
- callback(parsedData, metadata);
1264
+ parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata, contextType }) {
1265
+ if (!contextType) {
1266
+ const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data({ data: contextData.data, latest_fdc3_type: contextData.latest_fdc3_type });
1267
+ callback(parsedData, metadata);
1268
+ return;
1269
+ }
1270
+ const latestPublishedType = this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
1271
+ if (latestPublishedType !== contextType) {
1272
+ return;
1273
+ }
1274
+ const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, contextType);
1275
+ if (dataForContextType) {
1276
+ callback(dataForContextType, metadata);
1277
+ }
1278
+ }
1279
+ getLatestBroadcastedDataByContextType(contextData, contextType) {
1280
+ let foundData;
1281
+ Object.entries(contextData.data).find(([key, value]) => {
1282
+ if (!this.channelsParser.isFdc3DataKey(key)) {
1283
+ return;
1284
+ }
1285
+ const parsedType = this.channelsParser.revertGlueParsedTypeToInitialFDC3Type(key);
1286
+ if (parsedType !== contextType) {
1287
+ return;
1288
+ }
1289
+ foundData = Object.assign({ type: parsedType }, value);
1290
+ });
1291
+ return foundData;
1195
1292
  }
1196
1293
  checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData) {
1197
1294
  if (!didReplay.replayed) {
@@ -1203,6 +1300,11 @@ class GlueController {
1203
1300
  }
1204
1301
  return true;
1205
1302
  }
1303
+ contextsSetPaths(name, paths) {
1304
+ return __awaiter(this, void 0, void 0, function* () {
1305
+ yield this.glue.contexts.setPaths(name, paths);
1306
+ });
1307
+ }
1206
1308
  }
1207
1309
 
1208
1310
  const GLUE42_EVENT_NAME = "Glue42";
@@ -1238,6 +1340,7 @@ class DesktopAgent {
1238
1340
  }
1239
1341
  toApi() {
1240
1342
  const api = {
1343
+ getStartupContext: this.getStartupContext.bind(this),
1241
1344
  addContextListener: this.addContextListener.bind(this),
1242
1345
  addIntentListener: this.addIntentListener.bind(this),
1243
1346
  broadcast: this.broadcast.bind(this),
@@ -1350,6 +1453,11 @@ class DesktopAgent {
1350
1453
  return this.intentsController.addIntentListener({ commandId: generateCommandId(), intent, handler });
1351
1454
  });
1352
1455
  }
1456
+ getStartupContext() {
1457
+ return __awaiter(this, void 0, void 0, function* () {
1458
+ return this.channelsController.getStartupContext();
1459
+ });
1460
+ }
1353
1461
  getOrCreateChannel(channelId) {
1354
1462
  return __awaiter(this, void 0, void 0, function* () {
1355
1463
  nonEmptyStringDecoder.runWithException(channelId);
@@ -1455,7 +1563,7 @@ class ChannelsParser {
1455
1563
  parseFDC3ContextToGlueContexts(context) {
1456
1564
  const { type } = context, rest = __rest$1(context, ["type"]);
1457
1565
  const parsedType = this.mapFDC3TypeToChannelsDelimiter(type);
1458
- return { [`${this.channelsFdc3DataPrefix}${parsedType}`]: rest };
1566
+ return { path: `${this.channelsFdc3DataPrefix}${parsedType}`, value: rest };
1459
1567
  }
1460
1568
  mapFDC3TypeToChannelsDelimiter(type) {
1461
1569
  return type.split(".").join(this.fdc3Delimiter);
@@ -1472,76 +1580,60 @@ class ChannelsParser {
1472
1580
  * SPDX-License-Identifier: Apache-2.0
1473
1581
  * Copyright FINOS FDC3 contributors - see NOTICE file
1474
1582
  */
1475
-
1476
1583
  /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
1477
1584
  var OpenError;
1478
-
1479
1585
  (function (OpenError) {
1480
1586
  /** Returned if the specified application is not found.*/
1481
1587
  OpenError["AppNotFound"] = "AppNotFound";
1482
1588
  /** Returned if the specified application fails to launch correctly.*/
1483
-
1484
1589
  OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
1485
1590
  /** 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.*/
1486
-
1487
1591
  OpenError["AppTimeout"] = "AppTimeout";
1488
1592
  /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1489
-
1490
1593
  OpenError["ResolverUnavailable"] = "ResolverUnavailable";
1594
+ /** 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.*/
1595
+ OpenError["MalformedContext"] = "MalformedContext";
1491
1596
  })(OpenError || (OpenError = {}));
1492
1597
  /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
1493
-
1494
-
1495
1598
  var ResolveError;
1496
-
1497
1599
  (function (ResolveError) {
1498
1600
  /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
1499
1601
  ResolveError["NoAppsFound"] = "NoAppsFound";
1500
1602
  /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1501
-
1502
1603
  ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
1503
1604
  /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
1504
-
1505
1605
  ResolveError["UserCancelled"] = "UserCancelledResolution";
1506
1606
  /** 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.*/
1507
-
1508
1607
  ResolveError["ResolverTimeout"] = "ResolverTimeout";
1509
1608
  /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
1510
-
1511
1609
  ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
1512
1610
  /** Returned if a specified target application instance is not available, for example because it has been closed. */
1513
-
1514
1611
  ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
1515
1612
  /** 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.*/
1516
-
1517
1613
  ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
1614
+ /** 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.*/
1615
+ ResolveError["MalformedContext"] = "MalformedContext";
1518
1616
  })(ResolveError || (ResolveError = {}));
1519
-
1520
1617
  var ResultError;
1521
-
1522
1618
  (function (ResultError) {
1523
- /** Returned if the intent handler exited without returning a Promise or that Promise was not resolved with a Context or Channel object. */
1619
+ /** Returned if the intent handler exited without returning a valid result (a promise resolving to a Context, Channel object or void). */
1524
1620
  ResultError["NoResultReturned"] = "NoResultReturned";
1525
1621
  /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
1526
-
1527
1622
  ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
1528
1623
  })(ResultError || (ResultError = {}));
1529
-
1530
1624
  var ChannelError;
1531
-
1532
1625
  (function (ChannelError) {
1533
1626
  /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
1534
1627
  ChannelError["NoChannelFound"] = "NoChannelFound";
1535
1628
  /** 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. */
1536
-
1537
1629
  ChannelError["AccessDenied"] = "AccessDenied";
1538
1630
  /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
1539
-
1540
1631
  ChannelError["CreationFailed"] = "CreationFailed";
1632
+ /** 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.*/
1633
+ ChannelError["MalformedContext"] = "MalformedContext";
1541
1634
  })(ChannelError || (ChannelError = {}));
1542
1635
 
1543
1636
  var ContextTypes;
1544
-
1545
1637
  (function (ContextTypes) {
1546
1638
  ContextTypes["Chart"] = "fdc3.chart";
1547
1639
  ContextTypes["ChatInitSettings"] = "fdc3.chat.initSettings";
@@ -1562,13 +1654,13 @@ var ContextTypes;
1562
1654
 
1563
1655
  // To parse this data:
1564
1656
  //
1565
- // import { Convert, Context, Chart, ChatInitSettings, Contact, ContactList, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1657
+ // import { Convert, Chart, ChatInitSettings, Contact, ContactList, Context, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1566
1658
  //
1567
- // const context = Convert.toContext(json);
1568
1659
  // const chart = Convert.toChart(json);
1569
1660
  // const chatInitSettings = Convert.toChatInitSettings(json);
1570
1661
  // const contact = Convert.toContact(json);
1571
1662
  // const contactList = Convert.toContactList(json);
1663
+ // const context = Convert.toContext(json);
1572
1664
  // const country = Convert.toCountry(json);
1573
1665
  // const currency = Convert.toCurrency(json);
1574
1666
  // const email = Convert.toEmail(json);
@@ -1584,7 +1676,6 @@ var ContextTypes;
1584
1676
  // These functions will throw an error if the JSON doesn't
1585
1677
  // match the expected interface, even if the JSON is valid.
1586
1678
  var Style;
1587
-
1588
1679
  (function (Style) {
1589
1680
  Style["Bar"] = "bar";
1590
1681
  Style["Candle"] = "candle";
@@ -1596,10 +1687,9 @@ var Style;
1596
1687
  Style["Pie"] = "pie";
1597
1688
  Style["Scatter"] = "scatter";
1598
1689
  Style["StackedBar"] = "stacked-bar";
1599
- })(Style || (Style = {})); // Converts JSON strings to/from your types
1690
+ })(Style || (Style = {}));
1600
1691
 
1601
1692
  var Intents;
1602
-
1603
1693
  (function (Intents) {
1604
1694
  Intents["StartCall"] = "StartCall";
1605
1695
  Intents["StartChat"] = "StartChat";
@@ -1675,15 +1765,11 @@ const isChannel = (data) => {
1675
1765
  const isContext = (data) => {
1676
1766
  return defaultContextProps.every(prop => Object.keys(data).includes(prop));
1677
1767
  };
1678
- const isChannelMetadata = (data) => {
1679
- return typeof data === "object" && data.isChannel;
1680
- };
1681
1768
  const extractChannelMetadata = (channel) => {
1682
1769
  return {
1683
1770
  id: channel.id,
1684
1771
  type: channel.type,
1685
- displayMetadata: channel.displayMetadata,
1686
- isChannel: true
1772
+ displayMetadata: channel.displayMetadata
1687
1773
  };
1688
1774
  };
1689
1775
  const parseContextHandler = (handler, contextType) => {
@@ -1700,10 +1786,11 @@ const parseContextHandler = (handler, contextType) => {
1700
1786
  };
1701
1787
 
1702
1788
  class IntentsController {
1703
- constructor(glueController, channelsController, channelsFactory) {
1789
+ constructor(glueController, channelsController, channelsFactory, glueEventsController) {
1704
1790
  this.glueController = glueController;
1705
1791
  this.channelsController = channelsController;
1706
1792
  this.channelsFactory = channelsFactory;
1793
+ this.glueEventsController = glueEventsController;
1707
1794
  }
1708
1795
  get logger() {
1709
1796
  if (!this._logger) {
@@ -1795,11 +1882,33 @@ class IntentsController {
1795
1882
  });
1796
1883
  }
1797
1884
  addIntentListener({ commandId, intent, handler }) {
1885
+ var _a, _b;
1798
1886
  return __awaiter(this, void 0, void 0, function* () {
1799
1887
  yield this.glueController.gluePromise;
1800
1888
  this.logger.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
1801
1889
  const wrappedHandler = this.getWrappedIntentHandler(handler);
1802
- return this.glueController.addIntentListener(intent, wrappedHandler);
1890
+ const myInstance = this.glueController.getMyInteropInstance();
1891
+ const myApplication = this.glueController.getApplication(myInstance.applicationName);
1892
+ let appConfigIntentDef;
1893
+ const globalBrowserNamespace = window.glue42core || window.iobrowser;
1894
+ const globalDesktopNamespace = window.glue42gd || window.iodesktop;
1895
+ if (globalBrowserNamespace) {
1896
+ appConfigIntentDef = (_a = myApplication === null || myApplication === void 0 ? void 0 : myApplication.userProperties.intents) === null || _a === void 0 ? void 0 : _a.find((appIntent) => appIntent.name === intent);
1897
+ }
1898
+ if (globalDesktopNamespace) {
1899
+ const appConfig = yield myApplication.getConfiguration();
1900
+ appConfigIntentDef = (_b = appConfig === null || appConfig === void 0 ? void 0 : appConfig.intents) === null || _b === void 0 ? void 0 : _b.find((appIntent) => appIntent.name === intent);
1901
+ }
1902
+ const intentRequest = {
1903
+ intent,
1904
+ displayName: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.displayName,
1905
+ description: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.description,
1906
+ contextTypes: (appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.contexts) || Fdc3SupportedIntentTypes[intent],
1907
+ resultType: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.resultType
1908
+ };
1909
+ Object.keys(intentRequest)
1910
+ .forEach((key) => intentRequest[key] === undefined && delete intentRequest[key]);
1911
+ return this.glueController.addIntentListener(intentRequest, wrappedHandler);
1803
1912
  });
1804
1913
  }
1805
1914
  filterGlueIntentHandlers({ commandId, intent, context, target }) {
@@ -1819,7 +1928,7 @@ class IntentsController {
1819
1928
  this.logger.info(`[${commandId}] - Checking if application with name ${appName} exists`);
1820
1929
  const app = this.glueController.getApplication(appName);
1821
1930
  const serverInstances = this.serverInstanceAsIntentHandler(intent.name);
1822
- if (!app && (typeof target === "string" || !serverInstances.length)) {
1931
+ if (!app && (typeof target === "string" || !target.instanceId || !serverInstances.length)) {
1823
1932
  throw { message: ResolveError.TargetAppUnavailable, reason: `There's no app with appId ${appName}` };
1824
1933
  }
1825
1934
  this.logger.info(`[${commandId}] - target app ${appName} found. Filtering handlers by applicationName: ${appName}`);
@@ -1865,23 +1974,33 @@ class IntentsController {
1865
1974
  if (!isValidNonEmptyObject(result)) {
1866
1975
  return;
1867
1976
  }
1868
- const isResultChannelMetadata = isChannelMetadata(result);
1869
- if (!isResultChannelMetadata) {
1977
+ if (!result.fdc3intentChannel && !result.fdc3intentContext) {
1870
1978
  return result;
1871
1979
  }
1872
- const { clientId, creatorId } = yield this.glueController.getContext(result.id);
1873
- this.logger.info(`[${commandId}] - result is a private channel with creatorId ${creatorId} and clientId ${clientId}`);
1874
- const myInteropInstanceId = this.glueController.getMyInteropInstanceId();
1875
- if ((creatorId && creatorId !== myInteropInstanceId) && (clientId && clientId !== myInteropInstanceId)) {
1876
- throw { message: ResultError.NoResultReturned, reason: "There are already two parties on this private channel" };
1877
- }
1878
- const channel = this.channelsFactory.buildModel(result);
1879
- if (myInteropInstanceId && myInteropInstanceId !== creatorId) {
1880
- this.logger.info(`[${commandId}] - the current user is the second party of the private channel. Adding my id ${myInteropInstanceId} as a clientId`);
1881
- yield this.channelsController.addClientToPrivateChannel(commandId, channel.id, myInteropInstanceId);
1882
- }
1980
+ if (result.fdc3intentContext) {
1981
+ return result.fdc3intentContext;
1982
+ }
1983
+ const { fdc3intentChannel } = result;
1984
+ if (fdc3intentChannel.type === "user") {
1985
+ const glueChannel = (yield this.glueController.listAllChannels()).find(ch => ch.name === fdc3intentChannel.displayMetadata.name);
1986
+ return this.channelsFactory.buildModel(Object.assign(Object.assign({}, fdc3intentChannel), { displayMetadata: Object.assign(Object.assign({}, fdc3intentChannel.displayMetadata), { glueChannel }) }));
1987
+ }
1988
+ if (fdc3intentChannel.type !== "private") {
1989
+ return this.channelsFactory.buildModel(fdc3intentChannel);
1990
+ }
1991
+ yield this.glueEventsController.initializeCollaborateMethod();
1992
+ const channel = this.channelsController.buildPrivateChannel(fdc3intentChannel.id, commandId, false);
1993
+ channel.setCollaborator({ appId: glueIntentResult.handler.applicationName, instanceId: glueIntentResult.handler.instanceId }, commandId);
1994
+ const joinChannelArgs = {
1995
+ action: "joinPrivateChannel",
1996
+ correlationId: channel.id,
1997
+ collaborationObject: {
1998
+ channelId: channel.id
1999
+ }
2000
+ };
2001
+ yield this.glueController.invokeSystemMethod(joinChannelArgs, glueIntentResult.handler.instanceId);
1883
2002
  this.logger.info(`[${commandId}] - returning private channel`);
1884
- return channel;
2003
+ return channel.toApi();
1885
2004
  });
1886
2005
  }
1887
2006
  convertGlue42IntentToFDC3Intent(glueIntent) {
@@ -1916,15 +2035,23 @@ class IntentsController {
1916
2035
  throw new Error("Async handler function should return a promise that resolves to a Context or Channel");
1917
2036
  }
1918
2037
  getWrappedIntentHandler(handler) {
1919
- const wrappedHandler = (glue42Context) => __awaiter(this, void 0, void 0, function* () {
1920
- const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }));
2038
+ const wrappedHandler = (glue42Context, caller) => __awaiter(this, void 0, void 0, function* () {
2039
+ const contextMetadata = caller
2040
+ ? {
2041
+ source: {
2042
+ appId: caller.application || caller.applicationName || "",
2043
+ instanceId: caller.instance
2044
+ }
2045
+ }
2046
+ : undefined;
2047
+ const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }), contextMetadata);
1921
2048
  if (!handlerResult) {
1922
2049
  return;
1923
2050
  }
1924
2051
  const handlerResultType = this.getResultType(handlerResult);
1925
2052
  return handlerResultType === IntentHandlerResultTypes.Channel
1926
- ? extractChannelMetadata(handlerResult)
1927
- : handlerResult;
2053
+ ? { fdc3intentChannel: extractChannelMetadata(handlerResult) }
2054
+ : { fdc3intentContext: handlerResult };
1928
2055
  });
1929
2056
  return wrappedHandler;
1930
2057
  }
@@ -1971,13 +2098,14 @@ class IntentsController {
1971
2098
  }
1972
2099
  }
1973
2100
 
1974
- var version = "2.1.0";
2101
+ var version = "2.1.2";
1975
2102
 
1976
2103
  class ApplicationsController {
1977
- constructor(glueController) {
2104
+ constructor(glueController, appsStateStore, glueEventsController) {
1978
2105
  this.glueController = glueController;
1979
- this.defaultContextListenerInvokedPromiseTimeout = 60000;
1980
- this.contextListenerInvokedPromises = {};
2106
+ this.appsStateStore = appsStateStore;
2107
+ this.glueEventsController = glueEventsController;
2108
+ this.defaultContextListenerInvokedPromiseTimeout = 120 * 1000;
1981
2109
  }
1982
2110
  get logger() {
1983
2111
  if (!this._logger) {
@@ -1995,6 +2123,7 @@ class ApplicationsController {
1995
2123
  throw { message: OpenError.AppNotFound, reason: `Cannot find targeted ${name} application` };
1996
2124
  }
1997
2125
  if (context) {
2126
+ yield this.glueEventsController.initializeCollaborateMethod();
1998
2127
  this.logger.info(`[${commandId}] - opening app ${app} with startup context`);
1999
2128
  return this.openAppWithContext(app, context);
2000
2129
  }
@@ -2049,7 +2178,7 @@ class ApplicationsController {
2049
2178
  this.logger.info(`${commandId} - getInfo() invoked`);
2050
2179
  const appMetadata = yield this.getCurrentAppMetadata();
2051
2180
  return {
2052
- provider: "Glue42",
2181
+ provider: "io.Connect",
2053
2182
  providerVersion: version,
2054
2183
  fdc3Version: "2.0",
2055
2184
  optionalFeatures: {
@@ -2110,41 +2239,39 @@ class ApplicationsController {
2110
2239
  }
2111
2240
  openAppWithContext(app, context) {
2112
2241
  return __awaiter(this, void 0, void 0, function* () {
2113
- const methodName = yield this.registerContextListenerInteropMethod();
2114
- const startContext = this.buildGlueStartContext(context, methodName);
2115
- const glueInst = yield app.start(startContext);
2116
- this.createContextListenerResponsePromise(glueInst, methodName);
2242
+ const guid = nanoid();
2243
+ const startContext = this.buildStartContext(context, guid);
2244
+ const wrappedPromise = this.createContextListenerWrappedPromise(app);
2245
+ this.appsStateStore.addOpenAppPromise(guid, wrappedPromise);
2117
2246
  try {
2118
- yield this.contextListenerInvokedPromises[glueInst.id].promise;
2119
- yield this.unregisterContextListenerPromise(glueInst.id);
2247
+ const glueInst = yield app.start(startContext);
2248
+ yield wrappedPromise.promise;
2249
+ this.appsStateStore.removeOpenAppPromise(guid);
2120
2250
  return this.parseGlueInstToAppIdentifier(glueInst);
2121
2251
  }
2122
2252
  catch (error) {
2123
- yield this.unregisterContextListenerPromise(glueInst.id);
2253
+ this.appsStateStore.removeOpenAppPromise(guid);
2124
2254
  throw { message: OpenError.AppTimeout, reason: typeof error === "string" ? error : JSON.stringify(error) };
2125
2255
  }
2126
2256
  });
2127
2257
  }
2128
- buildGlueStartContext(fdc3Context, responseMethodName) {
2258
+ buildStartContext(fdc3Context, guid) {
2259
+ const myInteropInstance = this.glueController.getMyInteropInstance();
2129
2260
  return {
2130
- meta: {
2131
- responseMethodName,
2132
- instance: this.glueController.interopInstance().instance
2133
- },
2134
- context: fdc3Context
2261
+ fdc3: {
2262
+ collaborationId: guid,
2263
+ openApp: {
2264
+ appId: myInteropInstance.application || myInteropInstance.applicationName || "",
2265
+ instanceId: myInteropInstance.instance
2266
+ },
2267
+ context: {
2268
+ contextType: fdc3Context.type,
2269
+ payload: fdc3Context
2270
+ }
2271
+ }
2135
2272
  };
2136
2273
  }
2137
- registerContextListenerInteropMethod() {
2138
- return __awaiter(this, void 0, void 0, function* () {
2139
- const methodName = this.buildInteropMethodName();
2140
- yield this.glueController.registerMethod(methodName, this.contextListenerResponseHandler.bind(this));
2141
- return methodName;
2142
- });
2143
- }
2144
- buildInteropMethodName() {
2145
- return `${responseInteropMethodPrefix}.${nanoid()}`;
2146
- }
2147
- createContextListenerResponsePromise(instance, methodName) {
2274
+ createContextListenerWrappedPromise(app) {
2148
2275
  let resolve = () => { };
2149
2276
  let reject = () => { };
2150
2277
  const promise = promisePlus(() => {
@@ -2152,50 +2279,32 @@ class ApplicationsController {
2152
2279
  resolve = res;
2153
2280
  reject = rej;
2154
2281
  });
2155
- }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${instance.application.name} and instanceId: ${instance.id} to register context listener`);
2156
- this.contextListenerInvokedPromises[instance.id] = { promise, resolve, reject, methodName };
2157
- }
2158
- contextListenerResponseHandler(args, callerId) {
2159
- const result = ContextListenerResponseDecoder.run(args);
2160
- if (!result.ok) {
2161
- const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2162
- if (!contextListenerPromise) {
2163
- return;
2164
- }
2165
- contextListenerPromise.reject(`Method invoked with invalid argument - ${result.error.message}`);
2166
- return;
2167
- }
2168
- const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2169
- if (!contextListenerPromise) {
2170
- return;
2171
- }
2172
- contextListenerPromise.resolve();
2173
- }
2174
- unregisterContextListenerPromise(instanceId) {
2175
- return __awaiter(this, void 0, void 0, function* () {
2176
- const { methodName } = this.contextListenerInvokedPromises[instanceId];
2177
- yield this.glueController.unregisterMethod(methodName);
2178
- delete this.contextListenerInvokedPromises[instanceId];
2179
- });
2282
+ }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${app.name} to register context listener`);
2283
+ return { promise, resolve, reject };
2180
2284
  }
2181
2285
  }
2182
2286
 
2183
2287
  class ChannelsController {
2184
- constructor(glueController, channelsStateStore, channelsParser, channelsFactory, channelsCallbackRegistry) {
2288
+ constructor(glueController, channelsStateStore, channelsParser, channelsFactory, glueEventsController) {
2185
2289
  this.glueController = glueController;
2186
2290
  this.channelsStateStore = channelsStateStore;
2187
2291
  this.channelsParser = channelsParser;
2188
2292
  this.channelsFactory = channelsFactory;
2189
- this.channelsCallbackRegistry = channelsCallbackRegistry;
2293
+ this.glueEventsController = glueEventsController;
2190
2294
  this.invokeContextHandlerWithStartupContext = true;
2191
2295
  this.initDonePromise = this.initialize();
2192
- this.initDonePromise.catch(() => { });
2296
+ this.initDonePromise.catch((err) => {
2297
+ var _a;
2298
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(err);
2299
+ });
2193
2300
  }
2194
- get logger() {
2195
- if (!this._logger) {
2196
- this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2197
- }
2198
- return this._logger;
2301
+ getStartupContext() {
2302
+ var _a, _b;
2303
+ return __awaiter(this, void 0, void 0, function* () {
2304
+ yield this.initDonePromise;
2305
+ const fdc3StartupContext = yield this.glueController.getMyWindowContext();
2306
+ 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;
2307
+ });
2199
2308
  }
2200
2309
  addContextListener({ commandId, handler, contextType, channelId }) {
2201
2310
  var _a;
@@ -2233,14 +2342,14 @@ class ChannelsController {
2233
2342
  return __awaiter(this, void 0, void 0, function* () {
2234
2343
  yield this.initDonePromise;
2235
2344
  this.logger.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
2236
- const isPrivateChannel = this.isPrivateChannel(channelId);
2237
- if (isPrivateChannel) {
2238
- throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2239
- }
2240
2345
  const isUserChannel = this.isUserChannel(channelId);
2241
2346
  if (isUserChannel) {
2242
2347
  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" };
2243
2348
  }
2349
+ const isPrivateChannel = this.channelsStateStore.getPrivateChannelById(channelId);
2350
+ if (isPrivateChannel) {
2351
+ throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2352
+ }
2244
2353
  return this.getOrCreateAppChannel(commandId, channelId);
2245
2354
  });
2246
2355
  }
@@ -2318,26 +2427,28 @@ class ChannelsController {
2318
2427
  return __awaiter(this, void 0, void 0, function* () {
2319
2428
  yield this.initDonePromise;
2320
2429
  this.logger.info(`[${commandId}] - createPrivateChannel() invoked`);
2321
- const creatorId = this.glueController.getMyInteropInstanceId();
2322
- const channel = this.buildChannel(ChannelTypes.Private);
2323
- yield this.glueController.updateContext(channel.id, { creatorId });
2324
- this.logger.info(`[${commandId}] - private channel with id ${channel.id} created`);
2325
- return channel;
2430
+ const channelId = `${PrivateChannelPrefix}${nanoid()}`;
2431
+ yield this.glueEventsController.initializeCollaborateMethod();
2432
+ const pc = this.buildPrivateChannel(channelId, commandId, true);
2433
+ return pc.toApi();
2326
2434
  });
2327
2435
  }
2328
- announceDisconnect(commandId, channelId, instanceId) {
2436
+ removePrivateChannelFromStoreById(id) {
2329
2437
  return __awaiter(this, void 0, void 0, function* () {
2330
- yield this.initDonePromise;
2331
- this.logger.info(`[${commandId}] - disconnect() invoked on channel with id ${channelId}`);
2332
- yield this.glueController.updateContext(channelId, { disconnected: true });
2333
- this.logger.info(`[${commandId}] - glue context for ${channelId} updated with disconnected flag`);
2334
- const closedInstanceId = instanceId || this.glueController.getMyInteropInstanceId();
2335
- const targetInstance = yield this.getOtherInstanceIdFromClosedOne(channelId, closedInstanceId);
2336
- const replayContextTypes = yield this.getContextTypesForPrivateChannel(channelId);
2337
- this.logger.info(`[${commandId}] - invoking onDisconnect callback for instance ${targetInstance}`);
2338
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnDisconnect, { clientId: targetInstance, channelId, replayContextTypes });
2438
+ this.channelsStateStore.removePrivateChannelById(id);
2339
2439
  });
2340
2440
  }
2441
+ invokeSystemMethod(args, target) {
2442
+ return __awaiter(this, void 0, void 0, function* () {
2443
+ if (!target) {
2444
+ return;
2445
+ }
2446
+ return this.glueController.invokeSystemMethod(args, target);
2447
+ });
2448
+ }
2449
+ getMyServerInstance() {
2450
+ return this.glueController.getMyInteropInstance();
2451
+ }
2341
2452
  addClientToPrivateChannel(commandId, channelId, clientId) {
2342
2453
  return __awaiter(this, void 0, void 0, function* () {
2343
2454
  this.logger.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
@@ -2351,28 +2462,22 @@ class ChannelsController {
2351
2462
  return !!context.disconnected;
2352
2463
  });
2353
2464
  }
2354
- registerOnInstanceStopped({ commandId, channelId }) {
2355
- this.logger.info(`[${commandId}] - registering onInstanceStopped callback for channel with id ${channelId}`);
2356
- const handler = (instance) => __awaiter(this, void 0, void 0, function* () {
2357
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2358
- if (instance.id !== clientId && instance.id !== creatorId) {
2359
- return;
2360
- }
2361
- this.logger.info(`[${commandId}] - calling onDisconnect callback for channel with id ${channelId}`);
2362
- yield this.announceDisconnect(commandId, channelId, instance.id);
2363
- });
2465
+ subscribeOnInstanceStop(channelId, handler, commandId) {
2466
+ this.logger.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
2364
2467
  return this.glueController.registerOnInstanceStopped(handler.bind(this));
2365
2468
  }
2366
- addPrivateChannelEvent({ commandId, action, channelId, handler }) {
2367
- return __awaiter(this, void 0, void 0, function* () {
2368
- this.logger.info(`[${commandId}] - registering callback for ${action} event in channel with id ${channelId}`);
2369
- let replayArgs;
2370
- const targetInstanceId = yield this.getTargetedInstanceId(channelId);
2371
- if (action === PrivateChannelEventMethods.OnAddContextListener && targetInstanceId) {
2372
- replayArgs = yield this.getContextTypesForPrivateChannel(channelId);
2373
- }
2374
- return this.channelsCallbackRegistry.add({ action, channelId, handler, replayArgs });
2375
- });
2469
+ buildPrivateChannel(channelId, commandId, isCreator) {
2470
+ const logger = this.glueController.initSubLogger(channelId);
2471
+ const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
2472
+ this.logger.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
2473
+ this.channelsStateStore.addPrivateChannel(channel);
2474
+ return channel;
2475
+ }
2476
+ get logger() {
2477
+ if (!this._logger) {
2478
+ this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2479
+ }
2480
+ return this._logger;
2376
2481
  }
2377
2482
  initialize() {
2378
2483
  return __awaiter(this, void 0, void 0, function* () {
@@ -2421,39 +2526,43 @@ class ChannelsController {
2421
2526
  return __awaiter(this, void 0, void 0, function* () {
2422
2527
  const myWindow = this.glueController.getMyWindow();
2423
2528
  if (!myWindow) {
2424
- this.logger.log(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2529
+ this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2425
2530
  this.invokeContextHandlerWithStartupContext = false;
2426
2531
  return;
2427
2532
  }
2428
2533
  const windowContext = yield myWindow.getContext();
2429
- if (!isValidNonEmptyObject(windowContext)) {
2430
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2534
+ if (!windowContext) {
2535
+ this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2431
2536
  this.invokeContextHandlerWithStartupContext = false;
2432
2537
  return;
2433
2538
  }
2434
- const { context, meta } = windowContext;
2435
- const isSameContextType = contextType ? (context === null || context === void 0 ? void 0 : context.type) === contextType : true;
2436
- if (!isSameContextType || !meta) {
2437
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked`);
2539
+ if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
2540
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2541
+ this.invokeContextHandlerWithStartupContext = false;
2438
2542
  return;
2439
2543
  }
2440
- this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context`);
2441
- handler(context);
2442
- this.invokeContextHandlerWithStartupContext = false;
2443
- const { responseMethodName, instance } = meta;
2444
- const responseMethodExists = this.doesServerMethodExist(responseMethodName, instance);
2445
- if (!responseMethodExists) {
2446
- this.logger.info(`[${commandId}] - response method for instance ${instance} does not exist anymore. returning`);
2544
+ yield this.glueEventsController.initializeCollaborateMethod();
2545
+ FDC3StartupContextDecoder.runWithException(windowContext);
2546
+ const { fdc3 } = windowContext;
2547
+ this.logger.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
2548
+ const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
2549
+ if (!isSameContextType) {
2550
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
2447
2551
  return;
2448
2552
  }
2449
- this.logger.info(`[${commandId}] - invoking response method for instance ${instance}`);
2450
- yield this.glueController.invokeMethod(responseMethodName, instance, { listenerInvoked: true });
2553
+ this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
2554
+ try {
2555
+ handler(fdc3.context.payload, { source: fdc3.openApp });
2556
+ }
2557
+ catch (error) {
2558
+ this.logger.error(typeof error === "string" ? error : error.message ? JSON.stringify(error.message) : JSON.stringify(error));
2559
+ }
2560
+ this.invokeContextHandlerWithStartupContext = false;
2561
+ this.logger.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
2562
+ yield this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
2563
+ this.logger.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
2451
2564
  });
2452
2565
  }
2453
- doesServerMethodExist(methodName, instance) {
2454
- const serversForMethodName = this.glueController.getInteropServers({ name: methodName });
2455
- return !!serversForMethodName.find(server => server.instance === instance);
2456
- }
2457
2566
  getOrCreateAppChannel(commandId, channelId) {
2458
2567
  return __awaiter(this, void 0, void 0, function* () {
2459
2568
  const exists = this.doesAppChannelExist(channelId);
@@ -2462,7 +2571,8 @@ class ChannelsController {
2462
2571
  yield this.glueController.updateContext(channelId, {});
2463
2572
  }
2464
2573
  this.logger.info(`[${commandId}] - returning app channel with id ${channelId}`);
2465
- return this.buildChannel(ChannelTypes.App, { id: channelId });
2574
+ const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
2575
+ return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
2466
2576
  });
2467
2577
  }
2468
2578
  doesAppChannelExist(name) {
@@ -2474,12 +2584,6 @@ class ChannelsController {
2474
2584
  }
2475
2585
  return !!this.channelsStateStore.userChannels[channelId];
2476
2586
  }
2477
- isPrivateChannel(channelId) {
2478
- return channelId.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === channelId);
2479
- }
2480
- buildChannel(type, data) {
2481
- return this.channelsFactory.buildModel(Object.assign(Object.assign({ type }, data), { isChannel: true }));
2482
- }
2483
2587
  broadcastByChannelId(commandId, channelId, context) {
2484
2588
  return __awaiter(this, void 0, void 0, function* () {
2485
2589
  const isUserChannel = this.isUserChannel(channelId);
@@ -2497,7 +2601,7 @@ class ChannelsController {
2497
2601
  const subHandler = parseContextHandler(handler, contextType);
2498
2602
  if (!channelId) {
2499
2603
  this.logger.info(`[${commandId}] - Creating a channel subscription using glue.channels.subscribe`);
2500
- const unsubscribe = this.glueController.channelsSubscribe(subHandler);
2604
+ const unsubscribe = this.glueController.channelsSubscribe(subHandler, contextType);
2501
2605
  return { unsubscribe };
2502
2606
  }
2503
2607
  const channelType = this.getChannelTypeById(channelId);
@@ -2514,25 +2618,10 @@ class ChannelsController {
2514
2618
  }
2515
2619
  };
2516
2620
  }
2517
- if (channelType === ChannelTypes.Private) {
2518
- this.logger.info(`[${commandId}] - subscribing for fdc3 private channel with id ${channelId} (underlying glue context with same name)`);
2519
- const contextsUnsubscribe = yield this.glueController.contextsSubscribe(channelId, subHandler);
2520
- yield this.addContextTypeInPrivateChannelContext(channelId, contextType);
2521
- const targetInstance = yield this.getTargetedInstanceId(channelId);
2522
- const unsubscribe = () => {
2523
- this.logger.info(`[${commandId}] - unsubscribe invoked for private channel with id ${channelId}`);
2524
- contextsUnsubscribe();
2525
- this.logger.info(`[${commandId}] - invoking onUnsubscribe handler for private channel with id ${channelId}`);
2526
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnUnsubscribe, { channelId, clientId: targetInstance, contextType });
2527
- };
2528
- this.logger.info(`[${commandId}] - invoking onAddContextListener handler for private channel with id ${channelId}`);
2529
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnAddContextListener, { channelId: channelId, clientId: targetInstance, contextType });
2530
- return { unsubscribe };
2531
- }
2532
2621
  throw { message: ChannelError.AccessDenied, reason: "Cannot add a context listener on an invalid channel" };
2533
2622
  });
2534
2623
  }
2535
- addContextListenerOnUserChannel({ commandId, channelId, handler, invokedOnChannelModel }) {
2624
+ addContextListenerOnUserChannel({ commandId, channelId, handler, invokedOnChannelModel, contextType }) {
2536
2625
  return __awaiter(this, void 0, void 0, function* () {
2537
2626
  let unsubscribe;
2538
2627
  if (invokedOnChannelModel) {
@@ -2542,7 +2631,7 @@ class ChannelsController {
2542
2631
  }
2543
2632
  else {
2544
2633
  this.logger.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
2545
- unsubscribe = this.glueController.channelsSubscribe(handler);
2634
+ unsubscribe = this.glueController.channelsSubscribe(handler, contextType);
2546
2635
  }
2547
2636
  return {
2548
2637
  unsubscribe: () => {
@@ -2557,56 +2646,21 @@ class ChannelsController {
2557
2646
  if (isUser) {
2558
2647
  return ChannelTypes.User;
2559
2648
  }
2560
- const isPrivate = this.isPrivateChannel(channelId);
2561
- if (isPrivate) {
2562
- return ChannelTypes.Private;
2563
- }
2564
2649
  const isApp = this.doesAppChannelExist(channelId);
2565
2650
  if (isApp) {
2566
2651
  return ChannelTypes.App;
2567
2652
  }
2568
2653
  throw { message: ChannelError.NoChannelFound, reason: `Channel with id: ${channelId} does not exist` };
2569
2654
  }
2570
- getTargetedInstanceId(channelId) {
2571
- return __awaiter(this, void 0, void 0, function* () {
2572
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2573
- const myId = this.glueController.getMyInteropInstanceId();
2574
- return myId === clientId ? creatorId : clientId;
2575
- });
2576
- }
2577
- getOtherInstanceIdFromClosedOne(channelId, closedInstanceId) {
2578
- return __awaiter(this, void 0, void 0, function* () {
2579
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2580
- return closedInstanceId === clientId
2581
- ? creatorId
2582
- : clientId;
2583
- });
2584
- }
2585
- invokeSystemMethod(clientId, action, payload) {
2586
- if (clientId) {
2587
- this.glueController.invokeSystemMethod({ action, payload });
2588
- }
2589
- }
2590
- addContextTypeInPrivateChannelContext(channelId, contextType) {
2591
- return __awaiter(this, void 0, void 0, function* () {
2592
- const currentContext = yield this.glueController.getContext(channelId);
2593
- const updatedTypes = currentContext.contextListenerTypes ? [...currentContext.contextListenerTypes, contextType] : [contextType];
2594
- return this.glueController.updateContext(channelId, Object.assign(Object.assign({}, currentContext), { contextListenerTypes: updatedTypes }));
2595
- });
2596
- }
2597
- getContextTypesForPrivateChannel(channelId) {
2598
- return __awaiter(this, void 0, void 0, function* () {
2599
- const ctx = yield this.glueController.getContext(channelId);
2600
- return ctx.contextListenerTypes;
2601
- });
2655
+ buildChannel(type, data) {
2656
+ return this.channelsFactory.buildModel(Object.assign({ type }, data));
2602
2657
  }
2603
2658
  }
2604
2659
 
2605
2660
  class EventReceiver {
2606
- constructor(glueController, eventDispatcher, eventsController) {
2661
+ constructor(glueController, eventDispatcher) {
2607
2662
  this.glueController = glueController;
2608
2663
  this.eventDispatcher = eventDispatcher;
2609
- this.eventsController = eventsController;
2610
2664
  this.glueResponseReceived = false;
2611
2665
  this.glueInitialized = false;
2612
2666
  this.events = {
@@ -2652,7 +2706,6 @@ class EventReceiver {
2652
2706
  }
2653
2707
  window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
2654
2708
  this.glueController.initialize(glue);
2655
- yield this.eventsController.initialize();
2656
2709
  this.eventDispatcher.fireFdc3Ready();
2657
2710
  this.glueInitialized = true;
2658
2711
  });
@@ -2664,16 +2717,17 @@ class ChannelsStateStore {
2664
2717
  this._currentChannel = null;
2665
2718
  this._userChannels = {};
2666
2719
  this._fdc3ChannelIdsToGlueChannelNames = {};
2720
+ this._privateChannels = {};
2667
2721
  }
2668
2722
  get currentChannel() {
2669
2723
  return this._currentChannel;
2670
2724
  }
2671
- get userChannels() {
2672
- return this._userChannels;
2673
- }
2674
2725
  set currentChannel(newChannelValue) {
2675
2726
  this._currentChannel = newChannelValue;
2676
2727
  }
2728
+ get userChannels() {
2729
+ return this._userChannels;
2730
+ }
2677
2731
  addUserChannel(channel) {
2678
2732
  this._userChannels[channel.id] = channel;
2679
2733
  }
@@ -2687,140 +2741,14 @@ class ChannelsStateStore {
2687
2741
  const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
2688
2742
  return key;
2689
2743
  }
2690
- }
2691
-
2692
- class PrivateChannel {
2693
- constructor(channelsController, channelId) {
2694
- this.channelsController = channelsController;
2695
- this.type = ChannelTypes.Private;
2696
- this.id = channelId || `${PrivateChannelPrefix}${nanoid()}`;
2697
- this.unsubFromInstanceStopped = this.channelsController.registerOnInstanceStopped({ commandId: generateCommandId(), channelId: this.id });
2698
- }
2699
- toApi() {
2700
- const api = {
2701
- id: this.id,
2702
- type: this.type,
2703
- displayMetadata: this.displayMetadata,
2704
- broadcast: this.broadcast.bind(this),
2705
- getCurrentContext: this.getCurrentContext.bind(this),
2706
- addContextListener: this.addContextListener.bind(this),
2707
- onAddContextListener: this.onAddContextListener.bind(this),
2708
- onUnsubscribe: this.onUnsubscribe.bind(this),
2709
- onDisconnect: this.onDisconnect.bind(this),
2710
- disconnect: this.disconnect.bind(this),
2711
- };
2712
- return api;
2744
+ addPrivateChannel(privateChannel) {
2745
+ this._privateChannels[privateChannel.id] = privateChannel;
2713
2746
  }
2714
- broadcast(context) {
2715
- return __awaiter(this, void 0, void 0, function* () {
2716
- const commandId = generateCommandId();
2717
- const isDisconnected = yield this.channelsController.isPrivateChannelDisconnected({ commandId, channelId: this.id });
2718
- if (isDisconnected) {
2719
- throw { message: ChannelError.AccessDenied, reason: "Channel has disconnected - broadcast is no longer available" };
2720
- }
2721
- contextDecoder.runWithException(context);
2722
- return this.channelsController.broadcast(commandId, context, this.id);
2723
- });
2747
+ getPrivateChannelById(id) {
2748
+ return this._privateChannels[id];
2724
2749
  }
2725
- getCurrentContext(contextType) {
2726
- return __awaiter(this, void 0, void 0, function* () {
2727
- optionalNonEmptyStringDecoder.runWithException(contextType);
2728
- return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
2729
- });
2730
- }
2731
- addContextListener(contextType, handler) {
2732
- return __awaiter(this, arguments, void 0, function* () {
2733
- if (arguments.length === 1) {
2734
- if (typeof contextType !== "function") {
2735
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2736
- }
2737
- return this.channelsController.addContextListener({ commandId: generateCommandId(), handler: contextType, channelId: this.id });
2738
- }
2739
- const contextTypeDecoder = optionalNonEmptyStringDecoder.runWithException(contextType);
2740
- if (typeof handler !== "function") {
2741
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2742
- }
2743
- return this.channelsController.addContextListener({
2744
- commandId: generateCommandId(),
2745
- contextType: contextTypeDecoder,
2746
- channelId: this.id,
2747
- handler,
2748
- });
2749
- });
2750
- }
2751
- onAddContextListener(handler) {
2752
- if (typeof handler !== "function") {
2753
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2754
- }
2755
- const unsub = this.channelsController.addPrivateChannelEvent({
2756
- commandId: generateCommandId(),
2757
- action: PrivateChannelEventMethods.OnAddContextListener,
2758
- channelId: this.id,
2759
- handler
2760
- });
2761
- return AsyncListener(unsub);
2762
- }
2763
- onUnsubscribe(handler) {
2764
- if (typeof handler !== "function") {
2765
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2766
- }
2767
- const unsub = this.channelsController.addPrivateChannelEvent({
2768
- commandId: generateCommandId(),
2769
- action: PrivateChannelEventMethods.OnUnsubscribe,
2770
- channelId: this.id,
2771
- handler
2772
- });
2773
- return AsyncListener(unsub);
2774
- }
2775
- onDisconnect(handler) {
2776
- if (typeof handler !== "function") {
2777
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2778
- }
2779
- const unsub = this.channelsController.addPrivateChannelEvent({
2780
- commandId: generateCommandId(),
2781
- action: PrivateChannelEventMethods.OnDisconnect,
2782
- channelId: this.id,
2783
- handler
2784
- });
2785
- return AsyncListener(unsub);
2786
- }
2787
- disconnect() {
2788
- return __awaiter(this, void 0, void 0, function* () {
2789
- yield this.channelsController.announceDisconnect(generateCommandId(), this.id);
2790
- this.unsubFromInstanceStopped();
2791
- });
2792
- }
2793
- }
2794
-
2795
- class ChannelsFactory {
2796
- constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
2797
- this.createUserChannelFn = createUserChannelFn;
2798
- this.createAppChannel = createAppChannel;
2799
- this.createPrivateChannel = createPrivateChannel;
2800
- }
2801
- buildModel(data) {
2802
- const { type } = data;
2803
- if (type === ChannelTypes.User) {
2804
- return this.buildUserChannel(data.displayMetadata.glueChannel);
2805
- }
2806
- else if (type === ChannelTypes.App) {
2807
- return this.buildAppChannel(data.id);
2808
- }
2809
- else if (type === ChannelTypes.Private) {
2810
- return this.buildPrivateChannel(data.id);
2811
- }
2812
- else {
2813
- throw new Error("Pass one of the supported channel types: user, app, private");
2814
- }
2815
- }
2816
- buildUserChannel(data) {
2817
- return this.createUserChannelFn(data);
2818
- }
2819
- buildAppChannel(channelId) {
2820
- return this.createAppChannel(channelId);
2821
- }
2822
- buildPrivateChannel(channelId) {
2823
- return this.createPrivateChannel(channelId);
2750
+ removePrivateChannelById(id) {
2751
+ delete this._privateChannels[id];
2824
2752
  }
2825
2753
  }
2826
2754
 
@@ -2941,36 +2869,345 @@ function createRegistry(options) {
2941
2869
  createRegistry.default = createRegistry;
2942
2870
  var lib = createRegistry;
2943
2871
 
2944
- class ChannelsCallbackRegistry {
2945
- constructor() {
2872
+ class PrivateChannel {
2873
+ constructor(channelsController, logger, channelId, isCreator) {
2874
+ this.channelsController = channelsController;
2875
+ this.logger = logger;
2876
+ this.isCreator = isCreator;
2877
+ this.type = ChannelTypes.Private;
2878
+ this.disconnected = false;
2879
+ this.broadcastedContexts = {};
2880
+ this.collaboratorListenerTypes = [];
2881
+ this.myListenerTypesBeforeBound = [];
2946
2882
  this.registry = lib();
2883
+ this.id = channelId;
2884
+ const myServerInstance = this.channelsController.getMyServerInstance();
2885
+ this.myAppMetadata = { source: { appId: myServerInstance.applicationName, instanceId: myServerInstance.instance } };
2886
+ }
2887
+ toApi() {
2888
+ const api = {
2889
+ id: this.id,
2890
+ type: this.type,
2891
+ displayMetadata: this.displayMetadata,
2892
+ broadcast: this.broadcast.bind(this),
2893
+ getCurrentContext: this.getCurrentContext.bind(this),
2894
+ addContextListener: this.addContextListener.bind(this),
2895
+ onAddContextListener: this.onAddContextListener.bind(this),
2896
+ onUnsubscribe: this.onUnsubscribe.bind(this),
2897
+ onDisconnect: this.onDisconnect.bind(this),
2898
+ disconnect: this.disconnect.bind(this),
2899
+ };
2900
+ return api;
2901
+ }
2902
+ getCollaborator() {
2903
+ return this.collaborator;
2904
+ }
2905
+ setCollaborator(collaborator, commandId) {
2906
+ if (this.collaborator && this.collaborator.instanceId !== collaborator.instanceId) {
2907
+ throw new Error(`There's already a collaborator for private channel with id ${this.id}`);
2908
+ }
2909
+ this.collaborator = collaborator;
2910
+ this.subscribeForCollaboratorInstanceStop(commandId);
2911
+ }
2912
+ handleCollaboratorJoin(collaborator, commandId) {
2913
+ return __awaiter(this, void 0, void 0, function* () {
2914
+ this.setCollaborator(collaborator, commandId);
2915
+ yield Promise.all(this.myListenerTypesBeforeBound.map((contextType) => {
2916
+ var _a;
2917
+ const listenerAddedArgs = {
2918
+ action: "addedContextListenerOnPrivateChannel",
2919
+ correlationId: this.id,
2920
+ collaborationObject: {
2921
+ channelId: this.id,
2922
+ contextType: contextType || undefined
2923
+ }
2924
+ };
2925
+ this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
2926
+ return this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
2927
+ })).catch((err) => this.logger.error(err));
2928
+ });
2929
+ }
2930
+ handleCollaboratorBroadcast(context, metadata, commandId) {
2931
+ this.logger.trace(`[${commandId}] - heard context with type ${context.type} broadcasted on the channel`);
2932
+ this.lastBroadcastedContextType = context.type;
2933
+ this.broadcastedContexts[context.type] = { context, metadata };
2934
+ this.logger.trace(`[${commandId}] - invoking all context listeners`);
2935
+ this.registry.execute(PrivateChannelEventMethods.ListenerAdded, context, metadata);
2936
+ }
2937
+ handleCollaboratorAddContextListener(contextType, commandId) {
2938
+ this.logger.trace(`[${commandId}] - heard collaborator added context listener for type ${contextType}`);
2939
+ this.collaboratorListenerTypes.push(contextType);
2940
+ this.registry.execute(PrivateChannelEventMethods.OnAddContextListener, contextType);
2941
+ }
2942
+ handleCollaboratorRemovedListener(contextType, commandId) {
2943
+ this.logger.trace(`[${commandId}] - heard collaborator removed context listener with type ${contextType}`);
2944
+ const index = this.collaboratorListenerTypes.indexOf(contextType);
2945
+ this.collaboratorListenerTypes.splice(index, 1);
2946
+ this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType);
2947
+ }
2948
+ handleCollaboratorDisconnect() {
2949
+ this.disconnected = true;
2950
+ this.collaboratorListenerTypes.forEach((contextType) => this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType));
2951
+ this.registry.execute(PrivateChannelEventMethods.OnDisconnect);
2952
+ }
2953
+ announceJoin(targetInstance, commandId) {
2954
+ return __awaiter(this, void 0, void 0, function* () {
2955
+ const joinChannelArgs = {
2956
+ action: "joinPrivateChannel",
2957
+ correlationId: this.id,
2958
+ collaborationObject: {
2959
+ channelId: this.id
2960
+ }
2961
+ };
2962
+ this.logger.trace(`[${commandId}] - announcing ${"joinPrivateChannel"} to target instance with id ${JSON.stringify(targetInstance)}`);
2963
+ yield this.channelsController.invokeSystemMethod(joinChannelArgs, targetInstance);
2964
+ this.logger.trace(`[${commandId}] - collaborator received ${"joinPrivateChannel"} action`);
2965
+ });
2966
+ }
2967
+ broadcast(context) {
2968
+ var _a;
2969
+ return __awaiter(this, void 0, void 0, function* () {
2970
+ const commandId = generateCommandId();
2971
+ this.ensureAlive(commandId);
2972
+ this.ensureBound(commandId, "broadcast");
2973
+ contextDecoder.runWithException(context);
2974
+ this.lastBroadcastedContextType = context.type;
2975
+ this.broadcastedContexts[context.type] = { context, metadata: this.myAppMetadata };
2976
+ const broadcastArgs = {
2977
+ action: "publishOnPrivateChannel",
2978
+ correlationId: this.id,
2979
+ collaborationObject: {
2980
+ channelId: this.id,
2981
+ contextType: context.type,
2982
+ payload: context
2983
+ }
2984
+ };
2985
+ this.logger.trace(`[${commandId}] - announcing ${"publishOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
2986
+ yield this.channelsController.invokeSystemMethod(broadcastArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
2987
+ this.logger.trace(`[${commandId}] - collaborator received context for action ${"publishOnPrivateChannel"}`);
2988
+ });
2989
+ }
2990
+ getCurrentContext(contextType) {
2991
+ return __awaiter(this, void 0, void 0, function* () {
2992
+ const commandId = generateCommandId();
2993
+ this.ensureAlive(commandId);
2994
+ this.logger.trace(`[${commandId}] - getCurrentContext invoked ${contextType ? `with contextType ${contextType}` : ""}`);
2995
+ optionalNonEmptyStringDecoder.runWithException(contextType);
2996
+ if (!contextType && !this.lastBroadcastedContextType) {
2997
+ return null;
2998
+ }
2999
+ const searchedType = contextType || this.lastBroadcastedContextType;
3000
+ this.logger.trace(`[${commandId}] - Returning context with type ${searchedType}`);
3001
+ return this.broadcastedContexts[searchedType].context;
3002
+ });
3003
+ }
3004
+ addContextListener(contextType, handler) {
3005
+ var _a;
3006
+ return __awaiter(this, void 0, void 0, function* () {
3007
+ const commandId = generateCommandId();
3008
+ this.ensureAlive(commandId);
3009
+ optionalNonEmptyStringDecoder.runWithException(contextType);
3010
+ if (typeof handler !== "function") {
3011
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
3012
+ }
3013
+ this.logger.trace(`[${commandId}] - adding subscription for broadcasted contexts with type: ${contextType}`);
3014
+ const subHandler = (data, metadata) => {
3015
+ if (contextType) {
3016
+ if (data.type === contextType) {
3017
+ handler(data, metadata);
3018
+ }
3019
+ return;
3020
+ }
3021
+ handler(data, metadata);
3022
+ };
3023
+ const lastBroadcastedContextPerType = this.retrieveLatestBroadcastedContextPerType(contextType);
3024
+ const replayArgs = lastBroadcastedContextPerType ? [[lastBroadcastedContextPerType.context, lastBroadcastedContextPerType.metadata]] : undefined;
3025
+ const unsub = this.registry.add(PrivateChannelEventMethods.ListenerAdded, subHandler, replayArgs);
3026
+ if (this.collaborator) {
3027
+ const listenerAddedArgs = {
3028
+ action: "addedContextListenerOnPrivateChannel",
3029
+ correlationId: this.id,
3030
+ collaborationObject: {
3031
+ channelId: this.id,
3032
+ contextType: contextType || undefined
3033
+ }
3034
+ };
3035
+ this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3036
+ yield this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3037
+ this.logger.trace(`[${commandId}] - collaborator received action ${"addedContextListenerOnPrivateChannel"}`);
3038
+ }
3039
+ else {
3040
+ this.myListenerTypesBeforeBound.push(contextType);
3041
+ }
3042
+ const unsubscribe = this.getAddContextListenerUnsub(unsub, contextType, commandId);
3043
+ return AsyncListener(unsubscribe);
3044
+ });
2947
3045
  }
2948
- add({ action, channelId, handler, replayArgs }) {
2949
- return this.registry.add(`${action}-${channelId}`, handler, replayArgs);
3046
+ retrieveLatestBroadcastedContextPerType(contextType) {
3047
+ if (!contextType && !this.lastBroadcastedContextType) {
3048
+ return;
3049
+ }
3050
+ if (!contextType && this.lastBroadcastedContextType) {
3051
+ return {
3052
+ context: this.broadcastedContexts[this.lastBroadcastedContextType].context,
3053
+ metadata: this.broadcastedContexts[this.lastBroadcastedContextType].metadata
3054
+ };
3055
+ }
3056
+ return this.broadcastedContexts[contextType];
2950
3057
  }
2951
- invoke(action, argumentObj) {
2952
- const { channelId, contextType } = argumentObj;
2953
- this.registry.execute(`${action}-${channelId}`, contextType);
3058
+ getAddContextListenerUnsub(unsub, contextType, commandId) {
3059
+ return () => __awaiter(this, void 0, void 0, function* () {
3060
+ var _a;
3061
+ unsub();
3062
+ if (!this.collaborator) {
3063
+ const index = this.myListenerTypesBeforeBound.indexOf(contextType);
3064
+ this.myListenerTypesBeforeBound.splice(index, 1);
3065
+ return;
3066
+ }
3067
+ const unsubArgs = {
3068
+ action: "removedContextListenerOnPrivateChannel",
3069
+ correlationId: this.id,
3070
+ collaborationObject: {
3071
+ channelId: this.id,
3072
+ contextType: contextType || undefined
3073
+ }
3074
+ };
3075
+ this.logger.trace(`[${commandId}] - announcing unsubscribe from context listener for type ${contextType}`);
3076
+ yield this.channelsController.invokeSystemMethod(unsubArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3077
+ this.logger.trace(`[${commandId}] - collaborator heard ${"removedContextListenerOnPrivateChannel"}`);
3078
+ });
3079
+ }
3080
+ onAddContextListener(handler) {
3081
+ if (typeof handler !== "function") {
3082
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3083
+ }
3084
+ const commandId = generateCommandId();
3085
+ this.ensureAlive(commandId);
3086
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnAddContextListener, handler, this.collaboratorListenerTypes);
3087
+ return AsyncListener(unsub);
3088
+ }
3089
+ onUnsubscribe(handler) {
3090
+ if (typeof handler !== "function") {
3091
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3092
+ }
3093
+ const commandId = generateCommandId();
3094
+ this.ensureAlive(commandId);
3095
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnUnsubscribe, handler);
3096
+ return AsyncListener(unsub);
3097
+ }
3098
+ onDisconnect(handler) {
3099
+ if (typeof handler !== "function") {
3100
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3101
+ }
3102
+ const commandId = generateCommandId();
3103
+ this.ensureAlive(commandId);
3104
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnDisconnect, handler);
3105
+ return AsyncListener(unsub);
3106
+ }
3107
+ disconnect() {
3108
+ var _a;
3109
+ return __awaiter(this, void 0, void 0, function* () {
3110
+ const commandId = generateCommandId();
3111
+ if (this.isCreator && !this.collaborator) {
3112
+ this.disconnected = true;
3113
+ return;
3114
+ }
3115
+ this.ensureAlive(commandId);
3116
+ this.ensureBound(commandId, "disconnect");
3117
+ this.logger.trace(`[${commandId}] - disconnect invoked`);
3118
+ this.disconnected = true;
3119
+ this.logger.trace(`[${commandId}] - announcing ${"disconnectedFromPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3120
+ const disconnectArgs = {
3121
+ action: "disconnectedFromPrivateChannel",
3122
+ correlationId: this.id,
3123
+ collaborationObject: {
3124
+ channelId: this.id
3125
+ }
3126
+ };
3127
+ this.channelsController.removePrivateChannelFromStoreById(this.id);
3128
+ yield this.channelsController.invokeSystemMethod(disconnectArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3129
+ this.logger.trace(`[${commandId}] - collaborator received action ${"disconnectedFromPrivateChannel"}`);
3130
+ if (this.unsubFromInstanceStopped) {
3131
+ this.unsubFromInstanceStopped();
3132
+ }
3133
+ });
3134
+ }
3135
+ ensureAlive(commandId) {
3136
+ if (!this.disconnected) {
3137
+ return;
3138
+ }
3139
+ const errorMsg = "Channel is disconnected - operation is no longer available";
3140
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3141
+ throw { message: ChannelError.AccessDenied, reason: errorMsg };
3142
+ }
3143
+ ensureBound(commandId, operation) {
3144
+ if (this.collaborator) {
3145
+ return;
3146
+ }
3147
+ const errorMsg = `There's no collaborator on the other side of the channel - operation ${operation} is unavailable`;
3148
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3149
+ throw { message: ChannelError.AccessDenied, reason: errorMsg };
3150
+ }
3151
+ subscribeForCollaboratorInstanceStop(commandId) {
3152
+ const handler = (instance) => {
3153
+ var _a;
3154
+ if (instance.id !== ((_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId)) {
3155
+ return;
3156
+ }
3157
+ this.handleCollaboratorDisconnect();
3158
+ };
3159
+ this.unsubFromInstanceStopped = this.channelsController.subscribeOnInstanceStop(this.id, handler.bind(this), commandId);
3160
+ }
3161
+ }
3162
+
3163
+ class ChannelsFactory {
3164
+ constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
3165
+ this.createUserChannelFn = createUserChannelFn;
3166
+ this.createAppChannel = createAppChannel;
3167
+ this.createPrivateChannel = createPrivateChannel;
3168
+ }
3169
+ buildModel(data) {
3170
+ const { type } = data;
3171
+ const lowerType = type === null || type === void 0 ? void 0 : type.toLowerCase();
3172
+ if (lowerType === ChannelTypes.User) {
3173
+ return this.createUserChannelFn(data.displayMetadata.glueChannel);
3174
+ }
3175
+ if (lowerType === ChannelTypes.App) {
3176
+ return this.createAppChannel(data.id);
3177
+ }
3178
+ if (lowerType === ChannelTypes.Private) {
3179
+ return this.createPrivateChannel(data.logger, data.id, data.isCreator);
3180
+ }
3181
+ throw new Error("Pass one of the supported channel types: user, app, private");
2954
3182
  }
2955
3183
  }
2956
3184
 
2957
3185
  class GlueEventsController {
2958
- constructor(glueController, channelsCallbackRegistry) {
3186
+ constructor(glueController, channelsStateStore, appsStateStore) {
2959
3187
  this.glueController = glueController;
2960
- this.channelsCallbackRegistry = channelsCallbackRegistry;
3188
+ this.channelsStateStore = channelsStateStore;
3189
+ this.appsStateStore = appsStateStore;
3190
+ this.actionDictionary = {
3191
+ joinPrivateChannel: this.handleJoin.bind(this),
3192
+ publishOnPrivateChannel: this.handlePublish.bind(this),
3193
+ addedContextListenerOnPrivateChannel: this.handleContextListenerAdded.bind(this),
3194
+ removedContextListenerOnPrivateChannel: this.handleContextListenerRemoved.bind(this),
3195
+ disconnectedFromPrivateChannel: this.handleDisconnect.bind(this),
3196
+ startupContextOpened: this.handleStartupContextOpened.bind(this)
3197
+ };
2961
3198
  }
2962
- initialize() {
3199
+ initializeCollaborateMethod() {
2963
3200
  return __awaiter(this, void 0, void 0, function* () {
2964
- const isMethodRegisteredByThisApp = this.isSysMethodRegisteredByCurrentApp();
2965
- if (isMethodRegisteredByThisApp) {
3201
+ const methodRegisteredByMe = this.checkSystemMethodRegistered();
3202
+ if (methodRegisteredByMe) {
2966
3203
  return;
2967
3204
  }
2968
- yield this.glueController.registerMethod(Glue42FDC3SystemMethod, this.handleSystemMethodInvocation.bind(this));
3205
+ yield this.glueController.registerMethod(ioConnectFDC3SystemMethod, this.handleReceivedAction.bind(this));
2969
3206
  });
2970
3207
  }
2971
- isSysMethodRegisteredByCurrentApp() {
2972
- const methods = this.glueController.getInteropMethods(Glue42FDC3SystemMethod);
2973
- const myId = this.glueController.getMyInteropInstanceId();
3208
+ checkSystemMethodRegistered() {
3209
+ const methods = this.glueController.getInteropMethods(ioConnectFDC3SystemMethod);
3210
+ const myId = this.glueController.getMyInteropInstance().instance;
2974
3211
  const methodsByThisInstance = methods.filter(method => {
2975
3212
  return method.getServers().find(server => server.instance === myId)
2976
3213
  ? method
@@ -2978,29 +3215,111 @@ class GlueEventsController {
2978
3215
  });
2979
3216
  return !!methodsByThisInstance.length;
2980
3217
  }
2981
- handleSystemMethodInvocation(argumentObj) {
2982
- const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(argumentObj);
2983
- if (!argsDecodeResult.ok) {
2984
- throw new Error(`Interop Method ${Glue42FDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}.\n Expected ${JSON.stringify({ action: string, payload: { channelId: string, clientId: string } })}`);
3218
+ handleReceivedAction(eventArgs, instance) {
3219
+ return __awaiter(this, void 0, void 0, function* () {
3220
+ const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(eventArgs);
3221
+ if (!argsDecodeResult.ok) {
3222
+ throw new Error(`Interop Method ${ioConnectFDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}`);
3223
+ }
3224
+ const commandId = generateCommandId();
3225
+ this.logger.log(`${commandId} - received system method from instance with id ${instance.instance} for action ${eventArgs.action} with arguments: ${JSON.stringify(eventArgs)}`);
3226
+ const operation = this.actionDictionary[eventArgs.action];
3227
+ if (!operation) {
3228
+ const errorMsg = `Unsupported private channel action: ${eventArgs.action}`;
3229
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3230
+ throw new Error(errorMsg);
3231
+ }
3232
+ yield operation(eventArgs, instance, commandId);
3233
+ });
3234
+ }
3235
+ get logger() {
3236
+ if (!this._logger) {
3237
+ this._logger = this.glueController.initSubLogger("fdc3.private.channels.controller");
3238
+ }
3239
+ return this._logger;
3240
+ }
3241
+ validateAndRetrieveChannel({ action, correlationId }, instance, commandId) {
3242
+ const privateChannel = this.channelsStateStore.getPrivateChannelById(correlationId);
3243
+ if (!privateChannel) {
3244
+ const errorMsg = `There's no private channel with id ${correlationId}`;
3245
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3246
+ throw new Error(errorMsg);
2985
3247
  }
2986
- const { action, payload } = argsDecodeResult.result;
2987
- if (action === PrivateChannelEventMethods.OnDisconnect) {
2988
- return this.handleOnDisconnect(payload);
3248
+ const channelCollaborator = privateChannel.getCollaborator();
3249
+ if (action === "joinPrivateChannel") {
3250
+ return privateChannel;
2989
3251
  }
2990
- if (action === PrivateChannelEventMethods.OnAddContextListener || action === PrivateChannelEventMethods.OnUnsubscribe) {
2991
- return this.channelsCallbackRegistry.invoke(action, payload);
3252
+ if (channelCollaborator && channelCollaborator.instanceId === instance.instance) {
3253
+ this.logger.log(`[${commandId}] - request sent from correct collaborator with id ${instance.instance}. Returning channel`);
3254
+ return privateChannel;
2992
3255
  }
3256
+ const errorMsg = `Cannot proceed with action ${action} - ${channelCollaborator
3257
+ ? `private channel ${correlationId} established communication with collaborator with id ${channelCollaborator}`
3258
+ : `no collaborator joined private channel with id ${correlationId}`}`;
3259
+ this.logger.error(errorMsg);
3260
+ throw new Error(errorMsg);
3261
+ }
3262
+ handleJoin(eventArgs, instance, commandId) {
3263
+ return __awaiter(this, void 0, void 0, function* () {
3264
+ const collaborator = { appId: instance.application || instance.applicationName, instanceId: instance.instance };
3265
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3266
+ yield privateChannel.handleCollaboratorJoin(collaborator, commandId);
3267
+ this.logger.log(`[${commandId}] - collaborator ${JSON.stringify(collaborator)} set for private channel with id ${eventArgs.correlationId}`);
3268
+ });
3269
+ }
3270
+ handlePublish(eventArgs, instance, commandId) {
3271
+ var _a, _b;
3272
+ 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`);
3273
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3274
+ const metadata = {
3275
+ source: {
3276
+ appId: instance.application || instance.applicationName || "",
3277
+ instanceId: instance.instance
3278
+ }
3279
+ };
3280
+ privateChannel.handleCollaboratorBroadcast((_b = eventArgs.collaborationObject) === null || _b === void 0 ? void 0 : _b.payload, metadata, commandId);
3281
+ }
3282
+ handleContextListenerAdded(eventArgs, instance, commandId) {
3283
+ var _a;
3284
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onAddContextListener' callbacks`);
3285
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3286
+ privateChannel.handleCollaboratorAddContextListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
2993
3287
  }
2994
- handleOnDisconnect(payload) {
2995
- if (payload.replayContextTypes) {
2996
- this.invokeOnUnsubscribeHandlerMultipleTimes(payload);
3288
+ handleContextListenerRemoved(eventArgs, instance, commandId) {
3289
+ var _a;
3290
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onUnsubscribe' callbacks`);
3291
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3292
+ privateChannel.handleCollaboratorRemovedListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
3293
+ }
3294
+ handleDisconnect(eventArgs, instance, commandId) {
3295
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onDisconnect' callbacks`);
3296
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3297
+ privateChannel.handleCollaboratorDisconnect();
3298
+ }
3299
+ handleStartupContextOpened(eventArgs, instance, commandId) {
3300
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} with correlationId: ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3301
+ const wrappedPromise = this.appsStateStore.getOpenAppPromise(eventArgs.correlationId);
3302
+ if (!wrappedPromise) {
3303
+ this.logger.log(`[${commandId}] - there's no open app promise related to guid ${eventArgs.correlationId}`);
3304
+ return;
2997
3305
  }
2998
- this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnDisconnect, payload);
3306
+ this.logger.log(`[${commandId}] - resolving open app promise related to guid ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3307
+ wrappedPromise.resolve();
2999
3308
  }
3000
- invokeOnUnsubscribeHandlerMultipleTimes(payload) {
3001
- payload.replayContextTypes.forEach(contextType => {
3002
- this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnUnsubscribe, { channelId: payload.channelId, clientId: payload.clientId, contextType });
3003
- });
3309
+ }
3310
+
3311
+ class ApplicationsStateStore {
3312
+ constructor() {
3313
+ this.openAppPromises = {};
3314
+ }
3315
+ addOpenAppPromise(guid, promise) {
3316
+ this.openAppPromises[guid] = promise;
3317
+ }
3318
+ getOpenAppPromise(guid) {
3319
+ return this.openAppPromises[guid];
3320
+ }
3321
+ removeOpenAppPromise(guid) {
3322
+ delete this.openAppPromises[guid];
3004
3323
  }
3005
3324
  }
3006
3325
 
@@ -3010,7 +3329,7 @@ class IoC {
3010
3329
  }
3011
3330
  get eventReceiver() {
3012
3331
  if (!this._eventReceiver) {
3013
- this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher, this.eventsController);
3332
+ this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher);
3014
3333
  }
3015
3334
  return this._eventReceiver;
3016
3335
  }
@@ -3044,8 +3363,8 @@ class IoC {
3044
3363
  createAppChannel(id) {
3045
3364
  return new AppChannel(this.channelsController, id).toApi();
3046
3365
  }
3047
- createPrivateChannel(channelId) {
3048
- return new PrivateChannel(this.channelsController, channelId).toApi();
3366
+ createPrivateChannel(logger, channelId, isCreator) {
3367
+ return new PrivateChannel(this.channelsController, logger, channelId, isCreator);
3049
3368
  }
3050
3369
  get desktopAgent() {
3051
3370
  if (!this._desktopAgent) {
@@ -3061,19 +3380,19 @@ class IoC {
3061
3380
  }
3062
3381
  get intentsController() {
3063
3382
  if (!this._intentsController) {
3064
- this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory);
3383
+ this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory, this.eventsController);
3065
3384
  }
3066
3385
  return this._intentsController;
3067
3386
  }
3068
3387
  get applicationController() {
3069
3388
  if (!this._applicationController) {
3070
- this._applicationController = new ApplicationsController(this.glueController);
3389
+ this._applicationController = new ApplicationsController(this.glueController, this.applicationsStateStore, this.eventsController);
3071
3390
  }
3072
3391
  return this._applicationController;
3073
3392
  }
3074
3393
  get channelsController() {
3075
3394
  if (!this._channelsController) {
3076
- this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.channelsCallbackRegistry);
3395
+ this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.eventsController);
3077
3396
  }
3078
3397
  return this._channelsController;
3079
3398
  }
@@ -3083,18 +3402,18 @@ class IoC {
3083
3402
  }
3084
3403
  return this._channelsStateStore;
3085
3404
  }
3086
- get channelsCallbackRegistry() {
3087
- if (!this._channelsCallbackRegistry) {
3088
- this._channelsCallbackRegistry = new ChannelsCallbackRegistry();
3089
- }
3090
- return this._channelsCallbackRegistry;
3091
- }
3092
3405
  get eventsController() {
3093
3406
  if (!this._eventsController) {
3094
- this._eventsController = new GlueEventsController(this.glueController, this.channelsCallbackRegistry);
3407
+ this._eventsController = new GlueEventsController(this.glueController, this.channelsStateStore, this.applicationsStateStore);
3095
3408
  }
3096
3409
  return this._eventsController;
3097
3410
  }
3411
+ get applicationsStateStore() {
3412
+ if (!this._applicationsStateStore) {
3413
+ this._applicationsStateStore = new ApplicationsStateStore();
3414
+ }
3415
+ return this._applicationsStateStore;
3416
+ }
3098
3417
  }
3099
3418
 
3100
3419
  const fdc3Factory = () => {