@interopio/fdc3 2.3.4-next.0 → 2.3.4

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.
@@ -1245,11 +1245,88 @@
1245
1245
  const defaultGlue42APIs = ["contexts", "channels", "interop", "intents", "appManager", "windows"];
1246
1246
  const glueChannelNamePrefix = "___channel___";
1247
1247
  const fdc3NothingContextType = "fdc3.nothing";
1248
+ const Glue42EnterpriseNoAppWindow = "no-app-window";
1248
1249
  const RaiseTimeoutMs = 75 * 1000;
1249
1250
  const IntentsMethodPrefix = "Tick42.FDC3.Intents.";
1251
+ const Fdc3SupportedIntentTypes = {
1252
+ "CreateInteraction": [
1253
+ "fdc3.contactList",
1254
+ "fdc3.interaction"
1255
+ ],
1256
+ "StartCall": [
1257
+ "fdc3.contact",
1258
+ "fdc3.contactList"
1259
+ ],
1260
+ "StartChat": [
1261
+ "fdc3.contact",
1262
+ "fdc3.contactList",
1263
+ "fdc3.chat.initSettings"
1264
+ ],
1265
+ "StartEmail": [
1266
+ "fdc3.email"
1267
+ ],
1268
+ "SendChatMessage": [
1269
+ "fdc3.chat.message"
1270
+ ],
1271
+ "ViewAnalysis": [
1272
+ "fdc3.instrument",
1273
+ "fdc3.organization",
1274
+ "fdc3.portfolio"
1275
+ ],
1276
+ "ViewChat": [
1277
+ "fdc3.chat.room",
1278
+ "fdc3.contact",
1279
+ "fdc3.contactList"
1280
+ ],
1281
+ "ViewChart": [
1282
+ "fdc3.chart",
1283
+ "fdc3.instrument",
1284
+ "fdc3.instrumentList",
1285
+ "fdc3.portfolio",
1286
+ "fdc3.position"
1287
+ ],
1288
+ "ViewHoldings": [
1289
+ "fdc3.instrument",
1290
+ "fdc3.instrumentList",
1291
+ "fdc3.organization"
1292
+ ],
1293
+ "ViewInstrument": [
1294
+ "fdc3.instrument"
1295
+ ],
1296
+ "ViewInteractions": [
1297
+ "fdc3.contact",
1298
+ "fdc3.instrument",
1299
+ "fdc3.organization"
1300
+ ],
1301
+ "ViewMessages": [
1302
+ "fdc3.chat.searchCriteria"
1303
+ ],
1304
+ "ViewNews": [
1305
+ "fdc3.country",
1306
+ "fdc3.instrument",
1307
+ "fdc3.instrumentList",
1308
+ "fdc3.organization",
1309
+ "fdc3.portfolio"
1310
+ ],
1311
+ "ViewOrders": [
1312
+ "fdc3.contact",
1313
+ "fdc3.instrument",
1314
+ "fdc3.organization"
1315
+ ],
1316
+ "ViewProfile": [
1317
+ "fdc3.contact",
1318
+ "fdc3.organization"
1319
+ ],
1320
+ "ViewQuote": [
1321
+ "fdc3.instrument"
1322
+ ],
1323
+ "ViewResearch": [
1324
+ "fdc3.contact",
1325
+ "fdc3.instrument",
1326
+ "fdc3.organization"
1327
+ ]
1328
+ };
1250
1329
  const IO_ERRORS = errors.intents;
1251
- const BrowserClientControlMethodName = "T42.Web.Client.Control";
1252
- const DesktopClientControlMethodName = "T42.Channels.Command";
1253
1330
 
1254
1331
  const ioConnectFDC3SystemMethod = "FDC3.Collaborate";
1255
1332
  const PrivateChannelPrefix = "___privateFDC3Channel___";
@@ -2211,8 +2288,9 @@
2211
2288
  const latestTypePathValue = { path: "latest_fdc3_type", value: this.channelsParser.mapFDC3TypeToChannelsDelimiter(context.type) };
2212
2289
  await this.contextsSetPaths(contextId, [{ path: `data.${path}`, value: value }, latestTypePathValue]);
2213
2290
  }
