@interopio/fdc3-web-bridge 1.6.0 → 2.0.0

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.
@@ -755,7 +755,7 @@ var Decoder$1 = /** @class */ (function () {
755
755
  /** See `Decoder.string` */
756
756
  var string$1 = Decoder$1.string;
757
757
  /** See `Decoder.number` */
758
- Decoder$1.number;
758
+ var number$1 = Decoder$1.number;
759
759
  /** See `Decoder.boolean` */
760
760
  var boolean$1 = Decoder$1.boolean;
761
761
  /** See `Decoder.anyJson` */
@@ -1545,7 +1545,7 @@ var boolean = Decoder.boolean;
1545
1545
  /** See `Decoder.anyJson` */
1546
1546
  var anyJson = Decoder.anyJson;
1547
1547
  /** See `Decoder.unknownJson` */
1548
- Decoder.unknownJson;
1548
+ var unknownJson = Decoder.unknownJson;
1549
1549
  /** See `Decoder.constant` */
1550
1550
  var constant = Decoder.constant;
1551
1551
  /** See `Decoder.object` */
@@ -1563,13 +1563,13 @@ var oneOf = Decoder.oneOf;
1563
1563
  /** See `Decoder.union` */
1564
1564
  Decoder.union;
1565
1565
  /** See `Decoder.intersection` */
1566
- Decoder.intersection;
1566
+ var intersection = Decoder.intersection;
1567
1567
  /** See `Decoder.withDefault` */
1568
1568
  Decoder.withDefault;
1569
1569
  /** See `Decoder.valueAt` */
1570
1570
  Decoder.valueAt;
1571
1571
  /** See `Decoder.succeed` */
1572
- Decoder.succeed;
1572
+ var succeed = Decoder.succeed;
1573
1573
  /** See `Decoder.fail` */
1574
1574
  var fail = Decoder.fail;
1575
1575
  /** See `Decoder.lazy` */
@@ -1577,9 +1577,12 @@ Decoder.lazy;
1577
1577
 
1578
1578
  const nonEmptyStringDecoder$4 = string().where((s) => s.length > 0, "Expected a non-empty string");
1579
1579
  const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
1580
+ const positiveNumberDecoder = number().where((num) => num > 0, "Expected a positive number");
1581
+ const nullable$2 = (decoder) => unknownJson().andThen((value) => value === null ? succeed(null) : decoder);
1580
1582
  const regexDecoder = anyJson().andThen((value) => {
1581
1583
  return value instanceof RegExp ? anyJson() : fail(`expected a regex, got a ${typeof value}`);
1582
1584
  });
1585
+ const looseObjectDecoder = (fieldDecoders) => intersection(object(), object(fieldDecoders));
1583
1586
  const urlDecoder = nonEmptyStringDecoder$4.andThen((url) => {
1584
1587
  try {
1585
1588
  const { protocol } = new URL(url);
@@ -1921,8 +1924,11 @@ const decoders$1 = {
1921
1924
  common: {
1922
1925
  nonEmptyStringDecoder: nonEmptyStringDecoder$4,
1923
1926
  nonNegativeNumberDecoder,
1927
+ positiveNumberDecoder,
1928
+ nullable: nullable$2,
1924
1929
  regexDecoder,
1925
- urlDecoder
1930
+ urlDecoder,
1931
+ looseObjectDecoder
1926
1932
  },
1927
1933
  fdc3: {
1928
1934
  allDefinitionsDecoder,
@@ -1972,8 +1978,8 @@ const decoders = ioc.decoders;
1972
1978
  ioc.errors;
1973
1979
 
1974
1980
  const { nonEmptyStringDecoder: nonEmptyStringDecoder$3 } = decoders.common;
1975
- const requestMessageTypeDecoder = oneOf$1(constant$1("addContextListenerRequest"), constant$1("addEventListenerRequest"), constant$1("addIntentListenerRequest"), constant$1("broadcastRequest"), constant$1("contextListenerUnsubscribeRequest"), constant$1("createPrivateChannelRequest"), constant$1("eventListenerUnsubscribeRequest"), constant$1("findInstancesRequest"), constant$1("findIntentRequest"), constant$1("findIntentsByContextRequest"), constant$1("getAppMetadataRequest"), constant$1("getCurrentChannelRequest"), constant$1("getCurrentContextRequest"), constant$1("getInfoRequest"), constant$1("getOrCreateChannelRequest"), constant$1("getUserChannelsRequest"), constant$1("heartbeatAcknowledgementRequest"), constant$1("intentListenerUnsubscribeRequest"), constant$1("intentResultRequest"), constant$1("joinUserChannelRequest"), constant$1("leaveCurrentChannelRequest"), constant$1("openRequest"), constant$1("privateChannelAddEventListenerRequest"), constant$1("privateChannelDisconnectRequest"), constant$1("privateChannelUnsubscribeEventListenerRequest"), constant$1("raiseIntentForContextRequest"), constant$1("raiseIntentRequest"));
1976
- const responseMessageTypeDecoder = oneOf$1(constant$1("addContextListenerResponse"), constant$1("addEventListenerResponse"), constant$1("addIntentListenerResponse"), constant$1("broadcastResponse"), constant$1("contextListenerUnsubscribeResponse"), constant$1("createPrivateChannelResponse"), constant$1("eventListenerUnsubscribeResponse"), constant$1("findInstancesResponse"), constant$1("findIntentResponse"), constant$1("findIntentsByContextResponse"), constant$1("getAppMetadataResponse"), constant$1("getCurrentChannelResponse"), constant$1("getCurrentContextResponse"), constant$1("getInfoResponse"), constant$1("getOrCreateChannelResponse"), constant$1("getUserChannelsResponse"), constant$1("intentListenerUnsubscribeResponse"), constant$1("intentResultResponse"), constant$1("joinUserChannelResponse"), constant$1("leaveCurrentChannelResponse"), constant$1("openResponse"), constant$1("privateChannelAddEventListenerResponse"), constant$1("privateChannelDisconnectResponse"), constant$1("privateChannelUnsubscribeEventListenerResponse"), constant$1("raiseIntentForContextResponse"), constant$1("raiseIntentResponse"), constant$1("raiseIntentResultResponse"));
1981
+ const requestMessageTypeDecoder = oneOf$1(constant$1("addContextListenerRequest"), constant$1("addEventListenerRequest"), constant$1("addIntentListenerRequest"), constant$1("broadcastRequest"), constant$1("clearContextRequest"), constant$1("contextListenerUnsubscribeRequest"), constant$1("createPrivateChannelRequest"), constant$1("eventListenerUnsubscribeRequest"), constant$1("findInstancesRequest"), constant$1("findIntentRequest"), constant$1("findIntentsByContextRequest"), constant$1("getAppMetadataRequest"), constant$1("getCurrentChannelRequest"), constant$1("getCurrentContextRequest"), constant$1("getInfoRequest"), constant$1("getOrCreateChannelRequest"), constant$1("getUserChannelsRequest"), constant$1("heartbeatAcknowledgementRequest"), constant$1("intentListenerUnsubscribeRequest"), constant$1("intentResultRequest"), constant$1("joinUserChannelRequest"), constant$1("leaveCurrentChannelRequest"), constant$1("openRequest"), constant$1("privateChannelAddEventListenerRequest"), constant$1("privateChannelDisconnectRequest"), constant$1("privateChannelUnsubscribeEventListenerRequest"), constant$1("raiseIntentForContextRequest"), constant$1("raiseIntentRequest"), constant$1("closeRequest"));
1982
+ const responseMessageTypeDecoder = oneOf$1(constant$1("addContextListenerResponse"), constant$1("addEventListenerResponse"), constant$1("addIntentListenerResponse"), constant$1("broadcastResponse"), constant$1("clearContextResponse"), constant$1("contextListenerUnsubscribeResponse"), constant$1("createPrivateChannelResponse"), constant$1("eventListenerUnsubscribeResponse"), constant$1("findInstancesResponse"), constant$1("findIntentResponse"), constant$1("findIntentsByContextResponse"), constant$1("getAppMetadataResponse"), constant$1("getCurrentChannelResponse"), constant$1("getCurrentContextResponse"), constant$1("getInfoResponse"), constant$1("getOrCreateChannelResponse"), constant$1("getUserChannelsResponse"), constant$1("intentListenerUnsubscribeResponse"), constant$1("intentResultResponse"), constant$1("joinUserChannelResponse"), constant$1("leaveCurrentChannelResponse"), constant$1("openResponse"), constant$1("privateChannelAddEventListenerResponse"), constant$1("privateChannelDisconnectResponse"), constant$1("privateChannelUnsubscribeEventListenerResponse"), constant$1("raiseIntentForContextResponse"), constant$1("raiseIntentResponse"), constant$1("raiseIntentResultResponse"), constant$1("closeResponse"));
1977
1983
  const webConnectionProtocolMessageTypeDecoder = oneOf$1(constant$1("WCP1Hello"), constant$1("WCP2LoadUrl"), constant$1("WCP3Handshake"), constant$1("WCP4ValidateAppIdentity"), constant$1("WCP5ValidateAppIdentityFailedResponse"), constant$1("WCP5ValidateAppIdentityResponse"), constant$1("WCP6Goodbye"));
1978
1984
  const appIdentifierDecoder = object$1({
1979
1985
  appId: nonEmptyStringDecoder$3,
@@ -1982,18 +1988,18 @@ const appIdentifierDecoder = object$1({
1982
1988
  });
1983
1989
  const appRequestMetaDecoder = object$1({
1984
1990
  requestUuid: nonEmptyStringDecoder$3,
1985
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1991
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1986
1992
  source: optional$1(appIdentifierDecoder)
1987
1993
  });
1988
1994
  const responseMetaDecoder = object$1({
1989
1995
  requestUuid: nonEmptyStringDecoder$3,
1990
1996
  responseUuid: nonEmptyStringDecoder$3,
1991
1997
  source: optional$1(appIdentifierDecoder),
1992
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1998
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1993
1999
  });
1994
2000
  const connectionStepMetaDecoder = object$1({
1995
2001
  connectionAttemptUuid: nonEmptyStringDecoder$3,
1996
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2002
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
1997
2003
  });
1998
2004
  object$1({
1999
2005
  type: webConnectionProtocolMessageTypeDecoder,
@@ -2005,8 +2011,8 @@ const contextDecoder = object$1({
2005
2011
  name: optional$1(nonEmptyStringDecoder$3),
2006
2012
  id: optional$1(anyJson$1()),
2007
2013
  });
2008
- const responsePayloadErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"), constant$1("AppNotFound"), constant$1("AppTimeout"), constant$1("DesktopAgentNotFound"), constant$1("ErrorOnLaunch"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("IntentHandlerRejected"), constant$1("NoResultReturned"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
2009
- const fluffyErrorDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("DesktopAgentNotFound"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"));
2014
+ const responsePayloadErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("ApiTimeout"), constant$1("InvalidArguments"), constant$1("IntentListenerConflict"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"), constant$1("AppNotFound"), constant$1("AppTimeout"), constant$1("DesktopAgentNotFound"), constant$1("ErrorOnLaunch"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("IntentHandlerRejected"), constant$1("NoResultReturned"), constant$1("AgentDisconnected"), constant$1("NotConnectedToBridge"), constant$1("ResponseToBridgeTimedOut"), constant$1("MalformedMessage"));
2015
+ const fluffyErrorDecoder = oneOf$1(constant$1("MalformedContext"), constant$1("ApiTimeout"), constant$1("InvalidArguments"), constant$1("DesktopAgentNotFound"), constant$1("ResolverUnavailable"), constant$1("IntentDeliveryFailed"), constant$1("NoAppsFound"), constant$1("ResolverTimeout"), constant$1("TargetAppUnavailable"), constant$1("TargetInstanceUnavailable"), constant$1("UserCancelledResolution"), constant$1("IntentListenerConflict"));
2010
2016
  const wcp1HelloPayloadDecoder = object$1({
2011
2017
  actualUrl: nonEmptyStringDecoder$3,
2012
2018
  channelSelector: optional$1(boolean$1()),
@@ -2016,7 +2022,7 @@ const wcp1HelloPayloadDecoder = object$1({
2016
2022
  });
2017
2023
  const wcp1HelloMetaDecoder = object$1({
2018
2024
  connectionAttemptUuid: nonEmptyStringDecoder$3,
2019
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2025
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2020
2026
  });
2021
2027
  const wcp1HelloDecoder = object$1({
2022
2028
  type: constant$1("WCP1Hello"),
@@ -2086,7 +2092,6 @@ const appMetadataDecoder = object$1({
2086
2092
  });
2087
2093
  const optionalFeaturesDecoder = object$1({
2088
2094
  DesktopAgentBridging: boolean$1(),
2089
- OriginatingAppMetadata: boolean$1(),
2090
2095
  UserChannelMembershipAPIs: boolean$1()
2091
2096
  });
2092
2097
  const implementationMetadataDecoder = object$1({
@@ -2107,17 +2112,43 @@ object$1({
2107
2112
  meta: wcp1HelloMetaDecoder,
2108
2113
  payload: wcp5ValidateAppIdentitySuccessResponsePayloadDecoder
2109
2114
  });
2115
+ const detachedSignatureDecoder = object$1({
2116
+ protected: string$1(),
2117
+ signature: string$1()
2118
+ });
2119
+ const antiReplayClaimsDecoder = object$1({
2120
+ iat: number$1(),
2121
+ exp: number$1(),
2122
+ jti: string$1()
2123
+ });
2124
+ const appProvidableContextMetadataDecoder = object$1({
2125
+ traceId: optional$1(string$1()),
2126
+ signature: optional$1(detachedSignatureDecoder),
2127
+ antiReplay: optional$1(antiReplayClaimsDecoder),
2128
+ custom: optional$1(object$1())
2129
+ }).where((metadata) => !metadata.signature || !!metadata.antiReplay, "Expected antiReplay claims when signature is provided");
2130
+ const optionalAppProvidableContextMetadataDecoder = optional$1(appProvidableContextMetadataDecoder);
2131
+ const contextMetadataDecoder = object$1({
2132
+ source: appIdentifierDecoder,
2133
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, "Expected result metadata timestamp to be a Date"),
2134
+ traceId: string$1(),
2135
+ signature: optional$1(detachedSignatureDecoder),
2136
+ antiReplay: optional$1(antiReplayClaimsDecoder),
2137
+ custom: optional$1(object$1())
2138
+ }).where((metadata) => !metadata.signature || !!metadata.antiReplay, "Expected antiReplay claims when signature is provided");
2139
+ const contextTypesStringArrayDecoder = array$1(nonEmptyStringDecoder$3).where((types) => types.length > 0, "Expected at least one context type");
2110
2140
 
2111
- const { nonEmptyStringDecoder: nonEmptyStringDecoder$2 } = decoders.common;
2141
+ const { nonEmptyStringDecoder: nonEmptyStringDecoder$2, nullable: nullable$1 } = decoders.common;
2112
2142
  const addContextListenerRequestMetaDecoder = object$1({
2113
2143
  requestUuid: nonEmptyStringDecoder$2,
2114
2144
  source: optional$1(appIdentifierDecoder),
2115
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2145
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2116
2146
  });
2117
2147
  const addContextListenerRequestPayloadDecoder = object$1({
2118
- channelId: optional$1(nonEmptyStringDecoder$2),
2119
- contextType: optional$1(nonEmptyStringDecoder$2)
2120
- });
2148
+ channelId: nullable$1(nonEmptyStringDecoder$2),
2149
+ contextType: nullable$1(optional$1(nonEmptyStringDecoder$2)),
2150
+ contextTypes: oneOf$1(constant$1(undefined), contextTypesStringArrayDecoder)
2151
+ }).where((payload) => (payload.contextType !== undefined) !== (payload.contextTypes !== undefined), "Expected exactly one of 'contextType' or 'contextTypes' to be present");
2121
2152
  const addContextListenerRequestDecoder = object$1({
2122
2153
  type: constant$1("addContextListenerRequest"),
2123
2154
  meta: addContextListenerRequestMetaDecoder,
@@ -2127,11 +2158,12 @@ const addContextListenerResponseMetaDecoder = object$1({
2127
2158
  requestUuid: nonEmptyStringDecoder$2,
2128
2159
  responseUuid: nonEmptyStringDecoder$2,
2129
2160
  source: optional$1(appIdentifierDecoder),
2130
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2161
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2131
2162
  });
2132
- const addEventListenerTypeDecoder = oneOf$1(constant$1("USER_CHANNEL_CHANGED"));
2163
+ const addEventListenerTypeDecoder = oneOf$1(constant$1("USER_CHANNEL_CHANGED"), constant$1("CONTEXT_CLEARED"));
2133
2164
  const addEventListenerRequestPayloadDecoder = object$1({
2134
- type: optional$1(addEventListenerTypeDecoder)
2165
+ channelId: optional$1(nullable$1(nonEmptyStringDecoder$2)).map((channelId) => channelId ?? null),
2166
+ type: nullable$1(addEventListenerTypeDecoder)
2135
2167
  });
2136
2168
  const addEventListenerRequestDecoder = object$1({
2137
2169
  type: constant$1("addEventListenerRequest"),
@@ -2147,7 +2179,7 @@ const addEventListenerResponseDecoder = object$1({
2147
2179
  meta: addContextListenerResponseMetaDecoder,
2148
2180
  payload: addEventListenerResponsePayloadDecoder
2149
2181
  });
2150
- const purpleErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"));
2182
+ const purpleErrorDecoder = oneOf$1(constant$1("AccessDenied"), constant$1("CreationFailed"), constant$1("MalformedContext"), constant$1("NoChannelFound"), constant$1("ApiTimeout"), constant$1("InvalidArguments"));
2151
2183
  const addContextListenerResponsePayloadDecoder = object$1({
2152
2184
  error: optional$1(purpleErrorDecoder),
2153
2185
  listenerUUID: optional$1(nonEmptyStringDecoder$2)
@@ -2159,7 +2191,8 @@ const addContextListenerResponseDecoder = object$1({
2159
2191
  });
2160
2192
  const broadcastRequestPayloadDecoder = object$1({
2161
2193
  channelId: nonEmptyStringDecoder$2,
2162
- context: contextDecoder
2194
+ context: contextDecoder,
2195
+ metadata: optionalAppProvidableContextMetadataDecoder
2163
2196
  });
2164
2197
  const broadcastRequestDecoder = object$1({
2165
2198
  type: constant$1("broadcastRequest"),
@@ -2174,6 +2207,11 @@ const broadcastResponseDecoder = object$1({
2174
2207
  meta: responseMetaDecoder,
2175
2208
  payload: broadcastResponsePayloadDecoder
2176
2209
  });
2210
+ const clearContextResponseDecoder = object$1({
2211
+ type: constant$1("clearContextResponse"),
2212
+ meta: responseMetaDecoder,
2213
+ payload: broadcastResponsePayloadDecoder
2214
+ });
2177
2215
  const channelTypeDecoder = oneOf$1(constant$1("app"), constant$1("user"), constant$1("private"));
2178
2216
  const displayMetadataDecoder = object$1({
2179
2217
  color: optional$1(nonEmptyStringDecoder$2),
@@ -2188,6 +2226,15 @@ const channelDecoder = object$1({
2188
2226
  const contextListenerUnsubscribeRequestPayloadDecoder = object$1({
2189
2227
  listenerUUID: nonEmptyStringDecoder$2
2190
2228
  });
2229
+ const clearContextRequestPayloadDecoder = object$1({
2230
+ channelId: nonEmptyStringDecoder$2,
2231
+ contextType: nullable$1(nonEmptyStringDecoder$2)
2232
+ });
2233
+ const clearContextRequestDecoder = object$1({
2234
+ type: constant$1("clearContextRequest"),
2235
+ meta: addContextListenerRequestMetaDecoder,
2236
+ payload: clearContextRequestPayloadDecoder
2237
+ });
2191
2238
  const contextListenerUnsubscribeRequestDecoder = object$1({
2192
2239
  type: constant$1("contextListenerUnsubscribeRequest"),
2193
2240
  meta: addContextListenerRequestMetaDecoder,
@@ -2241,7 +2288,7 @@ const getCurrentChannelResponseDecoder = object$1({
2241
2288
  });
2242
2289
  const getCurrentContextRequestPayloadDecoder = object$1({
2243
2290
  channelId: nonEmptyStringDecoder$2,
2244
- contextType: optional$1(nonEmptyStringDecoder$2)
2291
+ contextType: nullable$1(nonEmptyStringDecoder$2)
2245
2292
  });
2246
2293
  const getCurrentContextRequestDecoder = object$1({
2247
2294
  type: constant$1("getCurrentContextRequest"),
@@ -2250,7 +2297,8 @@ const getCurrentContextRequestDecoder = object$1({
2250
2297
  });
2251
2298
  const getCurrentContextResponsePayloadDecoder = object$1({
2252
2299
  error: optional$1(purpleErrorDecoder),
2253
- context: optional$1(contextDecoder)
2300
+ context: optional$1(nullable$1(contextDecoder)),
2301
+ metadata: optional$1(nullable$1(contextMetadataDecoder))
2254
2302
  });
2255
2303
  const getCurrentContextResponseDecoder = object$1({
2256
2304
  type: constant$1("getCurrentContextResponse"),
@@ -2317,9 +2365,9 @@ const leaveCurrentChannelResponseDecoder = object$1({
2317
2365
  meta: addContextListenerResponseMetaDecoder,
2318
2366
  payload: leaveCurrentChannelResponsePayloadDecoder
2319
2367
  });
2320
- const privateChannelEventListenerTypesDecoder = oneOf$1(constant$1("addContextListener"), constant$1("unsubscribe"), constant$1("disconnect"));
2368
+ const privateChannelEventListenerTypesDecoder = oneOf$1(constant$1("addContextListener"), constant$1("unsubscribe"), constant$1("disconnect"), constant$1("contextCleared"));
2321
2369
  const privateChannelAddEventListenerRequestPayloadDecoder = object$1({
2322
- listenerType: optional$1(privateChannelEventListenerTypesDecoder),
2370
+ listenerType: nullable$1(privateChannelEventListenerTypesDecoder),
2323
2371
  privateChannelId: nonEmptyStringDecoder$2
2324
2372
  });
2325
2373
  const privateChannelAddEventListenerRequestDecoder = object$1({
@@ -2364,7 +2412,7 @@ const privateChannelUnsubscribeEventListenerResponseDecoder = object$1({
2364
2412
  });
2365
2413
  const broadcastEventMetaDecoder = object$1({
2366
2414
  eventUuid: nonEmptyStringDecoder$2,
2367
- timestamp: object$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2415
+ timestamp: anyJson$1().where((timestamp) => timestamp instanceof Date, `Expected 'input.meta.timestamp' to be instance of Date`),
2368
2416
  });
2369
2417
 
2370
2418
  const { nonEmptyStringDecoder: nonEmptyStringDecoder$1 } = decoders.common;
@@ -2391,7 +2439,8 @@ const getInfoRequestDecoder = object$1({
2391
2439
  });
2392
2440
  const openRequestPayloadDecoder = object$1({
2393
2441
  app: appIdentifierDecoder,
2394
- context: optional$1(contextDecoder)
2442
+ context: optional$1(contextDecoder),
2443
+ metadata: optionalAppProvidableContextMetadataDecoder
2395
2444
  });
2396
2445
  const openRequestDecoder = object$1({
2397
2446
  type: constant$1("openRequest"),
@@ -2450,17 +2499,171 @@ const heartbeatEventDecoder = object$1({
2450
2499
  meta: broadcastEventMetaDecoder,
2451
2500
  payload: heartbeatEventPayloadDecoder
2452
2501
  });
2502
+ const closeRequestDecoder = object$1({
2503
+ type: constant$1("closeRequest"),
2504
+ meta: addContextListenerRequestMetaDecoder,
2505
+ payload: anyJson$1()
2506
+ });
2507
+ const closeResponsePayloadError = constant$1('ApiTimeout');
2508
+ const closeResponsePayloadDecoder = object$1({
2509
+ error: optional$1(closeResponsePayloadError)
2510
+ });
2511
+ const closeResponseDecoder = object$1({
2512
+ type: constant$1("closeResponse"),
2513
+ meta: addContextListenerResponseMetaDecoder,
2514
+ payload: closeResponsePayloadDecoder
2515
+ });
2516
+
2517
+ var WCPMessageTypes;
2518
+ (function (WCPMessageTypes) {
2519
+ WCPMessageTypes["WCP1Hello"] = "WCP1Hello";
2520
+ WCPMessageTypes["WCP2LoadUrl"] = "WCP2LoadUrl";
2521
+ WCPMessageTypes["WCP3Handshake"] = "WCP3Handshake";
2522
+ WCPMessageTypes["WCP4ValidateAppIdentity"] = "WCP4ValidateAppIdentity";
2523
+ WCPMessageTypes["WCP5ValidateAppIdentityFailedResponse"] = "WCP5ValidateAppIdentityFailedResponse";
2524
+ WCPMessageTypes["WCP5ValidateAppIdentityResponse"] = "WCP5ValidateAppIdentityResponse";
2525
+ WCPMessageTypes["WCP6Goodbye"] = "WCP6Goodbye";
2526
+ })(WCPMessageTypes || (WCPMessageTypes = {}));
2527
+ const FDC3_READY_TIMEOUT = 120 * 1000;
2528
+ const channelTypes = ["user", "app", "private"];
2529
+ const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
2530
+
2531
+ const rejectWithErrorObj = (reject, error) => {
2532
+ if (error instanceof Error) {
2533
+ reject(error.message);
2534
+ return;
2535
+ }
2536
+ if (typeof error === "string") {
2537
+ reject(new Error(error));
2538
+ return;
2539
+ }
2540
+ reject(new Error(JSON.stringify(error)));
2541
+ };
2542
+ const wrapPromise = () => {
2543
+ let wrapperResolve;
2544
+ let wrapperReject;
2545
+ const promise = new Promise((resolve, reject) => {
2546
+ wrapperResolve = resolve;
2547
+ wrapperReject = reject;
2548
+ });
2549
+ return { promise, resolve: wrapperResolve, reject: wrapperReject };
2550
+ };
2551
+ const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
2552
+ return new Promise((resolve, reject) => {
2553
+ const timeout = setTimeout(() => {
2554
+ const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
2555
+ reject(new Error(message));
2556
+ }, timeoutMilliseconds);
2557
+ promise()
2558
+ .then((result) => {
2559
+ clearTimeout(timeout);
2560
+ resolve(result);
2561
+ })
2562
+ .catch((error) => {
2563
+ clearTimeout(timeout);
2564
+ rejectWithErrorObj(reject, error);
2565
+ });
2566
+ });
2567
+ };
2568
+ const compareOrigins = (url1, url2) => {
2569
+ try {
2570
+ const parsedUrl1 = new URL(url1);
2571
+ const parsedUrl2 = new URL(url2);
2572
+ return parsedUrl1.origin === parsedUrl2.origin;
2573
+ }
2574
+ catch {
2575
+ return false;
2576
+ }
2577
+ };
2578
+ const removeTrailingSlash = (pathname) => {
2579
+ return pathname.endsWith("/")
2580
+ ? pathname.slice(0, -1)
2581
+ : pathname;
2582
+ };
2583
+ const isRecordUrlMatchToIdentityUrl = (recordUrl, identityUrl) => {
2584
+ let parsedRecordUrl;
2585
+ let parsedIdentityUrl;
2586
+ try {
2587
+ parsedRecordUrl = new URL(recordUrl);
2588
+ parsedIdentityUrl = new URL(identityUrl);
2589
+ }
2590
+ catch {
2591
+ return false;
2592
+ }
2593
+ if (parsedRecordUrl.origin !== parsedIdentityUrl.origin) {
2594
+ return false;
2595
+ }
2596
+ const recordPath = removeTrailingSlash(parsedRecordUrl.pathname);
2597
+ const identityPath = removeTrailingSlash(parsedIdentityUrl.pathname);
2598
+ if (recordPath !== identityPath) {
2599
+ return false;
2600
+ }
2601
+ for (const [key, value] of parsedRecordUrl.searchParams) {
2602
+ if (parsedIdentityUrl.searchParams.get(key) !== value) {
2603
+ return false;
2604
+ }
2605
+ }
2606
+ if (parsedRecordUrl.hash && parsedRecordUrl.hash !== parsedIdentityUrl.hash) {
2607
+ return false;
2608
+ }
2609
+ return true;
2610
+ };
2611
+ const checkIfFDC3Channel = (object) => {
2612
+ if (!object || typeof object !== "object" || Array.isArray(object)) {
2613
+ return false;
2614
+ }
2615
+ if (!channelTypes.includes(object?.type)) {
2616
+ return false;
2617
+ }
2618
+ return defaultChannelsProps.every((prop) => Object.keys(object).includes(prop));
2619
+ };
2620
+ const checkIfFDC3Context = (object) => {
2621
+ if (!object || typeof object !== "object" || Array.isArray(object)) {
2622
+ return false;
2623
+ }
2624
+ return "type" in object && typeof object.type === "string";
2625
+ };
2626
+ const checkIfFDC3ContextWithMetadata = (object) => {
2627
+ if (!object || typeof object !== "object") {
2628
+ return false;
2629
+ }
2630
+ const hasContextAndMetadata = "context" in object && "metadata" in object;
2631
+ if (!hasContextAndMetadata) {
2632
+ return false;
2633
+ }
2634
+ const isValidContext = checkIfFDC3Context(object.context);
2635
+ if (!isValidContext) {
2636
+ return false;
2637
+ }
2638
+ const decodedMetadata = contextMetadataDecoder.run(object.metadata);
2639
+ return decodedMetadata.ok;
2640
+ };
2641
+ const buildEnrichedMetadata = (metadata, myAppMetadata) => {
2642
+ return {
2643
+ ...(metadata ?? {}),
2644
+ custom: {
2645
+ ...(metadata?.custom ?? {}),
2646
+ ___source___: {
2647
+ appId: myAppMetadata.appId,
2648
+ instanceId: myAppMetadata.instanceId,
2649
+ }
2650
+ }
2651
+ };
2652
+ };
2453
2653
 
2454
2654
  class ApplicationsController {
2655
+ myAppMetadata;
2455
2656
  logger;
2456
2657
  operations = {
2457
2658
  findInstancesRequest: { requestType: "findInstancesRequest", requestDecoder: findInstancesRequestDecoder, responseType: "findInstancesResponse", responseDecoder: findInstancesResponseDecoder, execute: this.handleFindInstancesRequest.bind(this) },
2458
2659
  getAppMetadataRequest: { requestType: "getAppMetadataRequest", requestDecoder: getAppMetadataRequestDecoder, responseType: "getAppMetadataResponse", responseDecoder: getAppMetadataResponseDecoder, execute: this.handleGetAppMetadataRequest.bind(this) },
2459
2660
  getInfoRequest: { requestType: "getInfoRequest", requestDecoder: getInfoRequestDecoder, responseType: "getInfoResponse", responseDecoder: getInfoResponseDecoder, execute: this.handleGetInfoRequest.bind(this) },
2460
2661
  openRequest: { requestType: "openRequest", requestDecoder: openRequestDecoder, responseType: "openResponse", responseDecoder: openResponseDecoder, execute: this.handleOpenRequest.bind(this) },
2461
- heartbeatAcknowledgementRequest: { requestType: "heartbeatAcknowledgementRequest", requestDecoder: heartbeatAcknowledgementRequestDecoder, responseType: "heartbeatEvent", responseDecoder: heartbeatEventDecoder, execute: this.handleHeartbeatAcknowledgementRequest.bind(this) }
2662
+ heartbeatAcknowledgementRequest: { requestType: "heartbeatAcknowledgementRequest", requestDecoder: heartbeatAcknowledgementRequestDecoder, responseType: "heartbeatEvent", responseDecoder: heartbeatEventDecoder, execute: this.handleHeartbeatAcknowledgementRequest.bind(this) },
2663
+ closeRequest: { requestType: "closeRequest", requestDecoder: closeRequestDecoder, responseType: "closeResponse", responseDecoder: closeResponseDecoder, execute: this.handleCloseRequest.bind(this) },
2462
2664
  };
2463
- constructor(logger) {
2665
+ constructor(myAppMetadata, logger) {
2666
+ this.myAppMetadata = myAppMetadata;
2464
2667
  this.logger = logger;
2465
2668
  }
2466
2669
  async handleControl(request) {
@@ -2495,24 +2698,51 @@ class ApplicationsController {
2495
2698
  this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
2496
2699
  return response;
2497
2700
  }
2701
+ async handlePostResponse(request) {
2702
+ const operation = this.operations[request.type];
2703
+ await operation.postResponse?.(request);
2704
+ }
2498
2705
  async handleFindInstancesRequest({ payload }) {
2499
- const appIdentifiers = await window.fdc3?.findInstances(payload.app);
2706
+ if (!window.fdc3) {
2707
+ return { error: "ApiTimeout" };
2708
+ }
2709
+ const appIdentifiers = await window.fdc3.findInstances(payload.app);
2500
2710
  return { appIdentifiers };
2501
2711
  }
2502
2712
  async handleGetAppMetadataRequest({ payload }) {
2503
- const appMetadata = await window.fdc3?.getAppMetadata(payload.app);
2713
+ if (!window.fdc3) {
2714
+ return { error: "ApiTimeout" };
2715
+ }
2716
+ const appMetadata = await window.fdc3.getAppMetadata(payload.app);
2504
2717
  return { appMetadata };
2505
2718
  }
2506
- async handleGetInfoRequest(request) {
2507
- const implementationMetadata = await window.fdc3?.getInfo();
2719
+ async handleGetInfoRequest(_request) {
2720
+ if (!window.fdc3) {
2721
+ return { error: "ApiTimeout" };
2722
+ }
2723
+ const info = await window.fdc3.getInfo();
2724
+ if (!info) {
2725
+ return { error: "NoResultReturned" };
2726
+ }
2727
+ const implementationMetadata = { ...info, appMetadata: this.myAppMetadata };
2508
2728
  return { implementationMetadata };
2509
2729
  }
2510
2730
  async handleOpenRequest({ payload }) {
2511
- const appIdentifier = await window.fdc3?.open(payload.app, payload.context);
2512
- return { appIdentifier };
2731
+ if (!window.fdc3) {
2732
+ return { error: "ApiTimeout" };
2733
+ }
2734
+ const enrichedMetadata = buildEnrichedMetadata(payload.metadata, this.myAppMetadata);
2735
+ try {
2736
+ const appIdentifier = await window.fdc3.open(payload.app, payload.context, enrichedMetadata);
2737
+ return { appIdentifier };
2738
+ }
2739
+ catch (error) {
2740
+ const errorMsg = error instanceof Error ? error.message : "ApiTimeout";
2741
+ return { error: errorMsg };
2742
+ }
2513
2743
  }
2514
- async handleHeartbeatAcknowledgementRequest({ heartbeatEventUuid }) {
2515
- return { alive: true, heartbeatEventUuid };
2744
+ handleHeartbeatAcknowledgementRequest({ heartbeatEventUuid }) {
2745
+ return Promise.resolve({ alive: true, heartbeatEventUuid });
2516
2746
  }
2517
2747
  decorateResponse({ payload, request, responseUuid }) {
2518
2748
  return {
@@ -2526,38 +2756,165 @@ class ApplicationsController {
2526
2756
  payload
2527
2757
  };
2528
2758
  }
2759
+ async handleCloseRequest(_request) {
2760
+ const error = "ApiTimeout";
2761
+ if (!window.fdc3) {
2762
+ return { error };
2763
+ }
2764
+ try {
2765
+ await window.fdc3.close();
2766
+ return {};
2767
+ }
2768
+ catch {
2769
+ return { error };
2770
+ }
2771
+ }
2529
2772
  }
2530
2773
 
2531
- var WCPMessageTypes;
2532
- (function (WCPMessageTypes) {
2533
- WCPMessageTypes["WCP1Hello"] = "WCP1Hello";
2534
- WCPMessageTypes["WCP2LoadUrl"] = "WCP2LoadUrl";
2535
- WCPMessageTypes["WCP3Handshake"] = "WCP3Handshake";
2536
- WCPMessageTypes["WCP4ValidateAppIdentity"] = "WCP4ValidateAppIdentity";
2537
- WCPMessageTypes["WCP5ValidateAppIdentityFailedResponse"] = "WCP5ValidateAppIdentityFailedResponse";
2538
- WCPMessageTypes["WCP5ValidateAppIdentityResponse"] = "WCP5ValidateAppIdentityResponse";
2539
- WCPMessageTypes["WCP6Goodbye"] = "WCP6Goodbye";
2540
- })(WCPMessageTypes || (WCPMessageTypes = {}));
2541
- const FDC3_READY_TIMEOUT = 120 * 1000;
2542
- const DESKTOP_AGENT_NAME = "io.Connect Browser";
2543
- const channelTypes = ["user", "app", "private"];
2544
- const defaultChannelsProps = ["id", "type", "broadcast", "addContextListener", "getCurrentContext"];
2774
+ /**
2775
+ * SPDX-License-Identifier: Apache-2.0
2776
+ * Copyright FINOS FDC3 contributors - see NOTICE file
2777
+ */
2778
+ /**
2779
+ * Contains constants representing the errors that can be encountered when trying to connect to a web-based Desktop Agent with the getAgent function.
2780
+ */
2781
+ var AgentError;
2782
+ (function (AgentError) {
2783
+ /** Returned if no Desktop Agent was found by any means available or
2784
+ * if the Agent previously connected to is not contactable on a
2785
+ * subsequent connection attempt.*/
2786
+ AgentError["AgentNotFound"] = "AgentNotFound";
2787
+ /** Returned if validation of the app identity by the Desktop Agent
2788
+ * Failed or the app is not being allowed to connect to the Desktop Agent
2789
+ * for another reason. */
2790
+ AgentError["AccessDenied"] = "AccessDenied";
2791
+ /** Returned if an error or exception occurs while trying to set
2792
+ * up communication with a Desktop Agent. */
2793
+ AgentError["ErrorOnConnect"] = "ErrorOnConnect";
2794
+ /** Returned if the failover function is not a function, or it did not
2795
+ * resolve to one of the allowed types. */
2796
+ AgentError["InvalidFailover"] = "InvalidFailover";
2797
+ /** Returned if an API call rejects after a timeout. Used where an API call
2798
+ * is not aligned to another error enumeration.
2799
+ */
2800
+ AgentError["ApiTimeout"] = "ApiTimeout";
2801
+ })(AgentError || (AgentError = {}));
2802
+ /** Constants representing the errors that can be encountered when calling the `open` method on the DesktopAgent object (`fdc3`). */
2803
+ var OpenError;
2804
+ (function (OpenError) {
2805
+ /** Returned if the specified application is not found.*/
2806
+ OpenError["AppNotFound"] = "AppNotFound";
2807
+ /** Returned if the specified application fails to launch correctly.*/
2808
+ OpenError["ErrorOnLaunch"] = "ErrorOnLaunch";
2809
+ /** Returned if the specified application launches and initializes FDC3, but fails to add a context listener in order to receive the context passed to the `fdc3.open` call.*/
2810
+ OpenError["AppTimeout"] = "AppTimeout";
2811
+ /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
2812
+ OpenError["ResolverUnavailable"] = "ResolverUnavailable";
2813
+ /** 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.*/
2814
+ OpenError["MalformedContext"] = "MalformedContext";
2815
+ /** @experimental Returned if the specified Desktop Agent is not found, via a connected Desktop Agent Bridge.*/
2816
+ OpenError["DesktopAgentNotFound"] = "DesktopAgentNotFound";
2817
+ /** Returned if the specified application launches but fails to initialize FDC3 in time, regardless of whether context was passed to `fdc3.open`. Opening a non-FDC3 application will result in this error.*/
2818
+ OpenError["ApiTimeout"] = "ApiTimeout";
2819
+ /** Returned when incorrect arguments are passed to API calls.*/
2820
+ OpenError["InvalidArguments"] = "InvalidArguments";
2821
+ })(OpenError || (OpenError = {}));
2822
+ /** Constants representing the errors that can be encountered when calling the `close` method on the DesktopAgent object (`fdc3`). */
2823
+ var CloseError;
2824
+ (function (CloseError) {
2825
+ /** Returned if the Desktop Agent cannot close the app's window or frame. */
2826
+ CloseError["ErrorOnClose"] = "ErrorOnClose";
2827
+ /** Returned if a timeout occurs before a call to close is resolved for any reason other than the app being closed. */
2828
+ CloseError["ApiTimeout"] = "ApiTimeout";
2829
+ })(CloseError || (CloseError = {}));
2830
+ /** Constants representing the errors that can be encountered when calling the `findIntent`, `findIntentsByContext`, `raiseIntent` or `raiseIntentForContext` methods on the DesktopAgent (`fdc3`). */
2831
+ var ResolveError;
2832
+ (function (ResolveError) {
2833
+ /** SHOULD be returned if no apps are available that can resolve the intent and context combination.*/
2834
+ ResolveError["NoAppsFound"] = "NoAppsFound";
2835
+ /** Returned if the FDC3 desktop agent implementation is not currently able to handle the request.*/
2836
+ ResolveError["ResolverUnavailable"] = "ResolverUnavailable";
2837
+ /** Returned if the user cancelled the resolution request, for example by closing or cancelling a resolver UI.*/
2838
+ ResolveError["UserCancelled"] = "UserCancelledResolution";
2839
+ /** 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.*/
2840
+ ResolveError["ResolverTimeout"] = "ResolverTimeout";
2841
+ /** Returned if a specified target application is not available or a new instance of it cannot be opened. */
2842
+ ResolveError["TargetAppUnavailable"] = "TargetAppUnavailable";
2843
+ /** Returned if a specified target application instance is not available, for example because it has been closed. */
2844
+ ResolveError["TargetInstanceUnavailable"] = "TargetInstanceUnavailable";
2845
+ /** 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.*/
2846
+ ResolveError["IntentDeliveryFailed"] = "IntentDeliveryFailed";
2847
+ /** 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.*/
2848
+ ResolveError["MalformedContext"] = "MalformedContext";
2849
+ /** Returned if `fdc3.addIntentListener` is called for a specified intent that the application has already added a listener for and has not subsequently removed it. */
2850
+ ResolveError["IntentListenerConflict"] = "IntentListenerConflict";
2851
+ /** @experimental Returned if the specified Desktop Agent is not found, via a connected Desktop Agent Bridge.*/
2852
+ ResolveError["DesktopAgentNotFound"] = "DesktopAgentNotFound";
2853
+ /** Returned if a timeout occurs before the API call is resolved for any reason other than the resolver timing out (use ResolverTimeout) or an app launched by a raiseIntent function doesn't add its intent listener in time (use IntentDeliveryFailed).*/
2854
+ ResolveError["ApiTimeout"] = "ApiTimeout";
2855
+ /** Returned when incorrect arguments are passed to API calls.*/
2856
+ ResolveError["InvalidArguments"] = "InvalidArguments";
2857
+ })(ResolveError || (ResolveError = {}));
2858
+ var ResultError;
2859
+ (function (ResultError) {
2860
+ /** Returned if the intent handler exited without returning a valid result (a promise resolving to a Context, Channel object or void). */
2861
+ ResultError["NoResultReturned"] = "NoResultReturned";
2862
+ /** Returned if the Intent handler function processing the raised intent throws an error or rejects the Promise it returned. */
2863
+ ResultError["IntentHandlerRejected"] = "IntentHandlerRejected";
2864
+ /** Returned if a timeout occurs before the getResult() API call is resolved.*/
2865
+ ResultError["ApiTimeout"] = "ApiTimeout";
2866
+ })(ResultError || (ResultError = {}));
2867
+ var ChannelError;
2868
+ (function (ChannelError) {
2869
+ /** Returned if the specified channel is not found when attempting to join a channel via the `joinUserChannel` function of the DesktopAgent (`fdc3`).*/
2870
+ ChannelError["NoChannelFound"] = "NoChannelFound";
2871
+ /** 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. */
2872
+ ChannelError["AccessDenied"] = "AccessDenied";
2873
+ /** SHOULD be returned when a channel cannot be created or retrieved via the `getOrCreateChannel` method of the DesktopAgent (`fdc3`).*/
2874
+ ChannelError["CreationFailed"] = "CreationFailed";
2875
+ /** 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.*/
2876
+ ChannelError["MalformedContext"] = "MalformedContext";
2877
+ /** Returned if a timeout occurs before any Channel related API call is resolved.*/
2878
+ ChannelError["ApiTimeout"] = "ApiTimeout";
2879
+ /** Returned when incorrect arguments are passed to API calls.*/
2880
+ ChannelError["InvalidArguments"] = "InvalidArguments";
2881
+ })(ChannelError || (ChannelError = {}));
2882
+ var BridgingError;
2883
+ (function (BridgingError) {
2884
+ /** @experimental Returned if a Desktop Agent did not return a response, via Desktop Agent Bridging, within the alloted timeout. */
2885
+ BridgingError["ResponseTimedOut"] = "ResponseToBridgeTimedOut";
2886
+ /** @experimental Returned if a Desktop Agent that has been targeted by a particular request has been disconnected from the Bridge before a response has been received from it. */
2887
+ BridgingError["AgentDisconnected"] = "AgentDisconnected";
2888
+ /** @experimental Returned for FDC3 API calls that are specified with arguments indicating that a remote Desktop agent should be targeted (e.g. raiseIntent with an app on a remote DesktopAgent targeted), when the local Desktop Agent is not connected to a bridge. */
2889
+ BridgingError["NotConnectedToBridge"] = "NotConnectedToBridge";
2890
+ /** @experimental Returned if a message to a Bridge deviates from the schema for that message sufficiently that it could not be processed. */
2891
+ BridgingError["MalformedMessage"] = "MalformedMessage";
2892
+ })(BridgingError || (BridgingError = {}));
2545
2893
 
2546
- var ChannelEventToTypeDictionary;
2547
- (function (ChannelEventToTypeDictionary) {
2548
- ChannelEventToTypeDictionary["USER_CHANNEL_CHANGED"] = "userChannelChanged";
2549
- })(ChannelEventToTypeDictionary || (ChannelEventToTypeDictionary = {}));
2894
+ const supportedEventTypes = ["userChannelChanged", "contextCleared"];
2895
+
2896
+ const ChannelEventToTypeDictionary = {
2897
+ "USER_CHANNEL_CHANGED": "userChannelChanged",
2898
+ "CONTEXT_CLEARED": "contextCleared"
2899
+ };
2550
2900
  const privateChannelPrefix = "___privateFDC3Channel___";
2551
2901
 
2552
2902
  class ChannelsController {
2553
2903
  sendBridgeMessage;
2904
+ myAppMetadata;
2554
2905
  logger;
2555
2906
  listenersCollection = {};
2907
+ contextListeners = new Map();
2908
+ eventListeners = new Map();
2909
+ userChannelMemberships = new WeakMap();
2910
+ pendingProxyJoins = new WeakMap();
2911
+ forwardedPrivateEvents = new WeakSet();
2556
2912
  privateChannelsCollection = {};
2557
2913
  operations = {
2558
2914
  addContextListenerRequest: { requestType: "addContextListenerRequest", requestDecoder: addContextListenerRequestDecoder, responseType: "addContextListenerResponse", responseDecoder: addContextListenerResponseDecoder, execute: this.handleAddContextListenerRequest.bind(this) },
2559
2915
  addEventListenerRequest: { requestType: "addEventListenerRequest", requestDecoder: addEventListenerRequestDecoder, responseType: "addEventListenerResponse", responseDecoder: addEventListenerResponseDecoder, execute: this.handleAddEventListenerRequest.bind(this) },
2560
2916
  broadcastRequest: { requestType: "broadcastRequest", responseType: "broadcastResponse", requestDecoder: broadcastRequestDecoder, responseDecoder: broadcastResponseDecoder, execute: this.handleBroadcastRequest.bind(this) },
2917
+ clearContextRequest: { requestType: "clearContextRequest", requestDecoder: clearContextRequestDecoder, responseType: "clearContextResponse", responseDecoder: clearContextResponseDecoder, execute: this.handleClearContextRequest.bind(this) },
2561
2918
  contextListenerUnsubscribeRequest: { requestType: "contextListenerUnsubscribeRequest", requestDecoder: contextListenerUnsubscribeRequestDecoder, responseType: "contextListenerUnsubscribeResponse", responseDecoder: contextListenerUnsubscribeResponseDecoder, execute: this.handleUnsubscribeRequest.bind(this) },
2562
2919
  createPrivateChannelRequest: { requestType: "createPrivateChannelRequest", requestDecoder: createPrivateChannelRequestDecoder, responseType: "createPrivateChannelResponse", responseDecoder: createPrivateChannelResponseDecoder, execute: this.handleCreatePrivateChannelRequest.bind(this) },
2563
2920
  eventListenerUnsubscribeRequest: { requestType: "eventListenerUnsubscribeRequest", requestDecoder: eventListenerUnsubscribeRequestDecoder, responseType: "eventListenerUnsubscribeResponse", responseDecoder: eventListenerUnsubscribeResponseDecoder, execute: this.handleUnsubscribeRequest.bind(this) },
@@ -2571,8 +2928,9 @@ class ChannelsController {
2571
2928
  privateChannelDisconnectRequest: { requestType: "privateChannelDisconnectRequest", requestDecoder: privateChannelDisconnectRequestDecoder, responseType: "privateChannelDisconnectResponse", responseDecoder: privateChannelDisconnectResponseDecoder, execute: this.handlePrivateChannelDisconnectRequest.bind(this) },
2572
2929
  privateChannelUnsubscribeEventListenerRequest: { requestType: "privateChannelUnsubscribeEventListenerRequest", requestDecoder: privateChannelUnsubscribeEventListenerRequestDecoder, responseType: "privateChannelUnsubscribeEventListenerResponse", responseDecoder: privateChannelUnsubscribeEventListenerResponseDecoder, execute: this.handlePrivateChannelUnsubscribeEventListenerRequest.bind(this) }
2573
2930
  };
2574
- constructor(sendBridgeMessage, logger) {
2931
+ constructor(sendBridgeMessage, myAppMetadata, logger) {
2575
2932
  this.sendBridgeMessage = sendBridgeMessage;
2933
+ this.myAppMetadata = myAppMetadata;
2576
2934
  this.logger = logger;
2577
2935
  }
2578
2936
  async handleControl(request) {
@@ -2607,105 +2965,317 @@ class ChannelsController {
2607
2965
  this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
2608
2966
  return response;
2609
2967
  }
2968
+ async handlePostResponse(request) {
2969
+ const operation = this.operations[request.type];
2970
+ await operation.postResponse?.(request);
2971
+ }
2610
2972
  addPrivateChannel(privateChannel) {
2611
2973
  this.logger?.info(`addPrivateChannel called with channel id: ${privateChannel.id}, type: ${privateChannel.type}`);
2612
2974
  this.privateChannelsCollection[privateChannel.id] = privateChannel;
2613
2975
  }
2614
2976
  async handleAddContextListenerRequest({ payload }) {
2977
+ if (!window.fdc3) {
2978
+ return { error: "AccessDenied" };
2979
+ }
2615
2980
  const listenerUUID = nanoid();
2981
+ const agent = window.fdc3;
2616
2982
  const channel = payload.channelId ? await this.getChannelById(payload.channelId) : null;
2617
- const handler = async (context, metadata) => {
2983
+ const initialChannel = payload.channelId == null ? await agent.getCurrentChannel?.() : null;
2984
+ const registrationMembership = this.userChannelMemberships.get(agent);
2985
+ const handler = async (context, metadata, replayChannelId, isInitialReplay) => {
2986
+ if (!window.fdc3) {
2987
+ return { error: "AccessDenied" };
2988
+ }
2618
2989
  this.logger?.info(`addContextListener handler invoked with context: ${JSON.stringify(context)} and metadata: ${JSON.stringify(metadata)}`);
2619
- const eventUuid = nanoid();
2620
- const channelId = !payload.channelId || channel?.type === "user"
2621
- ? (await window.fdc3?.getCurrentChannel())?.id ?? null
2622
- : payload.channelId;
2623
- const broadcastEventMsg = {
2624
- type: "broadcastEvent",
2625
- meta: {
2626
- eventUuid,
2627
- timestamp: new Date()
2628
- },
2629
- payload: {
2630
- channelId,
2631
- context,
2632
- originatingApp: {
2633
- appId: metadata?.source.appId ?? "",
2634
- instanceId: metadata?.source.instanceId,
2635
- desktopAgent: DESKTOP_AGENT_NAME
2636
- }
2637
- }
2638
- };
2639
- this.logger?.info(`Sending 'broadcastEvent' message: ${JSON.stringify(broadcastEventMsg)}`);
2640
- this.sendBridgeMessage(broadcastEventMsg);
2990
+ const hasDesktopListener = Array.from(this.contextListeners.values()).some((listener) => listener.agent === agent && listener.channelId === null);
2991
+ let currentChannel = null;
2992
+ if (hasDesktopListener) {
2993
+ currentChannel = await agent.getCurrentChannel();
2994
+ }
2995
+ const currentChannelId = currentChannel?.id ?? null;
2996
+ const channelId = payload.channelId ?? currentChannelId;
2997
+ if (payload.channelId == null && isInitialReplay) {
2998
+ await this.replayExternalChannelContext(listenerUUID, agent, currentChannel, replayChannelId, initialChannel?.id, registrationMembership);
2999
+ return;
3000
+ }
3001
+ if (!this.hasMatchingContextListener(listenerUUID, agent, channelId, context.type, currentChannelId)) {
3002
+ return;
3003
+ }
3004
+ const membership = this.userChannelMemberships.get(agent);
3005
+ if (membership?.channelId === channelId) {
3006
+ await membership.replay;
3007
+ }
3008
+ this.sendContextEvent(channelId, context, metadata);
2641
3009
  };
2642
- const addContextListenerInterfaceMsg = channel ? "channel '" + channel.id + "'" : "fdc3";
2643
- this.logger?.info(`Adding context listener on ${addContextListenerInterfaceMsg} interface for context type ${payload.contextType ?? null}`);
2644
- const listener = await (channel ?? window.fdc3)?.addContextListener(payload.contextType ?? null, handler);
2645
- this.listenersCollection[listenerUUID] = listener;
3010
+ const addContextListenerInterfaceMsg = channel ? `channel '${channel.id}'` : "fdc3";
3011
+ const contextTypesMsg = payload.contextTypes ? JSON.stringify(payload.contextTypes) : JSON.stringify(payload.contextType ?? null);
3012
+ this.logger?.info(`Adding context listener on ${addContextListenerInterfaceMsg} interface for context type(s) ${contextTypesMsg}`);
3013
+ const target = channel ?? window.fdc3;
3014
+ const registration = { agent, channelId: payload.channelId ?? null, types: payload.contextTypes ?? payload.contextType ?? null, isActive: false };
3015
+ this.contextListeners.set(listenerUUID, registration);
3016
+ try {
3017
+ const listener = await (payload.contextTypes != null
3018
+ ? target.addContextListener(payload.contextTypes, handler)
3019
+ : target.addContextListener(payload.contextType ?? null, handler));
3020
+ this.listenersCollection[listenerUUID] = listener;
3021
+ registration.isActive = true;
3022
+ }
3023
+ catch (error) {
3024
+ this.contextListeners.delete(listenerUUID);
3025
+ throw error;
3026
+ }
2646
3027
  return { listenerUUID };
2647
3028
  }
3029
+ updateUserChannelMembership(agent, channelId) {
3030
+ const previous = this.userChannelMemberships.get(agent);
3031
+ if (previous?.channelId === channelId) {
3032
+ return previous;
3033
+ }
3034
+ const pendingJoin = this.pendingProxyJoins.get(agent);
3035
+ const membership = pendingJoin?.channelId === channelId
3036
+ ? pendingJoin
3037
+ : { channelId, isProxyRequested: false };
3038
+ this.userChannelMemberships.set(agent, membership);
3039
+ return membership;
3040
+ }
3041
+ async replayExternalChannelContext(listenerUUID, agent, channel, replayChannelId, initialChannelId, registrationMembership) {
3042
+ if (!this.contextListeners.has(listenerUUID) || !channel) {
3043
+ return;
3044
+ }
3045
+ if (replayChannelId != null && replayChannelId !== channel.id) {
3046
+ return;
3047
+ }
3048
+ if (this.shouldSuppressContextReplay(agent, channel.id, initialChannelId, registrationMembership)) {
3049
+ return;
3050
+ }
3051
+ const membership = this.updateUserChannelMembership(agent, channel.id);
3052
+ membership.replay ??= this.readContextReplay(agent, channel, listenerUUID).then((contexts) => {
3053
+ if (window.fdc3 !== agent || this.userChannelMemberships.get(agent) !== membership) {
3054
+ return;
3055
+ }
3056
+ for (const { context, metadata } of contexts) {
3057
+ this.sendContextEvent(channel.id, context, metadata);
3058
+ }
3059
+ }).catch((error) => {
3060
+ membership.replay = undefined;
3061
+ this.logger?.warn(`Could not replay retained context on channel '${channel.id}': ${error}`);
3062
+ });
3063
+ await membership.replay;
3064
+ }
3065
+ async readContextReplay(agent, channel, listenerUUID) {
3066
+ const types = this.getContextReplayTypes(agent, listenerUUID);
3067
+ const latest = await channel.getCurrentContextWithMetadata();
3068
+ const requestedTypes = Array.from(types).filter((type) => type !== null && type !== latest?.context.type);
3069
+ const retained = await Promise.all(requestedTypes.map((type) => channel.getCurrentContextWithMetadata(type)));
3070
+ const contexts = retained.filter((result) => result !== null);
3071
+ if (latest && (types.has(null) || types.has(latest.context.type))) {
3072
+ contexts.push(latest);
3073
+ }
3074
+ return contexts;
3075
+ }
3076
+ getContextReplayTypes(agent, listenerUUID) {
3077
+ const types = new Set();
3078
+ for (const [uuid, listener] of this.contextListeners) {
3079
+ if (listener.agent !== agent || listener.channelId !== null || (!listener.isActive && uuid !== listenerUUID)) {
3080
+ continue;
3081
+ }
3082
+ const listenerTypes = Array.isArray(listener.types) ? listener.types : [listener.types];
3083
+ listenerTypes.forEach((type) => types.add(type));
3084
+ }
3085
+ return types;
3086
+ }
3087
+ sendContextEvent(channelId, context, metadata) {
3088
+ const broadcastEventMsg = {
3089
+ type: "broadcastEvent",
3090
+ meta: {
3091
+ eventUuid: nanoid(),
3092
+ timestamp: new Date()
3093
+ },
3094
+ payload: { channelId, context, metadata }
3095
+ };
3096
+ this.logger?.info(`Sending 'broadcastEvent' message: ${JSON.stringify(broadcastEventMsg)}`);
3097
+ this.sendBridgeMessage(broadcastEventMsg);
3098
+ }
3099
+ shouldSuppressContextReplay(agent, channelId, initialChannelId, registrationMembership) {
3100
+ const membership = this.userChannelMemberships.get(agent);
3101
+ if (this.pendingProxyJoins.get(agent)?.channelId === channelId) {
3102
+ return true;
3103
+ }
3104
+ if (initialChannelId === channelId && membership === registrationMembership) {
3105
+ return true;
3106
+ }
3107
+ return membership?.channelId === channelId && membership.isProxyRequested;
3108
+ }
3109
+ hasMatchingContextListener(listenerUUID, agent, channelId, type, currentChannelId) {
3110
+ for (const [uuid, listener] of this.contextListeners) {
3111
+ if (!listener.isActive && uuid !== listenerUUID) {
3112
+ continue;
3113
+ }
3114
+ const sameType = listener.types === null
3115
+ || listener.types === type
3116
+ || (Array.isArray(listener.types) && listener.types.includes(type));
3117
+ const listenerChannelId = listener.channelId ?? currentChannelId;
3118
+ if (listener.agent === agent && listenerChannelId === channelId && sameType) {
3119
+ return uuid === listenerUUID;
3120
+ }
3121
+ }
3122
+ return false;
3123
+ }
2648
3124
  async getChannelById(id) {
3125
+ if (!window.fdc3) {
3126
+ throw new Error("AccessDenied");
3127
+ }
2649
3128
  const privateChannel = this.privateChannelsCollection[id];
2650
3129
  if (privateChannel) {
2651
3130
  return privateChannel;
2652
3131
  }
2653
- const channel = await window.fdc3?.getOrCreateChannel(id);
3132
+ if (id.startsWith(privateChannelPrefix)) {
3133
+ throw new Error(ChannelError.AccessDenied);
3134
+ }
3135
+ const channel = await window.fdc3.getOrCreateChannel(id);
2654
3136
  return channel;
2655
3137
  }
3138
+ getMatchingEventListenerUUID(agent, scope, channelId, type) {
3139
+ for (const [listenerUUID, listener] of this.eventListeners) {
3140
+ const sameAgent = listener.agent === agent;
3141
+ const sameScope = listener.scope === scope;
3142
+ const sameChannel = listener.channelId === channelId;
3143
+ const sameType = listener.type === null || listener.type === type;
3144
+ if (!sameAgent || !sameScope || !sameChannel || !sameType) {
3145
+ continue;
3146
+ }
3147
+ return listenerUUID;
3148
+ }
3149
+ }
3150
+ hasMatchingEventListener(listenerUUID, agent, scope, channelId, type) {
3151
+ const eventListenerUUID = this.getMatchingEventListenerUUID(agent, scope, channelId, type);
3152
+ return !eventListenerUUID || eventListenerUUID === listenerUUID;
3153
+ }
2656
3154
  async handleAddEventListenerRequest({ payload }) {
3155
+ if (!window.fdc3) {
3156
+ return { error: ChannelError.AccessDenied };
3157
+ }
3158
+ if (payload.channelId && payload.type === "USER_CHANNEL_CHANGED") {
3159
+ this.logger?.error("Event 'userChannelChanged' cannot be listened to on a specific channel");
3160
+ return { error: ChannelError.InvalidArguments };
3161
+ }
2657
3162
  const listenerUUID = nanoid();
2658
- const handler = (event) => {
3163
+ const agent = window.fdc3;
3164
+ const handler = this.getEventHandler(listenerUUID, agent, payload);
3165
+ const type = payload.type ? ChannelEventToTypeDictionary[payload.type] : null;
3166
+ const listener = await (payload.channelId
3167
+ ? (await this.getChannelById(payload.channelId)).addEventListener(type, handler)
3168
+ : window.fdc3.addEventListener(type, handler));
3169
+ this.listenersCollection[listenerUUID] = listener;
3170
+ this.eventListeners.set(listenerUUID, { agent, scope: payload.channelId ? "channel" : "desktop", channelId: payload.channelId ?? null, type });
3171
+ return { listenerUUID };
3172
+ }
3173
+ getEventHandler(listenerUUID, agent, payload) {
3174
+ const scope = payload.channelId ? "channel" : "desktop";
3175
+ const channelId = payload.channelId ?? null;
3176
+ return (event) => {
3177
+ if (scope === "desktop" && event.type === "userChannelChanged") {
3178
+ this.updateUserChannelMembership(agent, event.details.currentChannelId ?? null);
3179
+ }
3180
+ if (scope === "desktop" && event.type === "contextCleared" && this.getMatchingEventListenerUUID(agent, "channel", event.details.channelId, event.type)) {
3181
+ return;
3182
+ }
3183
+ const hasMatching = this.hasMatchingEventListener(listenerUUID, agent, scope, channelId, event.type);
3184
+ if (!hasMatching) {
3185
+ return;
3186
+ }
2659
3187
  this.logger?.info(`addEventListener's callback invoked with event: ${JSON.stringify(event)}`);
2660
- const eventUuid = nanoid();
2661
- if (event.type !== "userChannelChanged") {
3188
+ if (!this.checkIfEventSupported(event, payload)) {
2662
3189
  return;
2663
3190
  }
2664
- const currentChannelId = event.details.currentChannelId ?? null;
2665
- const response = {
2666
- type: "channelChangedEvent",
2667
- meta: {
2668
- eventUuid,
2669
- timestamp: new Date()
2670
- },
2671
- payload: {
2672
- currentChannelId,
2673
- newChannelId: currentChannelId,
2674
- }
2675
- };
2676
- this.logger?.info(`Sending 'channelChangedEvent' message: ${JSON.stringify(response)}`);
3191
+ let response;
3192
+ if (event.type === "userChannelChanged") {
3193
+ response = this.getChannelChangedEvent(event);
3194
+ }
3195
+ if (event.type === "contextCleared") {
3196
+ response = this.getContextClearedEvent(event);
3197
+ }
3198
+ if (!response) {
3199
+ this.logger?.warn(`Unsupported event type: ${event.type}`);
3200
+ return;
3201
+ }
3202
+ this.logger?.info(`Sending '${response.type}' message: ${JSON.stringify(response)}`);
2677
3203
  this.sendBridgeMessage(response);
2678
3204
  };
2679
- this.logger?.info(`Adding event listener for type ${payload.type ?? null} on fdc3 interface`);
2680
- const type = this.getAddEventListenerTypeByRequestPayloadType(payload.type);
2681
- const listener = await window.fdc3.addEventListener(type, handler);
2682
- this.listenersCollection[listenerUUID] = listener;
2683
- return { listenerUUID };
2684
3205
  }
2685
- getAddEventListenerTypeByRequestPayloadType(requestType) {
2686
- if (!requestType) {
2687
- return null;
3206
+ checkIfEventSupported(event, payload) {
3207
+ if (!supportedEventTypes.includes(event.type)) {
3208
+ this.logger?.warn(`Unsupported event type: ${event.type}`);
3209
+ return false;
3210
+ }
3211
+ if (payload.channelId && event.type === "userChannelChanged") {
3212
+ this.logger?.warn("Event 'userChannelChanged' cannot be listened to on a specific channel");
3213
+ return false;
2688
3214
  }
2689
- return ChannelEventToTypeDictionary[requestType] ?? null;
3215
+ return true;
3216
+ }
3217
+ getChannelChangedEvent(event) {
3218
+ const currentChannelId = event.details.currentChannelId ?? null;
3219
+ const response = {
3220
+ type: "channelChangedEvent",
3221
+ meta: {
3222
+ eventUuid: nanoid(),
3223
+ timestamp: new Date()
3224
+ },
3225
+ payload: {
3226
+ currentChannelId,
3227
+ newChannelId: currentChannelId,
3228
+ }
3229
+ };
3230
+ return response;
3231
+ }
3232
+ getContextClearedEvent(event) {
3233
+ const response = {
3234
+ type: "contextClearedEvent",
3235
+ meta: {
3236
+ eventUuid: nanoid(),
3237
+ timestamp: new Date()
3238
+ },
3239
+ payload: {
3240
+ channelId: event.details.channelId,
3241
+ contextType: event.details.contextType ?? null
3242
+ }
3243
+ };
3244
+ return response;
2690
3245
  }
2691
3246
  async handleBroadcastRequest({ payload }) {
2692
- const { channelId, context } = payload;
3247
+ const { channelId, context, metadata } = payload;
3248
+ const channel = await this.getChannelById(channelId);
3249
+ const enrichedMetadata = buildEnrichedMetadata(metadata, this.myAppMetadata);
3250
+ await (channel ?? window.fdc3)?.broadcast(context, enrichedMetadata);
3251
+ return {};
3252
+ }
3253
+ async handleClearContextRequest({ payload }) {
3254
+ const { channelId, contextType } = payload;
2693
3255
  const channel = await this.getChannelById(channelId);
2694
- await (channel ?? window.fdc3)?.broadcast(context);
3256
+ if (!channel) {
3257
+ return { error: "NoChannelFound" };
3258
+ }
3259
+ await channel.clearContext(contextType ?? undefined);
2695
3260
  return {};
2696
3261
  }
2697
3262
  async handleUnsubscribeRequest({ payload }) {
2698
3263
  const listener = this.listenersCollection[payload.listenerUUID];
2699
3264
  if (!listener) {
2700
- return { error: "MalformedMessage", reason: `Cannot find listener with listenerUUID: ${payload.listenerUUID}` };
3265
+ return { error: ChannelError.AccessDenied };
2701
3266
  }
2702
3267
  this.logger?.info(`Unsubscribing listener with UUID: ${payload.listenerUUID}`);
2703
3268
  await listener.unsubscribe();
2704
3269
  delete this.listenersCollection[payload.listenerUUID];
3270
+ this.eventListeners.delete(payload.listenerUUID);
3271
+ this.contextListeners.delete(payload.listenerUUID);
2705
3272
  return {};
2706
3273
  }
2707
3274
  async handleCreatePrivateChannelRequest() {
2708
- const privateChannel = await window.fdc3?.createPrivateChannel();
3275
+ if (!window.fdc3) {
3276
+ return { error: "AccessDenied" };
3277
+ }
3278
+ const privateChannel = await window.fdc3.createPrivateChannel();
2709
3279
  if (!privateChannel) {
2710
3280
  return { error: "CreationFailed" };
2711
3281
  }
@@ -2714,36 +3284,83 @@ class ChannelsController {
2714
3284
  return { privateChannel: pureChannel };
2715
3285
  }
2716
3286
  async handleGetCurrentChannelRequest() {
2717
- const channel = await window.fdc3?.getCurrentChannel();
3287
+ if (!window.fdc3) {
3288
+ return { error: "AccessDenied" };
3289
+ }
3290
+ const channel = await window.fdc3.getCurrentChannel();
2718
3291
  const pureChannel = JSON.parse(JSON.stringify(channel));
2719
3292
  return { channel: pureChannel };
2720
3293
  }
2721
3294
  async handleGetCurrentContextRequest({ payload }) {
2722
- const channel = await window.fdc3?.getOrCreateChannel(payload.channelId);
3295
+ if (!window.fdc3) {
3296
+ return { error: "AccessDenied" };
3297
+ }
3298
+ const channel = await this.getChannelById(payload.channelId);
3299
+ if (!channel) {
3300
+ return { error: "NoChannelFound" };
3301
+ }
2723
3302
  const contextType = payload.contextType ?? undefined;
2724
- const context = await channel?.getCurrentContext(contextType);
2725
- return { context };
3303
+ const contextWithMetadata = await channel.getCurrentContextWithMetadata(contextType);
3304
+ return {
3305
+ context: contextWithMetadata?.context ?? null,
3306
+ metadata: contextWithMetadata?.metadata ?? null
3307
+ };
2726
3308
  }
2727
3309
  async handleGetOrCreateChannelRequest({ payload }) {
3310
+ if (!window.fdc3) {
3311
+ return { error: "AccessDenied" };
3312
+ }
2728
3313
  const isPrivateChannel = this.privateChannelsCollection[payload.channelId] ?? payload.channelId.startsWith(privateChannelPrefix);
2729
3314
  if (isPrivateChannel) {
2730
3315
  return { error: "AccessDenied" };
2731
3316
  }
2732
- const channel = await window.fdc3?.getOrCreateChannel(payload.channelId);
3317
+ const channel = await window.fdc3.getOrCreateChannel(payload.channelId);
2733
3318
  const pureChannel = JSON.parse(JSON.stringify(channel));
2734
3319
  return { channel: pureChannel };
2735
3320
  }
2736
3321
  async handleGetUserChannelsRequest() {
2737
- const userChannels = await window.fdc3?.getUserChannels() ?? [];
3322
+ if (!window.fdc3) {
3323
+ return { error: "AccessDenied" };
3324
+ }
3325
+ const userChannels = await window.fdc3.getUserChannels() ?? [];
2738
3326
  const pureChannels = userChannels.map((ch) => JSON.parse(JSON.stringify(ch)));
2739
3327
  return { userChannels: pureChannels };
2740
3328
  }
2741
3329
  async handleJoinUserChannelRequest({ payload }) {
2742
- await window.fdc3?.joinUserChannel(payload.channelId);
3330
+ if (!window.fdc3) {
3331
+ return { error: "AccessDenied" };
3332
+ }
3333
+ const agent = window.fdc3;
3334
+ const previous = this.userChannelMemberships.get(agent);
3335
+ const membership = { channelId: payload.channelId, isProxyRequested: true };
3336
+ this.userChannelMemberships.set(agent, membership);
3337
+ this.pendingProxyJoins.set(agent, membership);
3338
+ try {
3339
+ await agent.joinUserChannel(payload.channelId);
3340
+ }
3341
+ catch (error) {
3342
+ if (this.userChannelMemberships.get(agent) === membership) {
3343
+ this.userChannelMemberships.delete(agent);
3344
+ if (previous) {
3345
+ this.userChannelMemberships.set(agent, previous);
3346
+ }
3347
+ }
3348
+ throw error;
3349
+ }
3350
+ finally {
3351
+ if (this.pendingProxyJoins.get(agent) === membership) {
3352
+ this.pendingProxyJoins.delete(agent);
3353
+ }
3354
+ }
2743
3355
  return {};
2744
3356
  }
2745
3357
  async handleLeaveCurrentChannel(request) {
2746
- await window.fdc3?.leaveCurrentChannel();
3358
+ if (!window.fdc3) {
3359
+ return { error: "AccessDenied" };
3360
+ }
3361
+ const agent = window.fdc3;
3362
+ await agent.leaveCurrentChannel();
3363
+ this.updateUserChannelMembership(agent, null);
2747
3364
  return {};
2748
3365
  }
2749
3366
  async handlePrivateChannelAddEventListenerRequest({ payload }) {
@@ -2753,30 +3370,43 @@ class ChannelsController {
2753
3370
  if (!privateChannel) {
2754
3371
  return { error: "NoChannelFound" };
2755
3372
  }
3373
+ const listenerUUID = nanoid();
3374
+ const agent = window.fdc3 ?? privateChannel;
2756
3375
  const handler = (event) => {
2757
3376
  this.logger?.info(`Received event: ${JSON.stringify(event)}`);
3377
+ if (listenerType === null && event.type === "contextCleared") {
3378
+ return;
3379
+ }
3380
+ if (event.type === "contextCleared" && this.getMatchingEventListenerUUID(agent, "channel", privateChannelId, event.type)) {
3381
+ return;
3382
+ }
2758
3383
  if (listenerType && listenerType !== event.type) {
2759
3384
  this.logger?.info(`Listener type from private channel addEventListenerRequest '${listenerType}' does not match the event type '${event.type}'. Handler won't be invoked...`);
2760
3385
  return;
2761
3386
  }
2762
- const eventUuid = nanoid();
2763
- const responseType = {
2764
- type: this.getPrivateChannelResponseType(event.type),
2765
- meta: {
2766
- eventUuid,
2767
- timestamp: new Date()
2768
- },
2769
- payload: {
2770
- contextType: event.details?.contextType,
2771
- privateChannelId: payload.privateChannelId
2772
- }
2773
- };
2774
- this.logger?.info(`Sending private channel event response: ${JSON.stringify(responseType)}`);
2775
- this.sendBridgeMessage(responseType);
3387
+ if (this.forwardedPrivateEvents.has(event)) {
3388
+ return;
3389
+ }
3390
+ const response = event.type === "contextCleared"
3391
+ ? this.getContextClearedEvent(event)
3392
+ : {
3393
+ type: this.getPrivateChannelResponseType(event.type),
3394
+ meta: {
3395
+ eventUuid: nanoid(),
3396
+ timestamp: new Date()
3397
+ },
3398
+ payload: {
3399
+ contextType: event.details?.contextType,
3400
+ privateChannelId
3401
+ }
3402
+ };
3403
+ this.logger?.info(`Sending private channel event response: ${JSON.stringify(response)}`);
3404
+ this.forwardedPrivateEvents.add(event);
3405
+ this.sendBridgeMessage(response);
2776
3406
  };
2777
- const listenerUUID = nanoid();
2778
3407
  const listener = await privateChannel.addEventListener(payload.listenerType ?? null, handler);
2779
3408
  this.listenersCollection[listenerUUID] = listener;
3409
+ this.eventListeners.set(listenerUUID, { agent, scope: "private", channelId: privateChannelId, type: listenerType });
2780
3410
  return { listenerUUID };
2781
3411
  }
2782
3412
  async handlePrivateChannelDisconnectRequest({ payload }) {
@@ -2795,6 +3425,7 @@ class ChannelsController {
2795
3425
  }
2796
3426
  await listener.unsubscribe();
2797
3427
  delete this.listenersCollection[payload.listenerUUID];
3428
+ this.eventListeners.delete(payload.listenerUUID);
2798
3429
  return {};
2799
3430
  }
2800
3431
  decorateResponse({ request, payload, responseUuid }) {
@@ -2843,9 +3474,7 @@ class BridgeController {
2843
3474
  this._messageChannel?.port1.postMessage(data);
2844
3475
  }
2845
3476
  globalMessageHandler(event) {
2846
- const parentURL = document.referrer;
2847
- const origin = new URL(parentURL).origin;
2848
- if (event.origin !== origin) {
3477
+ if (window.parent === window || event.source !== window.parent) {
2849
3478
  return;
2850
3479
  }
2851
3480
  if (event.data?.type === WCPMessageTypes.WCP1Hello) {
@@ -2886,6 +3515,10 @@ class BridgeController {
2886
3515
  const result = await this.ioc.domainsController.handleMessage(event.data);
2887
3516
  this.logMessage({ level: "info", message: `Sending response message: ${JSON.stringify(result)}` });
2888
3517
  this.sendMessage(result);
3518
+ if (result.payload.error !== undefined) {
3519
+ return;
3520
+ }
3521
+ await this.ioc.domainsController.handlePostResponse(event.data);
2889
3522
  }
2890
3523
  async handleAppIdentityValidationRequest(data) {
2891
3524
  const decodedRequest = wcp4ValidateAppIdentityDecoder.run(data);
@@ -2905,6 +3538,10 @@ class BridgeController {
2905
3538
  this.cleanSetup();
2906
3539
  return;
2907
3540
  }
3541
+ this.ioc.myAppMetadata = {
3542
+ appId: validationResult.appId,
3543
+ instanceId: this.ioController.io?.interop.instance.instance,
3544
+ };
2908
3545
  await this.sendValidationSuccess(data.meta.connectionAttemptUuid, validationResult.appId);
2909
3546
  this.logMessage({ level: "info", message: `App validation is successful. Connection is completed` });
2910
3547
  this._connectionCompleted = true;
@@ -3031,10 +3668,14 @@ class DomainsController {
3031
3668
  }
3032
3669
  return result;
3033
3670
  }
3671
+ async handlePostResponse(data) {
3672
+ const domain = Object.values(this.domains).find((domain) => domain.requestTypes.includes(data.type));
3673
+ await domain?.controller.handlePostResponse?.(data);
3674
+ }
3034
3675
  setupDomains() {
3035
- const channelsRequestTypes = ["addContextListenerRequest", "addEventListenerRequest", "broadcastRequest", "contextListenerUnsubscribeRequest", "createPrivateChannelRequest", "eventListenerUnsubscribeRequest", "getCurrentChannelRequest", "getCurrentContextRequest", "getOrCreateChannelRequest", "getUserChannelsRequest", "joinUserChannelRequest", "leaveCurrentChannelRequest", "privateChannelAddEventListenerRequest", "privateChannelDisconnectRequest", "privateChannelUnsubscribeEventListenerRequest"];
3676
+ const channelsRequestTypes = ["addContextListenerRequest", "addEventListenerRequest", "broadcastRequest", "clearContextRequest", "contextListenerUnsubscribeRequest", "createPrivateChannelRequest", "eventListenerUnsubscribeRequest", "getCurrentChannelRequest", "getCurrentContextRequest", "getOrCreateChannelRequest", "getUserChannelsRequest", "joinUserChannelRequest", "leaveCurrentChannelRequest", "privateChannelAddEventListenerRequest", "privateChannelDisconnectRequest", "privateChannelUnsubscribeEventListenerRequest"];
3036
3677
  const intentsRequestTypes = ["addIntentListenerRequest", "findIntentRequest", "findIntentsByContextRequest", "intentListenerUnsubscribeRequest", "intentResultRequest", "raiseIntentForContextRequest", "raiseIntentRequest"];
3037
- const applicationsRequestTypes = ["findInstancesRequest", "getAppMetadataRequest", "getInfoRequest", "openRequest", "heartbeatAcknowledgementRequest"];
3678
+ const applicationsRequestTypes = ["findInstancesRequest", "getAppMetadataRequest", "getInfoRequest", "openRequest", "heartbeatAcknowledgementRequest", "closeRequest"];
3038
3679
  this.domains = {
3039
3680
  channels: {
3040
3681
  name: "channels",
@@ -3055,102 +3696,6 @@ class DomainsController {
3055
3696
  }
3056
3697
  }
3057
3698
 
3058
- const rejectWithErrorObj = (reject, error) => {
3059
- if (error instanceof Error) {
3060
- reject(error.message);
3061
- return;
3062
- }
3063
- if (typeof error === "string") {
3064
- reject(new Error(error));
3065
- return;
3066
- }
3067
- reject(new Error(JSON.stringify(error)));
3068
- };
3069
- const wrapPromise = () => {
3070
- let wrapperResolve;
3071
- let wrapperReject;
3072
- const promise = new Promise((resolve, reject) => {
3073
- wrapperResolve = resolve;
3074
- wrapperReject = reject;
3075
- });
3076
- return { promise, resolve: wrapperResolve, reject: wrapperReject };
3077
- };
3078
- const promisePlus = (promise, timeoutMilliseconds, timeoutMessage) => {
3079
- return new Promise((resolve, reject) => {
3080
- const timeout = setTimeout(() => {
3081
- const message = timeoutMessage || `Promise timeout hit: ${timeoutMilliseconds}`;
3082
- reject(new Error(message));
3083
- }, timeoutMilliseconds);
3084
- promise()
3085
- .then((result) => {
3086
- clearTimeout(timeout);
3087
- resolve(result);
3088
- })
3089
- .catch((error) => {
3090
- clearTimeout(timeout);
3091
- rejectWithErrorObj(reject, error);
3092
- });
3093
- });
3094
- };
3095
- const compareOrigins = (url1, url2) => {
3096
- try {
3097
- const parsedUrl1 = new URL(url1);
3098
- const parsedUrl2 = new URL(url2);
3099
- return parsedUrl1.origin === parsedUrl2.origin;
3100
- }
3101
- catch (e) {
3102
- return false;
3103
- }
3104
- };
3105
- const removeTrailingSlash = (pathname) => {
3106
- return pathname.endsWith("/")
3107
- ? pathname.slice(0, -1)
3108
- : pathname;
3109
- };
3110
- const isRecordUrlMatchToIdentityUrl = (recordUrl, identityUrl) => {
3111
- let parsedRecordUrl;
3112
- let parsedIdentityUrl;
3113
- try {
3114
- parsedRecordUrl = new URL(recordUrl);
3115
- parsedIdentityUrl = new URL(identityUrl);
3116
- }
3117
- catch (error) {
3118
- return false;
3119
- }
3120
- if (parsedRecordUrl.origin !== parsedIdentityUrl.origin) {
3121
- return false;
3122
- }
3123
- const recordPath = removeTrailingSlash(parsedRecordUrl.pathname);
3124
- const identityPath = removeTrailingSlash(parsedIdentityUrl.pathname);
3125
- if (recordPath !== identityPath) {
3126
- return false;
3127
- }
3128
- for (const [key, value] of parsedRecordUrl.searchParams) {
3129
- if (parsedIdentityUrl.searchParams.get(key) !== value) {
3130
- return false;
3131
- }
3132
- }
3133
- if (parsedRecordUrl.hash && parsedRecordUrl.hash !== parsedIdentityUrl.hash) {
3134
- return false;
3135
- }
3136
- return true;
3137
- };
3138
- const checkIfFDC3Channel = (object) => {
3139
- if (!object || typeof object !== "object" || Array.isArray(object)) {
3140
- return false;
3141
- }
3142
- if (!channelTypes.includes(object?.type)) {
3143
- return false;
3144
- }
3145
- return defaultChannelsProps.every((prop) => Object.keys(object).includes(prop));
3146
- };
3147
- const checkIfFDC3Context = (object) => {
3148
- if (!object || typeof object !== "object" || Array.isArray(object)) {
3149
- return false;
3150
- }
3151
- return "type" in object && typeof object.type === "string";
3152
- };
3153
-
3154
3699
  class IOController {
3155
3700
  _io;
3156
3701
  _initializationStarted = false;
@@ -3226,9 +3771,10 @@ class IOController {
3226
3771
  }
3227
3772
  }
3228
3773
 
3229
- const { nonEmptyStringDecoder } = decoders.common;
3774
+ const { nonEmptyStringDecoder, nullable } = decoders.common;
3230
3775
  const addIntentListenerRequestPayloadDecoder = object$1({
3231
- intent: nonEmptyStringDecoder
3776
+ intent: nonEmptyStringDecoder,
3777
+ contextTypes: optional$1(contextTypesStringArrayDecoder)
3232
3778
  });
3233
3779
  const addIntentListenerRequestDecoder = object$1({
3234
3780
  type: constant$1("addIntentListenerRequest"),
@@ -3269,7 +3815,8 @@ const intentResultDecoder = object$1({
3269
3815
  const intentResultRequestPayloadDecoder = object$1({
3270
3816
  intentEventUuid: nonEmptyStringDecoder,
3271
3817
  intentResult: intentResultDecoder,
3272
- raiseIntentRequestUuid: nonEmptyStringDecoder
3818
+ raiseIntentRequestUuid: nonEmptyStringDecoder,
3819
+ metadata: optionalAppProvidableContextMetadataDecoder
3273
3820
  });
3274
3821
  const intentResultRequestDecoder = object$1({
3275
3822
  type: constant$1("intentResultRequest"),
@@ -3278,7 +3825,9 @@ const intentResultRequestDecoder = object$1({
3278
3825
  });
3279
3826
  const raiseIntentForContextRequestPayloadDecoder = object$1({
3280
3827
  context: contextDecoder,
3281
- app: optional$1(appIdentifierDecoder)
3828
+ app: optional$1(appIdentifierDecoder),
3829
+ metadata: optionalAppProvidableContextMetadataDecoder,
3830
+ newInstance: optional$1(nullable(boolean$1())).map((value) => value ?? undefined)
3282
3831
  });
3283
3832
  const raiseIntentForContextRequestDecoder = object$1({
3284
3833
  type: constant$1("raiseIntentForContextRequest"),
@@ -3288,7 +3837,9 @@ const raiseIntentForContextRequestDecoder = object$1({
3288
3837
  const raiseIntentRequestPayloadDecoder = object$1({
3289
3838
  intent: nonEmptyStringDecoder,
3290
3839
  context: contextDecoder,
3291
- app: optional$1(appIdentifierDecoder)
3840
+ app: optional$1(appIdentifierDecoder),
3841
+ metadata: optionalAppProvidableContextMetadataDecoder,
3842
+ newInstance: optional$1(nullable(boolean$1())).map((value) => value ?? undefined)
3292
3843
  });
3293
3844
  const raiseIntentRequestDecoder = object$1({
3294
3845
  type: constant$1("raiseIntentRequest"),
@@ -3372,6 +3923,7 @@ const raiseIntentResponseDecoder = object$1({
3372
3923
  const raiseIntentResultResponsePayloadDecoder = object$1({
3373
3924
  error: optional$1(responsePayloadErrorDecoder),
3374
3925
  intentResult: optional$1(intentResultDecoder),
3926
+ resultMetadata: optional$1(contextMetadataDecoder)
3375
3927
  });
3376
3928
  const raiseIntentResultResponseDecoder = object$1({
3377
3929
  type: constant$1("raiseIntentResultResponse"),
@@ -3383,6 +3935,7 @@ class IntentsController {
3383
3935
  sendBridgeMessage;
3384
3936
  addPrivateChannel;
3385
3937
  isIntentResolverEnabled;
3938
+ myAppMetadata;
3386
3939
  logger;
3387
3940
  listenersCollection = {};
3388
3941
  intentResolutionsCollection = {};
@@ -3394,14 +3947,15 @@ class IntentsController {
3394
3947
  findIntentsByContextRequest: { requestType: "findIntentsByContextRequest", requestDecoder: findIntentsByContextRequestDecoder, responseType: "findIntentsByContextResponse", responseDecoder: findIntentsByContextResponseDecoder, execute: this.handleFindIntentsByContextRequest.bind(this) },
3395
3948
  intentListenerUnsubscribeRequest: { requestType: "intentListenerUnsubscribeRequest", requestDecoder: intentListenerUnsubscribeRequestDecoder, responseType: "intentListenerUnsubscribeResponse", responseDecoder: intentListenerUnsubscribeResponseDecoder, execute: this.handleIntentListenerUnsubscribeRequest.bind(this) },
3396
3949
  intentResultRequest: { requestType: "intentResultRequest", requestDecoder: intentResultRequestDecoder, responseType: "intentResultResponse", responseDecoder: intentResultResponseDecoder, execute: this.handleIntentResultRequest.bind(this) },
3397
- raiseIntentForContextRequest: { requestType: "raiseIntentForContextRequest", requestDecoder: raiseIntentForContextRequestDecoder, responseType: "raiseIntentForContextResponse", responseDecoder: raiseIntentForContextResponseDecoder, execute: this.handleRaiseIntentForContextRequest.bind(this) },
3398
- raiseIntentRequest: { requestType: "raiseIntentRequest", requestDecoder: raiseIntentRequestDecoder, responseType: "raiseIntentResponse", responseDecoder: raiseIntentResponseDecoder, execute: this.handleRaiseIntentRequest.bind(this) },
3399
- raiseIntentResultRequest: { requestType: "raiseIntentResultRequest", requestDecoder: raiseIntentResultRequestDecoder, responseType: "raiseIntentResultResponse", responseDecoder: raiseIntentResultResponseDecoder, execute: this.handleRaiseIntentResultResponse.bind(this) },
3950
+ raiseIntentForContextRequest: { requestType: "raiseIntentForContextRequest", requestDecoder: raiseIntentForContextRequestDecoder, responseType: "raiseIntentForContextResponse", responseDecoder: raiseIntentForContextResponseDecoder, execute: this.handleRaiseIntentForContextRequest.bind(this), postResponse: this.processRaiseIntentResultResponse.bind(this) },
3951
+ raiseIntentRequest: { requestType: "raiseIntentRequest", requestDecoder: raiseIntentRequestDecoder, responseType: "raiseIntentResponse", responseDecoder: raiseIntentResponseDecoder, execute: this.handleRaiseIntentRequest.bind(this), postResponse: this.processRaiseIntentResultResponse.bind(this) },
3952
+ raiseIntentResultRequest: { requestType: "raiseIntentResultRequest", requestDecoder: raiseIntentResultRequestDecoder, responseType: "raiseIntentResultResponse", responseDecoder: raiseIntentResultResponseDecoder, execute: this.handleRaiseIntentResultRequest.bind(this) },
3400
3953
  };
3401
- constructor(sendBridgeMessage, addPrivateChannel, isIntentResolverEnabled, logger) {
3954
+ constructor(sendBridgeMessage, addPrivateChannel, isIntentResolverEnabled, myAppMetadata, logger) {
3402
3955
  this.sendBridgeMessage = sendBridgeMessage;
3403
3956
  this.addPrivateChannel = addPrivateChannel;
3404
3957
  this.isIntentResolverEnabled = isIntentResolverEnabled;
3958
+ this.myAppMetadata = myAppMetadata;
3405
3959
  this.logger = logger;
3406
3960
  }
3407
3961
  async handleControl(request) {
@@ -3436,18 +3990,34 @@ class IntentsController {
3436
3990
  this.logger?.info(`Returning response: ${JSON.stringify(response)}`);
3437
3991
  return response;
3438
3992
  }
3993
+ async handlePostResponse(request) {
3994
+ const operation = this.operations[request.type];
3995
+ await operation.postResponse?.(request);
3996
+ }
3439
3997
  async handleAddIntentListenerRequest({ meta, payload }) {
3440
- const handler = async (context, metadata) => {
3998
+ const handler = this.createIntentHandler(payload.intent, meta);
3999
+ const listenerUUID = nanoid();
4000
+ try {
4001
+ const listener = await (payload.contextTypes
4002
+ ? window.fdc3?.addIntentListenerWithContext(payload.intent, payload.contextTypes, handler)
4003
+ : window.fdc3?.addIntentListener(payload.intent, handler));
4004
+ this.listenersCollection[listenerUUID] = listener;
4005
+ return { listenerUUID };
4006
+ }
4007
+ catch (error) {
4008
+ return {
4009
+ error: typeof error === "string" ? error : error.message
4010
+ };
4011
+ }
4012
+ }
4013
+ createIntentHandler(intent, meta) {
4014
+ return async (context, metadata) => {
3441
4015
  const eventUuid = nanoid();
3442
4016
  this.logger?.info(`Received intent event with context: ${JSON.stringify(context)} and metadata: ${JSON.stringify(metadata)}`);
3443
4017
  const intentEventPayload = {
3444
- intent: payload.intent,
4018
+ intent,
3445
4019
  context,
3446
- originatingApp: {
3447
- appId: metadata?.source.appId ?? "",
3448
- instanceId: metadata?.source.instanceId,
3449
- desktopAgent: DESKTOP_AGENT_NAME
3450
- },
4020
+ metadata,
3451
4021
  raiseIntentRequestUuid: meta.requestUuid
3452
4022
  };
3453
4023
  this.intentEventPayloadCollection[meta.requestUuid] = intentEventPayload;
@@ -3467,24 +4037,22 @@ class IntentsController {
3467
4037
  delete this.intentHandlerResultPromiseCollection[eventUuid];
3468
4038
  return resultToReturn;
3469
4039
  };
3470
- const listenerUUID = nanoid();
3471
- const listener = await window.fdc3?.addIntentListener(payload.intent, handler);
3472
- this.listenersCollection[listenerUUID] = listener;
3473
- return { listenerUUID };
3474
4040
  }
3475
- getIntentResultToReturn(result) {
3476
- this.logger?.info(`Processing received intent result: ${JSON.stringify(result)}`);
3477
- if (!result || (typeof result === "object" && !Object.keys(result).length)) {
4041
+ getIntentResultToReturn({ intentResult, metadata }) {
4042
+ this.logger?.info(`Processing received intent result: ${JSON.stringify(intentResult)}`);
4043
+ if (!intentResult || (typeof intentResult === "object" && !Object.keys(intentResult).length)) {
3478
4044
  return undefined;
3479
4045
  }
3480
- if (result.context) {
3481
- return result.context;
4046
+ if (intentResult.context) {
4047
+ return metadata
4048
+ ? { context: intentResult.context, metadata: metadata }
4049
+ : intentResult.context;
3482
4050
  }
3483
- if (result.channel) {
4051
+ if (intentResult.channel) {
3484
4052
  return {
3485
- id: result.channel.id,
3486
- type: result.channel.type,
3487
- displayMetadata: result.channel.displayMetadata,
4053
+ id: intentResult.channel.id,
4054
+ type: intentResult.channel.type,
4055
+ displayMetadata: intentResult.channel.displayMetadata,
3488
4056
  broadcast: async () => { },
3489
4057
  addContextListener: async () => { },
3490
4058
  getCurrentContext: async () => { }
@@ -3504,121 +4072,234 @@ class IntentsController {
3504
4072
  if (!listener) {
3505
4073
  return { error: "MalformedMessage", reason: `Cannot find listener with id ${payload.listenerUUID}` };
3506
4074
  }
3507
- listener.unsubscribe();
4075
+ await listener.unsubscribe();
3508
4076
  delete this.listenersCollection[payload.listenerUUID];
3509
4077
  return {};
3510
4078
  }
3511
- async handleIntentResultRequest({ payload }) {
4079
+ handleIntentResultRequest({ payload }) {
3512
4080
  this.logger?.info(`Received intent result request with payload: ${JSON.stringify(payload)}`);
3513
4081
  const intentEventUuid = payload.intentEventUuid;
3514
4082
  const intentEventResultPromise = this.intentHandlerResultPromiseCollection[intentEventUuid];
3515
4083
  if (!intentEventResultPromise) {
3516
4084
  this.logger?.error(`No intent handler result promise found for eventUuid: ${intentEventUuid}`);
3517
- return { error: "MalformedMessage" };
4085
+ return Promise.resolve({ error: "MalformedMessage" });
3518
4086
  }
3519
4087
  this.logger?.info(`Resolving intent handler result promise for eventUuid: ${intentEventUuid} with result: ${JSON.stringify(payload.intentResult)}`);
3520
- intentEventResultPromise.resolve(payload.intentResult);
3521
- return {};
4088
+ intentEventResultPromise.resolve({ intentResult: payload.intentResult, metadata: payload.metadata });
4089
+ return Promise.resolve({});
3522
4090
  }
3523
4091
  async handleRaiseIntentForContextRequest({ meta, payload, type }) {
3524
- if (this.isIntentResolverEnabled && !payload.app) {
4092
+ if (this.isIntentResolverEnabled) {
3525
4093
  return this.handleRaiseIntentForContextRequestWithResolver({ payload, meta, type });
3526
4094
  }
3527
- const intentResolution = await window.fdc3?.raiseIntentForContext(payload.context, payload.app);
4095
+ return this.raiseIntentForContext({ payload, meta });
4096
+ }
4097
+ async raiseIntentForContext({ payload, meta }) {
4098
+ const newInstance = payload.newInstance ?? undefined;
4099
+ const enrichedMetadata = buildEnrichedMetadata(payload.metadata, this.myAppMetadata);
4100
+ const intentResolution = await window.fdc3?.raiseIntentForContext(payload.context, payload.app, newInstance, enrichedMetadata);
3528
4101
  if (!intentResolution) {
3529
4102
  return { error: "IntentDeliveryFailed" };
3530
4103
  }
3531
4104
  this.logger?.info(`Saving intent resolution for requestUuid: ${meta.requestUuid}`);
3532
4105
  this.intentResolutionsCollection[meta.requestUuid] = intentResolution;
3533
4106
  const intentResolutionToReturn = { source: intentResolution.source, intent: intentResolution.intent };
3534
- this.processRaiseIntentResultResponseAsync({
3535
- type: "raiseIntentForContextRequest",
3536
- payload,
3537
- meta
3538
- });
3539
4107
  return { intentResolution: intentResolutionToReturn };
3540
4108
  }
3541
- async handleRaiseIntentForContextRequestWithResolver({ payload, meta, type }) {
3542
- const appIntents = await window.fdc3?.findIntentsByContext(payload.context);
3543
- if (!appIntents || !appIntents.length) {
3544
- return { error: "NoAppsFound" };
4109
+ async handleRaiseIntentForContextRequestWithResolver({ payload, meta }) {
4110
+ const appIntents = await window.fdc3?.findIntentsByContext(payload.context)
4111
+ .catch((error) => {
4112
+ if (error?.message === ResolveError.NoAppsFound) {
4113
+ return [];
4114
+ }
4115
+ throw error;
4116
+ });
4117
+ const eligibleAppIntents = (appIntents ?? [])
4118
+ .map((appIntent) => ({
4119
+ ...appIntent,
4120
+ apps: appIntent.apps.filter((app) => {
4121
+ if (payload.app && app.appId !== payload.app.appId) {
4122
+ return false;
4123
+ }
4124
+ if (payload.app?.instanceId) {
4125
+ return app.instanceId === payload.app.instanceId;
4126
+ }
4127
+ if (payload.newInstance === true) {
4128
+ return !app.instanceId;
4129
+ }
4130
+ if (payload.newInstance === false) {
4131
+ return !!app.instanceId;
4132
+ }
4133
+ return true;
4134
+ })
4135
+ }))
4136
+ .filter((appIntent) => appIntent.apps.length);
4137
+ const allAvailableHandlers = eligibleAppIntents.flatMap((intent) => intent.apps);
4138
+ if (!allAvailableHandlers.length) {
4139
+ if (payload.app?.instanceId) {
4140
+ return this.raiseIntentForContext({ payload: { ...payload, newInstance: undefined }, meta });
4141
+ }
4142
+ const error = payload.newInstance === false ? "TargetInstanceUnavailable" : "NoAppsFound";
4143
+ if (payload.app) {
4144
+ return this.getUnavailableAppTargetError(payload.app, error);
4145
+ }
4146
+ return { error };
3545
4147
  }
3546
- const allAvailableHandlers = appIntents.map((intent) => intent.apps).flat();
3547
- if (allAvailableHandlers.length > 1) {
4148
+ if (eligibleAppIntents.length > 1 || allAvailableHandlers.length > 1) {
3548
4149
  this.logger?.info(`Multiple apps found for context type '${payload.context.type}'. Requesting user to select app using the Intent Resolver UI. Apps: ${JSON.stringify(allAvailableHandlers)}`);
3549
- return { appIntents };
4150
+ return { appIntents: eligibleAppIntents };
3550
4151
  }
3551
- const updatedPayload = { ...payload, app: allAvailableHandlers[0] };
3552
- this.logger?.info(`Only one app found to handle context type '${payload.context.type}'. Proceeding to raise intent to app: '${updatedPayload.app}'`);
3553
- return this.handleRaiseIntentForContextRequest({ type, meta, payload: updatedPayload });
4152
+ const updatedPayload = {
4153
+ ...payload,
4154
+ app: allAvailableHandlers[0],
4155
+ newInstance: payload.app?.instanceId ? undefined : payload.newInstance
4156
+ };
4157
+ this.logger?.info(`Only one app found to handle context type '${payload.context.type}'. Proceeding to raise intent to app: '${JSON.stringify(updatedPayload.app)}'`);
4158
+ return this.raiseIntentForContext({ payload: updatedPayload, meta });
3554
4159
  }
3555
4160
  async handleRaiseIntentRequest({ payload, meta, type }) {
3556
- if (this.isIntentResolverEnabled && !payload.app) {
4161
+ if (payload.app?.instanceId) {
4162
+ const updatedPayload = { ...payload, newInstance: undefined };
4163
+ return this.raiseIntent({ payload: updatedPayload, meta, type });
4164
+ }
4165
+ if (this.isIntentResolverEnabled) {
3557
4166
  return this.handleRaiseIntentRequestWithResolver({ payload, meta, type });
3558
4167
  }
3559
- const intentResolution = await window.fdc3?.raiseIntent(payload.intent, payload.context, payload.app);
4168
+ return this.raiseIntent({ payload, meta, type });
4169
+ }
4170
+ async raiseIntent({ payload, meta }) {
4171
+ const newInstance = payload.newInstance ?? undefined;
4172
+ const metadata = buildEnrichedMetadata(payload.metadata, this.myAppMetadata);
4173
+ const intentResolution = await window.fdc3?.raiseIntent(payload.intent, payload.context, payload.app, newInstance, metadata);
3560
4174
  if (!intentResolution) {
3561
4175
  return { error: "IntentDeliveryFailed" };
3562
4176
  }
3563
4177
  this.logger?.info(`Saving intent resolution for requestUuid: ${meta.requestUuid}`);
3564
4178
  this.intentResolutionsCollection[meta.requestUuid] = intentResolution;
3565
4179
  const intentResolutionToReturn = { source: intentResolution.source, intent: intentResolution.intent };
3566
- this.processRaiseIntentResultResponseAsync({
3567
- type: "raiseIntentRequest",
3568
- payload,
3569
- meta
3570
- });
3571
4180
  return { intentResolution: intentResolutionToReturn };
3572
4181
  }
3573
4182
  async handleRaiseIntentRequestWithResolver({ payload, meta, type }) {
3574
- const appIntent = await window.fdc3?.findIntent(payload.intent, payload.context);
3575
- if (!appIntent || !appIntent.apps.length) {
4183
+ const appIntent = await window.fdc3?.findIntent(payload.intent, payload.context)
4184
+ .catch((error) => {
4185
+ if (error?.message === ResolveError.NoAppsFound) {
4186
+ return undefined;
4187
+ }
4188
+ throw error;
4189
+ });
4190
+ if (!appIntent?.apps?.length) {
4191
+ if (payload.app) {
4192
+ return this.getUnavailableAppTargetError(payload.app);
4193
+ }
3576
4194
  return { error: "NoAppsFound" };
3577
4195
  }
4196
+ if (payload.app) {
4197
+ return this.handleRaiseIntentRequestWithResolverAndAppTarget({ payload, meta, type }, appIntent);
4198
+ }
4199
+ if (typeof payload.newInstance === "boolean") {
4200
+ return this.handleRaiseIntentRequestWithResolverAndNewInstance({ payload, meta, type }, appIntent);
4201
+ }
3578
4202
  if (appIntent.apps.length > 1) {
3579
4203
  this.logger?.info(`Multiple apps found for intent '${payload.intent}'. Requesting user to select app using the Intent Resolver UI. Apps: ${JSON.stringify(appIntent.apps)}`);
3580
4204
  return { appIntent };
3581
4205
  }
3582
4206
  const updatedPayload = { ...payload, app: appIntent.apps[0] };
3583
- this.logger?.info(`Only one app found to handle intent. Proceeding to raise intent to app: '${updatedPayload.app}'`);
3584
- return this.handleRaiseIntentRequest({ type, meta, payload: updatedPayload });
4207
+ this.logger?.info(`Only one app found to handle intent. Proceeding to raise intent to app: '${JSON.stringify(updatedPayload.app)}'`);
4208
+ return this.raiseIntent({ type, meta, payload: updatedPayload });
3585
4209
  }
3586
- async handleRaiseIntentResultResponse({ payload, meta }) {
3587
- this.logger?.info(`handleRaiseIntentResultResponse called with payload: ${JSON.stringify(payload)} and meta: ${JSON.stringify(meta)}`);
3588
- const intentResolution = await this.intentResolutionsCollection[meta.requestUuid];
4210
+ async handleRaiseIntentRequestWithResolverAndAppTarget({ payload, type, meta }, appIntent) {
4211
+ if (!payload.app) {
4212
+ return { error: "TargetAppUnavailable" };
4213
+ }
4214
+ const targetApps = appIntent.apps.filter((app) => app.appId === payload.app?.appId);
4215
+ if (!targetApps.length) {
4216
+ return this.getUnavailableAppTargetError(payload.app);
4217
+ }
4218
+ if (typeof payload.newInstance !== "boolean") {
4219
+ return this.raiseIntent({ type, meta, payload });
4220
+ }
4221
+ const instanceHandlers = targetApps.filter((app) => app.instanceId);
4222
+ const appHandlers = targetApps.filter((app) => !app.instanceId);
4223
+ if (payload.newInstance === true) {
4224
+ if (!appHandlers.length) {
4225
+ return { error: "TargetAppUnavailable" };
4226
+ }
4227
+ return this.raiseIntent({ type, meta, payload: { ...payload, app: payload.app } });
4228
+ }
4229
+ if (payload.newInstance === false && !instanceHandlers.length) {
4230
+ return { error: "TargetInstanceUnavailable" };
4231
+ }
4232
+ if (instanceHandlers.length === 1) {
4233
+ const updatedPayload = {
4234
+ ...payload,
4235
+ app: instanceHandlers[0],
4236
+ newInstance: false
4237
+ };
4238
+ this.logger?.info(`Only one running instance found for target app '${payload.app?.appId}'. Proceeding to raise intent to app: '${JSON.stringify(updatedPayload.app)}'`);
4239
+ return this.raiseIntent({ type, meta, payload: updatedPayload });
4240
+ }
4241
+ this.logger?.info(`Multiple running instances found for target app '${payload.app?.appId}'. Requesting user to select app using the Intent Resolver UI. Apps: ${JSON.stringify(instanceHandlers)}`);
4242
+ return { appIntent: { intent: appIntent.intent, apps: instanceHandlers } };
4243
+ }
4244
+ async getUnavailableAppTargetError(app, knownAppError = "NoAppsFound") {
4245
+ const appMetadata = await window.fdc3?.getAppMetadata?.(app);
4246
+ return { error: appMetadata ? knownAppError : "TargetAppUnavailable" };
4247
+ }
4248
+ async handleRaiseIntentRequestWithResolverAndNewInstance({ payload, type, meta }, appIntent) {
4249
+ const { newInstance } = payload;
4250
+ const eligibleApps = appIntent.apps.filter((app) => newInstance ? !app.instanceId : !!app.instanceId);
4251
+ if (!eligibleApps.length) {
4252
+ return { error: "TargetInstanceUnavailable" };
4253
+ }
4254
+ if (eligibleApps.length === 1) {
4255
+ const updatedPayload = { ...payload, app: eligibleApps[0] };
4256
+ this.logger?.info(`Only one eligible app found to handle intent. Proceeding to raise intent to app: '${JSON.stringify(updatedPayload.app)}'`);
4257
+ return this.raiseIntent({ type, meta, payload: updatedPayload });
4258
+ }
4259
+ this.logger?.info(`Multiple eligible apps found for intent '${payload.intent}'. Requesting user to select app using the Intent Resolver UI. Apps: ${JSON.stringify(eligibleApps)}`);
4260
+ return { appIntent: { intent: appIntent.intent, apps: eligibleApps } };
4261
+ }
4262
+ async handleRaiseIntentResultRequest({ payload, meta }) {
4263
+ this.logger?.info(`handleRaiseIntentResultRequest called with payload: ${JSON.stringify(payload)} and meta: ${JSON.stringify(meta)}`);
4264
+ const intentResolution = this.intentResolutionsCollection[meta.requestUuid];
3589
4265
  if (!intentResolution) {
3590
4266
  this.logger?.info(`Did not find intent resolution for requestUuid: ${meta.requestUuid}`);
3591
4267
  return { error: "IntentDeliveryFailed" };
3592
4268
  }
3593
4269
  this.logger?.info(`Found intent resolution for requestUuid: ${meta.requestUuid}. Retrieving result...`);
3594
4270
  const result = await intentResolution.getResult();
3595
- this.logger?.info(`Received intent result: ${JSON.stringify(result)}`);
4271
+ const resultMetadata = await intentResolution.getResultMetadata();
4272
+ const responseMetadata = resultMetadata;
4273
+ this.logger?.info(`Received intent result: ${JSON.stringify(result)} with metadata: ${JSON.stringify(resultMetadata)}`);
3596
4274
  if (!result) {
3597
4275
  const intentStr = payload.intent ? "intent '" + payload.intent + "'" : "";
3598
4276
  const contextStr = payload.context ? "context type '" + payload.context.type + "'" : "";
3599
4277
  this.logger?.info(`Intent result is void for ${intentStr}, ${contextStr} and requestUuid: ${meta.requestUuid}`);
3600
- return { intentResult: undefined };
4278
+ return { intentResult: undefined, resultMetadata: responseMetadata };
3601
4279
  }
3602
- const intentResult = this.extractRaiseIntentResult(result);
3603
- this.logger?.info(`Extracted intent result: ${JSON.stringify(intentResult)}`);
4280
+ const intentResult = this.extractRaiseIntentResult(result, responseMetadata);
3604
4281
  return intentResult;
3605
4282
  }
3606
- extractRaiseIntentResult(receivedResult) {
4283
+ extractRaiseIntentResult(receivedResult, resultMetadata) {
3607
4284
  if (!receivedResult) {
3608
- return { intentResult: undefined };
4285
+ return { intentResult: undefined, resultMetadata };
3609
4286
  }
3610
4287
  const isChannel = checkIfFDC3Channel(receivedResult);
3611
4288
  if (isChannel) {
3612
4289
  this.checkSetPrivateChanel(receivedResult);
3613
- return { intentResult: { channel: JSON.parse(JSON.stringify(receivedResult)) } };
4290
+ return { intentResult: { channel: JSON.parse(JSON.stringify(receivedResult)) }, resultMetadata };
3614
4291
  }
3615
4292
  const isContext = checkIfFDC3Context(receivedResult);
3616
4293
  if (isContext) {
3617
- return { intentResult: { context: receivedResult } };
4294
+ return { intentResult: { context: receivedResult }, resultMetadata };
3618
4295
  }
3619
4296
  if (receivedResult.error) {
3620
4297
  return { error: receivedResult.error };
3621
4298
  }
4299
+ const isContextWithMetadata = checkIfFDC3ContextWithMetadata(receivedResult);
4300
+ if (isContextWithMetadata) {
4301
+ return { intentResult: { context: receivedResult.context }, resultMetadata: receivedResult.metadata };
4302
+ }
3622
4303
  return { error: "IntentDeliveryFailed" };
3623
4304
  }
3624
4305
  checkSetPrivateChanel(channel) {
@@ -3628,8 +4309,10 @@ class IntentsController {
3628
4309
  }
3629
4310
  this.addPrivateChannel(channel);
3630
4311
  }
3631
- async processRaiseIntentResultResponseAsync({ payload, meta }) {
3632
- this.logger?.warn("Processing raise intent result response asynchronously with payload: " + JSON.stringify(payload));
4312
+ async processRaiseIntentResultResponse({ payload, meta }) {
4313
+ if (!this.intentResolutionsCollection[meta.requestUuid]) {
4314
+ return;
4315
+ }
3633
4316
  const syntheticRequest = {
3634
4317
  type: "raiseIntentResultRequest",
3635
4318
  meta: {
@@ -3665,6 +4348,7 @@ class IoC {
3665
4348
  _intentsController;
3666
4349
  _applicationsController;
3667
4350
  _uiConfig;
4351
+ _myAppMetadata;
3668
4352
  resetState() {
3669
4353
  this._bridgeController = undefined;
3670
4354
  this._ioController = undefined;
@@ -3673,6 +4357,13 @@ class IoC {
3673
4357
  this._intentsController = undefined;
3674
4358
  this._applicationsController = undefined;
3675
4359
  this._uiConfig = undefined;
4360
+ this._myAppMetadata = undefined;
4361
+ }
4362
+ get myAppMetadata() {
4363
+ return this._myAppMetadata;
4364
+ }
4365
+ set myAppMetadata(value) {
4366
+ this._myAppMetadata = value;
3676
4367
  }
3677
4368
  get uiConfig() {
3678
4369
  return this._uiConfig;
@@ -3703,25 +4394,25 @@ class IoC {
3703
4394
  }
3704
4395
  get channelsController() {
3705
4396
  if (!this._channelsController) {
3706
- this._channelsController = new ChannelsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.ioController.getLogger("channels.controller"));
4397
+ this._channelsController = new ChannelsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.myAppMetadata, this.ioController.getLogger("channels.controller"));
3707
4398
  }
3708
4399
  return this._channelsController;
3709
4400
  }
3710
4401
  get intentsController() {
3711
4402
  if (!this._intentsController) {
3712
- this._intentsController = new IntentsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.channelsController.addPrivateChannel.bind(this.channelsController), this.uiConfig.isIntentResolverEnabled, this.ioController.getLogger("intents.controller"));
4403
+ this._intentsController = new IntentsController(this.bridgeController.sendMessage.bind(this.bridgeController), this.channelsController.addPrivateChannel.bind(this.channelsController), this.uiConfig.isIntentResolverEnabled, this.myAppMetadata, this.ioController.getLogger("intents.controller"));
3713
4404
  }
3714
4405
  return this._intentsController;
3715
4406
  }
3716
4407
  get applicationsController() {
3717
4408
  if (!this._applicationsController) {
3718
- this._applicationsController = new ApplicationsController(this.ioController.getLogger("applications.controller"));
4409
+ this._applicationsController = new ApplicationsController(this.myAppMetadata, this.ioController.getLogger("applications.controller"));
3719
4410
  }
3720
4411
  return this._applicationsController;
3721
4412
  }
3722
4413
  }
3723
4414
 
3724
- var version = "1.6.0";
4415
+ var version = "2.0.0";
3725
4416
 
3726
4417
  window.fdc3WebBridgeInfo = {
3727
4418
  version