@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.umd.js CHANGED
@@ -113,17 +113,95 @@
113
113
  const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
114
114
  const defaultContextProps = ["type"];
115
115
  const defaultGlue42APIs = ["contexts", "channels", "interop", "intents", "appManager", "windows"];
116
- const responseInteropMethodPrefix = "T42.FDC3.Open.Listener.Response";
117
116
  const glueChannelNamePrefix = "___channel___";
118
117
  const fdc3NothingContextType = "fdc3.nothing";
119
118
  const Glue42EnterpriseNoAppWindow = "no-app-window";
120
119
  const RaiseTimeoutMs = 75 * 1000;
121
- const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
120
+ const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
121
+ const Fdc3SupportedIntentTypes = {
122
+ "CreateInteraction": [
123
+ "fdc3.contactList",
124
+ "fdc3.interaction"
125
+ ],
126
+ "StartCall": [
127
+ "fdc3.contact",
128
+ "fdc3.contactList"
129
+ ],
130
+ "StartChat": [
131
+ "fdc3.contact",
132
+ "fdc3.contactList",
133
+ "fdc3.chat.initSettings"
134
+ ],
135
+ "StartEmail": [
136
+ "fdc3.email"
137
+ ],
138
+ "SendChatMessage": [
139
+ "fdc3.chat.message"
140
+ ],
141
+ "ViewAnalysis": [
142
+ "fdc3.instrument",
143
+ "fdc3.organization",
144
+ "fdc3.portfolio"
145
+ ],
146
+ "ViewChat": [
147
+ "fdc3.chat.room",
148
+ "fdc3.contact",
149
+ "fdc3.contactList"
150
+ ],
151
+ "ViewChart": [
152
+ "fdc3.chart",
153
+ "fdc3.instrument",
154
+ "fdc3.instrumentList",
155
+ "fdc3.portfolio",
156
+ "fdc3.position"
157
+ ],
158
+ "ViewHoldings": [
159
+ "fdc3.instrument",
160
+ "fdc3.instrumentList",
161
+ "fdc3.organization"
162
+ ],
163
+ "ViewInstrument": [
164
+ "fdc3.instrument"
165
+ ],
166
+ "ViewInteractions": [
167
+ "fdc3.contact",
168
+ "fdc3.instrument",
169
+ "fdc3.organization"
170
+ ],
171
+ "ViewMessages": [
172
+ "fdc3.chat.searchCriteria"
173
+ ],
174
+ "ViewNews": [
175
+ "fdc3.country",
176
+ "fdc3.instrument",
177
+ "fdc3.instrumentList",
178
+ "fdc3.organization",
179
+ "fdc3.portfolio"
180
+ ],
181
+ "ViewOrders": [
182
+ "fdc3.contact",
183
+ "fdc3.instrument",
184
+ "fdc3.organization"
185
+ ],
186
+ "ViewProfile": [
187
+ "fdc3.contact",
188
+ "fdc3.organization"
189
+ ],
190
+ "ViewQuote": [
191
+ "fdc3.instrument"
192
+ ],
193
+ "ViewResearch": [
194
+ "fdc3.contact",
195
+ "fdc3.instrument",
196
+ "fdc3.organization"
197
+ ]
198
+ };
122
199
 
123
- const Glue42FDC3SystemMethod = "T42.FDC3.Client.Control";
200
+ const ioConnectFDC3SystemMethod = "FDC3.Collaborate";
124
201
  const PrivateChannelPrefix = "___privateFDC3Channel___";
125
202
  var PrivateChannelEventMethods;
