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