2214
- async channelsUpdate(data, options) {
2215
- return this.glue.channels.publish(data, options);
2291
+ async channelsUpdate(channelId, context) {
2292
+ const { path, value } = this.channelsParser.parseFDC3ContextToGlueContexts(context);
2293
+ return this.glue.channels.publish({ [path]: value }, channelId);
2216
2294
  }
2217
2295
  async joinChannel(channelId) {
2218
2296
  return this.glue.channels.join(channelId);
@@ -2261,9 +2339,9 @@
2261
2339
  getInteropMethods(filter) {
2262
2340
  return this.glue.interop.methods(filter);
2263
2341
  }
2264
- legacyChannelsSubscribe(callback, contextType) {
2342
+ channelsSubscribe(callback, contextType) {
2265
2343
  const didReplay = { replayed: false };
2266
- return this.glue.channels.subscribe((data, contextData, updaterId) => {
2344
+ return this.glue.channels.subscribe((_, contextData, updaterId) => {
2267
2345
  if (this.isUpdateFromMe(updaterId) || !contextData || !contextData.latest_fdc3_type) {
2268
2346
  return;
2269
2347
  }
@@ -2274,28 +2352,13 @@
2274
2352
  didReplay.replayed = true;
2275
2353
  });
2276
2354
  }
2277
- channelsSubscribe(callback, contextType) {
2278
- const didReplay = { replayed: false };
2279
- return this.glue.channels.subscribe((data, contextData, updaterId) => {
2280
- if (this.isUpdateFromMe(updaterId) || !contextData || !data.fdc3) {
2281
- return;
2282
- }
2283
- if (contextType && data.fdc3.type !== contextType && !didReplay.replayed) {
2284
- this.invokePreviouslyBroadcastedData({ callback, contextData, metadata: this.getContextMetadata(updaterId), contextType });
2285
- didReplay.replayed = true;
2286
- return;
2287
- }
2288
- callback(data.fdc3, this.getContextMetadata(updaterId));
2289
- didReplay.replayed = true;
2290
- });
2291
- }
2292
2355
  contextsSubscribe(contextName, callback) {
2293
2356
  const didReplay = { replayed: false };
2294
2357
  return this.glue.contexts.subscribe(contextName, (contextData, addedData, removed, _, extraData) => {
2295
2358
  if (this.isUpdateFromMe(extraData?.updaterId)) {
2296
2359
  return;
2297
2360
  }
2298
- if (!this.checkIfShouldInvokeInitialReplay(didReplay, contextData)) {
2361
+ if (!this.checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData)) {
2299
2362
  return;
2300
2363
  }
2301
2364
  this.parseDataAndInvokeSubscribeCallback({ callback, contextData, metadata: this.getContextMetadata(extraData?.updaterId) });
@@ -2307,21 +2370,6 @@
2307
2370
  initSubLogger(name) {
2308
2371
  return this.logger?.subLogger(name);
2309
2372
  }
2310
- getPrefs(app) {
2311
- return this.glue.prefs.get(app);
2312
- }
2313
- async checkIsFdc3DataWrappingSupported() {
2314
- const globalBrowserNamespace = window.glue42core || window.iobrowser;
2315
- const methodName = globalBrowserNamespace ? BrowserClientControlMethodName : DesktopClientControlMethodName;
2316
- const data = globalBrowserNamespace ? { domain: "system", operation: "isFdc3DataWrappingSupported" } : { command: "isFdc3DataWrappingSupported" };
2317
- try {
2318
- const res = await this.glue.interop.invoke(methodName, data, { instance: this.interopInstance().instance });
2319
- return res.returned.isSupported;
2320
- }
2321
- catch (error) {
2322
- return false;
2323
- }
2324
- }
2325
2373
  invokePreviouslyBroadcastedData({ callback, contextData, metadata, contextType }) {
2326
2374
  const invokeForType = contextType || this.channelsParser.mapChannelsDelimiterToFDC3Type(contextData.latest_fdc3_type);
2327
2375
  const dataForContextType = this.getLatestBroadcastedDataByContextType(contextData, invokeForType);
@@ -2376,7 +2424,7 @@
2376
2424
  });
2377
2425
  return foundData;
2378
2426
  }
2379
- checkIfShouldInvokeInitialReplay(didReplay, contextData) {
2427
+ checkIfAppChannelShouldInvokeInitialReplay(didReplay, contextData) {
2380
2428
  if (!didReplay.replayed) {
2381
2429
  didReplay.replayed = true;
2382
2430
  return false;
@@ -2901,7 +2949,7 @@
2901
2949
  return this.channelsController.broadcast(generateCommandId(), context, this.id);
2902
2950
  }
2903
2951
  async getCurrentContext(contextType) {
2904
- optionalNonEmptyStringDecoder.run(contextType);
2952
+ nonEmptyStringDecoder.run(contextType);
2905
2953
  return this.channelsController.getContextForChannel({ commandId: generateCommandId(), channelId: this.id, contextType });
2906
2954
  }
2907
2955
  async addContextListener(contextType, handler) {
@@ -3043,10 +3091,6 @@
3043
3091
  this.logger?.info(`[${commandId}] - raiseIntentForContext() invoked with contextType ${context.type} and target ${target}`);
3044
3092
  const filteredHandlersMethodExist = this.glueController.doesFilterHandlersExist();
3045
3093
  const getIntentsMethodExist = this.glueController.doesGetIntentsExist();
3046
- const rememberedIntentHandlerForContextType = await this.checkForRememberedIntentHandlerForContext(context.type);
3047
- if (rememberedIntentHandlerForContextType) {
3048
- return this.invokeRaiseIntent(commandId, { context, intent: rememberedIntentHandlerForContextType.intent });
3049
- }
3050
3094
  if (!filteredHandlersMethodExist || !getIntentsMethodExist || target) {
3051
3095
  return this.legacyRaiseIntentForContext({ commandId, context, target });
3052
3096
  }
@@ -3076,23 +3120,28 @@
3076
3120
  await this.glueController.gluePromise;
3077
3121
  this.logger?.info(`[${commandId}] - addIntentListener() invoked for intent ${intent}`);
3078
3122
  const wrappedHandler = this.getWrappedIntentHandler(handler);
3079
- return this.glueController.addIntentListener(intent, wrappedHandler);
3080
- }
3081
- async checkForRememberedIntentHandlerForContext(contextType) {
3082
- const prefs = await this.glueController.getPrefs();
3083
- const intentPrefs = prefs.data?.intents;
3084
- if (!intentPrefs) {
3085
- return;
3123
+ const myInstance = this.glueController.getMyInteropInstance();
3124
+ const myApplication = this.glueController.getApplication(myInstance.applicationName);
3125
+ let appConfigIntentDef;
3126
+ const globalBrowserNamespace = window.glue42core || window.iobrowser;
3127
+ const globalDesktopNamespace = window.glue42gd || window.iodesktop;
3128
+ if (globalBrowserNamespace) {
3129
+ appConfigIntentDef = myApplication?.userProperties.intents?.find((appIntent) => appIntent.name === intent);
3086
3130
  }
3087
- const prefsForContextType = Object.entries(intentPrefs).find(([intentName, savedValue]) => savedValue.filter?.contextTypes?.includes(contextType));
3088
- if (!prefsForContextType) {
3089
- return;
3131
+ if (globalDesktopNamespace) {
3132
+ const appConfig = await myApplication.getConfiguration();
3133
+ appConfigIntentDef = appConfig?.intents?.find((appIntent) => appIntent.name === intent);
3090
3134
  }
3091
- const [intent, rememberedHandlerWithFilter] = prefsForContextType;
3092
- return {
3135
+ const intentRequest = {
3093
3136
  intent,
3094
- handler: rememberedHandlerWithFilter.handler
3137
+ displayName: appConfigIntentDef?.displayName,
3138
+ description: appConfigIntentDef?.description,
3139
+ contextTypes: appConfigIntentDef?.contexts || Fdc3SupportedIntentTypes[intent],
3140
+ resultType: appConfigIntentDef?.resultType
3095
3141
  };
3142
+ Object.keys(intentRequest)
3143
+ .forEach((key) => intentRequest[key] === undefined && delete intentRequest[key]);
3144
+ return this.glueController.addIntentListener(intentRequest, wrappedHandler);
3096
3145
  }
3097
3146
  filterGlueIntentHandlers({ commandId, intent, context, target }) {
3098
3147
  let filteredGlueIntent;
@@ -3142,7 +3191,9 @@
3142
3191
  return servers;
3143
3192
  }
3144
3193
  filterIntentHandlersByContext(intent, context) {
3145
- const filteredGlueIntent = this.getGlueIntentWithFilteredHandlers(intent, { contextType: context.type });
3194
+ const filteredGlueIntent = context.type === fdc3NothingContextType
3195
+ ? intent
3196
+ : this.getGlueIntentWithFilteredHandlers(intent, { contextType: context.type });
3146
3197
  if (!filteredGlueIntent.handlers.length) {
3147
3198
  throw { message: ResolveError.NoAppsFound, reason: `There's no app registering an intent with the passed context type ${context.type}` };
3148
3199
  }
@@ -3254,14 +3305,23 @@
3254
3305
  }
3255
3306
  getGlueIntentWithFilteredHandlers(glueIntent, filter) {
3256
3307
  const { name, handlers } = glueIntent;
3308
+ const desktopGlobal = window.glue42gd || window.iodesktop;
3257
3309
  let filteredHandlers = handlers;
3258
- const contextType = filter.contextType;
3259
- if (contextType) {
3260
- filteredHandlers = handlers.filter((handler) => handler.instanceId ? true : handler.contextTypes?.includes(contextType));
3310
+ if (filter.contextType) {
3311
+ filteredHandlers = handlers.filter((handler) => {
3312
+ if (handler.instanceId) {
3313
+ const appExists = desktopGlobal && handler.applicationName === Glue42EnterpriseNoAppWindow
3314
+ ? false
3315
+ : !!(this.glueController.getApplication(handler.applicationName));
3316
+ return appExists
3317
+ ? handler.contextTypes?.includes(filter.contextType)
3318
+ : handler;
3319
+ }
3320
+ return handler.contextTypes?.includes(filter.contextType);
3321
+ });
3261
3322
  }
3262
- const resultType = filter.resultType;
3263
- if (resultType) {
3264
- filteredHandlers = handlers.filter((handler) => handler.instanceId ? true : handler.resultType?.includes(resultType));
3323
+ if (filter.resultType) {
3324
+ filteredHandlers = handlers.filter((handler) => handler.resultType?.includes(filter.resultType));
3265
3325
  }
3266
3326
  return { name, handlers: filteredHandlers };
3267
3327
  }
@@ -3301,7 +3361,7 @@
3301
3361
  }
3302
3362
  }
3303
3363
 
3304
- var version = "2.3.4-next.0";
3364
+ var version = "2.3.4";
3305
3365
 
3306
3366
  class ApplicationsController {
3307
3367
  glueController;
@@ -3478,133 +3538,468 @@
3478
3538
  }
3479
3539
  }
3480
3540
 
3481
- class EventReceiver {
3541
+ class ChannelsController {
3482
3542
  glueController;
3483
- eventDispatcher;
3484
- glueResponseReceived = false;
3485
- glueInitialized = false;
3486
- _glueReceiverHandler;
3487
- events = {
3488
- "start": { name: START, handle: this.handleStart.bind(this) },
3489
- "requestGlueResponse": { name: REQUEST_GLUE_RESPONSE, handle: this.handleRequestGlueResponse.bind(this) }
3490
- };
3491
- constructor(glueController, eventDispatcher) {
3543
+ channelsStateStore;
3544
+ channelsParser;
3545
+ channelsFactory;
3546
+ glueEventsController;
3547
+ _logger;
3548
+ initDonePromise;
3549
+ invokeContextHandlerWithStartupContext = true;
3550
+ constructor(glueController, channelsStateStore, channelsParser, channelsFactory, glueEventsController) {
3492
3551
  this.glueController = glueController;
3493
- this.eventDispatcher = eventDispatcher;
3494
- }
3495
- start() {
3496
- this.wireCustomEventListener();
3497
- this.eventDispatcher.fireNotifyStarted();
3552
+ this.channelsStateStore = channelsStateStore;
3553
+ this.channelsParser = channelsParser;
3554
+ this.channelsFactory = channelsFactory;
3555
+ this.glueEventsController = glueEventsController;
3556
+ this.initDonePromise = this.initialize();
3557
+ this.initDonePromise.catch((err) => {
3558
+ this.logger?.error(err);
3559
+ });
3498
3560
  }
3499
- wireCustomEventListener() {
3500
- this._glueReceiverHandler = this.glueReceiverHandler.bind(this);
3501
- window.addEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3561
+ async getStartupContext() {
3562
+ await this.initDonePromise;
3563
+ const fdc3StartupContext = await this.glueController.getMyWindowContext();
3564
+ return fdc3StartupContext?.fdc3?.context?.payload || null;
3502
3565
  }
3503
- handleStart() {
3504
- this.eventDispatcher.fireRequestGlue();
3566
+ async addContextListener({ commandId, handler, contextType, channelId }) {
3567
+ await this.initDonePromise;
3568
+ this.logger?.info(`[${commandId}] - addContextListener() invoked for contextType ${contextType} and channelId ${channelId}`);
3569
+ if (this.invokeContextHandlerWithStartupContext && !channelId) {
3570
+ this.logger?.info(`[${commandId}] - trying to invoke context handler with window context`);
3571
+ this.handleWindowContextOnOpening(commandId, handler, contextType).catch((err) => this.logger?.warn(`[${commandId}] - ${err}`));
3572
+ }
3573
+ const channelIdToSubscribeTo = channelId || this.channelsStateStore.currentChannel?.id;
3574
+ return this.addContextListenerByChannelId({ commandId, handler, invokedOnChannelModel: !!channelId, channelId: channelIdToSubscribeTo, contextType });
3505
3575
  }
3506
- glueReceiverHandler(event) {
3507
- const data = event.detail;
3508
- if (!data || !data.glue42) {
3576
+ async broadcast(commandId, context, channelId) {
3577
+ await this.initDonePromise;
3578
+ this.logger?.info(`[${commandId}] - broadcast() invoked with contextType ${context.type} and channelId ${channelId}`);
3579
+ const canBroadcast = this.isBroadcastPermitted(commandId, channelId);
3580
+ if (!canBroadcast) {
3509
3581
  return;
3510
3582
  }
3511
- const glue42Event = data.glue42.event;
3512
- const foundHandler = this.events[glue42Event];
3513
- if (!foundHandler) {
3514
- return;
3583
+ const channelIdToBroadcastTo = channelId || this.channelsStateStore.currentChannel.id;
3584
+ return this.broadcastByChannelId(commandId, channelIdToBroadcastTo, context);
3585
+ }
3586
+ async getUserChannels(commandId) {
3587
+ await this.initDonePromise;
3588
+ this.logger?.info(`[${commandId}] - getUserChannels() invoked`);
3589
+ return Object.values(this.channelsStateStore.userChannels);
3590
+ }
3591
+ async getOrCreateChannel({ commandId, channelId }) {
3592
+ await this.initDonePromise;
3593
+ this.logger?.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
3594
+ const isUserChannel = this.isUserChannel(channelId);
3595
+ if (isUserChannel) {
3596
+ 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" };
3515
3597
  }
3516
- foundHandler.handle(data.glue42.message);
3598
+ const isPrivateChannel = this.channelsStateStore.getPrivateChannelById(channelId);
3599
+ if (isPrivateChannel) {
3600
+ throw { message: ChannelError.AccessDenied, reason: "Cannot retrieve a private channel" };
3601
+ }
3602
+ return this.getOrCreateAppChannel(commandId, channelId);
3517
3603
  }
3518
- async handleRequestGlueResponse(data) {
3519
- if (this.glueResponseReceived && this.glueInitialized) {
3520
- return;
3604
+ async joinUserChannel({ commandId, channelId }) {
3605
+ await this.initDonePromise;
3606
+ this.logger?.info(`[${commandId}] - joinUserChannel() invoked for channel with id ${channelId}`);
3607
+ const isAppChannel = this.doesAppChannelExist(channelId);
3608
+ if (isAppChannel) {
3609
+ throw { message: ChannelError.AccessDenied, reason: "Cannot join an app channel" };
3521
3610
  }
3522
- this.glueResponseReceived = true;
3523
- const { glue } = data;
3524
- const glueValidator = this.glueController.validateGlue(glue);
3525
- if (!glueValidator.isValid) {
3526
- this.glueController.initializeFailed(glueValidator.error);
3527
- window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3611
+ const channelToJoin = this.channelsStateStore.userChannels[channelId];
3612
+ if (!channelToJoin) {
3613
+ throw { message: ChannelError.NoChannelFound, reason: `Cannot find user channel with id ${channelId}` };
3614
+ }
3615
+ const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
3616
+ this.channelsStateStore.currentChannel = channelToJoin;
3617
+ this.logger?.info(`[${commandId}] - joining fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
3618
+ await this.glueController.joinChannel(glueChannelName);
3619
+ }
3620
+ async getCurrentChannel(commandId) {
3621
+ await this.initDonePromise;
3622
+ this.logger?.info(`[${commandId}] - getCurrentChannel() invoked`);
3623
+ return this.channelsStateStore.currentChannel;
3624
+ }
3625
+ async leaveCurrentChannel(commandId) {
3626
+ await this.initDonePromise;
3627
+ this.logger?.info(`[${commandId}] - leaveCurrentChannel() invoked`);
3628
+ if (!this.channelsStateStore.currentChannel) {
3629
+ this.logger?.info(`[${commandId}] - no channel to leave`);
3528
3630
  return;
3529
3631
  }
3530
- window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3531
- this.glueController.initialize(glue);
3532
- this.eventDispatcher.fireFdc3Ready();
3533
- this.glueInitialized = true;
3632
+ await this.glueController.leaveChannel();
3633
+ this.channelsStateStore.currentChannel = null;
3634
+ this.logger?.info(`[${commandId}] - current channel is left. unsubscribing from all listeners`);
3534
3635
  }
3535
- }
3536
-
3537
- class ChannelsStateStore {
3538
- _currentChannel = null;
3539
- _userChannels = {};
3540
- _fdc3ChannelIdsToGlueChannelNames = {};
3541
- _privateChannels = {};
3542
- get currentChannel() {
3543
- return this._currentChannel;
3636
+ async getContextForChannel({ commandId, channelId, contextType }) {
3637
+ await this.initDonePromise;
3638
+ this.logger?.info(`[${commandId}] - getContextForChannel() invoked for channel with id ${channelId}`);
3639
+ const isUserChannel = this.isUserChannel(channelId);
3640
+ if (!contextType) {
3641
+ this.logger?.info(`[${commandId}] - retrieving latest context broadcasted on channel with id ${channelId}`);
3642
+ let context;
3643
+ if (isUserChannel) {
3644
+ const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
3645
+ const glueChannelWithPrefix = this.channelsParser.mapChannelNameToContextName(glueChannelName);
3646
+ this.logger?.info(`[${commandId}] - getting context for user channel with id ${channelId} (underlying glue channel ${glueChannelName})`);
3647
+ context = await this.glueController.getContext(glueChannelWithPrefix);
3648
+ }
3649
+ else {
3650
+ this.logger?.info(`[${commandId}] - getting context for app channel with id ${channelId}`);
3651
+ context = await this.glueController.getContext(channelId);
3652
+ }
3653
+ return context.latest_fdc3_type
3654
+ ? this.channelsParser.parseContextsDataToInitialFDC3Data(context)
3655
+ : null;
3656
+ }
3657
+ this.logger?.info(`[${commandId}] Retrieving latest context of type ${contextType} broadcasted on ${isUserChannel ? "user" : "app"} channel with id ${channelId}`);
3658
+ const parsedType = this.channelsParser.mapFDC3TypeToChannelsDelimiter(contextType);
3659
+ const { data } = isUserChannel
3660
+ ? await this.glueController.getChannel(this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId))
3661
+ : await this.glueController.getContext(channelId);
3662
+ return data && data[`fdc3_${parsedType}`]
3663
+ ? this.channelsParser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
3664
+ : null;
3544
3665
  }
3545
- set currentChannel(newChannelValue) {
3546
- this._currentChannel = newChannelValue;
3666
+ async createPrivateChannel(commandId) {
3667
+ await this.initDonePromise;
3668
+ this.logger?.info(`[${commandId}] - createPrivateChannel() invoked`);
3669
+ const channelId = `${PrivateChannelPrefix}${nanoid()}`;
3670
+ await this.glueEventsController.initializeCollaborateMethod();
3671
+ const pc = this.buildPrivateChannel(channelId, commandId, true);
3672
+ return pc.toApi();
3547
3673
  }
3548
- get userChannels() {
3549
- return this._userChannels;
3674
+ async removePrivateChannelFromStoreById(id) {
3675
+ this.channelsStateStore.removePrivateChannelById(id);
3550
3676
  }
3551
- addUserChannel(channel) {
3552
- this._userChannels[channel.id] = channel;
3677
+ async invokeSystemMethod(args, target) {
3678
+ if (!target) {
3679
+ return;
3680
+ }
3681
+ return this.glueController.invokeSystemMethod(args, target);
3553
3682
  }
3554
- addFdc3IdToGlueChannelName(fdc3Id, glueChannelName) {
3555
- this._fdc3ChannelIdsToGlueChannelNames[fdc3Id] = glueChannelName;
3683
+ getMyServerInstance() {
3684
+ return this.glueController.getMyInteropInstance();
3556
3685
  }
3557
- getGlueChannelNameByFdc3ChannelId(fdc3Id) {
3558
- return this._fdc3ChannelIdsToGlueChannelNames[fdc3Id];
3686
+ async addClientToPrivateChannel(commandId, channelId, clientId) {
3687
+ this.logger?.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
3688
+ await this.glueController.updateContext(channelId, { clientId });
3559
3689
  }
3560
- getFdc3ChannelIdByGlueChannelName(glueChannelName) {
3561
- const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
3562
- return key;
3690
+ async isPrivateChannelDisconnected({ commandId, channelId }) {
3691
+ this.logger?.info(`[${commandId}] - checking if private channel with id ${channelId} is disconnected`);
3692
+ const context = await this.glueController.getContext(channelId);
3693
+ return !!context.disconnected;
3563
3694
  }
3564
- addPrivateChannel(privateChannel) {
3565
- this._privateChannels[privateChannel.id] = privateChannel;
3695
+ subscribeOnInstanceStop(channelId, handler, commandId) {
3696
+ this.logger?.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
3697
+ return this.glueController.registerOnInstanceStopped(handler.bind(this));
3566
3698
  }
3567
- getPrivateChannelById(id) {
3568
- return this._privateChannels[id];
3699
+ buildPrivateChannel(channelId, commandId, isCreator) {
3700
+ const logger = this.glueController.initSubLogger(channelId);
3701
+ const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
3702
+ this.logger?.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
3703
+ this.channelsStateStore.addPrivateChannel(channel);
3704
+ return channel;
3569
3705
  }
3570
- removePrivateChannelById(id) {
3571
- delete this._privateChannels[id];
3706
+ get logger() {
3707
+ if (!this._logger) {
3708
+ this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
3709
+ }
3710
+ return this._logger;
3572
3711
  }
3573
- }
3574
-
3575
- function getDefaultExportFromCjs (x) {
3576
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3577
- }
3578
-
3579
- function createRegistry(options) {
3580
- if (options && options.errorHandling
3581
- && typeof options.errorHandling !== "function"
3582
- && options.errorHandling !== "log"
3583
- && options.errorHandling !== "silent"
3584
- && options.errorHandling !== "throw") {
3585
- throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
3712
+ async initialize() {
3713
+ await this.glueController.gluePromise;
3714
+ const current = this.glueController.getCurrentChannel();
3715
+ const glueChannels = await this.glueController.listAllChannels();
3716
+ const glueChannelsWithFdc3Meta = glueChannels.filter((glueChannel) => glueChannel.meta.fdc3);
3717
+ glueChannelsWithFdc3Meta.forEach((glueChannel) => {
3718
+ const userChannel = this.buildChannel(ChannelTypes.User, { displayMetadata: { glueChannel } });
3719
+ this.channelsStateStore.addFdc3IdToGlueChannelName(userChannel.id, glueChannel.name);
3720
+ this.channelsStateStore.addUserChannel(userChannel);
3721
+ if (current && glueChannel.name === current) {
3722
+ this.channelsStateStore.currentChannel = userChannel;
3723
+ }
3724
+ });
3725
+ this.glueController.setOnChannelChanged(this.handleOnChannelChanged.bind(this));
3586
3726
  }
3587
- var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
3588
- var callbacks = {};
3589
- function add(key, callback, replayArgumentsArr) {
3590
- var callbacksForKey = callbacks[key];
3591
- if (!callbacksForKey) {
3592
- callbacksForKey = [];
3593
- callbacks[key] = callbacksForKey;
3727
+ async handleOnChannelChanged(channelId) {
3728
+ if (!channelId) {
3729
+ return;
3594
3730
  }
3595
- callbacksForKey.push(callback);
3596
- if (replayArgumentsArr) {
3597
- setTimeout(function () {
3598
- replayArgumentsArr.forEach(function (replayArgument) {
3599
- var _a;
3600
- if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) {
3601
- try {
3602
- if (Array.isArray(replayArgument)) {
3603
- callback.apply(undefined, replayArgument);
3604
- }
3605
- else {
3606
- callback.apply(undefined, [replayArgument]);
3607
- }
3731
+ const isFdc3ChannelName = fdc3ChannelNames.includes(channelId);
3732
+ const userChannelId = isFdc3ChannelName ? channelId : this.channelsStateStore.getFdc3ChannelIdByGlueChannelName(channelId);
3733
+ this.channelsStateStore.currentChannel = this.channelsStateStore.userChannels[userChannelId];
3734
+ }
3735
+ isBroadcastPermitted(commandId, channelId) {
3736
+ if (channelId) {
3737
+ return true;
3738
+ }
3739
+ if (!this.channelsStateStore.currentChannel) {
3740
+ this.logger?.info(`[${commandId}] - invocation of broadcast ignored - no channel to broadcast to`);
3741
+ console.error("You need to join a user channel in order to broadcast");
3742
+ return false;
3743
+ }
3744
+ if (this.channelsStateStore.currentChannel.type === ChannelTypes.App) {
3745
+ this.logger?.info(`[${commandId}] - invocation of broadcast ignored - cannot broadcast on app channel directly`);
3746
+ console.error("You can't broadcast to an app channel directly - use channel's broadcast method instead");
3747
+ return false;
3748
+ }
3749
+ return true;
3750
+ }
3751
+ async handleWindowContextOnOpening(commandId, handler, contextType) {
3752
+ const myWindow = this.glueController.getMyWindow();
3753
+ if (!myWindow) {
3754
+ this.logger?.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
3755
+ this.invokeContextHandlerWithStartupContext = false;
3756
+ return;
3757
+ }
3758
+ const windowContext = await myWindow.getContext();
3759
+ if (!windowContext) {
3760
+ this.logger?.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
3761
+ this.invokeContextHandlerWithStartupContext = false;
3762
+ return;
3763
+ }
3764
+ if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
3765
+ this.logger?.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
3766
+ this.invokeContextHandlerWithStartupContext = false;
3767
+ return;
3768
+ }
3769
+ await this.glueEventsController.initializeCollaborateMethod();
3770
+ FDC3StartupContextDecoder.runWithException(windowContext);
3771
+ const { fdc3 } = windowContext;
3772
+ this.logger?.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
3773
+ const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
3774
+ if (!isSameContextType) {
3775
+ this.logger?.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
3776
+ return;
3777
+ }
3778
+ this.logger?.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
3779
+ try {
3780
+ handler(fdc3.context.payload, { source: fdc3.openApp });
3781
+ }
3782
+ catch (error) {
3783
+ this.logger?.error(typeof error === "string" ? error : error.message ? JSON.stringify(error.message) : JSON.stringify(error));
3784
+ }
3785
+ this.invokeContextHandlerWithStartupContext = false;
3786
+ this.logger?.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
3787
+ await this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
3788
+ this.logger?.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
3789
+ }
3790
+ async getOrCreateAppChannel(commandId, channelId) {
3791
+ const exists = this.doesAppChannelExist(channelId);
3792
+ if (!exists) {
3793
+ this.logger?.info(`[${commandId}] - app channel with id ${channelId} does not exist. Creating one`);
3794
+ await this.glueController.updateContext(channelId, {});
3795
+ }
3796
+ this.logger?.info(`[${commandId}] - returning app channel with id ${channelId}`);
3797
+ const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
3798
+ return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
3799
+ }
3800
+ doesAppChannelExist(name) {
3801
+ return !name.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === name);
3802
+ }
3803
+ isUserChannel(channelId) {
3804
+ if (!channelId) {
3805
+ return false;
3806
+ }
3807
+ return !!this.channelsStateStore.userChannels[channelId];
3808
+ }
3809
+ async broadcastByChannelId(commandId, channelId, context) {
3810
+ const isUserChannel = this.isUserChannel(channelId);
3811
+ if (!isUserChannel) {
3812
+ this.logger?.info(`[${commandId}] - broadcasting on app channel with id ${channelId}`);
3813
+ return this.glueController.updateContextWithLatestFdc3Type(channelId, context);
3814
+ }
3815
+ const glueChannelName = this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId);
3816
+ this.logger?.info(`[${commandId}] - broadcasting on fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
3817
+ return this.glueController.channelsUpdate(glueChannelName, context);
3818
+ }
3819
+ async addContextListenerByChannelId({ commandId, channelId, handler, contextType, invokedOnChannelModel }) {
3820
+ const subHandler = parseContextHandler(handler, contextType);
3821
+ if (!channelId) {
3822
+ this.logger?.info(`[${commandId}] - Creating a channel subscription using glue.channels.subscribe`);
3823
+ const unsubscribe = this.glueController.channelsSubscribe(subHandler, contextType);
3824
+ return { unsubscribe };
3825
+ }
3826
+ const channelType = this.getChannelTypeById(channelId);
3827
+ if (channelType === ChannelTypes.User) {
3828
+ return this.addContextListenerOnUserChannel({ commandId, channelId, handler: subHandler, contextType, invokedOnChannelModel });
3829
+ }
3830
+ if (channelType === ChannelTypes.App) {
3831
+ this.logger?.info(`[${commandId}] - subscribing for fdc3 app channel with id ${channelId} (underlying glue context with same name)`);
3832
+ const unsubscribe = await this.glueController.contextsSubscribe(channelId, subHandler);
3833
+ return {
3834
+ unsubscribe: () => {
3835
+ this.logger?.info(`[${commandId}] - invoking unsubscribe for app channel with id ${channelId}`);
3836
+ unsubscribe();
3837
+ }
3838
+ };
3839
+ }
3840
+ throw { message: ChannelError.AccessDenied, reason: "Cannot add a context listener on an invalid channel" };
3841
+ }
3842
+ async addContextListenerOnUserChannel({ commandId, channelId, handler, invokedOnChannelModel, contextType }) {
3843
+ let unsubscribe;
3844
+ if (invokedOnChannelModel) {
3845
+ const contextToSubscribeTo = this.channelsParser.mapChannelNameToContextName(this.channelsStateStore.getGlueChannelNameByFdc3ChannelId(channelId));
3846
+ this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
3847
+ unsubscribe = await this.glueController.contextsSubscribe(contextToSubscribeTo, handler);
3848
+ }
3849
+ else {
3850
+ this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
3851
+ unsubscribe = this.glueController.channelsSubscribe(handler, contextType);
3852
+ }
3853
+ return {
3854
+ unsubscribe: () => {
3855
+ this.logger?.info(`[${commandId}] - invoking unsubscribe for fdc3 user channel with id ${channelId}`);
3856
+ unsubscribe();
3857
+ }
3858
+ };
3859
+ }
3860
+ getChannelTypeById(channelId) {
3861
+ const isUser = this.isUserChannel(channelId);
3862
+ if (isUser) {
3863
+ return ChannelTypes.User;
3864
+ }
3865
+ const isApp = this.doesAppChannelExist(channelId);
3866
+ if (isApp) {
3867
+ return ChannelTypes.App;
3868
+ }
3869
+ throw { message: ChannelError.NoChannelFound, reason: `Channel with id: ${channelId} does not exist` };
3870
+ }
3871
+ buildChannel(type, data) {
3872
+ return this.channelsFactory.buildModel({ type, ...data });
3873
+ }
3874
+ }
3875
+
3876
+ class EventReceiver {
3877
+ glueController;
3878
+ eventDispatcher;
3879
+ glueResponseReceived = false;
3880
+ glueInitialized = false;
3881
+ _glueReceiverHandler;
3882
+ events = {
3883
+ "start": { name: START, handle: this.handleStart.bind(this) },
3884
+ "requestGlueResponse": { name: REQUEST_GLUE_RESPONSE, handle: this.handleRequestGlueResponse.bind(this) }
3885
+ };
3886
+ constructor(glueController, eventDispatcher) {
3887
+ this.glueController = glueController;
3888
+ this.eventDispatcher = eventDispatcher;
3889
+ }
3890
+ start() {
3891
+ this.wireCustomEventListener();
3892
+ this.eventDispatcher.fireNotifyStarted();
3893
+ }
3894
+ wireCustomEventListener() {
3895
+ this._glueReceiverHandler = this.glueReceiverHandler.bind(this);
3896
+ window.addEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3897
+ }
3898
+ handleStart() {
3899
+ this.eventDispatcher.fireRequestGlue();
3900
+ }
3901
+ glueReceiverHandler(event) {
3902
+ const data = event.detail;
3903
+ if (!data || !data.glue42) {
3904
+ return;
3905
+ }
3906
+ const glue42Event = data.glue42.event;
3907
+ const foundHandler = this.events[glue42Event];
3908
+ if (!foundHandler) {
3909
+ return;
3910
+ }
3911
+ foundHandler.handle(data.glue42.message);
3912
+ }
3913
+ async handleRequestGlueResponse(data) {
3914
+ if (this.glueResponseReceived && this.glueInitialized) {
3915
+ return;
3916
+ }
3917
+ this.glueResponseReceived = true;
3918
+ const { glue } = data;
3919
+ const glueValidator = this.glueController.validateGlue(glue);
3920
+ if (!glueValidator.isValid) {
3921
+ this.glueController.initializeFailed(glueValidator.error);
3922
+ window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3923
+ return;
3924
+ }
3925
+ window.removeEventListener(GLUE42_EVENT_NAME, this._glueReceiverHandler);
3926
+ this.glueController.initialize(glue);
3927
+ this.eventDispatcher.fireFdc3Ready();
3928
+ this.glueInitialized = true;
3929
+ }
3930
+ }
3931
+
3932
+ class ChannelsStateStore {
3933
+ _currentChannel = null;
3934
+ _userChannels = {};
3935
+ _fdc3ChannelIdsToGlueChannelNames = {};
3936
+ _privateChannels = {};
3937
+ get currentChannel() {
3938
+ return this._currentChannel;
3939
+ }
3940
+ set currentChannel(newChannelValue) {
3941
+ this._currentChannel = newChannelValue;
3942
+ }
3943
+ get userChannels() {
3944
+ return this._userChannels;
3945
+ }
3946
+ addUserChannel(channel) {
3947
+ this._userChannels[channel.id] = channel;
3948
+ }
3949
+ addFdc3IdToGlueChannelName(fdc3Id, glueChannelName) {
3950
+ this._fdc3ChannelIdsToGlueChannelNames[fdc3Id] = glueChannelName;
3951
+ }
3952
+ getGlueChannelNameByFdc3ChannelId(fdc3Id) {
3953
+ return this._fdc3ChannelIdsToGlueChannelNames[fdc3Id];
3954
+ }
3955
+ getFdc3ChannelIdByGlueChannelName(glueChannelName) {
3956
+ const [key] = Object.entries(this._fdc3ChannelIdsToGlueChannelNames).find(([_, value]) => value === glueChannelName);
3957
+ return key;
3958
+ }
3959
+ addPrivateChannel(privateChannel) {
3960
+ this._privateChannels[privateChannel.id] = privateChannel;
3961
+ }
3962
+ getPrivateChannelById(id) {
3963
+ return this._privateChannels[id];
3964
+ }
3965
+ removePrivateChannelById(id) {
3966
+ delete this._privateChannels[id];
3967
+ }
3968
+ }
3969
+
3970
+ function getDefaultExportFromCjs (x) {
3971
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
3972
+ }
3973
+
3974
+ function createRegistry(options) {
3975
+ if (options && options.errorHandling
3976
+ && typeof options.errorHandling !== "function"
3977
+ && options.errorHandling !== "log"
3978
+ && options.errorHandling !== "silent"
3979
+ && options.errorHandling !== "throw") {
3980
+ throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
3981
+ }
3982
+ var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
3983
+ var callbacks = {};
3984
+ function add(key, callback, replayArgumentsArr) {
3985
+ var callbacksForKey = callbacks[key];
3986
+ if (!callbacksForKey) {
3987
+ callbacksForKey = [];
3988
+ callbacks[key] = callbacksForKey;
3989
+ }
3990
+ callbacksForKey.push(callback);
3991
+ if (replayArgumentsArr) {
3992
+ setTimeout(function () {
3993
+ replayArgumentsArr.forEach(function (replayArgument) {
3994
+ var _a;
3995
+ if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) {
3996
+ try {
3997
+ if (Array.isArray(replayArgument)) {
3998
+ callback.apply(undefined, replayArgument);
3999
+ }
4000
+ else {
4001
+ callback.apply(undefined, [replayArgument]);
4002
+ }
3608
4003
  }
3609
4004
  catch (err) {
3610
4005
  _handleError(err, key);
@@ -4141,427 +4536,6 @@
4141
4536
  }
4142
4537
  }
4143
4538
 
4144
- class ChannelsBaseController {
4145
- glueController;
4146
- stateStore;
4147
- parser;
4148
- channelsFactory;
4149
- glueEventsController;
4150
- legacyController;
4151
- ioFdc3SupportedController;
4152
- _logger;
4153
- initDonePromise;
4154
- invokeContextHandlerWithStartupContext = true;
4155
- isFdc3DataWrappingSupported;
4156
- constructor(glueController, stateStore, parser, channelsFactory, glueEventsController, legacyController, ioFdc3SupportedController) {
4157
- this.glueController = glueController;
4158
- this.stateStore = stateStore;
4159
- this.parser = parser;
4160
- this.channelsFactory = channelsFactory;
4161
- this.glueEventsController = glueEventsController;
4162
- this.legacyController = legacyController;
4163
- this.ioFdc3SupportedController = ioFdc3SupportedController;
4164
- this.initDonePromise = this.initialize();
4165
- this.initDonePromise.catch((err) => {
4166
- this.logger?.error(err);
4167
- });
4168
- }
4169
- async getStartupContext() {
4170
- await this.initDonePromise;
4171
- const fdc3StartupContext = await this.glueController.getMyWindowContext();
4172
- return fdc3StartupContext?.fdc3?.context?.payload || null;
4173
- }
4174
- async addContextListener({ commandId, handler, contextType, channelId }) {
4175
- await this.initDonePromise;
4176
- this.logger?.info(`[${commandId}] - addContextListener() invoked for contextType ${contextType} and channelId ${channelId}`);
4177
- if (this.invokeContextHandlerWithStartupContext && !channelId) {
4178
- this.logger?.info(`[${commandId}] - trying to invoke context handler with window context`);
4179
- this.handleWindowContextOnOpening(commandId, handler, contextType).catch((err) => this.logger?.warn(`[${commandId}] - ${err}`));
4180
- }
4181
- const channelIdToSubscribeTo = channelId || this.stateStore.currentChannel?.id;
4182
- if (!channelIdToSubscribeTo) {
4183
- return this.addContextListenerWithoutChannelId({ commandId, handler, invokedOnChannelModel: !!channelId, contextType });
4184
- }
4185
- return this.addContextListenerByChannelId({ commandId, handler, invokedOnChannelModel: !!channelId, channelId: channelIdToSubscribeTo, contextType });
4186
- }
4187
- async broadcast(commandId, context, channelId) {
4188
- await this.initDonePromise;
4189
- this.logger?.info(`[${commandId}] - broadcast() invoked with contextType ${context.type} and channelId ${channelId}`);
4190
- const canBroadcast = this.isBroadcastPermitted(commandId, channelId);
4191
- if (!canBroadcast) {
4192
- return;
4193
- }
4194
- const channelIdToBroadcastTo = channelId || this.stateStore.currentChannel.id;
4195
- return this.broadcastByChannelId(commandId, channelIdToBroadcastTo, context);
4196
- }
4197
- async getUserChannels(commandId) {
4198
- await this.initDonePromise;
4199
- this.logger?.info(`[${commandId}] - getUserChannels() invoked`);
4200
- return Object.values(this.stateStore.userChannels);
4201
- }
4202
- async getOrCreateChannel({ commandId, channelId }) {
4203
- await this.initDonePromise;
4204
- this.logger?.info(`[${commandId}] - getOrCreateChannel() invoked for channel with id ${channelId}`);
4205
- const isUserChannel = this.isUserChannel(channelId);
4206
- if (isUserChannel) {
4207
- this.logger?.error("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");
4208
- throw new Error(ChannelError.AccessDenied);
4209
- }
4210
- const isPrivateChannel = this.stateStore.getPrivateChannelById(channelId);
4211
- if (isPrivateChannel) {
4212
- this.logger?.error("Cannot retrieve a private channel");
4213
- throw new Error(ChannelError.AccessDenied);
4214
- }
4215
- return this.getOrCreateAppChannel(commandId, channelId);
4216
- }
4217
- async joinUserChannel({ commandId, channelId }) {
4218
- await this.initDonePromise;
4219
- this.logger?.info(`[${commandId}] - joinUserChannel() invoked for channel with id ${channelId}`);
4220
- const isAppChannel = this.doesAppChannelExist(channelId);
4221
- if (isAppChannel) {
4222
- this.logger?.error("Cannot join an app channel");
4223
- throw new Error(ChannelError.AccessDenied);
4224
- }
4225
- const channelToJoin = this.stateStore.userChannels[channelId];
4226
- if (!channelToJoin) {
4227
- this.logger?.error(`Cannot find user channel with id ${channelId}`);
4228
- throw new Error(ChannelError.NoChannelFound);
4229
- }
4230
- const glueChannelName = this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId);
4231
- this.stateStore.currentChannel = channelToJoin;
4232
- this.logger?.info(`[${commandId}] - joining fdc3 user channel with id ${channelId} (underlying glue channel: ${glueChannelName})`);
4233
- await this.glueController.joinChannel(glueChannelName);
4234
- }
4235
- async getCurrentChannel(commandId) {
4236
- await this.initDonePromise;
4237
- this.logger?.info(`[${commandId}] - getCurrentChannel() invoked`);
4238
- return this.stateStore.currentChannel;
4239
- }
4240
- async leaveCurrentChannel(commandId) {
4241
- await this.initDonePromise;
4242
- this.logger?.info(`[${commandId}] - leaveCurrentChannel() invoked`);
4243
- if (!this.stateStore.currentChannel) {
4244
- this.logger?.info(`[${commandId}] - no channel to leave`);
4245
- return;
4246
- }
4247
- await this.glueController.leaveChannel();
4248
- this.stateStore.currentChannel = null;
4249
- this.logger?.info(`[${commandId}] - current channel is left. unsubscribing from all listeners`);
4250
- }
4251
- async getContextForChannel({ commandId, channelId, contextType }) {
4252
- await this.initDonePromise;
4253
- this.logger?.info(`[${commandId}] - getContextForChannel() invoked for channel with id ${channelId}`);
4254
- const isUserChannel = this.isUserChannel(channelId);
4255
- if (isUserChannel) {
4256
- return this.userChannelsSupportController.getContext({ commandId, channelId, contextType });
4257
- }
4258
- if (!contextType) {
4259
- const context = await this.glueController.getContext(channelId);
4260
- return context.latest_fdc3_type ? this.parser.parseContextsDataToInitialFDC3Data(context) : null;
4261
- }
4262
- const parsedType = this.parser.mapFDC3TypeToChannelsDelimiter(contextType);
4263
- const { data } = await this.glueController.getContext(channelId);
4264
- return data?.[`fdc3_${parsedType}`]
4265
- ? this.parser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
4266
- : null;
4267
- }
4268
- async createPrivateChannel(commandId) {
4269
- await this.initDonePromise;
4270
- this.logger?.info(`[${commandId}] - createPrivateChannel() invoked`);
4271
- const channelId = `${PrivateChannelPrefix}${nanoid()}`;
4272
- await this.glueEventsController.initializeCollaborateMethod();
4273
- const pc = this.buildPrivateChannel(channelId, commandId, true);
4274
- return pc.toApi();
4275
- }
4276
- async removePrivateChannelFromStoreById(id) {
4277
- this.stateStore.removePrivateChannelById(id);
4278
- }
4279
- async invokeSystemMethod(args, target) {
4280
- if (!target) {
4281
- return;
4282
- }
4283
- return this.glueController.invokeSystemMethod(args, target);
4284
- }
4285
- getMyServerInstance() {
4286
- return this.glueController.getMyInteropInstance();
4287
- }
4288
- async addClientToPrivateChannel(commandId, channelId, clientId) {
4289
- this.logger?.info(`[${commandId}] - client with id ${clientId} added to private channel with id ${channelId}`);
4290
- await this.glueController.updateContext(channelId, { clientId });
4291
- }
4292
- async isPrivateChannelDisconnected({ commandId, channelId }) {
4293
- this.logger?.info(`[${commandId}] - checking if private channel with id ${channelId} is disconnected`);
4294
- const context = await this.glueController.getContext(channelId);
4295
- return !!context.disconnected;
4296
- }
4297
- subscribeOnInstanceStop(channelId, handler, commandId) {
4298
- this.logger?.info(`[${commandId}] - subscribing onInstanceStopped callback for channel with id ${channelId}`);
4299
- return this.glueController.registerOnInstanceStopped(handler.bind(this));
4300
- }
4301
- buildPrivateChannel(channelId, commandId, isCreator) {
4302
- const logger = this.glueController.initSubLogger(channelId);
4303
- const channel = this.buildChannel(ChannelTypes.Private, { id: channelId, logger, isCreator });
4304
- this.logger?.info(`[${commandId}] - private channel with id ${channelId} created. Adding it to the store`);
4305
- this.stateStore.addPrivateChannel(channel);
4306
- return channel;
4307
- }
4308
- buildChannel(type, data) {
4309
- return this.channelsFactory.buildModel({ type, ...data });
4310
- }
4311
- get logger() {
4312
- if (!this._logger) {
4313
- this._logger = this.glueController.initSubLogger("fdc3.channels.controller");
4314
- }
4315
- return this._logger;
4316
- }
4317
- get userChannelsSupportController() {
4318
- return this.isFdc3DataWrappingSupported ? this.ioFdc3SupportedController : this.legacyController;
4319
- }
4320
- async initialize() {
4321
- await this.glueController.gluePromise;
4322
- this.isFdc3DataWrappingSupported = await this.glueController.checkIsFdc3DataWrappingSupported();
4323
- const current = this.glueController.getCurrentChannel();
4324
- const glueChannels = await this.glueController.listAllChannels();
4325
- const glueChannelsWithFdc3Meta = glueChannels.filter((glueChannel) => glueChannel.meta.fdc3);
4326
- glueChannelsWithFdc3Meta.forEach((glueChannel) => {
4327
- const userChannel = this.buildChannel(ChannelTypes.User, { displayMetadata: { glueChannel } });
4328
- this.stateStore.addFdc3IdToGlueChannelName(userChannel.id, glueChannel.name);
4329
- this.stateStore.addUserChannel(userChannel);
4330
- if (current && glueChannel.name === current) {
4331
- this.stateStore.currentChannel = userChannel;
4332
- }
4333
- });
4334
- this.glueController.setOnChannelChanged(this.handleOnChannelChanged.bind(this));
4335
- }
4336
- async handleOnChannelChanged(channelId) {
4337
- if (!channelId) {
4338
- return;
4339
- }
4340
- const isFdc3ChannelName = fdc3ChannelNames.includes(channelId);
4341
- const userChannelId = isFdc3ChannelName ? channelId : this.stateStore.getFdc3ChannelIdByGlueChannelName(channelId);
4342
- this.stateStore.currentChannel = this.stateStore.userChannels[userChannelId];
4343
- }
4344
- isBroadcastPermitted(commandId, channelId) {
4345
- if (channelId) {
4346
- return true;
4347
- }
4348
- if (!this.stateStore.currentChannel) {
4349
- this.logger?.info(`[${commandId}] - invocation of broadcast ignored - no channel to broadcast to`);
4350
- console.warn("You need to join a user channel in order to broadcast");
4351
- return false;
4352
- }
4353
- if (this.stateStore.currentChannel.type === ChannelTypes.App) {
4354
- this.logger?.info(`[${commandId}] - invocation of broadcast ignored - cannot broadcast on app channel directly`);
4355
- console.error("You can't broadcast to an app channel directly - use channel's broadcast method instead");
4356
- return false;
4357
- }
4358
- return true;
4359
- }
4360
- async handleWindowContextOnOpening(commandId, handler, contextType) {
4361
- const myWindow = this.glueController.getMyWindow();
4362
- if (!myWindow) {
4363
- this.logger?.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
4364
- this.invokeContextHandlerWithStartupContext = false;
4365
- return;
4366
- }
4367
- const windowContext = await myWindow.getContext();
4368
- if (!windowContext) {
4369
- this.logger?.trace(`[${commandId}] - Cannot get window context because this is not a Glue window, it's probably an iframe`);
4370
- this.invokeContextHandlerWithStartupContext = false;
4371
- return;
4372
- }
4373
- if (!isValidNonEmptyObject(windowContext) || !windowContext.fdc3) {
4374
- this.logger?.info(`[${commandId}] - addContextListener handler won't be invoked - startup context is empty`);
4375
- this.invokeContextHandlerWithStartupContext = false;
4376
- return;
4377
- }
4378
- await this.glueEventsController.initializeCollaborateMethod();
4379
- FDC3StartupContextDecoder.runWithException(windowContext);
4380
- const { fdc3 } = windowContext;
4381
- this.logger?.trace(`[${commandId}] - received FDC3 startup context from ${JSON.stringify(fdc3.openApp)} for contextType ${fdc3.context.contextType}`);
4382
- const isSameContextType = contextType ? fdc3.context.contextType === contextType : true;
4383
- if (!isSameContextType) {
4384
- this.logger?.info(`[${commandId}] - addContextListener handler won't be invoked for contextType ${contextType} for startup context with type: ${fdc3.context.contextType}`);
4385
- return;
4386
- }
4387
- this.logger?.info(`[${commandId}] - invoking addContextListener handler with startup context with type ${fdc3.context.contextType}`);
4388
- try {
4389
- handler(fdc3.context.payload, { source: fdc3.openApp });
4390
- }
4391
- catch (error) {
4392
- const errorMsg = error.message ? JSON.stringify(error.message) : JSON.stringify(error);
4393
- this.logger?.error(typeof error === "string" ? error : errorMsg);
4394
- }
4395
- this.invokeContextHandlerWithStartupContext = false;
4396
- this.logger?.trace(`[${commandId}] - invoking response method to with target ${JSON.stringify(fdc3.openApp)}`);
4397
- await this.invokeSystemMethod({ action: "startupContextOpened", correlationId: fdc3.collaborationId }, fdc3.openApp.instanceId);
4398
- this.logger?.trace(`[${commandId}] - system method invocation success for 'startupContextOpened' heard`);
4399
- }
4400
- async getOrCreateAppChannel(commandId, channelId) {
4401
- const exists = this.doesAppChannelExist(channelId);
4402
- if (!exists) {
4403
- this.logger?.info(`[${commandId}] - app channel with id ${channelId} does not exist. Creating one`);
4404
- await this.glueController.updateContext(channelId, {});
4405
- }
4406
- this.logger?.info(`[${commandId}] - returning app channel with id ${channelId}`);
4407
- const logger = this.glueController.initSubLogger(`app.channel.${channelId}`);
4408
- return this.buildChannel(ChannelTypes.App, { id: channelId, logger });
4409
- }
4410
- doesAppChannelExist(name) {
4411
- return !name.includes(PrivateChannelPrefix) && this.glueController.getAllContexts().some((ctxName) => ctxName === name);
4412
- }
4413
- isUserChannel(channelId) {
4414
- if (!channelId) {
4415
- return false;
4416
- }
4417
- return !!this.stateStore.userChannels[channelId];
4418
- }
4419
- async broadcastByChannelId(commandId, channelId, context) {
4420
- const isUserChannel = this.isUserChannel(channelId);
4421
- if (!isUserChannel) {
4422
- this.logger?.info(`[${commandId}] - broadcasting on app channel with id ${channelId}`);
4423
- return this.glueController.updateContextWithLatestFdc3Type(channelId, context);
4424
- }
4425
- const ioChannelName = this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId);
4426
- this.logger?.info(`[${commandId}] - broadcasting on fdc3 user channel with id ${channelId} (underlying glue channel: ${ioChannelName})`);
4427
- return this.userChannelsSupportController.broadcast({ ioChannelName, context });
4428
- }
4429
- async addContextListenerWithoutChannelId({ commandId, contextType, handler }) {
4430
- this.logger?.info(`[${commandId}] - Creating a channel subscription using glue.channels.subscribe`);
4431
- const subHandler = parseContextHandler(handler, contextType);
4432
- const unsubscribe = this.glueController.legacyChannelsSubscribe(subHandler, contextType);
4433
- return { unsubscribe };
4434
- }
4435
- async addContextListenerByChannelId({ commandId, channelId, handler, contextType, invokedOnChannelModel }) {
4436
- const subHandler = parseContextHandler(handler, contextType);
4437
- const channelType = this.getChannelTypeById(channelId);
4438
- if (channelType === ChannelTypes.User) {
4439
- return this.userChannelsSupportController.addContextListener({ commandId, channelId, handler: subHandler, contextType, invokedOnChannelModel });
4440
- }
4441
- if (channelType === ChannelTypes.App) {
4442
- this.logger?.info(`[${commandId}] - subscribing for fdc3 app channel with id ${channelId} (underlying glue context with same name)`);
4443
- const unsubscribe = await this.glueController.contextsSubscribe(channelId, subHandler);
4444
- return {
4445
- unsubscribe: () => {
4446
- this.logger?.info(`[${commandId}] - invoking unsubscribe for app channel with id ${channelId}`);
4447
- unsubscribe();
4448
- }
4449
- };
4450
- }
4451
- this.logger?.error("Cannot add a context listener on an invalid channel");
4452
- throw new Error(ChannelError.AccessDenied);
4453
- }
4454
- getChannelTypeById(channelId) {
4455
- const isUser = this.isUserChannel(channelId);
4456
- if (isUser) {
4457
- return ChannelTypes.User;
4458
- }
4459
- const isApp = this.doesAppChannelExist(channelId);
4460
- if (isApp) {
4461
- return ChannelTypes.App;
4462
- }
4463
- this.logger?.error(`Channel with id: ${channelId} does not exist`);
4464
- throw new Error(ChannelError.NoChannelFound);
4465
- }
4466
- }
4467
-
4468
- class LegacyDataWrappingChannelsController {
4469
- parser;
4470
- stateStore;
4471
- glueController;
4472
- _logger;
4473
- constructor(parser, stateStore, glueController) {
4474
- this.parser = parser;
4475
- this.stateStore = stateStore;
4476
- this.glueController = glueController;
4477
- }
4478
- async getContext({ commandId, channelId, contextType }) {
4479
- this.logger?.info(`[${commandId}] - retrieving latest context of type ${contextType} broadcasted on channel with id ${channelId}`);
4480
- if (!contextType) {
4481
- const glueChannelName = this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId);
4482
- const glueChannelWithPrefix = this.parser.mapChannelNameToContextName(glueChannelName);
4483
- this.logger?.info(`[${commandId}] - getting context for user channel with id ${channelId} (underlying glue channel ${glueChannelName})`);
4484
- const context = await this.glueController.getContext(glueChannelWithPrefix);
4485
- return context.latest_fdc3_type ? this.parser.parseContextsDataToInitialFDC3Data(context) : null;
4486
- }
4487
- const parsedType = this.parser.mapFDC3TypeToChannelsDelimiter(contextType);
4488
- const { data } = await this.glueController.getChannel(this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId));
4489
- return data?.[`fdc3_${parsedType}`]
4490
- ? this.parser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
4491
- : null;
4492
- }
4493
- async broadcast({ ioChannelName, context }) {
4494
- const { path, value } = this.parser.parseFDC3ContextToGlueContexts(context);
4495
- return this.glueController.channelsUpdate({ [path]: value }, ioChannelName);
4496
- }
4497
- async addContextListener({ commandId, channelId, handler, invokedOnChannelModel, contextType }) {
4498
- if (!invokedOnChannelModel) {
4499
- this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
4500
- const unsubscribe = this.glueController.legacyChannelsSubscribe(handler, contextType);
4501
- return { unsubscribe };
4502
- }
4503
- const contextToSubscribeTo = this.parser.mapChannelNameToContextName(this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId));
4504
- this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
4505
- const unsubscribe = await this.glueController.contextsSubscribe(contextToSubscribeTo, handler);
4506
- return { unsubscribe };
4507
- }
4508
- get logger() {
4509
- if (!this._logger) {
4510
- this._logger = this.glueController.initSubLogger("fdc3.legacy.channels.controller");
4511
- }
4512
- return this._logger;
4513
- }
4514
- }
4515
-
4516
- class NewDataWrappingChannelsController {
4517
- parser;
4518
- stateStore;
4519
- glueController;
4520
- _logger;
4521
- constructor(parser, stateStore, glueController) {
4522
- this.parser = parser;
4523
- this.stateStore = stateStore;
4524
- this.glueController = glueController;
4525
- }
4526
- async getContext({ commandId, channelId, contextType }) {
4527
- this.logger?.info(`[${commandId}] - retrieving latest context of type ${contextType} broadcasted on channel with id ${channelId}`);
4528
- const ioChannelName = this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId);
4529
- const ioChannel = await this.glueController.getChannel(ioChannelName);
4530
- if (!contextType) {
4531
- return ioChannel.data.fdc3 || null;
4532
- }
4533
- if (contextType && ioChannel.data.fdc3?.type === contextType) {
4534
- return ioChannel.data.fdc3;
4535
- }
4536
- const ioChannelContextName = this.parser.mapChannelNameToContextName(ioChannelName);
4537
- const { data } = await this.glueController.getContext(ioChannelContextName);
4538
- const parsedType = this.parser.mapFDC3TypeToChannelsDelimiter(contextType);
4539
- return data?.[`fdc3_${parsedType}`]
4540
- ? this.parser.parseContextsDataToInitialFDC3Data({ data, latest_fdc3_type: parsedType })
4541
- : null;
4542
- }
4543
- async broadcast({ ioChannelName, context }) {
4544
- return this.glueController.channelsUpdate(context, { name: ioChannelName, fdc3: true });
4545
- }
4546
- async addContextListener({ commandId, channelId, invokedOnChannelModel, handler, contextType }) {
4547
- if (!invokedOnChannelModel) {
4548
- this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
4549
- const unsubscribe = this.glueController.channelsSubscribe(handler, contextType);
4550
- return { unsubscribe };
4551
- }
4552
- const contextToSubscribeTo = this.parser.mapChannelNameToContextName(this.stateStore.getGlueChannelNameByFdc3ChannelId(channelId));
4553
- this.logger?.info(`[${commandId}] - subscribing for fdc3 user channel with id ${channelId}`);
4554
- const unsubscribe = await this.glueController.contextsSubscribe(contextToSubscribeTo, handler);
4555
- return { unsubscribe };
4556
- }
4557
- get logger() {
4558
- if (!this._logger) {
4559
- this._logger = this.glueController.initSubLogger("fdc3.ioSupport.channels.controller");
4560
- }
4561
- return this._logger;
4562
- }
4563
- }
4564
-
4565
4539
  class IoC {
4566
4540
  _eventDispatcher;
4567
4541
  _eventReceiver;
@@ -4569,9 +4543,7 @@
4569
4543
  _glueController;
4570
4544
  _intentsController;
4571
4545
  _applicationController;
4572
- _channelsBaseController;
4573
- _legacyDataWrappingChannelsController;
4574
- _newDataWrappingChannelsController;
4546
+ _channelsController;
4575
4547
  _channelsParser;
4576
4548
  _channelsStateStore;
4577
4549
  _channelsFactory;
@@ -4612,17 +4584,17 @@
4612
4584
  return this._channelsFactory;
4613
4585
  }
4614
4586
  createUserChannel(glueChannel) {
4615
- return new UserChannel(this.channelsBaseController, glueChannel).toApi();
4587
+ return new UserChannel(this.channelsController, glueChannel).toApi();
4616
4588
  }
4617
4589
  createAppChannel(id) {
4618
- return new AppChannel(this.channelsBaseController, id).toApi();
4590
+ return new AppChannel(this.channelsController, id).toApi();
4619
4591
  }
4620
4592
  createPrivateChannel(logger, channelId, isCreator) {
4621
- return new PrivateChannel(this.channelsBaseController, logger, channelId, isCreator);
4593
+ return new PrivateChannel(this.channelsController, logger, channelId, isCreator);
4622
4594
  }
4623
4595
  get desktopAgent() {
4624
4596
  if (!this._desktopAgent) {
4625
- this._desktopAgent = new DesktopAgent(this.intentsController, this.applicationController, this.channelsBaseController);
4597
+ this._desktopAgent = new DesktopAgent(this.intentsController, this.applicationController, this.channelsController);
4626
4598
  }
4627
4599
  return this._desktopAgent;
4628
4600
  }
@@ -4634,7 +4606,7 @@
4634
4606
  }
4635
4607
  get intentsController() {
4636
4608
  if (!this._intentsController) {
4637
- this._intentsController = new IntentsController(this.glueController, this.channelsBaseController, this.channelsFactory, this.eventsController);
4609
+ this._intentsController = new IntentsController(this.glueController, this.channelsController, this.channelsFactory, this.eventsController);
4638
4610
  }
4639
4611
  return this._intentsController;
4640
4612
  }
@@ -4644,23 +4616,11 @@
4644
4616
  }
4645
4617
  return this._applicationController;
4646
4618
  }
4647
- get channelsBaseController() {
4648
- if (!this._channelsBaseController) {
4649
- this._channelsBaseController = new ChannelsBaseController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.eventsController, this.legacyDataWrappingChannelsController, this.ioFdc3SupportChannelsController);
4650
- }
4651
- return this._channelsBaseController;
4652
- }
4653
- get legacyDataWrappingChannelsController() {
4654
- if (!this._legacyDataWrappingChannelsController) {
4655
- this._legacyDataWrappingChannelsController = new LegacyDataWrappingChannelsController(this.channelsParser, this.channelsStateStore, this.glueController);
4656
- }
4657
- return this._legacyDataWrappingChannelsController;
4658
- }
4659
- get ioFdc3SupportChannelsController() {
4660
- if (!this._newDataWrappingChannelsController) {
4661
- this._newDataWrappingChannelsController = new NewDataWrappingChannelsController(this.channelsParser, this.channelsStateStore, this.glueController);
4619
+ get channelsController() {
4620
+ if (!this._channelsController) {
4621
+ this._channelsController = new ChannelsController(this.glueController, this.channelsStateStore, this.channelsParser, this.channelsFactory, this.eventsController);
4662
4622
  }
4663
- return this._newDataWrappingChannelsController;
4623
+ return this._channelsController;
4664
4624
  }
4665
4625
  get channelsStateStore() {
4666
4626
  if (!this._channelsStateStore) {