126
203
  (function (PrivateChannelEventMethods) {
204
+ PrivateChannelEventMethods["ListenerAdded"] = "listenerAdded";
127
205
  PrivateChannelEventMethods["OnAddContextListener"] = "onAddContextListener";
128
206
  PrivateChannelEventMethods["OnUnsubscribe"] = "onUnsubscribe";
129
207
  PrivateChannelEventMethods["OnDisconnect"] = "onDisconnect";
@@ -876,7 +954,7 @@
876
954
  /** See `Decoder.number` */
877
955
  var number = Decoder.number;
878
956
  /** See `Decoder.boolean` */
879
- var boolean = Decoder.boolean;
957
+ Decoder.boolean;
880
958
  /** See `Decoder.anyJson` */
881
959
  var anyJson = Decoder.anyJson;
882
960
  /** See `Decoder.unknownJson` */
@@ -948,31 +1026,35 @@
948
1026
  const optionalTargetApp = optional(appIdentifierDecoder);
949
1027
  const optionalAppIdentifier = optional(targetAppDecoder);
950
1028
  const optionalNonEmptyStringDecoder = optional(nonEmptyStringDecoder);
951
- const SystemMethodActionDecider = oneOf(constant(PrivateChannelEventMethods.OnAddContextListener), constant(PrivateChannelEventMethods.OnUnsubscribe), constant(PrivateChannelEventMethods.OnDisconnect));
952
- const SystemMethodEventPayloadDecoder = object({
953
- channelId: nonEmptyStringDecoder,
954
- clientId: nonEmptyStringDecoder,
955
- contextType: optional(string()),
956
- replayContextTypes: optional(array(string()))
1029
+ const SystemMethodActionDecoder = oneOf(constant("joinPrivateChannel"), constant("publishOnPrivateChannel"), constant("addedContextListenerOnPrivateChannel"), constant("removedContextListenerOnPrivateChannel"), constant("disconnectedFromPrivateChannel"), constant("startupContextOpened"));
1030
+ const CollaborationObjectDecoder = object({
1031
+ channelId: optional(nonEmptyStringDecoder),
1032
+ contextType: optional(nonEmptyStringDecoder),
1033
+ payload: optional(contextDecoder)
957
1034
  });
958
1035
  const SystemMethodInvocationArgumentDecoder = object({
959
- action: SystemMethodActionDecider,
960
- payload: SystemMethodEventPayloadDecoder
961
- });
962
- const ContextListenerResponseDecoder = object({
963
- listenerInvoked: optional(boolean())
1036
+ action: SystemMethodActionDecoder,
1037
+ correlationId: nonEmptyStringDecoder,
1038
+ collaborationObject: optional(CollaborationObjectDecoder)
964
1039
  });
965
- object({
966
- meta: object({
967
- responseMethodName: nonEmptyStringDecoder
968
- }),
969
- context: contextDecoder
1040
+ const FDC3StartupContextDecoder = object({
1041
+ fdc3: object({
1042
+ collaborationId: nonEmptyStringDecoder,
1043
+ openApp: object({
1044
+ appId: nonEmptyStringDecoder,
1045
+ instanceId: nonEmptyStringDecoder
1046
+ }),
1047
+ context: object({
1048
+ contextType: optional(string()),
1049
+ payload: contextDecoder
1050
+ })
1051
+ })
970
1052
  });
971
1053
 
972
1054
  class GlueController {
973
1055
  constructor(channelsParser) {
974
1056
  this.channelsParser = channelsParser;
975
- this.defaultGluePromiseTimeout = 120000;
1057
+ this.defaultGluePromiseTimeout = 120 * 1000;
976
1058
  }
977
1059
  get gluePromise() {
978
1060
  return this.glueInitPromise.then(this.initializeLogger.bind(this));
@@ -1028,6 +1110,15 @@
1028
1110
  return this.glue.intents.raise(request);
1029
1111
  });
1030
1112
  }
1113
+ getMyWindowContext() {
1114
+ return __awaiter(this, void 0, void 0, function* () {
1115
+ const myWin = this.getMyWindow();
1116
+ if (!myWin) {
1117
+ return;
1118
+ }
1119
+ return myWin.getContext();
1120
+ });
1121
+ }
1031
1122
  addIntentListener(intent, handler) {
1032
1123
  const registerMethodExists = this.glue.intents.register;
1033
1124
  return registerMethodExists
@@ -1095,8 +1186,8 @@
1095
1186
  const win = this.glue.windows.my();
1096
1187
  return isValidNonEmptyObject(win) ? win : undefined;
1097
1188
  }
1098
- getMyInteropInstanceId() {
1099
- return this.glue.interop.instance.instance;
1189
+ getMyInteropInstance() {
1190
+ return this.glue.interop.instance;
1100
1191
  }
1101
1192
  getGlueVersion() {
1102
1193
  var _a;
@@ -1105,21 +1196,14 @@
1105
1196
  registerOnInstanceStopped(cb) {
1106
1197
  return this.glue.appManager.onInstanceStopped(cb);
1107
1198
  }
1108
- invokeMethod(methodName, instance, argumentObj) {
1109
- return __awaiter(this, void 0, void 0, function* () {
1110
- const args = ContextListenerResponseDecoder.runWithException(argumentObj);
1111
- return this.glue.interop.invoke(methodName, args, { instance });
1112
- });
1113
- }
1114
1199
  unregisterMethod(methodName) {
1115
1200
  return __awaiter(this, void 0, void 0, function* () {
1116
1201
  return this.glue.interop.unregister(methodName);
1117
1202
  });
1118
1203
  }
1119
- invokeSystemMethod(argumentObj) {
1120
- const args = SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1121
- const target = args.payload.clientId;
1122
- return this.glue.interop.invoke(Glue42FDC3SystemMethod, args, { instance: target });
1204
+ invokeSystemMethod(argumentObj, target) {
1205
+ SystemMethodInvocationArgumentDecoder.runWithException(argumentObj);
1206
+ return this.glue.interop.invoke(ioConnectFDC3SystemMethod, argumentObj, { instance: target });
1123
1207
  }
1124
1208
  registerMethod(name, handler) {
1125
1209
  return this.glue.interop.register(name, handler);
@@ -1129,21 +1213,16 @@
1129
1213
  }
1130
1214
  channelsSubscribe(callback, contextType) {
1131
1215
  const didReplay = { replayed: false };
1132
- return this.glue.channels.subscribe((_, context, updaterId) => __awaiter(this, void 0, void 0, function* () {
1133
- if (this.isUpdateFromMe(updaterId) || !context) {
1216
+ return this.glue.channels.subscribe((_, contextData, updaterId) => {
1217
+ if (this.isUpdateFromMe(updaterId) || !contextData || !contextData.latest_fdc3_type) {
1134
1218
  return;
1135
1219
  }
1136
- const contextData = yield this.glue.contexts.get(`${glueChannelNamePrefix}${context.name}`);
1137
- if (!contextData.latest_fdc3_type) {
1138
- return;
1139
- }
1140
- if (!didReplay.replayed) {
1141
- this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1142
- didReplay.replayed = true;
1143
- return;
1220
+ if (didReplay.replayed) {
1221
+ return this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1144
1222
  }
1145
- this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1146
- }));
1223
+ this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
1224
+ didReplay.replayed = true;
1225
+ });
1147
1226
  }
1148
1227
  contextsSubscribe(contextName, callback) {
1149
1228
  const didReplay = { replayed: false };
@@ -1164,10 +1243,11 @@
1164
1243
  return this.logger.subLogger(name);
1165
1244
  }
1166
1245
  invokePreviouslyBroadcastedData({ callback, contextData, metadata, contextType }) {
1167
- if (!contextData.latest_fdc3_type) {
1168
- return;
1246
+ const invokeForType = contextType || this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
1247
+ const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, invokeForType);
1248
+ if (dataForContextType) {
1249
+ callback(dataForContextType, metadata);
1169
1250
  }
1170
- this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata, contextType });
1171
1251
  }
1172
1252
  isUpdateFromMe(updaterId) {
1173
1253
  return this.glue.interop.instance.peerId === updaterId;
@@ -1189,19 +1269,22 @@
1189
1269
  }
1190
1270
  parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata, contextType }) {
1191
1271
  if (!contextType) {
1192
- const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data(contextData);
1272
+ const parsedData = this.channelsParser.parseContextsDataToInitialFDC3Data({ data: contextData.data, latest_fdc3_type: contextData.latest_fdc3_type });
1193
1273
  callback(parsedData, metadata);
1194
1274
  return;
1195
1275
  }
1196
- const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, contextType);
1197
- if (!dataForContextType) {
1276
+ const latestPublishedType = this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
1277
+ if (latestPublishedType !== contextType) {
1198
1278
  return;
1199
1279
  }
1200
- callback(dataForContextType, metadata);
1280
+ const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, contextType);
1281
+ if (dataForContextType) {
1282
+ callback(dataForContextType, metadata);
1283
+ }
1201
1284
  }
1202
1285
  getLatestBroadcastedDataByContextType(contextData, contextType) {
1203
1286
  let foundData;
1204
- Object.entries(contextData.data).find(([key, value]) => {
1287
+ Object.entries(contextData.data).forEach(([key, value]) => {
1205
1288
  if (!this.channelsParser.isFdc3DataKey(key)) {
1206
1289
  return;
1207
1290
  }
@@ -1263,6 +1346,7 @@
1263
1346
  }
1264
1347
  toApi() {
1265
1348
  const api = {
1349
+ getStartupContext: this.getStartupContext.bind(this),
1266
1350
  addContextListener: this.addContextListener.bind(this),
1267
1351
  addIntentListener: this.addIntentListener.bind(this),
1268
1352
  broadcast: this.broadcast.bind(this),
@@ -1375,6 +1459,11 @@
1375
1459
  return this.intentsController.addIntentListener({ commandId: generateCommandId(), intent, handler });
1376
1460
  });
1377
1461
  }
1462
+ getStartupContext() {
1463
+ return __awaiter(this, void 0, void 0, function* () {
1464
+ return this.channelsController.getStartupContext();
1465
+ });
1466
+ }
1378
1467
  getOrCreateChannel(channelId) {
1379
1468
  return __awaiter(this, void 0, void 0, function* () {
1380
1469
  nonEmptyStringDecoder.runWithException(channelId);
@@ -1497,76 +1586,60 @@
1497
1586
  * SPDX-License-Identifier: Apache-2.0
1498
1587
  * Copyright FINOS FDC3 contributors - see NOTICE file
1499
1588
  */
1500
-
1501
1589
  /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
1502
1590
  var OpenError;
1503
-
1504
1591
  (function (OpenError) {
1505
1592
  /** Returned if the specified application is not found.*/
1506
1593
  OpenError["AppNotFound"] = "AppNotFound";
1507
1594
  /** Returned if the specified application fails to launch correctly.*/
1508
-
1509
1595
  OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
1510
1596
  /** 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.*/
1511
-
1512
1597
  OpenError["AppTimeout"] = "AppTimeout";
1513
1598
  /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1514
-
1515
1599
  OpenError["ResolverUnavailable"] = "ResolverUnavailable";
1600
+ /** 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.*/
1601
+ OpenError["MalformedContext"] = "MalformedContext";
1516
1602
  })(OpenError || (OpenError = {}));
1517
1603
  /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
1518
-
1519
-
1520
1604
  var ResolveError;
1521
-
1522
1605
  (function (ResolveError) {
1523
1606
  /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
1524
1607
  ResolveError["NoAppsFound"] = "NoAppsFound";
1525
1608
  /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
1526
-
1527
1609
  ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
1528
1610
  /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
1529
-
1530
1611
  ResolveError["UserCancelled"] = "UserCancelledResolution";
1531
1612
  /** 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.*/
1532
-
1533
1613
  ResolveError["ResolverTimeout"] = "ResolverTimeout";
1534
1614
  /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
1535
-
1536
1615
  ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
1537
1616
  /** Returned if a specified target application instance is not available, for example because it has been closed. */
1538
-
1539
1617
  ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
1540
1618
  /** 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.*/
1541
-
1542
1619
  ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
1620
+ /** 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.*/
1621
+ ResolveError["MalformedContext"] = "MalformedContext";
1543
1622
  })(ResolveError || (ResolveError = {}));
1544
-
1545
1623
  var ResultError;
1546
-
1547
1624
  (function (ResultError) {
1548
- /** Returned if the intent handler exited without returning a Promise or that Promise was not resolved with a Context or Channel object. */
1625
+ /** Returned if the intent handler exited without returning a valid result (a promise resolving to a Context, Channel object or void). */
1549
1626
  ResultError["NoResultReturned"] = "NoResultReturned";
1550
1627
  /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
1551
-
1552
1628
  ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
1553
1629
  })(ResultError || (ResultError = {}));
1554
-
1555
1630
  var ChannelError;
1556
-
1557
1631
  (function (ChannelError) {
1558
1632
  /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
1559
1633
  ChannelError["NoChannelFound"] = "NoChannelFound";
1560
1634
  /** 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. */
1561
-
1562
1635
  ChannelError["AccessDenied"] = "AccessDenied";
1563
1636
  /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
1564
-
1565
1637
  ChannelError["CreationFailed"] = "CreationFailed";
1638
+ /** 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.*/
1639
+ ChannelError["MalformedContext"] = "MalformedContext";
1566
1640
  })(ChannelError || (ChannelError = {}));
1567
1641
 
1568
1642
  var ContextTypes;
1569
-
1570
1643
  (function (ContextTypes) {
1571
1644
  ContextTypes["Chart"] = "fdc3.chart";
1572
1645
  ContextTypes["ChatInitSettings"] = "fdc3.chat.initSettings";
@@ -1587,13 +1660,13 @@
1587
1660
 
1588
1661
  // To parse this data:
1589
1662
  //
1590
- // import { Convert, Context, Chart, ChatInitSettings, Contact, ContactList, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1663
+ // import { Convert, Chart, ChatInitSettings, Contact, ContactList, Context, Country, Currency, Email, Instrument, InstrumentList, Nothing, Organization, Portfolio, Position, TimeRange, Valuation } from "./file";
1591
1664
  //
1592
- // const context = Convert.toContext(json);
1593
1665
  // const chart = Convert.toChart(json);
1594
1666
  // const chatInitSettings = Convert.toChatInitSettings(json);
1595
1667
  // const contact = Convert.toContact(json);
1596
1668
  // const contactList = Convert.toContactList(json);
1669
+ // const context = Convert.toContext(json);
1597
1670
  // const country = Convert.toCountry(json);
1598
1671
  // const currency = Convert.toCurrency(json);
1599
1672
  // const email = Convert.toEmail(json);
@@ -1609,7 +1682,6 @@
1609
1682
  // These functions will throw an error if the JSON doesn't
1610
1683
  // match the expected interface, even if the JSON is valid.
1611
1684
  var Style;
1612
-
1613
1685
  (function (Style) {
1614
1686
  Style["Bar"] = "bar";
1615
1687
  Style["Candle"] = "candle";
@@ -1621,10 +1693,9 @@
1621
1693
  Style["Pie"] = "pie";
1622
1694
  Style["Scatter"] = "scatter";
1623
1695
  Style["StackedBar"] = "stacked-bar";
1624
- })(Style || (Style = {})); // Converts JSON strings to/from your types
1696
+ })(Style || (Style = {}));
1625
1697
 
1626
1698
  var Intents;
1627
-
1628
1699
  (function (Intents) {
1629
1700
  Intents["StartCall"] = "StartCall";
1630
1701
  Intents["StartChat"] = "StartChat";
@@ -1700,15 +1771,11 @@
1700
1771
  const isContext = (data) => {
1701
1772
  return defaultContextProps.every(prop => Object.keys(data).includes(prop));
1702
1773
  };
1703
- const isChannelMetadata = (data) => {
1704
- return typeof data === "object" && data.isChannel;
1705
- };
1706
1774
  const extractChannelMetadata = (channel) => {
1707
1775
  return {
1708
1776
  id: channel.id,
1709
1777
  type: channel.type,
1710
- displayMetadata: channel.displayMetadata,
1711
- isChannel: true
1778
+ displayMetadata: channel.displayMetadata
1712
1779
  };
1713
1780
  };
1714
1781
  const parseContextHandler = (handler, contextType) => {
@@ -1725,10 +1792,11 @@
1725
1792
  };
1726
1793
 
1727
1794
  class IntentsController {
1728
- constructor(glueController, channelsController, channelsFactory) {
1795
+ constructor(glueController, channelsController, channelsFactory, glueEventsController) {
1729
1796
  this.glueController = glueController;
1730
1797
  this.channelsController = channelsController;
1731
1798
  this.channelsFactory = channelsFactory;
1799
+ this.glueEventsController = glueEventsController;
1732
1800
  }
1733
1801
  get logger() {
1734
1802
  if (!this._logger) {
@@ -1820,11 +1888,33 @@
1820
1888
  });
1821
1889
  }
1822
1890
  addIntentListener({ commandId, intent, handler }) {
1891
+ var _a, _b;
1823
1892
  return __awaiter(this, void 0, void 0, function* () {
1824
1893
  yield this.glueController.gluePromise;
1825
1894
  this.logger.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
1826
1895
  const wrappedHandler = this.getWrappedIntentHandler(handler);
1827
- return this.glueController.addIntentListener(intent, wrappedHandler);
1896
+ const myInstance = this.glueController.getMyInteropInstance();
1897
+ const myApplication = this.glueController.getApplication(myInstance.applicationName);
1898
+ let appConfigIntentDef;
1899
+ const globalBrowserNamespace = window.glue42core || window.iobrowser;
1900
+ const globalDesktopNamespace = window.glue42gd || window.iodesktop;
1901
+ if (globalBrowserNamespace) {
1902
+ appConfigIntentDef = (_a = myApplication === null || myApplication === void 0 ? void 0 : myApplication.userProperties.intents) === null || _a === void 0 ? void 0 : _a.find((appIntent) => appIntent.name === intent);
1903
+ }
1904
+ if (globalDesktopNamespace) {
1905
+ const appConfig = yield myApplication.getConfiguration();
1906
+ appConfigIntentDef = (_b = appConfig === null || appConfig === void 0 ? void 0 : appConfig.intents) === null || _b === void 0 ? void 0 : _b.find((appIntent) => appIntent.name === intent);
1907
+ }
1908
+ const intentRequest = {
1909
+ intent,
1910
+ displayName: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.displayName,
1911
+ description: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.description,
1912
+ contextTypes: (appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.contexts) || Fdc3SupportedIntentTypes[intent],
1913
+ resultType: appConfigIntentDef === null || appConfigIntentDef === void 0 ? void 0 : appConfigIntentDef.resultType
1914
+ };
1915
+ Object.keys(intentRequest)
1916
+ .forEach((key) => intentRequest[key] === undefined && delete intentRequest[key]);
1917
+ return this.glueController.addIntentListener(intentRequest, wrappedHandler);
1828
1918
  });
1829
1919
  }
1830
1920
  filterGlueIntentHandlers({ commandId, intent, context, target }) {
@@ -1844,7 +1934,7 @@
1844
1934
  this.logger.info(`[${commandId}] - Checking if application with name ${appName} exists`);
1845
1935
  const app = this.glueController.getApplication(appName);
1846
1936
  const serverInstances = this.serverInstanceAsIntentHandler(intent.name);
1847
- if (!app && (typeof target === "string" || !serverInstances.length)) {
1937
+ if (!app && (typeof target === "string" || !target.instanceId || !serverInstances.length)) {
1848
1938
  throw { message: ResolveError.TargetAppUnavailable, reason: `There's no app with appId ${appName}` };
1849
1939
  }
1850
1940
  this.logger.info(`[${commandId}] - target app ${appName} found. Filtering handlers by applicationName: ${appName}`);
@@ -1890,23 +1980,33 @@
1890
1980
  if (!isValidNonEmptyObject(result)) {
1891
1981
  return;
1892
1982
  }
1893
- const isResultChannelMetadata = isChannelMetadata(result);
1894
- if (!isResultChannelMetadata) {
1983
+ if (!result.fdc3intentChannel && !result.fdc3intentContext) {
1895
1984
  return result;
1896
1985
  }
1897
- const { clientId, creatorId } = yield this.glueController.getContext(result.id);
1898
- this.logger.info(`[${commandId}] - result is a private channel with creatorId ${creatorId} and clientId ${clientId}`);
1899
- const myInteropInstanceId = this.glueController.getMyInteropInstanceId();
1900
- if ((creatorId && creatorId !== myInteropInstanceId) && (clientId && clientId !== myInteropInstanceId)) {
1901
- throw { message: ResultError.NoResultReturned, reason: "There are already two parties on this private channel" };
1902
- }
1903
- const channel = this.channelsFactory.buildModel(result);
1904
- if (myInteropInstanceId && myInteropInstanceId !== creatorId) {
1905
- this.logger.info(`[${commandId}] - the current user is the second party of the private channel. Adding my id ${myInteropInstanceId} as a clientId`);
1906
- yield this.channelsController.addClientToPrivateChannel(commandId, channel.id, myInteropInstanceId);
1907
- }
1986
+ if (result.fdc3intentContext) {
1987
+ return result.fdc3intentContext.payload;
1988
+ }
1989
+ const { fdc3intentChannel } = result;
1990
+ if (fdc3intentChannel.type === "user") {
1991
+ const glueChannel = (yield this.glueController.listAllChannels()).find(ch => ch.name === fdc3intentChannel.displayMetadata.name);
1992
+ return this.channelsFactory.buildModel(Object.assign(Object.assign({}, fdc3intentChannel), { displayMetadata: Object.assign(Object.assign({}, fdc3intentChannel.displayMetadata), { glueChannel }) }));
1993
+ }
1994
+ if (fdc3intentChannel.type !== "private") {
1995
+ return this.channelsFactory.buildModel(fdc3intentChannel);
1996
+ }
1997
+ yield this.glueEventsController.initializeCollaborateMethod();
1998
+ const channel = this.channelsController.buildPrivateChannel(fdc3intentChannel.id, commandId, false);
1999
+ channel.setCollaborator({ appId: glueIntentResult.handler.applicationName, instanceId: glueIntentResult.handler.instanceId }, commandId);
2000
+ const joinChannelArgs = {
2001
+ action: "joinPrivateChannel",
2002
+ correlationId: channel.id,
2003
+ collaborationObject: {
2004
+ channelId: channel.id
2005
+ }
2006
+ };
2007
+ yield this.glueController.invokeSystemMethod(joinChannelArgs, glueIntentResult.handler.instanceId);
1908
2008
  this.logger.info(`[${commandId}] - returning private channel`);
1909
- return channel;
2009
+ return channel.toApi();
1910
2010
  });
1911
2011
  }
1912
2012
  convertGlue42IntentToFDC3Intent(glueIntent) {
@@ -1941,15 +2041,23 @@
1941
2041
  throw new Error("Async handler function should return a promise that resolves to a Context or Channel");
1942
2042
  }
1943
2043
  getWrappedIntentHandler(handler) {
1944
- const wrappedHandler = (glue42Context) => __awaiter(this, void 0, void 0, function* () {
1945
- const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }));
2044
+ const wrappedHandler = (glue42Context, caller) => __awaiter(this, void 0, void 0, function* () {
2045
+ const contextMetadata = caller
2046
+ ? {
2047
+ source: {
2048
+ appId: caller.application || caller.applicationName || "",
2049
+ instanceId: caller.instance
2050
+ }
2051
+ }
2052
+ : undefined;
2053
+ const handlerResult = yield handler(Object.assign(Object.assign({}, glue42Context.data), { type: glue42Context.type || "" }), contextMetadata);
1946
2054
  if (!handlerResult) {
1947
2055
  return;
1948
2056
  }
1949
2057
  const handlerResultType = this.getResultType(handlerResult);
1950
2058
  return handlerResultType === IntentHandlerResultTypes.Channel
1951
- ? extractChannelMetadata(handlerResult)
1952
- : handlerResult;
2059
+ ? { fdc3intentChannel: extractChannelMetadata(handlerResult) }
2060
+ : { fdc3intentContext: { contextType: handlerResult.type, payload: handlerResult } };
1953
2061
  });
1954
2062
  return wrappedHandler;
1955
2063
  }
@@ -1996,13 +2104,14 @@
1996
2104
  }
1997
2105
  }
1998
2106
 
1999
- var version = "2.1.1";
2107
+ var version = "2.1.3";
2000
2108
 
2001
2109
  class ApplicationsController {
2002
- constructor(glueController) {
2110
+ constructor(glueController, appsStateStore, glueEventsController) {
2003
2111
  this.glueController = glueController;
2004
- this.defaultContextListenerInvokedPromiseTimeout = 60000;
2005
- this.contextListenerInvokedPromises = {};
2112
+ this.appsStateStore = appsStateStore;
2113
+ this.glueEventsController = glueEventsController;
2114
+ this.defaultContextListenerInvokedPromiseTimeout = 120 * 1000;
2006
2115
  }
2007
2116
  get logger() {
2008
2117
  if (!this._logger) {
@@ -2020,6 +2129,7 @@
2020
2129
  throw { message: OpenError.AppNotFound, reason: `Cannot find targeted ${name} application` };
2021
2130
  }
2022
2131
  if (context) {
2132
+ yield this.glueEventsController.initializeCollaborateMethod();
2023
2133
  this.logger.info(`[${commandId}] - opening app ${app} with startup context`);
2024
2134
  return this.openAppWithContext(app, context);
2025
2135
  }
@@ -2135,41 +2245,39 @@
2135
2245
  }
2136
2246
  openAppWithContext(app, context) {
2137
2247
  return __awaiter(this, void 0, void 0, function* () {
2138
- const methodName = yield this.registerContextListenerInteropMethod();
2139
- const startContext = this.buildGlueStartContext(context, methodName);
2140
- const glueInst = yield app.start(startContext);
2141
- this.createContextListenerResponsePromise(glueInst, methodName);
2248
+ const guid = nanoid();
2249
+ const startContext = this.buildStartContext(context, guid);
2250
+ const wrappedPromise = this.createContextListenerWrappedPromise(app);
2251
+ this.appsStateStore.addOpenAppPromise(guid, wrappedPromise);
2142
2252
  try {
2143
- yield this.contextListenerInvokedPromises[glueInst.id].promise;
2144
- yield this.unregisterContextListenerPromise(glueInst.id);
2253
+ const glueInst = yield app.start(startContext);
2254
+ yield wrappedPromise.promise;
2255
+ this.appsStateStore.removeOpenAppPromise(guid);
2145
2256
  return this.parseGlueInstToAppIdentifier(glueInst);
2146
2257
  }
2147
2258
  catch (error) {
2148
- yield this.unregisterContextListenerPromise(glueInst.id);
2259
+ this.appsStateStore.removeOpenAppPromise(guid);
2149
2260
  throw { message: OpenError.AppTimeout, reason: typeof error === "string" ? error : JSON.stringify(error) };
2150
2261
  }
2151
2262
  });
2152
2263
  }
2153
- buildGlueStartContext(fdc3Context, responseMethodName) {
2264
+ buildStartContext(fdc3Context, guid) {
2265
+ const myInteropInstance = this.glueController.getMyInteropInstance();
2154
2266
  return {
2155
- meta: {
2156
- responseMethodName,
2157
- instance: this.glueController.interopInstance().instance
2158
- },
2159
- context: fdc3Context
2267
+ fdc3: {
2268
+ collaborationId: guid,
2269
+ openApp: {
2270
+ appId: myInteropInstance.application || myInteropInstance.applicationName || "",
2271
+ instanceId: myInteropInstance.instance
2272
+ },
2273
+ context: {
2274
+ contextType: fdc3Context.type,
2275
+ payload: fdc3Context
2276
+ }
2277
+ }
2160
2278
  };
2161
2279
  }
2162
- registerContextListenerInteropMethod() {
2163
- return __awaiter(this, void 0, void 0, function* () {
2164
- const methodName = this.buildInteropMethodName();
2165
- yield this.glueController.registerMethod(methodName, this.contextListenerResponseHandler.bind(this));
2166
- return methodName;
2167
- });
2168
- }
2169
- buildInteropMethodName() {
2170
- return `${responseInteropMethodPrefix}.${nanoid()}`;
2171
- }
2172
- createContextListenerResponsePromise(instance, methodName) {
2280
+ createContextListenerWrappedPromise(app) {
2173
2281
  let resolve = () => { };
2174
2282
  let reject = () => { };
2175
2283
  const promise = promisePlus(() => {
@@ -2177,50 +2285,32 @@
2177
2285
  resolve = res;
2178
2286
  reject = rej;
2179
2287
  });
2180
- }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${instance.application.name} and instanceId: ${instance.id} to register context listener`);
2181
- this.contextListenerInvokedPromises[instance.id] = { promise, resolve, reject, methodName };
2182
- }
2183
- contextListenerResponseHandler(args, callerId) {
2184
- const result = ContextListenerResponseDecoder.run(args);
2185
- if (!result.ok) {
2186
- const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2187
- if (!contextListenerPromise) {
2188
- return;
2189
- }
2190
- contextListenerPromise.reject(`Method invoked with invalid argument - ${result.error.message}`);
2191
- return;
2192
- }
2193
- const contextListenerPromise = this.contextListenerInvokedPromises[callerId.instance];
2194
- if (!contextListenerPromise) {
2195
- return;
2196
- }
2197
- contextListenerPromise.resolve();
2198
- }
2199
- unregisterContextListenerPromise(instanceId) {
2200
- return __awaiter(this, void 0, void 0, function* () {
2201
- const { methodName } = this.contextListenerInvokedPromises[instanceId];
2202
- yield this.glueController.unregisterMethod(methodName);
2203
- delete this.contextListenerInvokedPromises[instanceId];
2204
- });
2288
+ }, this.defaultContextListenerInvokedPromiseTimeout, `Timeout of ${this.defaultContextListenerInvokedPromiseTimeout}ms hit waiting for application with appId: ${app.name} to register context listener`);
2289
+ return { promise, resolve, reject };
2205
2290
  }
2206
2291
  }
2207
2292
 
2208
2293
  class ChannelsController {
2209
- constructor(glueController, channelsStateStore, channelsParser, channelsFactory, channelsCallbackRegistry) {
2294
+ constructor(glueController, channelsStateStore, channelsParser, channelsFactory, glueEventsController) {
2210
2295
  this.glueController = glueController;
2211
2296
  this.channelsStateStore = channelsStateStore;
2212
2297
  this.channelsParser = channelsParser;
2213
2298
  this.channelsFactory = channelsFactory;
2214
- this.channelsCallbackRegistry = channelsCallbackRegistry;
2299
+ this.glueEventsController = glueEventsController;
2215
2300
  this.invokeContextHandlerWithStartupContext = true;
2216
2301
  this.initDonePromise = this.initialize();
2217
- this.initDonePromise.catch(() => { });
2302
+ this.initDonePromise.catch((err) => {
2303
+ var _a;
2304
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.error(err);
2305
+ });
2218
2306
  }
2219
- get logger() {
2220
- if (!this._logger) {
2221
- this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2222
- }
2223
- return this._logger;
2307
+ getStartupContext() {
2308
+ var _a, _b;
2309
+ return __awaiter(this, void 0, void 0, function* () {
2310
+ yield this.initDonePromise;
2311
+ const fdc3StartupContext = yield this.glueController.getMyWindowContext();
2312
+ 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;
2313
+ });
2224
2314
  }
2225
2315
  addContextListener({ commandId, handler, contextType, channelId }) {
2226
2316
  var _a;
@@ -2258,14 +2348,14 @@
2258
2348
  return __awaiter(this, void 0, void 0, function* () {
2259
2349
  yield this.initDonePromise;
2260
2350
  this.logger.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
2261
- const isPrivateChannel = this.isPrivateChannel(channelId);
2262
- if (isPrivateChannel) {
2263
- throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2264
- }
2265
2351
  const isUserChannel = this.isUserChannel(channelId);
2266
2352
  if (isUserChannel) {
2267
2353
  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" };
2268
2354
  }
2355
+ const isPrivateChannel = this.channelsStateStore.getPrivateChannelById(channelId);
2356
+ if (isPrivateChannel) {
2357
+ throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
2358
+ }
2269
2359
  return this.getOrCreateAppChannel(commandId, channelId);
2270
2360
  });
2271
2361
  }
@@ -2343,26 +2433,28 @@
2343
2433
  return __awaiter(this, void 0, void 0, function* () {
2344
2434
  yield this.initDonePromise;
2345
2435
  this.logger.info(`[${commandId}] - createPrivateChannel() invoked`);
2346
- const creatorId = this.glueController.getMyInteropInstanceId();
2347
- const channel = this.buildChannel(ChannelTypes.Private);
2348
- yield this.glueController.updateContext(channel.id, { creatorId });
2349
- this.logger.info(`[${commandId}] - private channel with id ${channel.id} created`);
2350
- return channel;
2436
+ const channelId = `${PrivateChannelPrefix}${nanoid()}`;
2437
+ yield this.glueEventsController.initializeCollaborateMethod();
2438
+ const pc = this.buildPrivateChannel(channelId, commandId, true);
2439
+ return pc.toApi();
2351
2440
  });
2352
2441
  }
2353
- announceDisconnect(commandId, channelId, instanceId) {
2442
+ removePrivateChannelFromStoreById(id) {
2354
2443
  return __awaiter(this, void 0, void 0, function* () {
2355
- yield this.initDonePromise;
2356
- this.logger.info(`[${commandId}] - disconnect() invoked on channel with id ${channelId}`);
2357
- yield this.glueController.updateContext(channelId, { disconnected: true });
2358
- this.logger.info(`[${commandId}] - glue context for ${channelId} updated with disconnected flag`);
2359
- const closedInstanceId = instanceId || this.glueController.getMyInteropInstanceId();
2360
- const targetInstance = yield this.getOtherInstanceIdFromClosedOne(channelId, closedInstanceId);
2361
- const replayContextTypes = yield this.getContextTypesForPrivateChannel(channelId);
2362
- this.logger.info(`[${commandId}] - invoking onDisconnect callback for instance ${targetInstance}`);
2363
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnDisconnect, { clientId: targetInstance, channelId, replayContextTypes });
2444
+ this.channelsStateStore.removePrivateChannelById(id);
2445
+ });
2446
+ }
2447
+ invokeSystemMethod(args, target) {
2448
+ return __awaiter(this, void 0, void 0, function* () {
2449
+ if (!target) {
2450
+ return;
2451
+ }
2452
+ return this.glueController.invokeSystemMethod(args, target);
2364
2453
  });
2365
2454
  }
2455
+ getMyServerInstance() {
2456
+ return this.glueController.getMyInteropInstance();
2457
+ }
2366
2458
  addClientToPrivateChannel(commandId, channelId, clientId) {
2367
2459
  return __awaiter(this, void 0, void 0, function* () {
2368
2460
  this.logger.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
@@ -2376,28 +2468,22 @@
2376
2468
  return !!context.disconnected;
2377
2469
  });
2378
2470
  }
2379
- registerOnInstanceStopped({ commandId, channelId }) {
2380
- this.logger.info(`[${commandId}] - registering onInstanceStopped callback for channel with id ${channelId}`);
2381
- const handler = (instance) => __awaiter(this, void 0, void 0, function* () {
2382
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2383
- if (instance.id !== clientId && instance.id !== creatorId) {
2384
- return;
2385
- }
2386
- this.logger.info(`[${commandId}] - calling onDisconnect callback for channel with id ${channelId}`);
2387
- yield this.announceDisconnect(commandId, channelId, instance.id);
2388
- });
2471
+ subscribeOnInstanceStop(channelId, handler, commandId) {
2472
+ this.logger.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
2389
2473
  return this.glueController.registerOnInstanceStopped(handler.bind(this));
2390
2474
  }
2391
- addPrivateChannelEvent({ commandId, action, channelId, handler }) {
2392
- return __awaiter(this, void 0, void 0, function* () {
2393
- this.logger.info(`[${commandId}] - registering callback for ${action} event in channel with id ${channelId}`);
2394
- let replayArgs;
2395
- const targetInstanceId = yield this.getTargetedInstanceId(channelId);
2396
- if (action === PrivateChannelEventMethods.OnAddContextListener && targetInstanceId) {
2397
- replayArgs = yield this.getContextTypesForPrivateChannel(channelId);
2398
- }
2399
- return this.channelsCallbackRegistry.add({ action, channelId, handler, replayArgs });
2400
- });
2475
+ buildPrivateChannel(channelId, commandId, isCreator) {
2476
+ const logger = this.glueController.initSubLogger(channelId);
2477
+ const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
2478
+ this.logger.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
2479
+ this.channelsStateStore.addPrivateChannel(channel);
2480
+ return channel;
2481
+ }
2482
+ get logger() {
2483
+ if (!this._logger) {
2484
+ this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
2485
+ }
2486
+ return this._logger;
2401
2487
  }
2402
2488
  initialize() {
2403
2489
  return __awaiter(this, void 0, void 0, function* () {
@@ -2446,39 +2532,43 @@
2446
2532
  return __awaiter(this, void 0, void 0, function* () {
2447
2533
  const myWindow = this.glueController.getMyWindow();
2448
2534
  if (!myWindow) {
2449
- this.logger.log(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
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
2539
  const windowContext = yield myWindow.getContext();
2454
- if (!isValidNonEmptyObject(windowContext)) {
2455
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2540
+ if (!windowContext) {
2541
+ this.logger.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
2456
2542
  this.invokeContextHandlerWithStartupContext = false;
2457
2543
  return;
2458
2544
  }
2459
- const { context, meta } = windowContext;
2460
- const isSameContextType = contextType ? (context === null || context === void 0 ? void 0 : context.type) === contextType : true;
2461
- if (!isSameContextType || !meta) {
2462
- this.logger.info(`[${commandId}] - addContextListener handler won't be invoked`);
2545
+ if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
2546
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
2547
+ this.invokeContextHandlerWithStartupContext = false;
2463
2548
  return;
2464
2549
  }
2465
- this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context`);
2466
- handler(context);
2467
- this.invokeContextHandlerWithStartupContext = false;
2468
- const { responseMethodName, instance } = meta;
2469
- const responseMethodExists = this.doesServerMethodExist(responseMethodName, instance);
2470
- if (!responseMethodExists) {
2471
- this.logger.info(`[${commandId}] - response method for instance ${instance} does not exist anymore. returning`);
2550
+ yield this.glueEventsController.initializeCollaborateMethod();
2551
+ FDC3StartupContextDecoder.runWithException(windowContext);
2552
+ const { fdc3 } = windowContext;
2553
+ this.logger.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
2554
+ const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
2555
+ if (!isSameContextType) {
2556
+ this.logger.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
2472
2557
  return;
2473
2558
  }
2474
- this.logger.info(`[${commandId}] - invoking response method for instance ${instance}`);
2475
- yield this.glueController.invokeMethod(responseMethodName, instance, { listenerInvoked: true });
2559
+ this.logger.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
2560
+ try {
2561
+ handler(fdc3.context.payload, { source: fdc3.openApp });
2562
+ }
2563
+ catch (error) {
2564
+ this.logger.error(typeof error === "string" ? error : error.message ? JSON.stringify(error.message) : JSON.stringify(error));
2565
+ }
2566
+ this.invokeContextHandlerWithStartupContext = false;
2567
+ this.logger.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
2568
+ yield this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
2569
+ this.logger.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
2476
2570
  });
2477
2571
  }
2478
- doesServerMethodExist(methodName, instance) {
2479
- const serversForMethodName = this.glueController.getInteropServers({ name: methodName });
2480
- return !!serversForMethodName.find(server => server.instance === instance);
2481
- }
2482
2572
  getOrCreateAppChannel(commandId, channelId) {
2483
2573
  return __awaiter(this, void 0, void 0, function* () {
2484
2574
  const exists = this.doesAppChannelExist(channelId);
@@ -2487,7 +2577,8 @@
2487
2577
  yield this.glueController.updateContext(channelId, {});
2488
2578
  }
2489
2579
  this.logger.info(`[${commandId}] - returning app channel with id ${channelId}`);
2490
- return this.buildChannel(ChannelTypes.App, { id: channelId });
2580
+ const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
2581
+ return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
2491
2582
  });
2492
2583
  }
2493
2584
  doesAppChannelExist(name) {
@@ -2499,12 +2590,6 @@
2499
2590
  }
2500
2591
  return !!this.channelsStateStore.userChannels[channelId];
2501
2592
  }
2502
- isPrivateChannel(channelId) {
2503
- return channelId.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === channelId);
2504
- }
2505
- buildChannel(type, data) {
2506
- return this.channelsFactory.buildModel(Object.assign(Object.assign({ type }, data), { isChannel: true }));
2507
- }
2508
2593
  broadcastByChannelId(commandId, channelId, context) {
2509
2594
  return __awaiter(this, void 0, void 0, function* () {
2510
2595
  const isUserChannel = this.isUserChannel(channelId);
@@ -2539,21 +2624,6 @@
2539
2624
  }
2540
2625
  };
2541
2626
  }
2542
- if (channelType === ChannelTypes.Private) {
2543
- this.logger.info(`[${commandId}] - subscribing for fdc3 private channel with id ${channelId} (underlying glue context with same name)`);
2544
- const contextsUnsubscribe = yield this.glueController.contextsSubscribe(channelId, subHandler);
2545
- yield this.addContextTypeInPrivateChannelContext(channelId, contextType);
2546
- const targetInstance = yield this.getTargetedInstanceId(channelId);
2547
- const unsubscribe = () => {
2548
- this.logger.info(`[${commandId}] - unsubscribe invoked for private channel with id ${channelId}`);
2549
- contextsUnsubscribe();
2550
- this.logger.info(`[${commandId}] - invoking onUnsubscribe handler for private channel with id ${channelId}`);
2551
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnUnsubscribe, { channelId, clientId: targetInstance, contextType });
2552
- };
2553
- this.logger.info(`[${commandId}] - invoking onAddContextListener handler for private channel with id ${channelId}`);
2554
- this.invokeSystemMethod(targetInstance, PrivateChannelEventMethods.OnAddContextListener, { channelId: channelId, clientId: targetInstance, contextType });
2555
- return { unsubscribe };
2556
- }
2557
2627
  throw { message: ChannelError.AccessDenied, reason: "Cannot add a context listener on an invalid channel" };
2558
2628
  });
2559
2629
  }
@@ -2582,56 +2652,21 @@
2582
2652
  if (isUser) {
2583
2653
  return ChannelTypes.User;
2584
2654
  }
2585
- const isPrivate = this.isPrivateChannel(channelId);
2586
- if (isPrivate) {
2587
- return ChannelTypes.Private;
2588
- }
2589
2655
  const isApp = this.doesAppChannelExist(channelId);
2590
2656
  if (isApp) {
2591
2657
  return ChannelTypes.App;
2592
2658
  }
2593
2659
  throw { message: ChannelError.NoChannelFound, reason: `Channel with id: ${channelId} does not exist` };
2594
2660
  }
2595
- getTargetedInstanceId(channelId) {
2596
- return __awaiter(this, void 0, void 0, function* () {
2597
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2598
- const myId = this.glueController.getMyInteropInstanceId();
2599
- return myId === clientId ? creatorId : clientId;
2600
- });
2601
- }
2602
- getOtherInstanceIdFromClosedOne(channelId, closedInstanceId) {
2603
- return __awaiter(this, void 0, void 0, function* () {
2604
- const { clientId, creatorId } = yield this.glueController.getContext(channelId);
2605
- return closedInstanceId === clientId
2606
- ? creatorId
2607
- : clientId;
2608
- });
2609
- }
2610
- invokeSystemMethod(clientId, action, payload) {
2611
- if (clientId) {
2612
- this.glueController.invokeSystemMethod({ action, payload });
2613
- }
2614
- }
2615
- addContextTypeInPrivateChannelContext(channelId, contextType) {
2616
- return __awaiter(this, void 0, void 0, function* () {
2617
- const currentContext = yield this.glueController.getContext(channelId);
2618
- const updatedTypes = currentContext.contextListenerTypes ? [...currentContext.contextListenerTypes, contextType] : [contextType];
2619
- return this.glueController.updateContext(channelId, Object.assign(Object.assign({}, currentContext), { contextListenerTypes: updatedTypes }));
2620
- });
2621
- }
2622
- getContextTypesForPrivateChannel(channelId) {
2623
- return __awaiter(this, void 0, void 0, function* () {
2624
- const ctx = yield this.glueController.getContext(channelId);
2625
- return ctx.contextListenerTypes;
2626
- });
2661
+ buildChannel(type, data) {
2662
+ return this.channelsFactory.buildModel(Object.assign({ type }, data));
2627
2663
  }
2628
2664
  }
2629
2665
 
2630
2666
  class EventReceiver {
2631
- constructor(glueController, eventDispatcher, eventsController) {
2667
+ constructor(glueController, eventDispatcher) {
2632
2668
  this.glueController = glueController;
2633
2669
  this.eventDispatcher = eventDispatcher;
2634
- this.eventsController = eventsController;
2635
2670
  this.glueResponseReceived = false;
2636
2671
  this.glueInitialized = false;
2637
2672
  this.events = {
@@ -2677,7 +2712,6 @@
2677
2712
  }
2678
2713
  window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
2679
2714
  this.glueController.initialize(glue);
2680
- yield this.eventsController.initialize();
2681
2715
  this.eventDispatcher.fireFdc3Ready();
2682
2716
  this.glueInitialized = true;
2683
2717
  });
@@ -2689,16 +2723,17 @@
2689
2723
  this._currentChannel = null;
2690
2724
  this._userChannels = {};
2691
2725
  this._fdc3ChannelIdsToGlueChannelNames = {};
2726
+ this._privateChannels = {};
2692
2727
  }
2693
2728
  get currentChannel() {
2694
2729
  return this._currentChannel;
2695
2730
  }
2696
- get userChannels() {
2697
- return this._userChannels;
2698
- }
2699
2731
  set currentChannel(newChannelValue) {
2700
2732
  this._currentChannel = newChannelValue;
2701
2733
  }
2734
+ get userChannels() {
2735
+ return this._userChannels;
2736
+ }
2702
2737
  addUserChannel(channel) {
2703
2738
  this._userChannels[channel.id] = channel;
2704
2739
  }
@@ -2712,140 +2747,14 @@
2712
2747
  const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
2713
2748
  return key;
2714
2749
  }
2715
- }
2716
-
2717
- class PrivateChannel {
2718
- constructor(channelsController, channelId) {
2719
- this.channelsController = channelsController;
2720
- this.type = ChannelTypes.Private;
2721
- this.id = channelId || `${PrivateChannelPrefix}${nanoid()}`;
2722
- this.unsubFromInstanceStopped = this.channelsController.registerOnInstanceStopped({ commandId: generateCommandId(), channelId: this.id });
2723
- }
2724
- toApi() {
2725
- const api = {
2726
- id: this.id,
2727
- type: this.type,
2728
- displayMetadata: this.displayMetadata,
2729
- broadcast: this.broadcast.bind(this),
2730
- getCurrentContext: this.getCurrentContext.bind(this),
2731
- addContextListener: this.addContextListener.bind(this),
2732
- onAddContextListener: this.onAddContextListener.bind(this),
2733
- onUnsubscribe: this.onUnsubscribe.bind(this),
2734
- onDisconnect: this.onDisconnect.bind(this),
2735
- disconnect: this.disconnect.bind(this),
2736
- };
2737
- return api;
2738
- }
2739
- broadcast(context) {
2740
- return __awaiter(this, void 0, void 0, function* () {
2741
- const commandId = generateCommandId();
2742
- const isDisconnected = yield this.channelsController.isPrivateChannelDisconnected({ commandId, channelId: this.id });
2743
- if (isDisconnected) {
2744
- throw { message: ChannelError.AccessDenied, reason: "Channel has disconnected - broadcast is no longer available" };
2745
- }
2746
- contextDecoder.runWithException(context);
2747
- return this.channelsController.broadcast(commandId, context, this.id);
2748
- });
2750
+ addPrivateChannel(privateChannel) {
2751
+ this._privateChannels[privateChannel.id] = privateChannel;
2749
2752
  }
2750
- getCurrentContext(contextType) {
2751
- return __awaiter(this, void 0, void 0, function* () {
2752
- optionalNonEmptyStringDecoder.runWithException(contextType);
2753
- return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
2754
- });
2753
+ getPrivateChannelById(id) {
2754
+ return this._privateChannels[id];
2755
2755
  }
2756
- addContextListener(contextType, handler) {
2757
- return __awaiter(this, arguments, void 0, function* () {
2758
- if (arguments.length === 1) {
2759
- if (typeof contextType !== "function") {
2760
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2761
- }
2762
- return this.channelsController.addContextListener({ commandId: generateCommandId(), handler: contextType, channelId: this.id });
2763
- }
2764
- const contextTypeDecoder = optionalNonEmptyStringDecoder.runWithException(contextType);
2765
- if (typeof handler !== "function") {
2766
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
2767
- }
2768
- return this.channelsController.addContextListener({
2769
- commandId: generateCommandId(),
2770
- contextType: contextTypeDecoder,
2771
- channelId: this.id,
2772
- handler,
2773
- });
2774
- });
2775
- }
2776
- onAddContextListener(handler) {
2777
- if (typeof handler !== "function") {
2778
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2779
- }
2780
- const unsub = this.channelsController.addPrivateChannelEvent({
2781
- commandId: generateCommandId(),
2782
- action: PrivateChannelEventMethods.OnAddContextListener,
2783
- channelId: this.id,
2784
- handler
2785
- });
2786
- return AsyncListener(unsub);
2787
- }
2788
- onUnsubscribe(handler) {
2789
- if (typeof handler !== "function") {
2790
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2791
- }
2792
- const unsub = this.channelsController.addPrivateChannelEvent({
2793
- commandId: generateCommandId(),
2794
- action: PrivateChannelEventMethods.OnUnsubscribe,
2795
- channelId: this.id,
2796
- handler
2797
- });
2798
- return AsyncListener(unsub);
2799
- }
2800
- onDisconnect(handler) {
2801
- if (typeof handler !== "function") {
2802
- throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
2803
- }
2804
- const unsub = this.channelsController.addPrivateChannelEvent({
2805
- commandId: generateCommandId(),
2806
- action: PrivateChannelEventMethods.OnDisconnect,
2807
- channelId: this.id,
2808
- handler
2809
- });
2810
- return AsyncListener(unsub);
2811
- }
2812
- disconnect() {
2813
- return __awaiter(this, void 0, void 0, function* () {
2814
- yield this.channelsController.announceDisconnect(generateCommandId(), this.id);
2815
- this.unsubFromInstanceStopped();
2816
- });
2817
- }
2818
- }
2819
-
2820
- class ChannelsFactory {
2821
- constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
2822
- this.createUserChannelFn = createUserChannelFn;
2823
- this.createAppChannel = createAppChannel;
2824
- this.createPrivateChannel = createPrivateChannel;
2825
- }
2826
- buildModel(data) {
2827
- const { type } = data;
2828
- if (type === ChannelTypes.User) {
2829
- return this.buildUserChannel(data.displayMetadata.glueChannel);
2830
- }
2831
- else if (type === ChannelTypes.App) {
2832
- return this.buildAppChannel(data.id);
2833
- }
2834
- else if (type === ChannelTypes.Private) {
2835
- return this.buildPrivateChannel(data.id);
2836
- }
2837
- else {
2838
- throw new Error("Pass one of the supported channel types: user, app, private");
2839
- }
2840
- }
2841
- buildUserChannel(data) {
2842
- return this.createUserChannelFn(data);
2843
- }
2844
- buildAppChannel(channelId) {
2845
- return this.createAppChannel(channelId);
2846
- }
2847
- buildPrivateChannel(channelId) {
2848
- return this.createPrivateChannel(channelId);
2756
+ removePrivateChannelById(id) {
2757
+ delete this._privateChannels[id];
2849
2758
  }
2850
2759
  }
2851
2760
 
@@ -2966,36 +2875,345 @@
2966
2875
  createRegistry.default = createRegistry;
2967
2876
  var lib = createRegistry;
2968
2877
 
2969
- class ChannelsCallbackRegistry {
2970
- constructor() {
2878
+ class PrivateChannel {
2879
+ constructor(channelsController, logger, channelId, isCreator) {
2880
+ this.channelsController = channelsController;
2881
+ this.logger = logger;
2882
+ this.isCreator = isCreator;
2883
+ this.type = ChannelTypes.Private;
2884
+ this.disconnected = false;
2885
+ this.broadcastedContexts = {};
2886
+ this.collaboratorListenerTypes = [];
2887
+ this.myListenerTypesBeforeBound = [];
2971
2888
  this.registry = lib();
2889
+ this.id = channelId;
2890
+ const myServerInstance = this.channelsController.getMyServerInstance();
2891
+ this.myAppMetadata = { source: { appId: myServerInstance.applicationName, instanceId: myServerInstance.instance } };
2972
2892
  }
2973
- add({ action, channelId, handler, replayArgs }) {
2974
- return this.registry.add(`${action}-${channelId}`, handler, replayArgs);
2893
+ toApi() {
2894
+ const api = {
2895
+ id: this.id,
2896
+ type: this.type,
2897
+ displayMetadata: this.displayMetadata,
2898
+ broadcast: this.broadcast.bind(this),
2899
+ getCurrentContext: this.getCurrentContext.bind(this),
2900
+ addContextListener: this.addContextListener.bind(this),
2901
+ onAddContextListener: this.onAddContextListener.bind(this),
2902
+ onUnsubscribe: this.onUnsubscribe.bind(this),
2903
+ onDisconnect: this.onDisconnect.bind(this),
2904
+ disconnect: this.disconnect.bind(this),
2905
+ };
2906
+ return api;
2907
+ }
2908
+ getCollaborator() {
2909
+ return this.collaborator;
2910
+ }
2911
+ setCollaborator(collaborator, commandId) {
2912
+ if (this.collaborator && this.collaborator.instanceId !== collaborator.instanceId) {
2913
+ throw new Error(`There's already a collaborator for private channel with id ${this.id}`);
2914
+ }
2915
+ this.collaborator = collaborator;
2916
+ this.subscribeForCollaboratorInstanceStop(commandId);
2917
+ }
2918
+ handleCollaboratorJoin(collaborator, commandId) {
2919
+ return __awaiter(this, void 0, void 0, function* () {
2920
+ this.setCollaborator(collaborator, commandId);
2921
+ yield Promise.all(this.myListenerTypesBeforeBound.map((contextType) => {
2922
+ var _a;
2923
+ const listenerAddedArgs = {
2924
+ action: "addedContextListenerOnPrivateChannel",
2925
+ correlationId: this.id,
2926
+ collaborationObject: {
2927
+ channelId: this.id,
2928
+ contextType: contextType || undefined
2929
+ }
2930
+ };
2931
+ this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
2932
+ return this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
2933
+ })).catch((err) => this.logger.error(err));
2934
+ });
2935
+ }
2936
+ handleCollaboratorBroadcast(context, metadata, commandId) {
2937
+ this.logger.trace(`[${commandId}] - heard context with type ${context.type} broadcasted on the channel`);
2938
+ this.lastBroadcastedContextType = context.type;
2939
+ this.broadcastedContexts[context.type] = { context, metadata };
2940
+ this.logger.trace(`[${commandId}] - invoking all context listeners`);
2941
+ this.registry.execute(PrivateChannelEventMethods.ListenerAdded, context, metadata);
2942
+ }
2943
+ handleCollaboratorAddContextListener(contextType, commandId) {
2944
+ this.logger.trace(`[${commandId}] - heard collaborator added context listener for type ${contextType}`);
2945
+ this.collaboratorListenerTypes.push(contextType);
2946
+ this.registry.execute(PrivateChannelEventMethods.OnAddContextListener, contextType);
2947
+ }
2948
+ handleCollaboratorRemovedListener(contextType, commandId) {
2949
+ this.logger.trace(`[${commandId}] - heard collaborator removed context listener with type ${contextType}`);
2950
+ const index = this.collaboratorListenerTypes.indexOf(contextType);
2951
+ this.collaboratorListenerTypes.splice(index, 1);
2952
+ this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType);
2953
+ }
2954
+ handleCollaboratorDisconnect() {
2955
+ this.disconnected = true;
2956
+ this.collaboratorListenerTypes.forEach((contextType) => this.registry.execute(PrivateChannelEventMethods.OnUnsubscribe, contextType));
2957
+ this.registry.execute(PrivateChannelEventMethods.OnDisconnect);
2958
+ }
2959
+ announceJoin(targetInstance, commandId) {
2960
+ return __awaiter(this, void 0, void 0, function* () {
2961
+ const joinChannelArgs = {
2962
+ action: "joinPrivateChannel",
2963
+ correlationId: this.id,
2964
+ collaborationObject: {
2965
+ channelId: this.id
2966
+ }
2967
+ };
2968
+ this.logger.trace(`[${commandId}] - announcing ${"joinPrivateChannel"} to target instance with id ${JSON.stringify(targetInstance)}`);
2969
+ yield this.channelsController.invokeSystemMethod(joinChannelArgs, targetInstance);
2970
+ this.logger.trace(`[${commandId}] - collaborator received ${"joinPrivateChannel"} action`);
2971
+ });
2972
+ }
2973
+ broadcast(context) {
2974
+ var _a;
2975
+ return __awaiter(this, void 0, void 0, function* () {
2976
+ const commandId = generateCommandId();
2977
+ this.ensureAlive(commandId);
2978
+ this.ensureBound(commandId, "broadcast");
2979
+ contextDecoder.runWithException(context);
2980
+ this.lastBroadcastedContextType = context.type;
2981
+ this.broadcastedContexts[context.type] = { context, metadata: this.myAppMetadata };
2982
+ const broadcastArgs = {
2983
+ action: "publishOnPrivateChannel",
2984
+ correlationId: this.id,
2985
+ collaborationObject: {
2986
+ channelId: this.id,
2987
+ contextType: context.type,
2988
+ payload: context
2989
+ }
2990
+ };
2991
+ this.logger.trace(`[${commandId}] - announcing ${"publishOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
2992
+ yield this.channelsController.invokeSystemMethod(broadcastArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
2993
+ this.logger.trace(`[${commandId}] - collaborator received context for action ${"publishOnPrivateChannel"}`);
2994
+ });
2995
+ }
2996
+ getCurrentContext(contextType) {
2997
+ return __awaiter(this, void 0, void 0, function* () {
2998
+ const commandId = generateCommandId();
2999
+ this.ensureAlive(commandId);
3000
+ this.logger.trace(`[${commandId}] - getCurrentContext invoked ${contextType ? `with contextType ${contextType}` : ""}`);
3001
+ optionalNonEmptyStringDecoder.runWithException(contextType);
3002
+ if (!contextType && !this.lastBroadcastedContextType) {
3003
+ return null;
3004
+ }
3005
+ const searchedType = contextType || this.lastBroadcastedContextType;
3006
+ this.logger.trace(`[${commandId}] - Returning context with type ${searchedType}`);
3007
+ return this.broadcastedContexts[searchedType].context;
3008
+ });
2975
3009
  }
2976
- invoke(action, argumentObj) {
2977
- const { channelId, contextType } = argumentObj;
2978
- this.registry.execute(`${action}-${channelId}`, contextType);
3010
+ addContextListener(contextType, handler) {
3011
+ var _a;
3012
+ return __awaiter(this, void 0, void 0, function* () {
3013
+ const commandId = generateCommandId();
3014
+ this.ensureAlive(commandId);
3015
+ optionalNonEmptyStringDecoder.runWithException(contextType);
3016
+ if (typeof handler !== "function") {
3017
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof contextType}` };
3018
+ }
3019
+ this.logger.trace(`[${commandId}] - adding subscription for broadcasted contexts with type: ${contextType}`);
3020
+ const subHandler = (data, metadata) => {
3021
+ if (contextType) {
3022
+ if (data.type === contextType) {
3023
+ handler(data, metadata);
3024
+ }
3025
+ return;
3026
+ }
3027
+ handler(data, metadata);
3028
+ };
3029
+ const lastBroadcastedContextPerType = this.retrieveLatestBroadcastedContextPerType(contextType);
3030
+ const replayArgs = lastBroadcastedContextPerType ? [[lastBroadcastedContextPerType.context, lastBroadcastedContextPerType.metadata]] : undefined;
3031
+ const unsub = this.registry.add(PrivateChannelEventMethods.ListenerAdded, subHandler, replayArgs);
3032
+ if (this.collaborator) {
3033
+ const listenerAddedArgs = {
3034
+ action: "addedContextListenerOnPrivateChannel",
3035
+ correlationId: this.id,
3036
+ collaborationObject: {
3037
+ channelId: this.id,
3038
+ contextType: contextType || undefined
3039
+ }
3040
+ };
3041
+ this.logger.trace(`[${commandId}] - announcing ${"addedContextListenerOnPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3042
+ yield this.channelsController.invokeSystemMethod(listenerAddedArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3043
+ this.logger.trace(`[${commandId}] - collaborator received action ${"addedContextListenerOnPrivateChannel"}`);
3044
+ }
3045
+ else {
3046
+ this.myListenerTypesBeforeBound.push(contextType);
3047
+ }
3048
+ const unsubscribe = this.getAddContextListenerUnsub(unsub, contextType, commandId);
3049
+ return AsyncListener(unsubscribe);
3050
+ });
3051
+ }
3052
+ retrieveLatestBroadcastedContextPerType(contextType) {
3053
+ if (!contextType && !this.lastBroadcastedContextType) {
3054
+ return;
3055
+ }
3056
+ if (!contextType && this.lastBroadcastedContextType) {
3057
+ return {
3058
+ context: this.broadcastedContexts[this.lastBroadcastedContextType].context,
3059
+ metadata: this.broadcastedContexts[this.lastBroadcastedContextType].metadata
3060
+ };
3061
+ }
3062
+ return this.broadcastedContexts[contextType];
3063
+ }
3064
+ getAddContextListenerUnsub(unsub, contextType, commandId) {
3065
+ return () => __awaiter(this, void 0, void 0, function* () {
3066
+ var _a;
3067
+ unsub();
3068
+ if (!this.collaborator) {
3069
+ const index = this.myListenerTypesBeforeBound.indexOf(contextType);
3070
+ this.myListenerTypesBeforeBound.splice(index, 1);
3071
+ return;
3072
+ }
3073
+ const unsubArgs = {
3074
+ action: "removedContextListenerOnPrivateChannel",
3075
+ correlationId: this.id,
3076
+ collaborationObject: {
3077
+ channelId: this.id,
3078
+ contextType: contextType || undefined
3079
+ }
3080
+ };
3081
+ this.logger.trace(`[${commandId}] - announcing unsubscribe from context listener for type ${contextType}`);
3082
+ yield this.channelsController.invokeSystemMethod(unsubArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3083
+ this.logger.trace(`[${commandId}] - collaborator heard ${"removedContextListenerOnPrivateChannel"}`);
3084
+ });
3085
+ }
3086
+ onAddContextListener(handler) {
3087
+ if (typeof handler !== "function") {
3088
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3089
+ }
3090
+ const commandId = generateCommandId();
3091
+ this.ensureAlive(commandId);
3092
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnAddContextListener, handler, this.collaboratorListenerTypes);
3093
+ return AsyncListener(unsub);
3094
+ }
3095
+ onUnsubscribe(handler) {
3096
+ if (typeof handler !== "function") {
3097
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3098
+ }
3099
+ const commandId = generateCommandId();
3100
+ this.ensureAlive(commandId);
3101
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnUnsubscribe, handler);
3102
+ return AsyncListener(unsub);
3103
+ }
3104
+ onDisconnect(handler) {
3105
+ if (typeof handler !== "function") {
3106
+ throw { message: ChannelError.AccessDenied, reason: `Expected function as an argument, got ${typeof handler}` };
3107
+ }
3108
+ const commandId = generateCommandId();
3109
+ this.ensureAlive(commandId);
3110
+ const unsub = this.registry.add(PrivateChannelEventMethods.OnDisconnect, handler);
3111
+ return AsyncListener(unsub);
3112
+ }
3113
+ disconnect() {
3114
+ var _a;
3115
+ return __awaiter(this, void 0, void 0, function* () {
3116
+ const commandId = generateCommandId();
3117
+ if (this.isCreator && !this.collaborator) {
3118
+ this.disconnected = true;
3119
+ return;
3120
+ }
3121
+ this.ensureAlive(commandId);
3122
+ this.ensureBound(commandId, "disconnect");
3123
+ this.logger.trace(`[${commandId}] - disconnect invoked`);
3124
+ this.disconnected = true;
3125
+ this.logger.trace(`[${commandId}] - announcing ${"disconnectedFromPrivateChannel"} to collaborator ${JSON.stringify(this.collaborator)}`);
3126
+ const disconnectArgs = {
3127
+ action: "disconnectedFromPrivateChannel",
3128
+ correlationId: this.id,
3129
+ collaborationObject: {
3130
+ channelId: this.id
3131
+ }
3132
+ };
3133
+ this.channelsController.removePrivateChannelFromStoreById(this.id);
3134
+ yield this.channelsController.invokeSystemMethod(disconnectArgs, (_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId);
3135
+ this.logger.trace(`[${commandId}] - collaborator received action ${"disconnectedFromPrivateChannel"}`);
3136
+ if (this.unsubFromInstanceStopped) {
3137
+ this.unsubFromInstanceStopped();
3138
+ }
3139
+ });
3140
+ }
3141
+ ensureAlive(commandId) {
3142
+ if (!this.disconnected) {
3143
+ return;
3144
+ }
3145
+ const errorMsg = "Channel is disconnected - operation is no longer available";
3146
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3147
+ throw { message: ChannelError.AccessDenied, reason: errorMsg };
3148
+ }
3149
+ ensureBound(commandId, operation) {
3150
+ if (this.collaborator) {
3151
+ return;
3152
+ }
3153
+ const errorMsg = `There's no collaborator on the other side of the channel - operation ${operation} is unavailable`;
3154
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3155
+ throw { message: ChannelError.AccessDenied, reason: errorMsg };
3156
+ }
3157
+ subscribeForCollaboratorInstanceStop(commandId) {
3158
+ const handler = (instance) => {
3159
+ var _a;
3160
+ if (instance.id !== ((_a = this.collaborator) === null || _a === void 0 ? void 0 : _a.instanceId)) {
3161
+ return;
3162
+ }
3163
+ this.handleCollaboratorDisconnect();
3164
+ };
3165
+ this.unsubFromInstanceStopped = this.channelsController.subscribeOnInstanceStop(this.id, handler.bind(this), commandId);
3166
+ }
3167
+ }
3168
+
3169
+ class ChannelsFactory {
3170
+ constructor(createUserChannelFn, createAppChannel, createPrivateChannel) {
3171
+ this.createUserChannelFn = createUserChannelFn;
3172
+ this.createAppChannel = createAppChannel;
3173
+ this.createPrivateChannel = createPrivateChannel;
3174
+ }
3175
+ buildModel(data) {
3176
+ const { type } = data;
3177
+ const lowerType = type === null || type === void 0 ? void 0 : type.toLowerCase();
3178
+ if (lowerType === ChannelTypes.User) {
3179
+ return this.createUserChannelFn(data.displayMetadata.glueChannel);
3180
+ }
3181
+ if (lowerType === ChannelTypes.App) {
3182
+ return this.createAppChannel(data.id);
3183
+ }
3184
+ if (lowerType === ChannelTypes.Private) {
3185
+ return this.createPrivateChannel(data.logger, data.id, data.isCreator);
3186
+ }
3187
+ throw new Error("Pass one of the supported channel types: user, app, private");
2979
3188
  }
2980
3189
  }
2981
3190
 
2982
3191
  class GlueEventsController {
2983
- constructor(glueController, channelsCallbackRegistry) {
3192
+ constructor(glueController, channelsStateStore, appsStateStore) {
2984
3193
  this.glueController = glueController;
2985
- this.channelsCallbackRegistry = channelsCallbackRegistry;
3194
+ this.channelsStateStore = channelsStateStore;
3195
+ this.appsStateStore = appsStateStore;
3196
+ this.actionDictionary = {
3197
+ joinPrivateChannel: this.handleJoin.bind(this),
3198
+ publishOnPrivateChannel: this.handlePublish.bind(this),
3199
+ addedContextListenerOnPrivateChannel: this.handleContextListenerAdded.bind(this),
3200
+ removedContextListenerOnPrivateChannel: this.handleContextListenerRemoved.bind(this),
3201
+ disconnectedFromPrivateChannel: this.handleDisconnect.bind(this),
3202
+ startupContextOpened: this.handleStartupContextOpened.bind(this)
3203
+ };
2986
3204
  }
2987
- initialize() {
3205
+ initializeCollaborateMethod() {
2988
3206
  return __awaiter(this, void 0, void 0, function* () {
2989
- const isMethodRegisteredByThisApp = this.isSysMethodRegisteredByCurrentApp();
2990
- if (isMethodRegisteredByThisApp) {
3207
+ const methodRegisteredByMe = this.checkSystemMethodRegistered();
3208
+ if (methodRegisteredByMe) {
2991
3209
  return;
2992
3210
  }
2993
- yield this.glueController.registerMethod(Glue42FDC3SystemMethod, this.handleSystemMethodInvocation.bind(this));
3211
+ yield this.glueController.registerMethod(ioConnectFDC3SystemMethod, this.handleReceivedAction.bind(this));
2994
3212
  });
2995
3213
  }
2996
- isSysMethodRegisteredByCurrentApp() {
2997
- const methods = this.glueController.getInteropMethods(Glue42FDC3SystemMethod);
2998
- const myId = this.glueController.getMyInteropInstanceId();
3214
+ checkSystemMethodRegistered() {
3215
+ const methods = this.glueController.getInteropMethods(ioConnectFDC3SystemMethod);
3216
+ const myId = this.glueController.getMyInteropInstance().instance;
2999
3217
  const methodsByThisInstance = methods.filter(method => {
3000
3218
  return method.getServers().find(server => server.instance === myId)
3001
3219
  ? method
@@ -3003,29 +3221,111 @@
3003
3221
  });
3004
3222
  return !!methodsByThisInstance.length;
3005
3223
  }
3006
- handleSystemMethodInvocation(argumentObj) {
3007
- const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(argumentObj);
3008
- if (!argsDecodeResult.ok) {
3009
- throw new Error(`Interop Method ${Glue42FDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}.\n Expected ${JSON.stringify({ action: string, payload: { channelId: string, clientId: string } })}`);
3224
+ handleReceivedAction(eventArgs, instance) {
3225
+ return __awaiter(this, void 0, void 0, function* () {
3226
+ const argsDecodeResult = SystemMethodInvocationArgumentDecoder.run(eventArgs);
3227
+ if (!argsDecodeResult.ok) {
3228
+ throw new Error(`Interop Method ${ioConnectFDC3SystemMethod} invoked with invalid argument object - ${argsDecodeResult.error}`);
3229
+ }
3230
+ const commandId = generateCommandId();
3231
+ this.logger.log(`${commandId} - received system method from instance with id ${instance.instance} for action ${eventArgs.action} with arguments: ${JSON.stringify(eventArgs)}`);
3232
+ const operation = this.actionDictionary[eventArgs.action];
3233
+ if (!operation) {
3234
+ const errorMsg = `Unsupported private channel action: ${eventArgs.action}`;
3235
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3236
+ throw new Error(errorMsg);
3237
+ }
3238
+ yield operation(eventArgs, instance, commandId);
3239
+ });
3240
+ }
3241
+ get logger() {
3242
+ if (!this._logger) {
3243
+ this._logger = this.glueController.initSubLogger("fdc3.private.channels.controller");
3244
+ }
3245
+ return this._logger;
3246
+ }
3247
+ validateAndRetrieveChannel({ action, correlationId }, instance, commandId) {
3248
+ const privateChannel = this.channelsStateStore.getPrivateChannelById(correlationId);
3249
+ if (!privateChannel) {
3250
+ const errorMsg = `There's no private channel with id ${correlationId}`;
3251
+ this.logger.error(`[${commandId}] - ${errorMsg}`);
3252
+ throw new Error(errorMsg);
3010
3253
  }
3011
- const { action, payload } = argsDecodeResult.result;
3012
- if (action === PrivateChannelEventMethods.OnDisconnect) {
3013
- return this.handleOnDisconnect(payload);
3254
+ const channelCollaborator = privateChannel.getCollaborator();
3255
+ if (action === "joinPrivateChannel") {
3256
+ return privateChannel;
3014
3257
  }
3015
- if (action === PrivateChannelEventMethods.OnAddContextListener || action === PrivateChannelEventMethods.OnUnsubscribe) {
3016
- return this.channelsCallbackRegistry.invoke(action, payload);
3258
+ if (channelCollaborator && channelCollaborator.instanceId === instance.instance) {
3259
+ this.logger.log(`[${commandId}] - request sent from correct collaborator with id ${instance.instance}. Returning channel`);
3260
+ return privateChannel;
3017
3261
  }
3262
+ const errorMsg = `Cannot proceed with action ${action} - ${channelCollaborator
3263
+ ? `private channel ${correlationId} established communication with collaborator with id ${channelCollaborator}`
3264
+ : `no collaborator joined private channel with id ${correlationId}`}`;
3265
+ this.logger.error(errorMsg);
3266
+ throw new Error(errorMsg);
3018
3267
  }
3019
- handleOnDisconnect(payload) {
3020
- if (payload.replayContextTypes) {
3021
- this.invokeOnUnsubscribeHandlerMultipleTimes(payload);
3268
+ handleJoin(eventArgs, instance, commandId) {
3269
+ return __awaiter(this, void 0, void 0, function* () {
3270
+ const collaborator = { appId: instance.application || instance.applicationName, instanceId: instance.instance };
3271
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3272
+ yield privateChannel.handleCollaboratorJoin(collaborator, commandId);
3273
+ this.logger.log(`[${commandId}] - collaborator ${JSON.stringify(collaborator)} set for private channel with id ${eventArgs.correlationId}`);
3274
+ });
3275
+ }
3276
+ handlePublish(eventArgs, instance, commandId) {
3277
+ var _a, _b;
3278
+ 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`);
3279
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3280
+ const metadata = {
3281
+ source: {
3282
+ appId: instance.application || instance.applicationName || "",
3283
+ instanceId: instance.instance
3284
+ }
3285
+ };
3286
+ privateChannel.handleCollaboratorBroadcast((_b = eventArgs.collaborationObject) === null || _b === void 0 ? void 0 : _b.payload, metadata, commandId);
3287
+ }
3288
+ handleContextListenerAdded(eventArgs, instance, commandId) {
3289
+ var _a;
3290
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onAddContextListener' callbacks`);
3291
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3292
+ privateChannel.handleCollaboratorAddContextListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
3293
+ }
3294
+ handleContextListenerRemoved(eventArgs, instance, commandId) {
3295
+ var _a;
3296
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onUnsubscribe' callbacks`);
3297
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3298
+ privateChannel.handleCollaboratorRemovedListener(((_a = eventArgs.collaborationObject) === null || _a === void 0 ? void 0 : _a.contextType) || null, commandId);
3299
+ }
3300
+ handleDisconnect(eventArgs, instance, commandId) {
3301
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} action, invoking all 'onDisconnect' callbacks`);
3302
+ const privateChannel = this.validateAndRetrieveChannel(eventArgs, instance, commandId);
3303
+ privateChannel.handleCollaboratorDisconnect();
3304
+ }
3305
+ handleStartupContextOpened(eventArgs, instance, commandId) {
3306
+ this.logger.log(`[${commandId}] - received ${eventArgs.action} with correlationId: ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3307
+ const wrappedPromise = this.appsStateStore.getOpenAppPromise(eventArgs.correlationId);
3308
+ if (!wrappedPromise) {
3309
+ this.logger.log(`[${commandId}] - there's no open app promise related to guid ${eventArgs.correlationId}`);
3310
+ return;
3022
3311
  }
3023
- this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnDisconnect, payload);
3312
+ this.logger.log(`[${commandId}] - resolving open app promise related to guid ${eventArgs.correlationId} from instance with id ${instance.instance}`);
3313
+ wrappedPromise.resolve();
3024
3314
  }
3025
- invokeOnUnsubscribeHandlerMultipleTimes(payload) {
3026
- payload.replayContextTypes.forEach(contextType => {
3027
- this.channelsCallbackRegistry.invoke(PrivateChannelEventMethods.OnUnsubscribe, { channelId: payload.channelId, clientId: payload.clientId, contextType });
3028
- });
3315
+ }
3316
+
3317
+ class ApplicationsStateStore {
3318
+ constructor() {
3319
+ this.openAppPromises = {};
3320
+ }
3321
+ addOpenAppPromise(guid, promise) {
3322
+ this.openAppPromises[guid] = promise;
3323
+ }
3324
+ getOpenAppPromise(guid) {
3325
+ return this.openAppPromises[guid];
3326
+ }
3327
+ removeOpenAppPromise(guid) {
3328
+ delete this.openAppPromises[guid];
3029
3329
  }
3030
3330
  }
3031
3331
 
@@ -3035,7 +3335,7 @@
3035
3335
  }
3036
3336
  get eventReceiver() {
3037
3337
  if (!this._eventReceiver) {
3038
- this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher, this.eventsController);
3338
+ this._eventReceiver = new EventReceiver(this.glueController, this.eventDispatcher);
3039
3339
  }
3040
3340
  return this._eventReceiver;
3041
3341
  }
@@ -3069,8 +3369,8 @@
3069
3369
  createAppChannel(id) {
3070
3370
  return new AppChannel(this.channelsController, id).toApi();
3071
3371
  }
3072
- createPrivateChannel(channelId) {
3073
- return new PrivateChannel(this.channelsController, channelId).toApi();
3372
+ createPrivateChannel(logger, channelId, isCreator) {
3373
+ return new PrivateChannel(this.channelsController, logger, channelId, isCreator);
3074
3374
  }
3075
3375
  get desktopAgent() {
3076
3376
  if (!this._desktopAgent) {
@@ -3086,19 +3386,19 @@
3086
3386
  }
3087
3387
  get intentsController() {
3088
3388
  if (!this._intentsController) {
3089
- this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory);
3389
+ this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory, this.eventsController);
3090
3390
  }
3091
3391
  return this._intentsController;
3092
3392
  }
3093
3393
  get applicationController() {
3094
3394
  if (!this._applicationController) {
3095
- this._applicationController = new ApplicationsController(this.glueController);
3395
+ this._applicationController = new ApplicationsController(this.glueController, this.applicationsStateStore, this.eventsController);
3096
3396
  }
3097
3397
  return this._applicationController;
3098
3398
  }
3099
3399
  get channelsController() {
3100
3400
  if (!this._channelsController) {
3101
- this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.channelsCallbackRegistry);
3401
+ this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.eventsController);
3102
3402
  }
3103
3403
  return this._channelsController;
3104
3404
  }
@@ -3108,18 +3408,18 @@
3108
3408
  }
3109
3409
  return this._channelsStateStore;
3110
3410
  }
3111
- get channelsCallbackRegistry() {
3112
- if (!this._channelsCallbackRegistry) {
3113
- this._channelsCallbackRegistry = new ChannelsCallbackRegistry();
3114
- }
3115
- return this._channelsCallbackRegistry;
3116
- }
3117
3411
  get eventsController() {
3118
3412
  if (!this._eventsController) {
3119
- this._eventsController = new GlueEventsController(this.glueController, this.channelsCallbackRegistry);
3413
+ this._eventsController = new GlueEventsController(this.glueController, this.channelsStateStore, this.applicationsStateStore);
3120
3414
  }
3121
3415
  return this._eventsController;
3122
3416
  }
3417
+ get applicationsStateStore() {
3418
+ if (!this._applicationsStateStore) {
3419
+ this._applicationsStateStore = new ApplicationsStateStore();
3420
+ }
3421
+ return this._applicationsStateStore;
3422
+ }
3123
3423
  }
3124
3424
 
3125
3425
  const fdc3Factory = () => {