@interopio/fdc3 2.1.1 → 2.1.3

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