@interopio/browser 4.2.4 → 4.3.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.
@@ -8,56 +8,56 @@
8
8
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
9
9
  }
10
10
 
11
- var isMergeableObject = function isMergeableObject(value) {
12
- return isNonNullObject(value)
13
- && !isSpecial(value)
11
+ var isMergeableObject$1 = function isMergeableObject(value) {
12
+ return isNonNullObject$1(value)
13
+ && !isSpecial$1(value)
14
14
  };
15
15
 
16
- function isNonNullObject(value) {
16
+ function isNonNullObject$1(value) {
17
17
  return !!value && typeof value === 'object'
18
18
  }
19
19
 
20
- function isSpecial(value) {
20
+ function isSpecial$1(value) {
21
21
  var stringValue = Object.prototype.toString.call(value);
22
22
 
23
23
  return stringValue === '[object RegExp]'
24
24
  || stringValue === '[object Date]'
25
- || isReactElement(value)
25
+ || isReactElement$1(value)
26
26
  }
27
27
 
28
28
  // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
29
- var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
30
- var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
29
+ var canUseSymbol$1 = typeof Symbol === 'function' && Symbol.for;
30
+ var REACT_ELEMENT_TYPE$1 = canUseSymbol$1 ? Symbol.for('react.element') : 0xeac7;
31
31
 
32
- function isReactElement(value) {
33
- return value.$$typeof === REACT_ELEMENT_TYPE
32
+ function isReactElement$1(value) {
33
+ return value.$$typeof === REACT_ELEMENT_TYPE$1
34
34
  }
35
35
 
36
- function emptyTarget(val) {
36
+ function emptyTarget$1(val) {
37
37
  return Array.isArray(val) ? [] : {}
38
38
  }
39
39
 
40
- function cloneUnlessOtherwiseSpecified(value, options) {
40
+ function cloneUnlessOtherwiseSpecified$1(value, options) {
41
41
  return (options.clone !== false && options.isMergeableObject(value))
42
- ? deepmerge(emptyTarget(value), value, options)
42
+ ? deepmerge$1(emptyTarget$1(value), value, options)
43
43
  : value
44
44
  }
45
45
 
46
- function defaultArrayMerge(target, source, options) {
46
+ function defaultArrayMerge$1(target, source, options) {
47
47
  return target.concat(source).map(function(element) {
48
- return cloneUnlessOtherwiseSpecified(element, options)
48
+ return cloneUnlessOtherwiseSpecified$1(element, options)
49
49
  })
50
50
  }
51
51
 
52
- function getMergeFunction(key, options) {
52
+ function getMergeFunction$1(key, options) {
53
53
  if (!options.customMerge) {
54
- return deepmerge
54
+ return deepmerge$1
55
55
  }
56
56
  var customMerge = options.customMerge(key);
57
- return typeof customMerge === 'function' ? customMerge : deepmerge
57
+ return typeof customMerge === 'function' ? customMerge : deepmerge$1
58
58
  }
59
59
 
60
- function getEnumerableOwnPropertySymbols(target) {
60
+ function getEnumerableOwnPropertySymbols$1(target) {
61
61
  return Object.getOwnPropertySymbols
62
62
  ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
63
63
  return Object.propertyIsEnumerable.call(target, symbol)
@@ -65,11 +65,11 @@
65
65
  : []
66
66
  }
67
67
 
68
- function getKeys(target) {
69
- return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
68
+ function getKeys$1(target) {
69
+ return Object.keys(target).concat(getEnumerableOwnPropertySymbols$1(target))
70
70
  }
71
71
 
72
- function propertyIsOnObject(object, property) {
72
+ function propertyIsOnObject$1(object, property) {
73
73
  try {
74
74
  return property in object
75
75
  } catch(_) {
@@ -78,69 +78,69 @@
78
78
  }
79
79
 
80
80
  // Protects from prototype poisoning and unexpected merging up the prototype chain.
81
- function propertyIsUnsafe(target, key) {
82
- return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
81
+ function propertyIsUnsafe$1(target, key) {
82
+ return propertyIsOnObject$1(target, key) // Properties are safe to merge if they don't exist in the target yet,
83
83
  && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
84
84
  && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
85
85
  }
86
86
 
87
- function mergeObject(target, source, options) {
87
+ function mergeObject$1(target, source, options) {
88
88
  var destination = {};
89
89
  if (options.isMergeableObject(target)) {
90
- getKeys(target).forEach(function(key) {
91
- destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
90
+ getKeys$1(target).forEach(function(key) {
91
+ destination[key] = cloneUnlessOtherwiseSpecified$1(target[key], options);
92
92
  });
93
93
  }
94
- getKeys(source).forEach(function(key) {
95
- if (propertyIsUnsafe(target, key)) {
94
+ getKeys$1(source).forEach(function(key) {
95
+ if (propertyIsUnsafe$1(target, key)) {
96
96
  return
97
97
  }
98
98
 
99
- if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
100
- destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
99
+ if (propertyIsOnObject$1(target, key) && options.isMergeableObject(source[key])) {
100
+ destination[key] = getMergeFunction$1(key, options)(target[key], source[key], options);
101
101
  } else {
102
- destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
102
+ destination[key] = cloneUnlessOtherwiseSpecified$1(source[key], options);
103
103
  }
104
104
  });
105
105
  return destination
106
106
  }
107
107
 
108
- function deepmerge(target, source, options) {
108
+ function deepmerge$1(target, source, options) {
109
109
  options = options || {};
110
- options.arrayMerge = options.arrayMerge || defaultArrayMerge;
111
- options.isMergeableObject = options.isMergeableObject || isMergeableObject;
110
+ options.arrayMerge = options.arrayMerge || defaultArrayMerge$1;
111
+ options.isMergeableObject = options.isMergeableObject || isMergeableObject$1;
112
112
  // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
113
113
  // implementations can use it. The caller may not replace it.
114
- options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
114
+ options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified$1;
115
115
 
116
116
  var sourceIsArray = Array.isArray(source);
117
117
  var targetIsArray = Array.isArray(target);
118
118
  var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
119
119
 
120
120
  if (!sourceAndTargetTypesMatch) {
121
- return cloneUnlessOtherwiseSpecified(source, options)
121
+ return cloneUnlessOtherwiseSpecified$1(source, options)
122
122
  } else if (sourceIsArray) {
123
123
  return options.arrayMerge(target, source, options)
124
124
  } else {
125
- return mergeObject(target, source, options)
125
+ return mergeObject$1(target, source, options)
126
126
  }
127
127
  }
128
128
 
129
- deepmerge.all = function deepmergeAll(array, options) {
129
+ deepmerge$1.all = function deepmergeAll(array, options) {
130
130
  if (!Array.isArray(array)) {
131
131
  throw new Error('first argument should be an array')
132
132
  }
133
133
 
134
134
  return array.reduce(function(prev, next) {
135
- return deepmerge(prev, next, options)
135
+ return deepmerge$1(prev, next, options)
136
136
  }, {})
137
137
  };
138
138
 
139
- var deepmerge_1 = deepmerge;
139
+ var deepmerge_1$1 = deepmerge$1;
140
140
 
141
- var cjs = deepmerge_1;
141
+ var cjs$1 = deepmerge_1$1;
142
142
 
143
- var deepmerge$1 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs);
143
+ var deepmerge$2 = /*@__PURE__*/getDefaultExportFromCjs$1(cjs$1);
144
144
 
145
145
  /**
146
146
  * Wraps values in an `Ok` type.
@@ -1813,6 +1813,15 @@
1813
1813
  const regexDecoder = anyJson$1().andThen((value) => {
1814
1814
  return value instanceof RegExp ? anyJson$1() : fail(`expected a regex, got a ${typeof value}`);
1815
1815
  });
1816
+ const urlDecoder = nonEmptyStringDecoder$3.andThen((url) => {
1817
+ try {
1818
+ new URL(url);
1819
+ return nonEmptyStringDecoder$3;
1820
+ }
1821
+ catch {
1822
+ return fail("Should be a valid URL");
1823
+ }
1824
+ });
1816
1825
 
1817
1826
  const intentDefinitionDecoder$1 = object$1({
1818
1827
  name: nonEmptyStringDecoder$3,
@@ -2140,7 +2149,8 @@
2140
2149
  common: {
2141
2150
  nonEmptyStringDecoder: nonEmptyStringDecoder$3,
2142
2151
  nonNegativeNumberDecoder: nonNegativeNumberDecoder$3,
2143
- regexDecoder
2152
+ regexDecoder,
2153
+ urlDecoder
2144
2154
  },
2145
2155
  fdc3: {
2146
2156
  allDefinitionsDecoder,
@@ -2344,7 +2354,8 @@
2344
2354
  title: optional$2(nonEmptyStringDecoder$2),
2345
2355
  version: optional$2(nonEmptyStringDecoder$2),
2346
2356
  icon: optional$2(string$2()),
2347
- caption: optional$2(nonEmptyStringDecoder$2)
2357
+ caption: optional$2(nonEmptyStringDecoder$2),
2358
+ fdc3: optional$2(anyJson$2())
2348
2359
  });
2349
2360
  const baseApplicationDataDecoder = object$2({
2350
2361
  name: nonEmptyStringDecoder$2,
@@ -2353,7 +2364,8 @@
2353
2364
  title: optional$2(nonEmptyStringDecoder$2),
2354
2365
  version: optional$2(nonEmptyStringDecoder$2),
2355
2366
  icon: optional$2(string$2()),
2356
- caption: optional$2(nonEmptyStringDecoder$2)
2367
+ caption: optional$2(nonEmptyStringDecoder$2),
2368
+ fdc3: optional$2(anyJson$2())
2357
2369
  });
2358
2370
  const appDirectoryStateChangeDecoder = object$2({
2359
2371
  appsAdded: array$2(baseApplicationDataDecoder),
@@ -2403,7 +2415,8 @@
2403
2415
  allowExtract: optional$2(boolean$2()),
2404
2416
  allowReorder: optional$2(boolean$2()),
2405
2417
  showCloseButton: optional$2(boolean$2()),
2406
- isMaximized: optional$2(boolean$2())
2418
+ isMaximized: optional$2(boolean$2()),
2419
+ instanceId: optional$2(nonEmptyStringDecoder$2)
2407
2420
  })
2408
2421
  });
2409
2422
  const groupLayoutItemDecoder = object$2({
@@ -3027,6 +3040,7 @@
3027
3040
  app: nonEmptyStringDecoder$2,
3028
3041
  }),
3029
3042
  validNonExistentApps: optional$2(array$2(nonEmptyStringDecoder$2)),
3043
+ isAppValidationEnabled: optional$2(boolean$2()),
3030
3044
  });
3031
3045
  const clientErrorDataDecoder = object$2({
3032
3046
  message: nonEmptyStringDecoder$2
@@ -3263,9 +3277,9 @@
3263
3277
  isPlatformInternal,
3264
3278
  logger: config.systemLogger?.level ?? "info",
3265
3279
  customLogger: config.systemLogger?.customLogger,
3266
- widget: deepmerge$1(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}),
3267
- modals: deepmerge$1(defaultModalsConfig, decodedModalsConfigResult.result ?? {}),
3268
- intentResolver: deepmerge$1(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}),
3280
+ widget: deepmerge$2(defaultWidgetConfig, decodedWidgetConfigResult.result ?? {}),
3281
+ modals: deepmerge$2(defaultModalsConfig, decodedModalsConfigResult.result ?? {}),
3282
+ intentResolver: deepmerge$2(defaultIntentResolverConfig, decodedIntentResolverConfigResult.result ?? {}),
3269
3283
  };
3270
3284
  return combined;
3271
3285
  };
@@ -4136,7 +4150,7 @@
4136
4150
  return ioError.raiseError(error);
4137
4151
  }
4138
4152
  }
4139
- async createNotificationsSteam() {
4153
+ async createThemesSubscription() {
4140
4154
  const streamExists = this.coreGlue.interop.methods().some((method) => method.name === GlueCorePlusThemesStream);
4141
4155
  if (!streamExists) {
4142
4156
  return ioError.raiseError("Cannot subscribe to theme changes, because the underlying interop stream does not exist. Most likely this is the case when this client is not connected to Core Plus.");
@@ -4588,6 +4602,7 @@
4588
4602
  userProperties: this.data.userProperties,
4589
4603
  instances: this.instances,
4590
4604
  start: this.start.bind(this),
4605
+ getConfiguration: this.getConfiguration.bind(this),
4591
4606
  onInstanceStarted: this.onInstanceStarted.bind(this),
4592
4607
  onInstanceStopped: this.onInstanceStopped.bind(this)
4593
4608
  };
@@ -4619,6 +4634,30 @@
4619
4634
  const verifiedOptions = runDecoderWithIOError(startApplicationOptionsDecoder, options);
4620
4635
  return this.controller.startApplication(this.data.name, verifiedContext, verifiedOptions);
4621
4636
  }
4637
+ async getConfiguration() {
4638
+ const { details, intents, hidden, ...customProperties } = this.data.userProperties;
4639
+ const definition = {
4640
+ name: this.data.name,
4641
+ type: this.data.type,
4642
+ details,
4643
+ customProperties
4644
+ };
4645
+ const optionalProperties = {
4646
+ title: this.data.title,
4647
+ version: this.data.version,
4648
+ icon: this.data.icon,
4649
+ caption: this.data.caption,
4650
+ intents,
4651
+ hidden,
4652
+ fdc3: this.data.fdc3
4653
+ };
4654
+ for (const [key, value] of Object.entries(optionalProperties)) {
4655
+ if (value !== undefined) {
4656
+ definition[key] = value;
4657
+ }
4658
+ }
4659
+ return definition;
4660
+ }
4622
4661
  }
4623
4662
 
4624
4663
  const operations$8 = {
@@ -6862,18 +6901,18 @@
6862
6901
  bridge;
6863
6902
  registry = CallbackRegistryFactory$1();
6864
6903
  themesSubscription;
6865
- activeThemeSubs = 0;
6866
6904
  async start(coreGlue, ioc) {
6867
6905
  this.logger = coreGlue.logger.subLogger("themes.controller.web");
6868
6906
  this.logger.trace("starting the web themes controller");
6869
6907
  this.bridge = ioc.bridge;
6908
+ await this.setupSubscription();
6909
+ this.logger.trace("themes subscription is ready");
6870
6910
  const api = this.toApi();
6871
6911
  coreGlue.themes = api;
6872
6912
  this.logger.trace("themes are ready");
6873
6913
  }
6874
6914
  handlePlatformShutdown() {
6875
6915
  this.registry.clear();
6876
- this.activeThemeSubs = 0;
6877
6916
  this.themesSubscription?.close();
6878
6917
  delete this.themesSubscription;
6879
6918
  }
@@ -6900,47 +6939,30 @@
6900
6939
  runDecoderWithIOError(nonEmptyStringDecoder$2, name);
6901
6940
  await this.bridge.send("themes", operations$2.select, { name }, undefined, { includeOperationCheck: true });
6902
6941
  }
6903
- async onChanged(callback) {
6942
+ onChanged(callback) {
6904
6943
  if (typeof callback !== "function") {
6905
6944
  return ioError.raiseError("onChanged requires a callback of type function");
6906
6945
  }
6907
- const subReady = this.themesSubscription ?
6908
- Promise.resolve() :
6909
- this.configureThemeSubscription();
6910
- await subReady;
6911
- ++this.activeThemeSubs;
6912
- const unsubFunc = this.registry.add("on-theme-change", callback);
6913
- return () => this.themeUnsub(unsubFunc);
6946
+ return this.registry.add("on-theme-change", callback);
6914
6947
  }
6915
- async configureThemeSubscription() {
6916
- if (this.themesSubscription) {
6917
- return;
6918
- }
6919
- this.themesSubscription = await this.bridge.createNotificationsSteam();
6920
- this.themesSubscription.onData((data) => {
6921
- const eventData = data.data;
6922
- const validation = simpleThemeResponseDecoder.run(eventData);
6923
- if (!validation.ok) {
6924
- this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`);
6925
- return;
6926
- }
6927
- const themeChanged = validation.result;
6928
- this.registry.execute("on-theme-change", themeChanged.theme);
6929
- });
6930
- this.themesSubscription.onClosed(() => {
6931
- this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received");
6932
- this.registry.clear();
6933
- this.activeThemeSubs = 0;
6934
- delete this.themesSubscription;
6935
- });
6948
+ async setupSubscription() {
6949
+ this.themesSubscription = await this.bridge.createThemesSubscription();
6950
+ this.themesSubscription.onData(this.handleStreamData.bind(this));
6951
+ this.themesSubscription.onClosed(this.handleStreamClosure.bind(this));
6936
6952
  }
6937
- themeUnsub(registryUnsub) {
6938
- registryUnsub();
6939
- --this.activeThemeSubs;
6940
- if (this.activeThemeSubs) {
6953
+ handleStreamData(data) {
6954
+ const eventData = data.data;
6955
+ const validation = simpleThemeResponseDecoder.run(eventData);
6956
+ if (!validation.ok) {
6957
+ this.logger.warn(`Received invalid theme data on the theme event stream: ${JSON.stringify(validation.error)}`);
6941
6958
  return;
6942
6959
  }
6943
- this.themesSubscription?.close();
6960
+ const themeChanged = validation.result;
6961
+ this.registry.execute("on-theme-change", themeChanged.theme);
6962
+ }
6963
+ handleStreamClosure() {
6964
+ this.logger.warn("The Themes interop stream was closed, no theme changes notifications will be received");
6965
+ this.registry.clear();
6944
6966
  delete this.themesSubscription;
6945
6967
  }
6946
6968
  }
@@ -7050,6 +7072,7 @@
7050
7072
  validNonExistentApps;
7051
7073
  signaledSubscription = false;
7052
7074
  interopId;
7075
+ isAppValidationEnabled;
7053
7076
  handlePlatformShutdown() {
7054
7077
  this.registry.clear();
7055
7078
  }
@@ -7065,6 +7088,7 @@
7065
7088
  const prefsHelloSuccess = await this.bridge.send("prefs", operations$1.prefsHello, undefined, undefined, { includeOperationCheck: true });
7066
7089
  this.platformAppName = prefsHelloSuccess.platform.app;
7067
7090
  this.validNonExistentApps = prefsHelloSuccess.validNonExistentApps ?? [];
7091
+ this.isAppValidationEnabled = prefsHelloSuccess.isAppValidationEnabled ?? true;
7068
7092
  }
7069
7093
  catch (error) {
7070
7094
  this.logger.warn("The platform of this client is outdated and does not support Prefs API.");
@@ -7149,7 +7173,9 @@
7149
7173
  subscribeFor(app, callback) {
7150
7174
  const verifiedApp = runDecoderWithIOError(nonEmptyStringDecoder$2, app);
7151
7175
  const applications = this.appManagerController.getApplications();
7152
- const isValidApp = verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp);
7176
+ const isValidApp = this.isAppValidationEnabled
7177
+ ? verifiedApp === this.platformAppName || applications.some((application) => application.name === verifiedApp) || this.validNonExistentApps.includes(verifiedApp)
7178
+ : true;
7153
7179
  if (!isValidApp) {
7154
7180
  return ioError.raiseError(`The provided app name "${app}" is not valid.`);
7155
7181
  }
@@ -7221,6 +7247,7 @@
7221
7247
  widgetResources;
7222
7248
  modalsResources;
7223
7249
  intentResolverResources;
7250
+ rootElements = [];
7224
7251
  modalsUiApi;
7225
7252
  isDialogOpen = false;
7226
7253
  intentResolverUiApi;
@@ -7258,6 +7285,7 @@
7258
7285
  const initializeWidgetPromise = this.widgetResources ? this.initializeWidget(io, this.widgetResources) : Promise.resolve();
7259
7286
  const initializeModalsPromise = this.modalsResources ? this.initializeModalsUi(io, this.modalsResources) : Promise.resolve();
7260
7287
  const initializeIntentResolverPromise = this.intentResolverResources ? this.initializeIntentResolverUI(io, this.intentResolverResources) : Promise.resolve();
7288
+ this.subscribeForThemeChanges(io);
7261
7289
  await Promise.all([
7262
7290
  this.config.widget.awaitFactory ? initializeWidgetPromise : Promise.resolve(),
7263
7291
  this.config.modals.awaitFactory ? initializeModalsPromise : Promise.resolve(),
@@ -7462,9 +7490,9 @@
7462
7490
  async initializeWidget(io, resources) {
7463
7491
  this.logger.trace("Initializing IOBrowserWidget.");
7464
7492
  const { rootElement } = this.appendWidgetResources(resources);
7465
- this.subscribeForThemeChanges(io, rootElement);
7493
+ this.rootElements.push(rootElement);
7466
7494
  const config = {
7467
- ...deepmerge$1(resources.config, this.config.widget),
7495
+ ...deepmerge$2(resources.config, this.config.widget),
7468
7496
  rootElement
7469
7497
  };
7470
7498
  return PromiseWrap(async () => {
@@ -7477,7 +7505,7 @@
7477
7505
  async initializeModalsUi(io, resources) {
7478
7506
  this.logger.trace("Initializing IOBrowserModalsUI.");
7479
7507
  const { rootElement } = this.appendModalsResources(resources);
7480
- this.subscribeForThemeChanges(io, rootElement);
7508
+ this.rootElements.push(rootElement);
7481
7509
  const config = {
7482
7510
  ...this.config.modals,
7483
7511
  rootElement
@@ -7492,7 +7520,7 @@
7492
7520
  async initializeIntentResolverUI(io, resources) {
7493
7521
  this.logger.trace("Initializing IOBrowserIntentResolverUI.");
7494
7522
  const { rootElement } = this.appendIntentResolverResources(resources);
7495
- this.subscribeForThemeChanges(io, rootElement);
7523
+ this.rootElements.push(rootElement);
7496
7524
  const config = {
7497
7525
  ...this.config.intentResolver,
7498
7526
  rootElement
@@ -7573,22 +7601,25 @@
7573
7601
  }
7574
7602
  this.intentResolverResources = resources;
7575
7603
  }
7576
- subscribeForThemeChanges(io, element) {
7604
+ subscribeForThemeChanges(io) {
7577
7605
  const themesApi = io.themes;
7578
7606
  if (!themesApi) {
7579
7607
  return;
7580
7608
  }
7581
7609
  const changeTheme = async (theme) => {
7582
- if (element.classList.contains(theme.name)) {
7583
- return;
7584
- }
7585
- const allThemes = await themesApi.list();
7586
- element.classList.remove(...allThemes.map(({ name }) => name));
7587
- element.classList.add(theme.name);
7610
+ await Promise.all(this.rootElements.map((element) => this.applyThemeToElement(element, themesApi, theme)));
7588
7611
  };
7589
7612
  themesApi.onChanged(changeTheme);
7590
7613
  themesApi.getCurrent().then(changeTheme);
7591
7614
  }
7615
+ async applyThemeToElement(element, themesApi, theme) {
7616
+ if (element.classList.contains(theme.name)) {
7617
+ return;
7618
+ }
7619
+ const allThemes = await themesApi.list();
7620
+ element.classList.remove(...allThemes.map(({ name }) => name));
7621
+ element.classList.add(theme.name);
7622
+ }
7592
7623
  }
7593
7624
 
7594
7625
  class IoC {
@@ -7751,7 +7782,7 @@
7751
7782
  }
7752
7783
  }
7753
7784
 
7754
- var version$1 = "4.2.4";
7785
+ var version$1 = "4.3.0";
7755
7786
 
7756
7787
  const setupGlobalSystem = (io, bridge) => {
7757
7788
  return {
@@ -8846,6 +8877,9 @@
8846
8877
  return Utils._isNode;
8847
8878
  }
8848
8879
  static _isNode;
8880
+ static getMethodName(method) {
8881
+ return typeof method === "string" ? method : method?.name;
8882
+ }
8849
8883
  }
8850
8884
 
8851
8885
  class PromiseWrapper {
@@ -10805,186 +10839,2201 @@
10805
10839
  }
10806
10840
  };
10807
10841
 
10808
- var version = "6.8.1";
10842
+ var version = "6.10.0";
10809
10843
 
10810
- function prepareConfig (configuration, ext, glue42gd) {
10811
- let nodeStartingContext;
10812
- if (Utils.isNode()) {
10813
- const startingContextString = process.env._GD_STARTING_CONTEXT_;
10814
- if (startingContextString) {
10815
- try {
10816
- nodeStartingContext = JSON.parse(startingContextString);
10817
- }
10818
- catch {
10819
- }
10820
- }
10821
- }
10822
- function getConnection() {
10823
- const gwConfig = configuration.gateway;
10824
- const protocolVersion = gwConfig?.protocolVersion ?? 3;
10825
- const reconnectInterval = gwConfig?.reconnectInterval;
10826
- const reconnectAttempts = gwConfig?.reconnectAttempts;
10827
- const defaultWs = "ws://localhost:8385";
10828
- let ws = gwConfig?.ws;
10829
- const sharedWorker = gwConfig?.sharedWorker;
10830
- const inproc = gwConfig?.inproc;
10831
- const webPlatform = gwConfig?.webPlatform ?? undefined;
10832
- if (glue42gd) {
10833
- ws = glue42gd.gwURL;
10834
- }
10835
- if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) {
10836
- ws = nodeStartingContext.gwURL;
10837
- }
10838
- if (!ws && !sharedWorker && !inproc) {
10839
- ws = defaultWs;
10840
- }
10841
- let instanceId;
10842
- let windowId;
10843
- let pid;
10844
- let environment;
10845
- let region;
10846
- const appName = getApplication();
10847
- let uniqueAppName = appName;
10848
- if (typeof glue42gd !== "undefined") {
10849
- windowId = glue42gd.windowId;
10850
- pid = glue42gd.pid;
10851
- if (glue42gd.env) {
10852
- environment = glue42gd.env.env;
10853
- region = glue42gd.env.region;
10854
- }
10855
- uniqueAppName = glue42gd.application ?? "glue-app";
10856
- instanceId = glue42gd.appInstanceId;
10857
- }
10858
- else if (Utils.isNode()) {
10859
- pid = process.pid;
10860
- if (nodeStartingContext) {
10861
- environment = nodeStartingContext.env;
10862
- region = nodeStartingContext.region;
10863
- instanceId = nodeStartingContext.instanceId;
10864
- }
10865
- }
10866
- else if (typeof window?.glue42electron !== "undefined") {
10867
- windowId = window?.glue42electron.instanceId;
10868
- pid = window?.glue42electron.pid;
10869
- environment = window?.glue42electron.env;
10870
- region = window?.glue42electron.region;
10871
- uniqueAppName = window?.glue42electron.application ?? "glue-app";
10872
- instanceId = window?.glue42electron.instanceId;
10873
- }
10874
- else ;
10875
- const replaySpecs = configuration.gateway?.replaySpecs ?? [];
10876
- replaySpecs.push(ContextMessageReplaySpec);
10877
- let identity = {
10878
- application: uniqueAppName,
10879
- applicationName: appName,
10880
- windowId,
10881
- instance: instanceId,
10882
- process: pid,
10883
- region,
10884
- environment,
10885
- api: ext.version || version
10886
- };
10887
- if (configuration.identity) {
10888
- identity = Object.assign(identity, configuration.identity);
10889
- }
10890
- return {
10891
- identity,
10892
- reconnectInterval,
10893
- ws,
10894
- sharedWorker,
10895
- webPlatform,
10896
- inproc,
10897
- protocolVersion,
10898
- reconnectAttempts,
10899
- replaySpecs,
10900
- };
10901
- }
10902
- function getContexts() {
10903
- const defaultConfig = {
10904
- reAnnounceKnownContexts: true,
10905
- subscribeOnUpdate: true,
10906
- subscribeOnGet: true,
10907
- onlyReAnnounceSubscribedContexts: true
10908
- };
10909
- if (typeof configuration.contexts === "undefined") {
10910
- return defaultConfig;
10911
- }
10912
- if (typeof configuration.contexts === "boolean" && configuration.contexts) {
10913
- return defaultConfig;
10914
- }
10915
- if (typeof configuration.contexts === "object") {
10916
- return { ...defaultConfig, ...configuration.contexts };
10917
- }
10844
+ /*!
10845
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
10846
+ *
10847
+ * Copyright (c) 2014-2017, Jon Schlinkert.
10848
+ * Released under the MIT License.
10849
+ */
10850
+ function isObject$1(o) {
10851
+ return Object.prototype.toString.call(o) === '[object Object]';
10852
+ }
10853
+ function isPlainObject$2(o) {
10854
+ let ctor;
10855
+ let prot;
10856
+ if (isObject$1(o) === false)
10857
+ return false;
10858
+ ctor = o.constructor;
10859
+ if (ctor === undefined)
10860
+ return true;
10861
+ prot = ctor.prototype;
10862
+ if (isObject$1(prot) === false)
10863
+ return false;
10864
+ if (prot.hasOwnProperty('isPrototypeOf') === false) {
10918
10865
  return false;
10919
10866
  }
10920
- function getApplication() {
10921
- if (configuration.application) {
10922
- return configuration.application;
10923
- }
10924
- if (glue42gd) {
10925
- return glue42gd.applicationName;
10926
- }
10927
- if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") {
10928
- return window.glue42electron.application;
10929
- }
10930
- const uid = nanoid(10);
10931
- if (Utils.isNode()) {
10932
- if (nodeStartingContext) {
10933
- return nodeStartingContext.applicationConfig.name;
10934
- }
10935
- return "NodeJS" + uid;
10936
- }
10937
- if (typeof window !== "undefined" && typeof document !== "undefined") {
10938
- return document.title + ` (${uid})`;
10939
- }
10940
- return uid;
10941
- }
10942
- function getAuth() {
10943
- if (typeof configuration.auth === "string") {
10944
- return {
10945
- token: configuration.auth
10946
- };
10947
- }
10948
- if (configuration.auth) {
10949
- return configuration.auth;
10950
- }
10951
- if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) {
10952
- return {
10953
- gatewayToken: nodeStartingContext.gwToken
10954
- };
10955
- }
10956
- if (configuration.gateway?.webPlatform) {
10957
- return {
10958
- username: "glue42",
10959
- password: ""
10960
- };
10961
- }
10962
- }
10963
- function getLogger() {
10964
- let config = configuration.logger;
10965
- const defaultLevel = "warn";
10966
- if (!config) {
10967
- config = defaultLevel;
10968
- }
10969
- let gdConsoleLevel;
10970
- if (glue42gd) {
10971
- gdConsoleLevel = glue42gd.consoleLogLevel;
10972
- }
10973
- if (typeof config === "string") {
10974
- return { console: gdConsoleLevel ?? config, publish: defaultLevel };
10975
- }
10976
- return {
10977
- console: gdConsoleLevel ?? config.console ?? defaultLevel,
10978
- publish: config.publish ?? defaultLevel
10979
- };
10980
- }
10981
- const connection = getConnection();
10982
- let application = getApplication();
10983
- if (typeof window !== "undefined") {
10984
- const windowAsAny = window;
10985
- const containerApplication = windowAsAny.htmlContainer ?
10986
- `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` :
10987
- windowAsAny?.glue42gd?.application;
10867
+ return true;
10868
+ }
10869
+
10870
+ var isMergeableObject = function isMergeableObject(value) {
10871
+ return isNonNullObject(value)
10872
+ && !isSpecial(value)
10873
+ };
10874
+
10875
+ function isNonNullObject(value) {
10876
+ return !!value && typeof value === 'object'
10877
+ }
10878
+
10879
+ function isSpecial(value) {
10880
+ var stringValue = Object.prototype.toString.call(value);
10881
+
10882
+ return stringValue === '[object RegExp]'
10883
+ || stringValue === '[object Date]'
10884
+ || isReactElement(value)
10885
+ }
10886
+
10887
+ // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
10888
+ var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
10889
+ var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
10890
+
10891
+ function isReactElement(value) {
10892
+ return value.$$typeof === REACT_ELEMENT_TYPE
10893
+ }
10894
+
10895
+ function emptyTarget(val) {
10896
+ return Array.isArray(val) ? [] : {}
10897
+ }
10898
+
10899
+ function cloneUnlessOtherwiseSpecified(value, options) {
10900
+ return (options.clone !== false && options.isMergeableObject(value))
10901
+ ? deepmerge(emptyTarget(value), value, options)
10902
+ : value
10903
+ }
10904
+
10905
+ function defaultArrayMerge(target, source, options) {
10906
+ return target.concat(source).map(function(element) {
10907
+ return cloneUnlessOtherwiseSpecified(element, options)
10908
+ })
10909
+ }
10910
+
10911
+ function getMergeFunction(key, options) {
10912
+ if (!options.customMerge) {
10913
+ return deepmerge
10914
+ }
10915
+ var customMerge = options.customMerge(key);
10916
+ return typeof customMerge === 'function' ? customMerge : deepmerge
10917
+ }
10918
+
10919
+ function getEnumerableOwnPropertySymbols(target) {
10920
+ return Object.getOwnPropertySymbols
10921
+ ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
10922
+ return Object.propertyIsEnumerable.call(target, symbol)
10923
+ })
10924
+ : []
10925
+ }
10926
+
10927
+ function getKeys(target) {
10928
+ return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
10929
+ }
10930
+
10931
+ function propertyIsOnObject(object, property) {
10932
+ try {
10933
+ return property in object
10934
+ } catch(_) {
10935
+ return false
10936
+ }
10937
+ }
10938
+
10939
+ // Protects from prototype poisoning and unexpected merging up the prototype chain.
10940
+ function propertyIsUnsafe(target, key) {
10941
+ return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
10942
+ && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
10943
+ && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
10944
+ }
10945
+
10946
+ function mergeObject(target, source, options) {
10947
+ var destination = {};
10948
+ if (options.isMergeableObject(target)) {
10949
+ getKeys(target).forEach(function(key) {
10950
+ destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
10951
+ });
10952
+ }
10953
+ getKeys(source).forEach(function(key) {
10954
+ if (propertyIsUnsafe(target, key)) {
10955
+ return
10956
+ }
10957
+
10958
+ if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
10959
+ destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
10960
+ } else {
10961
+ destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
10962
+ }
10963
+ });
10964
+ return destination
10965
+ }
10966
+
10967
+ function deepmerge(target, source, options) {
10968
+ options = options || {};
10969
+ options.arrayMerge = options.arrayMerge || defaultArrayMerge;
10970
+ options.isMergeableObject = options.isMergeableObject || isMergeableObject;
10971
+ // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
10972
+ // implementations can use it. The caller may not replace it.
10973
+ options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
10974
+
10975
+ var sourceIsArray = Array.isArray(source);
10976
+ var targetIsArray = Array.isArray(target);
10977
+ var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
10978
+
10979
+ if (!sourceAndTargetTypesMatch) {
10980
+ return cloneUnlessOtherwiseSpecified(source, options)
10981
+ } else if (sourceIsArray) {
10982
+ return options.arrayMerge(target, source, options)
10983
+ } else {
10984
+ return mergeObject(target, source, options)
10985
+ }
10986
+ }
10987
+
10988
+ deepmerge.all = function deepmergeAll(array, options) {
10989
+ if (!Array.isArray(array)) {
10990
+ throw new Error('first argument should be an array')
10991
+ }
10992
+
10993
+ return array.reduce(function(prev, next) {
10994
+ return deepmerge(prev, next, options)
10995
+ }, {})
10996
+ };
10997
+
10998
+ var deepmerge_1 = deepmerge;
10999
+
11000
+ var cjs = deepmerge_1;
11001
+
11002
+ var deepMerge = /*@__PURE__*/getDefaultExportFromCjs(cjs);
11003
+
11004
+ var dist = {};
11005
+
11006
+ var builder$3 = {};
11007
+
11008
+ var builder$2 = {};
11009
+
11010
+ var nullMetricsManager = {};
11011
+
11012
+ var nullManager$1 = {};
11013
+
11014
+ Object.defineProperty(nullManager$1, "__esModule", { value: true });
11015
+ nullManager$1.NullManager = void 0;
11016
+ class NullManager {
11017
+ constructor() {
11018
+ this.started = false;
11019
+ }
11020
+ waitForFinalExport(timeoutMs) {
11021
+ return Promise.resolve();
11022
+ }
11023
+ get settings() {
11024
+ return {};
11025
+ }
11026
+ start() {
11027
+ this.started = true;
11028
+ return Promise.resolve();
11029
+ }
11030
+ stop() {
11031
+ this.started = false;
11032
+ return Promise.resolve();
11033
+ }
11034
+ }
11035
+ nullManager$1.NullManager = NullManager;
11036
+
11037
+ var safeStringify$1 = {};
11038
+
11039
+ var isPlainObject$1 = {};
11040
+
11041
+ // https://github.com/jonschlinkert/is-plain-object/blob/master/is-plain-object.js
11042
+ // cf204a3
11043
+ Object.defineProperty(isPlainObject$1, "__esModule", { value: true });
11044
+ isPlainObject$1.isPlainObject = void 0;
11045
+ /*!
11046
+ * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
11047
+ *
11048
+ * Copyright (c) 2014-2017, Jon Schlinkert.
11049
+ * Released under the MIT License.
11050
+ */
11051
+ function isObject(o) {
11052
+ return Object.prototype.toString.call(o) === '[object Object]';
11053
+ }
11054
+ function isPlainObject(o) {
11055
+ let ctor;
11056
+ let prot;
11057
+ if (isObject(o) === false)
11058
+ return false;
11059
+ // If has modified constructor
11060
+ ctor = o.constructor;
11061
+ if (ctor === undefined)
11062
+ return true;
11063
+ // If has modified prototype
11064
+ prot = ctor.prototype;
11065
+ if (isObject(prot) === false)
11066
+ return false;
11067
+ // If constructor does not have an Object-specific method
11068
+ if (prot.hasOwnProperty('isPrototypeOf') === false) {
11069
+ return false;
11070
+ }
11071
+ // Most likely a plain Object
11072
+ return true;
11073
+ }
11074
+ isPlainObject$1.isPlainObject = isPlainObject;
11075
+
11076
+ Object.defineProperty(safeStringify$1, "__esModule", { value: true });
11077
+ safeStringify$1.safeStringify = void 0;
11078
+ const is_plain_object_1 = isPlainObject$1;
11079
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
11080
+ function safeStringify(obj) {
11081
+ if (!obj) {
11082
+ return JSON.stringify(obj);
11083
+ }
11084
+ return JSON.stringify(obj, (k, v) => {
11085
+ if (!v || typeof v !== "object")
11086
+ return v;
11087
+ if (!(0, is_plain_object_1.isPlainObject)(v))
11088
+ return Object.prototype.toString.call(v);
11089
+ return v;
11090
+ });
11091
+ }
11092
+ safeStringify$1.safeStringify = safeStringify;
11093
+
11094
+ var _null$1 = {};
11095
+
11096
+ Object.defineProperty(_null$1, "__esModule", { value: true });
11097
+ _null$1.NullMetric = void 0;
11098
+ class NullMetric {
11099
+ constructor(settings, logger) {
11100
+ this.settings = settings;
11101
+ this.logger = logger;
11102
+ this.started = false;
11103
+ }
11104
+ start() {
11105
+ var _a;
11106
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`null metric has been started instead of ${this.settings.type} one`);
11107
+ this.started = true;
11108
+ return Promise.resolve();
11109
+ }
11110
+ stop() {
11111
+ var _a;
11112
+ (_a = this.logger) === null || _a === void 0 ? void 0 : _a.debug(`null metric has been stopped instead of ${this.settings.type} one`);
11113
+ this.started = false;
11114
+ return Promise.resolve();
11115
+ }
11116
+ add() { }
11117
+ record() { }
11118
+ }
11119
+ _null$1.NullMetric = NullMetric;
11120
+
11121
+ Object.defineProperty(nullMetricsManager, "__esModule", { value: true });
11122
+ nullMetricsManager.NullMetricsManager = void 0;
11123
+ const nullManager_1$2 = nullManager$1;
11124
+ const safe_stringify_1$2 = safeStringify$1;
11125
+ const null_1 = _null$1;
11126
+ class NullMetricsManager extends nullManager_1$2.NullManager {
11127
+ constructor(settings, otelSettings, logger) {
11128
+ if ((otelSettings === null || otelSettings === void 0 ? void 0 : otelSettings.logSettingsOnStartup) !== false) {
11129
+ logger === null || logger === void 0 ? void 0 : logger.info(`Starting NullMetrcsManager with settings ${(0, safe_stringify_1$2.safeStringify)(settings)}`);
11130
+ }
11131
+ super();
11132
+ }
11133
+ waitForFinalExport(timeoutMs) {
11134
+ return Promise.resolve();
11135
+ }
11136
+ getFromSettings(settings) {
11137
+ return new null_1.NullMetric(settings);
11138
+ }
11139
+ get(type) {
11140
+ return new null_1.NullMetric({ name: type, type, enabled: false, description: type });
11141
+ }
11142
+ }
11143
+ nullMetricsManager.NullMetricsManager = NullMetricsManager;
11144
+
11145
+ var hasRequiredBuilder$3;
11146
+
11147
+ function requireBuilder$3 () {
11148
+ if (hasRequiredBuilder$3) return builder$2;
11149
+ hasRequiredBuilder$3 = 1;
11150
+ Object.defineProperty(builder$2, "__esModule", { value: true });
11151
+ builder$2.MetricsManagerBuilder = void 0;
11152
+ const nullMetricsManager_1 = nullMetricsManager;
11153
+ const __1 = requireDist();
11154
+ class MetricsManagerBuilder {
11155
+ withLogger(logger) {
11156
+ this.logger = logger;
11157
+ return this;
11158
+ }
11159
+ withSettings(settings) {
11160
+ this.settings = settings;
11161
+ return this;
11162
+ }
11163
+ withMeterProvider(meterProviderCreateFunc) {
11164
+ this.meterProviderCreateFunc = meterProviderCreateFunc;
11165
+ return this;
11166
+ }
11167
+ withDependencyContainer(container) {
11168
+ this.dependencyContainer = container;
11169
+ return this;
11170
+ }
11171
+ build() {
11172
+ var _a, _b, _c, _d;
11173
+ if (((_a = globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.metrics) &&
11174
+ ((_b = this.settings) === null || _b === void 0 ? void 0 : _b.definitiveInstance) !== true) {
11175
+ return globalThis.ioInsightsInternals.metrics;
11176
+ }
11177
+ const toReturn = this.buildCore();
11178
+ globalThis.ioInsightsInternals = (_c = globalThis.ioInsightsInternals) !== null && _c !== void 0 ? _c : {};
11179
+ if (!globalThis.ioInsightsInternals.metrics ||
11180
+ ((_d = this.settings) === null || _d === void 0 ? void 0 : _d.definitiveInstance)) {
11181
+ globalThis.ioInsightsInternals.metrics = toReturn;
11182
+ }
11183
+ return toReturn;
11184
+ }
11185
+ buildCore() {
11186
+ var _a, _b, _c, _d;
11187
+ let metricsPlugin;
11188
+ if (((_a = this.settings) === null || _a === void 0 ? void 0 : _a.enabled) !== true ||
11189
+ ((_c = (_b = this.settings) === null || _b === void 0 ? void 0 : _b.metrics) === null || _c === void 0 ? void 0 : _c.enabled) !== true ||
11190
+ !(metricsPlugin = (0, __1.loadInsightsPlugin)("metrics", this.logger))) {
11191
+ return new nullMetricsManager_1.NullMetricsManager((_d = this.settings) === null || _d === void 0 ? void 0 : _d.metrics, this.settings, this.logger);
11192
+ }
11193
+ const manager = metricsPlugin.newMetricsManager(this.settings, this.dependencyContainer, this.meterProviderCreateFunc, this.logger);
11194
+ return manager;
11195
+ }
11196
+ }
11197
+ builder$2.MetricsManagerBuilder = MetricsManagerBuilder;
11198
+
11199
+ return builder$2;
11200
+ }
11201
+
11202
+ var builder$1 = {};
11203
+
11204
+ var nullTracesManager = {};
11205
+
11206
+ var nullTracingState = {};
11207
+
11208
+ Object.defineProperty(nullTracingState, "__esModule", { value: true });
11209
+ class NullTracingState {
11210
+ constructor(source, propagationInfo, disablePropagation) {
11211
+ this.source = source;
11212
+ this.propagationInfo = propagationInfo;
11213
+ this.disablePropagation = disablePropagation;
11214
+ this.currentSpanStatus = { code: 0 /*SpanStatusCode.UNSET*/ };
11215
+ this.level = "OFF";
11216
+ }
11217
+ endSpan() {
11218
+ return Promise.resolve();
11219
+ }
11220
+ get enabled() {
11221
+ return false;
11222
+ }
11223
+ get id() {
11224
+ return undefined;
11225
+ }
11226
+ get traceId() {
11227
+ return undefined;
11228
+ }
11229
+ set status(status) {
11230
+ this.currentSpanStatus = Object.assign({}, status);
11231
+ }
11232
+ get status() {
11233
+ return this.currentSpanStatus;
11234
+ }
11235
+ addEvent(name, attributesOrStartTime, startTime) {
11236
+ return this;
11237
+ }
11238
+ recordException(exception, time) { }
11239
+ isRecording() {
11240
+ return false;
11241
+ }
11242
+ updateName(name) {
11243
+ return this;
11244
+ }
11245
+ spanContext() {
11246
+ return undefined;
11247
+ }
11248
+ addData(level, data) {
11249
+ }
11250
+ end() { }
11251
+ getPropagationInfo() {
11252
+ if (this.propagationInfo) {
11253
+ return this.propagationInfo;
11254
+ }
11255
+ return null;
11256
+ // // todo vnikolov: should we use otel's own context management at all?
11257
+ // const propagationInfo = { };
11258
+ // propagation.inject(context.active(), propagationInfo);
11259
+ // return propagationInfo;
11260
+ }
11261
+ injectPropagationInfo(carrier) {
11262
+ if (this.propagationInfo && !this.disablePropagation) {
11263
+ carrier.__interopIOTracePropagationInfo = this.propagationInfo;
11264
+ }
11265
+ }
11266
+ }
11267
+ nullTracingState.default = NullTracingState;
11268
+
11269
+ var traces = {};
11270
+
11271
+ var otelUtils = {};
11272
+
11273
+ var container = {};
11274
+
11275
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
11276
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11277
+ return new (P || (P = Promise))(function (resolve, reject) {
11278
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11279
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11280
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11281
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11282
+ });
11283
+ };
11284
+ Object.defineProperty(container, "__esModule", { value: true });
11285
+ container.Container = void 0;
11286
+ const safe_stringify_1$1 = safeStringify$1;
11287
+ class Container {
11288
+ static get instance() {
11289
+ var _a, _b;
11290
+ return (_a = Container._instance) !== null && _a !== void 0 ? _a : (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _b === void 0 ? void 0 : _b.instance;
11291
+ }
11292
+ static get settings() {
11293
+ var _a;
11294
+ return (_a = Container._settings) !== null && _a !== void 0 ? _a : Container.instance.settings;
11295
+ }
11296
+ static set settings(value) {
11297
+ Container._settings = value;
11298
+ }
11299
+ static errorless(callback, defaultValue) {
11300
+ try {
11301
+ if (typeof callback !== "function") {
11302
+ return callback;
11303
+ }
11304
+ // eslint-disable-next-line @typescript-eslint/ban-types
11305
+ const toReturn = callback();
11306
+ return toReturn;
11307
+ }
11308
+ catch (err) {
11309
+ return Container.handleErrorlessMode(err, defaultValue);
11310
+ }
11311
+ }
11312
+ static errorlessDefined(callback, defaultValue) {
11313
+ try {
11314
+ if (typeof callback !== "function") {
11315
+ return callback;
11316
+ }
11317
+ // eslint-disable-next-line @typescript-eslint/ban-types
11318
+ const toReturn = callback();
11319
+ return toReturn;
11320
+ }
11321
+ catch (err) {
11322
+ return Container.handleErrorlessMode(err, defaultValue);
11323
+ }
11324
+ }
11325
+ static errorlessAsync(callback, defaultValue) {
11326
+ return __awaiter(this, void 0, void 0, function* () {
11327
+ try {
11328
+ if (typeof callback !== "function") {
11329
+ return callback;
11330
+ }
11331
+ // eslint-disable-next-line @typescript-eslint/ban-types
11332
+ const toReturn = (yield callback)();
11333
+ return toReturn;
11334
+ }
11335
+ catch (err) {
11336
+ return Container.handleErrorlessMode(err, defaultValue);
11337
+ }
11338
+ });
11339
+ }
11340
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
11341
+ static handleErrorlessMode(err, defaultValue) {
11342
+ var _a, _b, _c, _d, _e;
11343
+ let message = undefined;
11344
+ try {
11345
+ if (err === null || err === void 0 ? void 0 : err.message) {
11346
+ message = (err === null || err === void 0 ? void 0 : err.message) + " " + ((_a = err === null || err === void 0 ? void 0 : err.stack) !== null && _a !== void 0 ? _a : new Error().stack);
11347
+ }
11348
+ if (!message) {
11349
+ try {
11350
+ message = (0, safe_stringify_1$1.safeStringify)(err) + " " + new Error().stack;
11351
+ }
11352
+ catch ( /*silent catch*/_f) { /*silent catch*/ }
11353
+ }
11354
+ if (!message) {
11355
+ try {
11356
+ message = (err === null || err === void 0 ? void 0 : err.toString()) + " " + new Error().stack;
11357
+ }
11358
+ catch ( /*silent catch*/_g) { /*silent catch*/ }
11359
+ }
11360
+ }
11361
+ catch ( /*silent catch*/_h) { /*silent catch*/ }
11362
+ if (!message) {
11363
+ message = "unknown " + new Error().stack;
11364
+ }
11365
+ try {
11366
+ if (!((_c = (_b = Container.instance) === null || _b === void 0 ? void 0 : _b.settings) === null || _c === void 0 ? void 0 : _c.errorlessMode)) {
11367
+ (_d = Container.instance.logger) === null || _d === void 0 ? void 0 : _d.error("Observed error " + message);
11368
+ throw err;
11369
+ }
11370
+ }
11371
+ catch (_j) {
11372
+ throw err;
11373
+ }
11374
+ try {
11375
+ (_e = Container.instance.logger) === null || _e === void 0 ? void 0 : _e.warn("Caught error " + message);
11376
+ return defaultValue;
11377
+ }
11378
+ catch (_k) {
11379
+ return defaultValue;
11380
+ }
11381
+ }
11382
+ constructor(_settings, _traces, metrics, logs, logger) {
11383
+ var _a;
11384
+ this._settings = _settings;
11385
+ this._traces = _traces;
11386
+ this.metrics = metrics;
11387
+ this.logs = logs;
11388
+ this.logger = logger;
11389
+ this.started = false;
11390
+ Container._instance = this;
11391
+ globalThis.ioInsightsInternals = (_a = globalThis.ioInsightsInternals) !== null && _a !== void 0 ? _a : {};
11392
+ globalThis.ioInsightsInternals.instance = this;
11393
+ }
11394
+ get traces() {
11395
+ var _a, _b;
11396
+ if ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.traces) {
11397
+ return (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _b === void 0 ? void 0 : _b.traces;
11398
+ }
11399
+ return this._traces;
11400
+ }
11401
+ waitForFinalExport(timeoutMs) {
11402
+ var _a, _b, _c;
11403
+ return Promise.allSettled([
11404
+ (_a = this.traces) === null || _a === void 0 ? void 0 : _a.waitForFinalExport(timeoutMs),
11405
+ (_b = this.metrics) === null || _b === void 0 ? void 0 : _b.waitForFinalExport(timeoutMs),
11406
+ (_c = this.logs) === null || _c === void 0 ? void 0 : _c.waitForFinalExport(timeoutMs)
11407
+ ]);
11408
+ }
11409
+ get settings() {
11410
+ return this._settings;
11411
+ }
11412
+ start() {
11413
+ return __awaiter(this, void 0, void 0, function* () {
11414
+ // vnikolov TODO: maybe log this? don't silently refuse to start
11415
+ const metricsPromise = this.metrics.settings.enabled ? this.metrics.start() : Promise.resolve();
11416
+ const tracesPromise = this.traces.settings.enabled ? this.traces.start() : Promise.resolve();
11417
+ const logsPromise = this.logs.settings.enabled ? this.logs.start() : Promise.resolve();
11418
+ yield Promise.all([metricsPromise, tracesPromise, logsPromise]);
11419
+ this.started = true;
11420
+ });
11421
+ }
11422
+ stop() {
11423
+ return __awaiter(this, void 0, void 0, function* () {
11424
+ const metricsPromise = this.metrics.started ? this.metrics.stop() : Promise.resolve();
11425
+ const tracesPromise = this.traces.started ? this.traces.stop() : Promise.resolve();
11426
+ const logsPromise = this.logs.started ? this.logs.stop() : Promise.resolve();
11427
+ yield Promise.all([metricsPromise, tracesPromise, logsPromise]);
11428
+ this.started = false;
11429
+ });
11430
+ }
11431
+ }
11432
+ container.Container = Container;
11433
+
11434
+ (function (exports$1) {
11435
+ Object.defineProperty(exports$1, "__esModule", { value: true });
11436
+ exports$1.extractFilteringContextFromArgs = exports$1.deep_value = exports$1.getOTELData = exports$1.flattenOtelAtributes = void 0;
11437
+ const container_1 = container;
11438
+ /* eslint-disable @typescript-eslint/no-explicit-any */
11439
+ const flattenOtelAtributes = (data, maxDepth) => {
11440
+ if (data === undefined ||
11441
+ data === null) {
11442
+ return {};
11443
+ }
11444
+ if (typeof data !== "object") {
11445
+ data = { unknownAttribute: data };
11446
+ }
11447
+ const toReturn = {};
11448
+ for (const [key, value] of Object.entries(data)) {
11449
+ const otelValues = (0, exports$1.getOTELData)(key, value, 0, maxDepth);
11450
+ for (const [otelKey, otelValue] of otelValues) {
11451
+ toReturn[otelKey] = otelValue;
11452
+ }
11453
+ }
11454
+ return toReturn;
11455
+ };
11456
+ exports$1.flattenOtelAtributes = flattenOtelAtributes;
11457
+ const getOTELData = (key, value, depth, maxDepth) => {
11458
+ depth += 1;
11459
+ if (depth > maxDepth) {
11460
+ return [[key, "<depth exceeded>"]];
11461
+ }
11462
+ const isObject = Boolean(value && typeof value === "object");
11463
+ const isValidPrimitiveValue = typeof value === "number" || typeof value === "string" || typeof value === "boolean";
11464
+ if (isValidPrimitiveValue) {
11465
+ return [[key, value]];
11466
+ }
11467
+ if (isAttributeArray(value)) {
11468
+ return [[key, value]].concat(flatten(key, value, depth, maxDepth));
11469
+ }
11470
+ else if (isObject) {
11471
+ return flatten(key, value, depth, maxDepth);
11472
+ }
11473
+ else if (typeof value === "function") {
11474
+ return [];
11475
+ }
11476
+ else if (value) {
11477
+ return [[key, value + ""]];
11478
+ }
11479
+ else {
11480
+ return [];
11481
+ }
11482
+ };
11483
+ exports$1.getOTELData = getOTELData;
11484
+ const flatten = (key, obj, depth, maxDepth) => {
11485
+ const toReturn = [];
11486
+ for (const [key2, val2] of Object.entries(obj)) {
11487
+ for (const [key3, val3] of (0, exports$1.getOTELData)(key2, val2, depth, maxDepth)) {
11488
+ toReturn.push([key + "." + key3, val3]);
11489
+ }
11490
+ }
11491
+ return toReturn;
11492
+ };
11493
+ const isAttributeArray = (value) => {
11494
+ if (!Array.isArray(value)) {
11495
+ return false;
11496
+ }
11497
+ return value.every((item) => item === null ||
11498
+ item === undefined ||
11499
+ typeof item === "string" ||
11500
+ typeof item === "number" ||
11501
+ typeof item === "boolean");
11502
+ };
11503
+ // todo vnikolov: document all the places where deep_value is used in the spec, as well
11504
+ // as the regex matches
11505
+ const deep_value = function (obj, path) {
11506
+ // eslint-disable-next-line no-var
11507
+ if (!path) {
11508
+ return null;
11509
+ }
11510
+ // eslint-disable-next-line no-var
11511
+ for (var i = 0, path = path.split("."), len = path.length; i < len; i++) {
11512
+ if (obj === null || obj === undefined) {
11513
+ return undefined;
11514
+ }
11515
+ obj = obj[path[i]];
11516
+ }
11517
+ return obj;
11518
+ };
11519
+ exports$1.deep_value = deep_value;
11520
+ // https://stackoverflow.com/a/8817473
11521
+ const extractFilteringContextFromArgs = (template, args, that) => {
11522
+ let filteringContext = {};
11523
+ if (typeof template.thisMapping === "function") {
11524
+ filteringContext = Object.assign(Object.assign({}, filteringContext), container_1.Container.errorless(() => template.thisMapping.apply(that, [that])));
11525
+ }
11526
+ else {
11527
+ Object.keys(template.thisMapping || {}).forEach((keyOrPath) => {
11528
+ if (!keyOrPath || !template.thisMapping) {
11529
+ return;
11530
+ }
11531
+ const filteringContextKey = template.thisMapping[keyOrPath];
11532
+ filteringContext[filteringContextKey] = (0, exports$1.deep_value)(that, keyOrPath);
11533
+ });
11534
+ }
11535
+ if (typeof template.argMapping === "function") {
11536
+ filteringContext = Object.assign(Object.assign({}, filteringContext), container_1.Container.errorless(() => template.argMapping.apply(that, args)));
11537
+ }
11538
+ else {
11539
+ Object.keys(template.argMapping || {}).forEach((keyOrPath) => {
11540
+ if (!keyOrPath || !template.argMapping) {
11541
+ return;
11542
+ }
11543
+ const filteringContextKey = template.argMapping[keyOrPath];
11544
+ const value = (0, exports$1.deep_value)(args, keyOrPath);
11545
+ if (typeof value === "string" ||
11546
+ typeof value === "number") {
11547
+ filteringContext[filteringContextKey] = value;
11548
+ }
11549
+ });
11550
+ }
11551
+ return filteringContext;
11552
+ };
11553
+ exports$1.extractFilteringContextFromArgs = extractFilteringContextFromArgs;
11554
+
11555
+ } (otelUtils));
11556
+
11557
+ var hasRequiredTraces;
11558
+
11559
+ function requireTraces () {
11560
+ if (hasRequiredTraces) return traces;
11561
+ hasRequiredTraces = 1;
11562
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
11563
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11564
+ return new (P || (P = Promise))(function (resolve, reject) {
11565
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11566
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11567
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11568
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11569
+ });
11570
+ };
11571
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
11572
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11573
+ };
11574
+ Object.defineProperty(traces, "__esModule", { value: true });
11575
+ traces.withSpan = void 0;
11576
+ const otelUtils_1 = otelUtils;
11577
+ const nullTracesManager_1 = requireNullTracesManager();
11578
+ const nullTracingState_1 = __importDefault(nullTracingState);
11579
+ /**
11580
+ * Null-safe singleton class that can be invoked even if you haven't initialized
11581
+ * the library (yet?), or if you don't have access to the current manager instance.
11582
+ */
11583
+ class Traces {
11584
+ static get instance() {
11585
+ var _a, _b;
11586
+ if ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.traces) {
11587
+ return (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _b === void 0 ? void 0 : _b.traces;
11588
+ }
11589
+ if (!Traces._instance) {
11590
+ Traces._instance = new nullTracesManager_1.NullTracesManager(undefined, undefined, undefined);
11591
+ }
11592
+ return Traces._instance;
11593
+ }
11594
+ static set instance(value) {
11595
+ Traces._instance = value;
11596
+ }
11597
+ static get currentTracingState() {
11598
+ var _a;
11599
+ return ((_a = Traces.instance) === null || _a === void 0 ? void 0 : _a.currentTracingState) || new nullTracingState_1.default("unknown", null, true);
11600
+ }
11601
+ static set currentTracingState(value) {
11602
+ if (Traces.instance) {
11603
+ Traces.instance.currentTracingState = value;
11604
+ }
11605
+ }
11606
+ static removePropagationInfo(propagationInfoCarrier) {
11607
+ Traces.extractPropagationInfo(propagationInfoCarrier, true);
11608
+ return propagationInfoCarrier;
11609
+ }
11610
+ static extractPropagationInfo(propagationInfoCarrier, deleteProperty) {
11611
+ if (propagationInfoCarrier === null || propagationInfoCarrier === void 0 ? void 0 : propagationInfoCarrier.traceparent) {
11612
+ return propagationInfoCarrier;
11613
+ }
11614
+ const nestedPropagationInfo = propagationInfoCarrier === null || propagationInfoCarrier === void 0 ? void 0 : propagationInfoCarrier.__interopIOTracePropagationInfo;
11615
+ if (nestedPropagationInfo) {
11616
+ if (deleteProperty === true) {
11617
+ delete propagationInfoCarrier.__interopIOTracePropagationInfo;
11618
+ }
11619
+ return nestedPropagationInfo;
11620
+ }
11621
+ else {
11622
+ return null;
11623
+ }
11624
+ }
11625
+ withSequenceSpanEx(source, traceName, filteringContextOrCallback, optionsOrCallback, callback) {
11626
+ return __awaiter(this, void 0, void 0, function* () {
11627
+ return Traces.instance.withSequenceSpanEx(source, traceName, filteringContextOrCallback, optionsOrCallback, callback);
11628
+ });
11629
+ }
11630
+ withSequenceSpan(source, filteringContextOrCallback, optionsOrCallback, callback) {
11631
+ return __awaiter(this, void 0, void 0, function* () {
11632
+ return Traces.instance.withSequenceSpan(source, filteringContextOrCallback, optionsOrCallback, callback);
11633
+ });
11634
+ }
11635
+ static withSpan(source, filteringContextOrDecoratorOptionsOrCallback, propagationInfoOrCallback, optionsOrCallback, callback) {
11636
+ // decorator or wrapping a function
11637
+ if (!(filteringContextOrDecoratorOptionsOrCallback instanceof Function) &&
11638
+ (!filteringContextOrDecoratorOptionsOrCallback ||
11639
+ filteringContextOrDecoratorOptionsOrCallback.argMapping ||
11640
+ filteringContextOrDecoratorOptionsOrCallback.thisMapping ||
11641
+ filteringContextOrDecoratorOptionsOrCallback.defaults) &&
11642
+ !propagationInfoOrCallback &&
11643
+ !optionsOrCallback &&
11644
+ !callback) {
11645
+ return function (target, propertyKey, descriptor) {
11646
+ let originalFn;
11647
+ if (descriptor) {
11648
+ // decorator
11649
+ originalFn = descriptor.value;
11650
+ }
11651
+ else {
11652
+ // wrapping function directly
11653
+ originalFn = target;
11654
+ }
11655
+ let tracedFunction = function (...args) {
11656
+ return Traces.withSpan(source, filteringContextOrDecoratorOptionsOrCallback
11657
+ ? (0, otelUtils_1.extractFilteringContextFromArgs)(filteringContextOrDecoratorOptionsOrCallback, args, this)
11658
+ : {}, null, filteringContextOrDecoratorOptionsOrCallback, () => {
11659
+ return originalFn.apply(this, args);
11660
+ });
11661
+ };
11662
+ if (Traces.isAsyncFunction(originalFn)) {
11663
+ // fix for interception API using toString() to check for async functions
11664
+ const inner = tracedFunction;
11665
+ tracedFunction = function __insightsAsyncTracedFunction(...args) {
11666
+ return inner.apply(this, args);
11667
+ };
11668
+ Object.defineProperty(tracedFunction, Symbol.toStringTag, {
11669
+ value: "AsyncFunction",
11670
+ configurable: true,
11671
+ });
11672
+ }
11673
+ if (descriptor) {
11674
+ descriptor.value = tracedFunction;
11675
+ }
11676
+ else {
11677
+ return tracedFunction;
11678
+ }
11679
+ };
11680
+ }
11681
+ return Traces.instance.withSpan(source, filteringContextOrDecoratorOptionsOrCallback, propagationInfoOrCallback, optionsOrCallback, callback);
11682
+ }
11683
+ static isAsyncFunction(value) {
11684
+ return value && {}.toString.call(value) === '[object AsyncFunction]';
11685
+ }
11686
+ static withSpans(tracingMap, objectToTrace) {
11687
+ for (const tracingMapPropertyName in tracingMap) {
11688
+ if (typeof objectToTrace[tracingMapPropertyName] === "function") {
11689
+ const originalMethod = objectToTrace[tracingMapPropertyName];
11690
+ const tracingMapPropertyValue = tracingMap[tracingMapPropertyName];
11691
+ if (!tracingMapPropertyValue) {
11692
+ continue;
11693
+ }
11694
+ let wrapperMaker;
11695
+ if (typeof tracingMapPropertyValue === "string") {
11696
+ wrapperMaker = Traces.withSpan(tracingMapPropertyValue);
11697
+ }
11698
+ else {
11699
+ wrapperMaker = Traces.withSpan(tracingMapPropertyValue.source, tracingMapPropertyValue.decoratorOptions);
11700
+ }
11701
+ objectToTrace[tracingMapPropertyName] = wrapperMaker(originalMethod);
11702
+ }
11703
+ }
11704
+ return objectToTrace;
11705
+ }
11706
+ }
11707
+ traces.default = Traces;
11708
+ traces.withSpan = Traces.withSpan;
11709
+
11710
+ return traces;
11711
+ }
11712
+
11713
+ var hasRequiredNullTracesManager;
11714
+
11715
+ function requireNullTracesManager () {
11716
+ if (hasRequiredNullTracesManager) return nullTracesManager;
11717
+ hasRequiredNullTracesManager = 1;
11718
+ var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
11719
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
11720
+ return new (P || (P = Promise))(function (resolve, reject) {
11721
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11722
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11723
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11724
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
11725
+ });
11726
+ };
11727
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
11728
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11729
+ };
11730
+ Object.defineProperty(nullTracesManager, "__esModule", { value: true });
11731
+ nullTracesManager.NullTracesManager = void 0;
11732
+ const nullTracingState_1 = __importDefault(nullTracingState);
11733
+ const traces_1 = __importDefault(requireTraces());
11734
+ const nullManager_1 = nullManager$1;
11735
+ const safe_stringify_1 = safeStringify$1;
11736
+ class NullTracesManager extends nullManager_1.NullManager {
11737
+ get settings() {
11738
+ return this._settings || {};
11739
+ }
11740
+ set settings(value) {
11741
+ this._settings = value;
11742
+ }
11743
+ constructor(_settings, otelSettings, logger) {
11744
+ if ((otelSettings === null || otelSettings === void 0 ? void 0 : otelSettings.logSettingsOnStartup) !== false) {
11745
+ logger === null || logger === void 0 ? void 0 : logger.info(`Starting NullTracesManager with settings ${(0, safe_stringify_1.safeStringify)(_settings)}`);
11746
+ }
11747
+ super();
11748
+ this._settings = _settings;
11749
+ this.logger = logger;
11750
+ }
11751
+ withSequenceSpan(source, filteringContextOrCallback, optionsOrCallback, callback) {
11752
+ return __awaiter(this, void 0, void 0, function* () {
11753
+ return this.withSequenceSpanEx(source, source + ".start", filteringContextOrCallback, optionsOrCallback, callback);
11754
+ });
11755
+ }
11756
+ withSequenceSpanEx(source, traceName, filteringContextOrCallback, optionsOrCallback, callback) {
11757
+ return __awaiter(this, void 0, void 0, function* () {
11758
+ return this.withSpan(source, filteringContextOrCallback, null, optionsOrCallback, callback);
11759
+ });
11760
+ }
11761
+ get currentTracingState() {
11762
+ return new nullTracingState_1.default("nullTracingState", null, true);
11763
+ }
11764
+ set currentTracingState(ts) {
11765
+ }
11766
+ waitForFinalExport(timeoutMs) {
11767
+ return Promise.resolve();
11768
+ }
11769
+ withSpan(source, filteringContextOrCallback, propagationInfoOrCallback, optionsOrCallback, callback) {
11770
+ const actualCallback =
11771
+ // eslint-disable-next-line no-nested-ternary
11772
+ typeof filteringContextOrCallback === "function"
11773
+ ? filteringContextOrCallback
11774
+ : typeof propagationInfoOrCallback === "function"
11775
+ ? propagationInfoOrCallback
11776
+ : typeof optionsOrCallback === "function"
11777
+ ? optionsOrCallback
11778
+ : callback;
11779
+ if (!actualCallback) {
11780
+ throw new Error("callback must be provided");
11781
+ }
11782
+ if (typeof actualCallback !== "function") {
11783
+ throw new Error("Callback must be a function, received " + typeof actualCallback);
11784
+ }
11785
+ // ! DO NOT log in this method, danger of infinite loop with
11786
+ // interop log publishing
11787
+ //
11788
+ // this.logger?.debug("nullTracesManager.withSpan: " + source);
11789
+ // ! a null manager means no propagation
11790
+ //
11791
+ // let extractedPI: PropagationInfo | null = null;
11792
+ // if (propagationInfoOrCallback) {
11793
+ // let propagationInfoCarrier = {};
11794
+ // if (!isFunctionType(propagationInfoOrCallback)) {
11795
+ // propagationInfoCarrier = { ...propagationInfoOrCallback };
11796
+ // }
11797
+ // extractedPI = Traces.extractPropagationInfo(propagationInfoCarrier);
11798
+ // } else {
11799
+ // extractedPI = Traces.currentTracingState?.getPropagationInfo() || null;
11800
+ // }
11801
+ // const nts = new NullTracingState(source, extractedPI);
11802
+ const nts = new nullTracingState_1.default(source, null, true);
11803
+ traces_1.default.currentTracingState = nts;
11804
+ try {
11805
+ return actualCallback(nts);
11806
+ }
11807
+ finally {
11808
+ traces_1.default.currentTracingState = null;
11809
+ }
11810
+ }
11811
+ setFilterConfig(filters) {
11812
+ }
11813
+ get startupTraceFinished() {
11814
+ return (() => { });
11815
+ }
11816
+ get userJourneyMarker() {
11817
+ return (() => { });
11818
+ }
11819
+ setUserJourneyMarker(userJourneyMarker) {
11820
+ }
11821
+ get clickstreamMarker() {
11822
+ return (() => { });
11823
+ }
11824
+ }
11825
+ nullTracesManager.NullTracesManager = NullTracesManager;
11826
+
11827
+ return nullTracesManager;
11828
+ }
11829
+
11830
+ var hasRequiredBuilder$2;
11831
+
11832
+ function requireBuilder$2 () {
11833
+ if (hasRequiredBuilder$2) return builder$1;
11834
+ hasRequiredBuilder$2 = 1;
11835
+ Object.defineProperty(builder$1, "__esModule", { value: true });
11836
+ builder$1.TracesManagerBuilder = void 0;
11837
+ const nullTracesManager_1 = requireNullTracesManager();
11838
+ const __1 = requireDist();
11839
+ class TracesManagerBuilder {
11840
+ constructor() {
11841
+ this.traceLogger = null;
11842
+ }
11843
+ withLogger(logger) {
11844
+ this.logger = logger;
11845
+ return this;
11846
+ }
11847
+ withTraceLogger(traceLogger) {
11848
+ this.traceLogger = traceLogger;
11849
+ return this;
11850
+ }
11851
+ withSettings(settings) {
11852
+ this.settings = settings;
11853
+ return this;
11854
+ }
11855
+ withMetrics(metrics) {
11856
+ this.metrics = metrics;
11857
+ return this;
11858
+ }
11859
+ withTracerProvider(tracerProvider) {
11860
+ this.tracerProvider = tracerProvider;
11861
+ return this;
11862
+ }
11863
+ withContextManager(contextManager) {
11864
+ var _a, _b;
11865
+ this.settings = (_a = this.settings) !== null && _a !== void 0 ? _a : { enabled: false };
11866
+ this.settings.traces = (_b = this.settings.traces) !== null && _b !== void 0 ? _b : { enabled: false };
11867
+ this.settings.traces.contextManager = () => contextManager;
11868
+ this.settings.traces.useOTELContextManager = true;
11869
+ return this;
11870
+ }
11871
+ withPropagationInfoStorage(store, read) {
11872
+ this.store = store;
11873
+ this.read = read;
11874
+ return this;
11875
+ }
11876
+ build() {
11877
+ var _a, _b, _c, _d;
11878
+ if (((_a = globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.traces) &&
11879
+ ((_b = this.settings) === null || _b === void 0 ? void 0 : _b.definitiveInstance) !== true) {
11880
+ return globalThis.ioInsightsInternals.traces;
11881
+ }
11882
+ const toReturn = this.buildCore();
11883
+ globalThis.ioInsightsInternals = (_c = globalThis.ioInsightsInternals) !== null && _c !== void 0 ? _c : {};
11884
+ if (!globalThis.ioInsightsInternals.traces ||
11885
+ ((_d = this.settings) === null || _d === void 0 ? void 0 : _d.definitiveInstance)) {
11886
+ globalThis.ioInsightsInternals.traces = toReturn;
11887
+ }
11888
+ return toReturn;
11889
+ }
11890
+ buildCore() {
11891
+ var _a, _b, _c, _d, _e, _f, _g, _h;
11892
+ this.settings.traces = (_a = this.settings.traces) !== null && _a !== void 0 ? _a : { enabled: false };
11893
+ this.settings.traces.otlpExporterConfig = (_b = this.settings.traces.exporterSettings) !== null && _b !== void 0 ? _b : this.settings.traces.otlpExporterConfig;
11894
+ this.settings.traces.exporterSettings = (_c = this.settings.traces.exporterSettings) !== null && _c !== void 0 ? _c : this.settings.traces.otlpExporterConfig;
11895
+ let tracePlugin;
11896
+ if (((_d = this.settings) === null || _d === void 0 ? void 0 : _d.enabled) !== true ||
11897
+ ((_f = (_e = this.settings) === null || _e === void 0 ? void 0 : _e.traces) === null || _f === void 0 ? void 0 : _f.enabled) !== true ||
11898
+ !(tracePlugin = (0, __1.loadInsightsPlugin)("traces", this.logger))) {
11899
+ return new nullTracesManager_1.NullTracesManager((_g = this.settings) === null || _g === void 0 ? void 0 : _g.traces, this.settings, this.logger);
11900
+ }
11901
+ const manager = tracePlugin.newTracesManager(this.logger, this.settings, (_h = this.traceLogger) !== null && _h !== void 0 ? _h : this.logger, this.metrics, this.store, this.read);
11902
+ return manager;
11903
+ }
11904
+ }
11905
+ builder$1.TracesManagerBuilder = TracesManagerBuilder;
11906
+
11907
+ return builder$1;
11908
+ }
11909
+
11910
+ var _null = {};
11911
+
11912
+ Object.defineProperty(_null, "__esModule", { value: true });
11913
+ _null.NullLogger = void 0;
11914
+ class NullLogger {
11915
+ get level() {
11916
+ return 60 /* IOInsights.LoggerLogLevel.INFO */;
11917
+ }
11918
+ error() {
11919
+ // do nothing
11920
+ }
11921
+ warn() {
11922
+ // do nothing
11923
+ }
11924
+ info() {
11925
+ // do nothing
11926
+ }
11927
+ debug() {
11928
+ // do nothing
11929
+ }
11930
+ verbose() {
11931
+ // do nothing
11932
+ }
11933
+ }
11934
+ _null.NullLogger = NullLogger;
11935
+
11936
+ var nullManager = {};
11937
+
11938
+ Object.defineProperty(nullManager, "__esModule", { value: true });
11939
+ nullManager.NullLogsManager = void 0;
11940
+ const nullManager_1$1 = nullManager$1;
11941
+ const safe_stringify_1 = safeStringify$1;
11942
+ class NullLogsManager extends nullManager_1$1.NullManager {
11943
+ constructor(settings, otelSettings, logger) {
11944
+ if ((otelSettings === null || otelSettings === void 0 ? void 0 : otelSettings.logSettingsOnStartup) !== false) {
11945
+ logger === null || logger === void 0 ? void 0 : logger.info(`Starting NullLogsManager with settings ${(0, safe_stringify_1.safeStringify)(settings)}`);
11946
+ }
11947
+ super();
11948
+ }
11949
+ emit(logRecord) {
11950
+ return null;
11951
+ }
11952
+ }
11953
+ nullManager.NullLogsManager = NullLogsManager;
11954
+
11955
+ var constants = {};
11956
+
11957
+ Object.defineProperty(constants, "__esModule", { value: true });
11958
+ constants.Defaults = void 0;
11959
+ constants.Defaults = {
11960
+ DEFAULT_USER: "unknown-user",
11961
+ DEFAULT_SERVICE_NAME: "unknown-service-name",
11962
+ DEFAULT_SERVICE_ID: "unknown-service-id",
11963
+ DEFAULT_SERVICE_VERSION: "unknown-service-version",
11964
+ DEFAULT_PLATFORM_VERSION: "unknown-platform-version",
11965
+ };
11966
+
11967
+ var logWrapper = {};
11968
+
11969
+ Object.defineProperty(logWrapper, "__esModule", { value: true });
11970
+ logWrapper.LogWrapper = void 0;
11971
+ // wraps an OTEL library logger into an OTEL library logger
11972
+ // allows filtering messages etc
11973
+ class LogWrapper {
11974
+ constructor(logger, dropLog) {
11975
+ this.logger = logger;
11976
+ this.dropLog = dropLog;
11977
+ }
11978
+ get level() {
11979
+ var _a;
11980
+ return (_a = this.logger.level) !== null && _a !== void 0 ? _a : 0 /* IOInsights.LoggerLogLevel.NONE */;
11981
+ }
11982
+ error(message, ...args) {
11983
+ var _a;
11984
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 50 /* IOInsights.LoggerLogLevel.WARN */, message)) {
11985
+ return;
11986
+ }
11987
+ // we log errors as warn because some of our clients stopped the platform if an log error is observed (they consider it as broken state)
11988
+ // we can do that since otel impl is not considered critical
11989
+ this.logger.warn(message, ...args);
11990
+ }
11991
+ warn(message, ...args) {
11992
+ var _a;
11993
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 50 /* IOInsights.LoggerLogLevel.WARN */, message)) {
11994
+ return;
11995
+ }
11996
+ this.logger.warn(message, ...args);
11997
+ }
11998
+ info(message, ...args) {
11999
+ var _a;
12000
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 60 /* IOInsights.LoggerLogLevel.INFO */, message)) {
12001
+ return;
12002
+ }
12003
+ this.logger.info(message, ...args);
12004
+ }
12005
+ debug(message, ...args) {
12006
+ var _a;
12007
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 70 /* IOInsights.LoggerLogLevel.DEBUG */, message)) {
12008
+ return;
12009
+ }
12010
+ this.logger.debug(message, ...args);
12011
+ }
12012
+ verbose(message, ...args) {
12013
+ var _a;
12014
+ if ((_a = this.dropLog) === null || _a === void 0 ? void 0 : _a.call(this, 80 /* IOInsights.LoggerLogLevel.VERBOSE */, message)) {
12015
+ return;
12016
+ }
12017
+ this.logger.verbose(message, ...args);
12018
+ }
12019
+ }
12020
+ logWrapper.LogWrapper = LogWrapper;
12021
+
12022
+ var builder = {};
12023
+
12024
+ var hasRequiredBuilder$1;
12025
+
12026
+ function requireBuilder$1 () {
12027
+ if (hasRequiredBuilder$1) return builder;
12028
+ hasRequiredBuilder$1 = 1;
12029
+ Object.defineProperty(builder, "__esModule", { value: true });
12030
+ builder.LogsManagerBuilder = void 0;
12031
+ const __1 = requireDist();
12032
+ const nullManager_1 = nullManager;
12033
+ class LogsManagerBuilder {
12034
+ withLogger(logger) {
12035
+ this.logger = logger;
12036
+ return this;
12037
+ }
12038
+ withSettings(settings) {
12039
+ this.settings = settings;
12040
+ return this;
12041
+ }
12042
+ build() {
12043
+ var _a, _b, _c, _d;
12044
+ if (((_a = globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.logs) &&
12045
+ ((_b = this.settings) === null || _b === void 0 ? void 0 : _b.definitiveInstance) !== true) {
12046
+ return globalThis.ioInsightsInternals.logs;
12047
+ }
12048
+ const toReturn = this.buildCore();
12049
+ globalThis.ioInsightsInternals = (_c = globalThis.ioInsightsInternals) !== null && _c !== void 0 ? _c : {};
12050
+ if (!globalThis.ioInsightsInternals.logs ||
12051
+ ((_d = this.settings) === null || _d === void 0 ? void 0 : _d.definitiveInstance)) {
12052
+ globalThis.ioInsightsInternals.logs = toReturn;
12053
+ }
12054
+ return toReturn;
12055
+ }
12056
+ buildCore() {
12057
+ var _a, _b, _c, _d;
12058
+ let logsPlugin;
12059
+ if (((_a = this.settings) === null || _a === void 0 ? void 0 : _a.enabled) !== true ||
12060
+ ((_c = (_b = this.settings) === null || _b === void 0 ? void 0 : _b.logs) === null || _c === void 0 ? void 0 : _c.enabled) !== true ||
12061
+ !(logsPlugin = (0, __1.loadInsightsPlugin)("logs", this.logger))) {
12062
+ return new nullManager_1.NullLogsManager((_d = this.settings) === null || _d === void 0 ? void 0 : _d.logs, this.settings, this.logger);
12063
+ }
12064
+ const logs = logsPlugin.newLogsManager(this.logger, this.settings.logs, this.settings);
12065
+ return logs;
12066
+ }
12067
+ }
12068
+ builder.LogsManagerBuilder = LogsManagerBuilder;
12069
+
12070
+ return builder;
12071
+ }
12072
+
12073
+ var hasRequiredBuilder;
12074
+
12075
+ function requireBuilder () {
12076
+ if (hasRequiredBuilder) return builder$3;
12077
+ hasRequiredBuilder = 1;
12078
+ Object.defineProperty(builder$3, "__esModule", { value: true });
12079
+ builder$3.Builder = void 0;
12080
+ const builder_1 = requireBuilder$3();
12081
+ const builder_2 = requireBuilder$2();
12082
+ const null_1 = _null;
12083
+ const container_1 = container;
12084
+ const nullMetricsManager_1 = nullMetricsManager;
12085
+ const nullTracesManager_1 = requireNullTracesManager();
12086
+ const nullManager_1 = nullManager;
12087
+ const constants_1 = constants;
12088
+ const logWrapper_1 = logWrapper;
12089
+ const _1 = requireDist();
12090
+ const safe_stringify_1 = safeStringify$1;
12091
+ const builder_3 = requireBuilder$1();
12092
+ class Builder {
12093
+ constructor() {
12094
+ this.logger = new null_1.NullLogger();
12095
+ }
12096
+ // these methods must be invoked...
12097
+ withLogger(loggerArg) {
12098
+ var _a;
12099
+ if (loggerArg) {
12100
+ this.logger = new logWrapper_1.LogWrapper(loggerArg, (_, msg) => {
12101
+ var _a, _b, _c;
12102
+ if (((_a = this.settings) === null || _a === void 0 ? void 0 : _a.suppressDoubleInitializationWarnings) &&
12103
+ ~(msg + "").indexOf("@opentelemetry/api: Attempted duplicate registration of API")) {
12104
+ return true;
12105
+ }
12106
+ if (((_b = this.settings) === null || _b === void 0 ? void 0 : _b.suppressDoubleInitializationWarnings) &&
12107
+ ~(msg + "").indexOf("Current logger will overwrite one already registered")) {
12108
+ return true;
12109
+ }
12110
+ if (((_c = this.settings) === null || _c === void 0 ? void 0 : _c.suppressDoubleInitializationWarnings) &&
12111
+ ~(msg + "").indexOf("Current logger will be overwritten")) {
12112
+ return true;
12113
+ }
12114
+ return false;
12115
+ });
12116
+ }
12117
+ const basePlugin = (0, _1.loadInsightsPlugin)("base", this.logger);
12118
+ if (basePlugin) {
12119
+ if (this.logger.level) {
12120
+ const level = (_a = this.logger.level) === null || _a === void 0 ? void 0 : _a.valueOf();
12121
+ basePlugin.diag.setLogger(this.logger, level);
12122
+ }
12123
+ else {
12124
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
12125
+ basePlugin.diag.setLogger(this.logger, 70 /* IOInsights.LoggerLogLevel.DEBUG */);
12126
+ }
12127
+ }
12128
+ return this;
12129
+ }
12130
+ withSettings(settings) {
12131
+ this.settings = settings;
12132
+ container_1.Container.settings = settings;
12133
+ return this;
12134
+ }
12135
+ // ...before these methods
12136
+ withMetrics() {
12137
+ this.metricsBuilder = new builder_1.MetricsManagerBuilder();
12138
+ this.metricsBuilder.withLogger(this.logger);
12139
+ this.metricsBuilder.withSettings(Object.assign({ enabled: false }, this.settings));
12140
+ return this.metricsBuilder;
12141
+ }
12142
+ withTraces() {
12143
+ this.tracesBuilder = new builder_2.TracesManagerBuilder();
12144
+ this.tracesBuilder.withLogger(this.logger);
12145
+ this.tracesBuilder.withSettings(Object.assign({ enabled: false }, this.settings));
12146
+ return this.tracesBuilder;
12147
+ }
12148
+ withLogs() {
12149
+ this.logsBuilder = new builder_3.LogsManagerBuilder();
12150
+ this.logsBuilder.withLogger(this.logger);
12151
+ this.logsBuilder.withSettings(Object.assign({ enabled: false }, this.settings));
12152
+ return this.logsBuilder;
12153
+ }
12154
+ build() {
12155
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
12156
+ this.settings = (_a = this.settings) !== null && _a !== void 0 ? _a : { enabled: false };
12157
+ const nonPartialSettings = Object.assign({ enabled: false }, this.settings);
12158
+ if (((_b = this.settings) === null || _b === void 0 ? void 0 : _b.logSettingsOnStartup) !== false) {
12159
+ this.logger.info(`Starting interop.io OTEL with settings ${(0, safe_stringify_1.safeStringify)(this.settings)}`);
12160
+ }
12161
+ if (((_c = this.settings) === null || _c === void 0 ? void 0 : _c.enabled) == false ||
12162
+ !((0, _1.loadInsightsPlugin)("base", this.logger))) {
12163
+ return new container_1.Container(nonPartialSettings, new nullTracesManager_1.NullTracesManager(this.settings.traces, nonPartialSettings, this.logger), new nullMetricsManager_1.NullMetricsManager(this.settings.metrics, nonPartialSettings, this.logger), new nullManager_1.NullLogsManager(this.settings.logs, nonPartialSettings, this.logger), this.logger);
12164
+ }
12165
+ if (((_e = (_d = this.settings) === null || _d === void 0 ? void 0 : _d.metrics) === null || _e === void 0 ? void 0 : _e.enabled) &&
12166
+ ((_f = this.settings) === null || _f === void 0 ? void 0 : _f.metrics.platformMetricsEnabled) &&
12167
+ !this.metricsBuilder) {
12168
+ throw new Error("metrics.platformMetricsEnabled is true, but .withMetrics() method not called.");
12169
+ }
12170
+ const providedAdditionalResourceAttributes = this.settings.additionalResourceAttributes;
12171
+ this.settings.additionalResourceAttributes = () => {
12172
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z;
12173
+ const evaluatedAdditionalResourceAttributes = (_a = container_1.Container.errorlessDefined(providedAdditionalResourceAttributes, {})) !== null && _a !== void 0 ? _a : {};
12174
+ return Object.assign(Object.assign({}, evaluatedAdditionalResourceAttributes), { user: (_e = (_d = (_b = evaluatedAdditionalResourceAttributes.userId) !== null && _b !== void 0 ? _b : (_c = this.settings) === null || _c === void 0 ? void 0 : _c.userId) !== null && _d !== void 0 ? _d : evaluatedAdditionalResourceAttributes["user.id"]) !== null && _e !== void 0 ? _e : constants_1.Defaults.DEFAULT_USER, "user.id": (_j = (_h = (_f = evaluatedAdditionalResourceAttributes.userId) !== null && _f !== void 0 ? _f : (_g = this.settings) === null || _g === void 0 ? void 0 : _g.userId) !== null && _h !== void 0 ? _h : evaluatedAdditionalResourceAttributes["user.id"]) !== null && _j !== void 0 ? _j : constants_1.Defaults.DEFAULT_USER, "service.name": (_o = (_m = (_k = evaluatedAdditionalResourceAttributes.serviceName) !== null && _k !== void 0 ? _k : (_l = this.settings) === null || _l === void 0 ? void 0 : _l.serviceName) !== null && _m !== void 0 ? _m : evaluatedAdditionalResourceAttributes["service.name"]) !== null && _o !== void 0 ? _o : constants_1.Defaults.DEFAULT_SERVICE_NAME, "service.instance.id": (_s = (_r = (_p = evaluatedAdditionalResourceAttributes.serviceId) !== null && _p !== void 0 ? _p : (_q = this.settings) === null || _q === void 0 ? void 0 : _q.serviceId) !== null && _r !== void 0 ? _r : evaluatedAdditionalResourceAttributes["service.instance.id"]) !== null && _s !== void 0 ? _s : constants_1.Defaults.DEFAULT_SERVICE_ID, "service.version": (_w = (_v = (_t = evaluatedAdditionalResourceAttributes.serviceVersion) !== null && _t !== void 0 ? _t : (_u = this.settings) === null || _u === void 0 ? void 0 : _u.serviceVersion) !== null && _v !== void 0 ? _v : evaluatedAdditionalResourceAttributes["service.version"]) !== null && _w !== void 0 ? _w : constants_1.Defaults.DEFAULT_SERVICE_VERSION, platformVersion: (_z = (_x = evaluatedAdditionalResourceAttributes.platformVersion) !== null && _x !== void 0 ? _x : (_y = this.settings) === null || _y === void 0 ? void 0 : _y.platformVersion) !== null && _z !== void 0 ? _z : constants_1.Defaults.DEFAULT_PLATFORM_VERSION });
12175
+ };
12176
+ Builder.maybeAddResourceAttributesToAttributes(this.settings);
12177
+ Builder.maybeAddResourceAttributesToAttributes(this.settings.logs);
12178
+ Builder.maybeAddResourceAttributesToAttributes(this.settings.metrics);
12179
+ Builder.maybeAddResourceAttributesToAttributes(this.settings.traces);
12180
+ Builder.propagateAttributeDown("useSSOAuth", this.settings, this.settings.logs);
12181
+ Builder.propagateAttributeDown("useSSOAuth", this.settings, this.settings.metrics);
12182
+ Builder.propagateAttributeDown("useSSOAuth", this.settings, this.settings.traces);
12183
+ Builder.propagateAttributeDown("useSSOAuthRawToken", this.settings, this.settings.logs);
12184
+ Builder.propagateAttributeDown("useSSOAuthRawToken", this.settings, this.settings.metrics);
12185
+ Builder.propagateAttributeDown("useSSOAuthRawToken", this.settings, this.settings.traces);
12186
+ Builder.propagateAttributesDown("headers", this.settings, this.settings.logs);
12187
+ Builder.propagateAttributesDown("headers", this.settings, this.settings.metrics);
12188
+ Builder.propagateAttributesDown("headers", this.settings, this.settings.traces);
12189
+ Builder.propagateAttributesDown("additionalAttributes", this.settings, this.settings.logs);
12190
+ Builder.propagateAttributesDown("additionalResourceAttributes", this.settings, this.settings.logs);
12191
+ Builder.propagateAttributesDown("additionalAttributes", this.settings, this.settings.metrics);
12192
+ Builder.propagateAttributesDown("additionalResourceAttributes", this.settings, this.settings.metrics);
12193
+ Builder.propagateAttributesDown("additionalAttributes", this.settings, this.settings.traces);
12194
+ Builder.propagateAttributesDown("additionalResourceAttributes", this.settings, this.settings.traces);
12195
+ const metricsBuilder = (_g = this.metricsBuilder) !== null && _g !== void 0 ? _g : this.withMetrics();
12196
+ const metrics = metricsBuilder
12197
+ .withLogger(this.logger)
12198
+ .withSettings(this.settings)
12199
+ .build();
12200
+ const tracesBuilder = (_h = this.tracesBuilder) !== null && _h !== void 0 ? _h : this.withTraces();
12201
+ const traces = tracesBuilder
12202
+ .withLogger(this.logger)
12203
+ .withSettings(this.settings)
12204
+ .withMetrics(metrics)
12205
+ .build();
12206
+ _1.Traces.instance = traces;
12207
+ const logsBuilder = (_j = this.logsBuilder) !== null && _j !== void 0 ? _j : this.withLogs();
12208
+ const logs = logsBuilder
12209
+ .withLogger(this.logger)
12210
+ .withSettings(this.settings)
12211
+ .build();
12212
+ _1.Logs.instance = logs;
12213
+ return new container_1.Container(nonPartialSettings, traces, metrics, logs, this.logger);
12214
+ }
12215
+ static propagateAttributeDown(k, otelSettings, settings) {
12216
+ var _a;
12217
+ if (!settings) {
12218
+ return;
12219
+ }
12220
+ settings[k] = (_a = settings[k]) !== null && _a !== void 0 ? _a : otelSettings[k];
12221
+ }
12222
+ static propagateAttributesDown(k, otelSettings, settings) {
12223
+ var _a, _b;
12224
+ if (!settings) {
12225
+ return;
12226
+ }
12227
+ const providedOtel = (_a = otelSettings[k]) !== null && _a !== void 0 ? _a : {};
12228
+ const provided = (_b = settings[k]) !== null && _b !== void 0 ? _b : {};
12229
+ settings[k] = () => (Object.assign(Object.assign({}, container_1.Container.errorless(providedOtel)), container_1.Container.errorless(provided)));
12230
+ }
12231
+ static maybeAddResourceAttributesToAttributes(settings) {
12232
+ if (settings === null || settings === void 0 ? void 0 : settings.addResourceAttributesToAttributes) {
12233
+ const providedAdditionalResourceAttributes = settings.additionalResourceAttributes;
12234
+ const providedAdditionalAttributes = settings.additionalAttributes;
12235
+ settings.additionalAttributes = () => (Object.assign(Object.assign({}, container_1.Container.errorless(providedAdditionalResourceAttributes)), container_1.Container.errorless(providedAdditionalAttributes)));
12236
+ }
12237
+ }
12238
+ }
12239
+ builder$3.Builder = Builder;
12240
+
12241
+ return builder$3;
12242
+ }
12243
+
12244
+ var log4jsWrapper = {};
12245
+
12246
+ Object.defineProperty(log4jsWrapper, "__esModule", { value: true });
12247
+ log4jsWrapper.Log4jsWrapper = void 0;
12248
+ // wraps a log4js wrapper into an OTEL library logger
12249
+ class Log4jsWrapper {
12250
+ constructor(logger) {
12251
+ this.logger = logger;
12252
+ }
12253
+ get level() {
12254
+ return this.convert("level" in this.logger ? this.logger.level : this.logger.publishLevel());
12255
+ }
12256
+ error(message, ...args) {
12257
+ // we log errors as warn because some of our clients stopped the platform if an log error is observed (they consider it as broken state)
12258
+ // we can do that since otel impl is not considered critical
12259
+ this.logger.warn(message, ...args);
12260
+ }
12261
+ warn(message, ...args) {
12262
+ this.logger.warn(message, ...args);
12263
+ }
12264
+ info(message, ...args) {
12265
+ this.logger.info(message, ...args);
12266
+ }
12267
+ debug(message, ...args) {
12268
+ this.logger.debug(message, ...args);
12269
+ }
12270
+ verbose(message, ...args) {
12271
+ this.logger.trace(message, ...args);
12272
+ }
12273
+ convert(level) {
12274
+ if (level === undefined) {
12275
+ return 60 /* IOInsights.LoggerLogLevel.INFO */;
12276
+ }
12277
+ const currentLevel = typeof level !== "string" ? level.levelStr.toLowerCase() : level.toLowerCase();
12278
+ switch (currentLevel) {
12279
+ case "off": {
12280
+ return 0 /* IOInsights.LoggerLogLevel.NONE */;
12281
+ }
12282
+ case "error": {
12283
+ return 30 /* IOInsights.LoggerLogLevel.ERROR */;
12284
+ }
12285
+ case "warn": {
12286
+ return 50 /* IOInsights.LoggerLogLevel.WARN */;
12287
+ }
12288
+ case "info": {
12289
+ return 60 /* IOInsights.LoggerLogLevel.INFO */;
12290
+ }
12291
+ case "debug": {
12292
+ return 70 /* IOInsights.LoggerLogLevel.DEBUG */;
12293
+ }
12294
+ case "trace": {
12295
+ return 80 /* IOInsights.LoggerLogLevel.VERBOSE */;
12296
+ }
12297
+ default: {
12298
+ return 60 /* IOInsights.LoggerLogLevel.INFO */;
12299
+ }
12300
+ }
12301
+ }
12302
+ }
12303
+ log4jsWrapper.Log4jsWrapper = Log4jsWrapper;
12304
+
12305
+ var metricsDependencyBuilder = {};
12306
+
12307
+ var nullPerfProvider = {};
12308
+
12309
+ Object.defineProperty(nullPerfProvider, "__esModule", { value: true });
12310
+ nullPerfProvider.NullPerformanceProvider = void 0;
12311
+ class NullPerformanceProvider {
12312
+ getAppsCPU() {
12313
+ return Promise.resolve(undefined);
12314
+ }
12315
+ getAppsMemory() {
12316
+ return Promise.resolve(undefined);
12317
+ }
12318
+ getSystemCPU() {
12319
+ return Promise.resolve(undefined);
12320
+ }
12321
+ getSystemMemory() {
12322
+ return Promise.resolve(undefined);
12323
+ }
12324
+ }
12325
+ nullPerfProvider.NullPerformanceProvider = NullPerformanceProvider;
12326
+
12327
+ Object.defineProperty(metricsDependencyBuilder, "__esModule", { value: true });
12328
+ metricsDependencyBuilder.MetricsDependencyBuilder = void 0;
12329
+ const nullPerfProvider_1 = nullPerfProvider;
12330
+ class MetricsDependencyBuilder {
12331
+ constructor() {
12332
+ this.performanceProvider = new nullPerfProvider_1.NullPerformanceProvider();
12333
+ this.instanceFocusedHandler = () => () => { };
12334
+ this.instanceStartedHandler = () => () => { };
12335
+ this.instanceStoppedHandler = () => () => { };
12336
+ this.instanceReadyHandler = () => () => { };
12337
+ this.instanceErrorHandler = () => () => { };
12338
+ this.instanceCrashHandler = () => () => { };
12339
+ this.layoutRestoredHandler = () => () => { };
12340
+ this.platformStartedHandler = () => () => { };
12341
+ this.platformErrorHandler = () => () => { };
12342
+ this.workspaceLoadedHandler = () => () => { };
12343
+ this.workspaceRestoredHandler = () => () => { };
12344
+ this.workspaceSavedHandler = () => () => { };
12345
+ this.workspaceStoppedHandler = () => () => { };
12346
+ this.workspaceSelectedHandler = () => () => { };
12347
+ this.workspaceStartedHandler = () => () => { };
12348
+ this.workspaceFrameCreatedHandler = () => () => { };
12349
+ this.workspaceFrameInitHandler = () => () => { };
12350
+ this.workspaceFramePageLoadHandler = () => () => { };
12351
+ this.workspaceFrameWorkspaceRenderHandler = () => () => { };
12352
+ this.workspaceComponentCreatedHandler = () => () => { };
12353
+ this.workspaceAppsStartedHandler = () => () => { };
12354
+ this.workspaceStartupHandler = () => () => { };
12355
+ }
12356
+ build() {
12357
+ const container = {
12358
+ performanceProvider: this.performanceProvider,
12359
+ instanceStartedHandler: this.instanceStartedHandler,
12360
+ instanceStoppedHandler: this.instanceStoppedHandler,
12361
+ instanceReadyHandler: this.instanceReadyHandler,
12362
+ instanceFocusedHandler: this.instanceFocusedHandler,
12363
+ instanceErrorHandler: this.instanceErrorHandler,
12364
+ instanceCrashHandler: this.instanceCrashHandler,
12365
+ layoutRestoredHandler: this.layoutRestoredHandler,
12366
+ platformStartedHandler: this.platformStartedHandler,
12367
+ platformErrorHandler: this.platformErrorHandler,
12368
+ workspaceLoadedHandler: this.workspaceLoadedHandler,
12369
+ workspaceSavedHandler: this.workspaceSavedHandler,
12370
+ workspaceStoppedHandler: this.workspaceStoppedHandler,
12371
+ workspaceSelectedHandler: this.workspaceSelectedHandler,
12372
+ workspaceRestoredHandler: this.workspaceRestoredHandler,
12373
+ workspaceStartedHandler: this.workspaceStartedHandler,
12374
+ workspaceStartupHandler: this.workspaceStartupHandler,
12375
+ workspaceFrameCreatedHandler: this.workspaceFrameCreatedHandler,
12376
+ workspaceFrameInitHandler: this.workspaceFrameInitHandler,
12377
+ workspaceFramePageLoadHandler: this.workspaceFramePageLoadHandler,
12378
+ workspaceFrameWorkspaceRenderHandler: this.workspaceFrameWorkspaceRenderHandler,
12379
+ workspaceComponentCreatedHandler: this.workspaceComponentCreatedHandler,
12380
+ workspaceAppsStartedHandler: this.workspaceAppsStartedHandler,
12381
+ };
12382
+ return container;
12383
+ }
12384
+ withInstanceStartedHandler(instanceStartedHandler) {
12385
+ this.instanceStartedHandler = instanceStartedHandler;
12386
+ return this;
12387
+ }
12388
+ withInstanceStoppedHandler(instanceStoppedHandler) {
12389
+ this.instanceStoppedHandler = instanceStoppedHandler;
12390
+ return this;
12391
+ }
12392
+ withInstanceReadyHandler(instanceReadyHandler) {
12393
+ this.instanceReadyHandler = instanceReadyHandler;
12394
+ return this;
12395
+ }
12396
+ withInstanceFocusedHandler(instanceFocusedHandler) {
12397
+ this.instanceFocusedHandler = instanceFocusedHandler;
12398
+ return this;
12399
+ }
12400
+ withInstanceErrorHandler(instanceErrorHandler) {
12401
+ this.instanceErrorHandler = instanceErrorHandler;
12402
+ return this;
12403
+ }
12404
+ withInstanceCrashHandler(instanceCrashHandler) {
12405
+ this.instanceCrashHandler = instanceCrashHandler;
12406
+ return this;
12407
+ }
12408
+ withLayoutRestoredHandler(layoutRestoredHandler) {
12409
+ this.layoutRestoredHandler = layoutRestoredHandler;
12410
+ return this;
12411
+ }
12412
+ withWorkspaceLoadedHandler(workspaceLoadedHandler) {
12413
+ this.workspaceLoadedHandler = workspaceLoadedHandler;
12414
+ return this;
12415
+ }
12416
+ withWorkspaceSavedHandler(workspaceSavedHandler) {
12417
+ this.workspaceSavedHandler = workspaceSavedHandler;
12418
+ return this;
12419
+ }
12420
+ withWorkspaceStartedHandler(workspaceStartedHandler) {
12421
+ this.workspaceRestoredHandler = () => () => { };
12422
+ this.workspaceStartedHandler = workspaceStartedHandler;
12423
+ return this;
12424
+ }
12425
+ withWorkspaceStoppedHandler(workspaceStoppedHandler) {
12426
+ this.workspaceStoppedHandler = workspaceStoppedHandler;
12427
+ return this;
12428
+ }
12429
+ withWorkspaceSelectedHandler(workspaceSelectedHandler) {
12430
+ this.workspaceSelectedHandler = workspaceSelectedHandler;
12431
+ return this;
12432
+ }
12433
+ withPlatformStartedHandler(platformStartedHandler) {
12434
+ this.platformStartedHandler = platformStartedHandler;
12435
+ return this;
12436
+ }
12437
+ withPlatformErrorHandler(platformErrorHandler) {
12438
+ this.platformErrorHandler = platformErrorHandler;
12439
+ return this;
12440
+ }
12441
+ withPerfProvider(perfProvider) {
12442
+ this.performanceProvider = perfProvider;
12443
+ return this;
12444
+ }
12445
+ withWorkspaceRestoredHandler(workspaceRestoredHandler) {
12446
+ this.workspaceRestoredHandler = workspaceRestoredHandler;
12447
+ this.workspaceStartedHandler = () => () => { };
12448
+ return this;
12449
+ }
12450
+ withWorkspaceStartupHandler(workspaceStartupHandler) {
12451
+ this.workspaceStartupHandler = workspaceStartupHandler;
12452
+ return this;
12453
+ }
12454
+ withWorkspaceFrameCreatedHandler(workspaceFrameCreatedHandler) {
12455
+ this.workspaceFrameCreatedHandler = workspaceFrameCreatedHandler;
12456
+ return this;
12457
+ }
12458
+ withWorkspaceFrameInitHandler(workspaceFrameInitHandler) {
12459
+ this.workspaceFrameInitHandler = workspaceFrameInitHandler;
12460
+ return this;
12461
+ }
12462
+ withWorkspaceFramePageLoadHandler(workspaceFramePageLoadHandler) {
12463
+ this.workspaceFramePageLoadHandler = workspaceFramePageLoadHandler;
12464
+ return this;
12465
+ }
12466
+ withWorkspaceFrameWorkspaceRenderHandler(workspaceFrameWorkspaceRenderHandler) {
12467
+ this.workspaceFrameWorkspaceRenderHandler = workspaceFrameWorkspaceRenderHandler;
12468
+ return this;
12469
+ }
12470
+ withWorkspaceComponentCreatedHandler(workspaceComponentCreatedHandler) {
12471
+ this.workspaceComponentCreatedHandler = workspaceComponentCreatedHandler;
12472
+ return this;
12473
+ }
12474
+ withWorkspaceAppsStartedHandler(workspaceAppsStartedHandler) {
12475
+ this.workspaceAppsStartedHandler = workspaceAppsStartedHandler;
12476
+ return this;
12477
+ }
12478
+ }
12479
+ metricsDependencyBuilder.MetricsDependencyBuilder = MetricsDependencyBuilder;
12480
+
12481
+ var logs = {};
12482
+
12483
+ Object.defineProperty(logs, "__esModule", { value: true });
12484
+ logs.Logs = void 0;
12485
+ const nullManager_1 = nullManager;
12486
+ class Logs {
12487
+ static get instance() {
12488
+ var _a, _b;
12489
+ if ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _a === void 0 ? void 0 : _a.logs) {
12490
+ return (_b = globalThis === null || globalThis === void 0 ? void 0 : globalThis.ioInsightsInternals) === null || _b === void 0 ? void 0 : _b.logs;
12491
+ }
12492
+ if (!Logs._instance) {
12493
+ Logs._instance = new nullManager_1.NullLogsManager(undefined, undefined, undefined);
12494
+ }
12495
+ return Logs._instance;
12496
+ }
12497
+ static set instance(value) {
12498
+ Logs._instance = value;
12499
+ }
12500
+ static emit(record) {
12501
+ return Logs.instance.emit(record);
12502
+ }
12503
+ }
12504
+ logs.Logs = Logs;
12505
+
12506
+ var pluginLoader = {};
12507
+
12508
+ Object.defineProperty(pluginLoader, "__esModule", { value: true });
12509
+ pluginLoader.registerInsightsPlugin = pluginLoader.loadInsightsPlugin = void 0;
12510
+ const returnedPlugins = new Map();
12511
+ function loadInsightsPlugin(name, logger) {
12512
+ if (returnedPlugins.get(name) !== undefined) {
12513
+ return returnedPlugins.get(name);
12514
+ }
12515
+ if (typeof globalThis.ioInsightsPlugins === "undefined") {
12516
+ return null;
12517
+ }
12518
+ let plugin = globalThis.ioInsightsPlugins[name];
12519
+ if (!plugin) {
12520
+ return null;
12521
+ }
12522
+ if (typeof plugin === "function") {
12523
+ try {
12524
+ plugin = plugin();
12525
+ }
12526
+ catch (err) {
12527
+ logger === null || logger === void 0 ? void 0 : logger.error(`Error loading io.Insights plugin ${name}`, err);
12528
+ returnedPlugins.set(name, null);
12529
+ return null;
12530
+ }
12531
+ }
12532
+ returnedPlugins.set(name, plugin);
12533
+ return plugin;
12534
+ }
12535
+ pluginLoader.loadInsightsPlugin = loadInsightsPlugin;
12536
+ function registerInsightsPlugin(name, pluginOrFactoryFunc) {
12537
+ if (typeof globalThis.ioInsightsPlugins === "undefined") {
12538
+ globalThis.ioInsightsPlugins = {};
12539
+ }
12540
+ globalThis.ioInsightsPlugins[name] = pluginOrFactoryFunc;
12541
+ }
12542
+ pluginLoader.registerInsightsPlugin = registerInsightsPlugin;
12543
+
12544
+ var isNode$1 = {};
12545
+
12546
+ Object.defineProperty(isNode$1, "__esModule", { value: true });
12547
+ isNode$1.isNode = void 0;
12548
+ let _isNode;
12549
+ function isNode() {
12550
+ if (typeof _isNode !== "undefined") {
12551
+ return _isNode;
12552
+ }
12553
+ if (typeof window !== "undefined") {
12554
+ _isNode = false;
12555
+ return false;
12556
+ }
12557
+ // Only Node.JS has a process variable that is of [[Class]] process
12558
+ try {
12559
+ _isNode = Object.prototype.toString.call(commonjsGlobal.process) === "[object process]";
12560
+ }
12561
+ catch (e) {
12562
+ _isNode = false;
12563
+ }
12564
+ return _isNode;
12565
+ }
12566
+ isNode$1.isNode = isNode;
12567
+
12568
+ var hasRequiredDist;
12569
+
12570
+ function requireDist () {
12571
+ if (hasRequiredDist) return dist;
12572
+ hasRequiredDist = 1;
12573
+ (function (exports$1) {
12574
+ var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
12575
+ if (k2 === undefined) k2 = k;
12576
+ var desc = Object.getOwnPropertyDescriptor(m, k);
12577
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
12578
+ desc = { enumerable: true, get: function() { return m[k]; } };
12579
+ }
12580
+ Object.defineProperty(o, k2, desc);
12581
+ }) : (function(o, m, k, k2) {
12582
+ if (k2 === undefined) k2 = k;
12583
+ o[k2] = m[k];
12584
+ }));
12585
+ var __setModuleDefault = (commonjsGlobal && commonjsGlobal.__setModuleDefault) || (Object.create ? (function(o, v) {
12586
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
12587
+ }) : function(o, v) {
12588
+ o["default"] = v;
12589
+ });
12590
+ var __importStar = (commonjsGlobal && commonjsGlobal.__importStar) || function (mod) {
12591
+ if (mod && mod.__esModule) return mod;
12592
+ var result = {};
12593
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
12594
+ __setModuleDefault(result, mod);
12595
+ return result;
12596
+ };
12597
+ var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
12598
+ return (mod && mod.__esModule) ? mod : { "default": mod };
12599
+ };
12600
+ Object.defineProperty(exports$1, "__esModule", { value: true });
12601
+ exports$1.SpanStatusCode = exports$1.deep_value = exports$1.extractFilteringContextFromArgs = exports$1.getOTELData = exports$1.flattenOtelAtributes = exports$1.safeStringify = exports$1.isNode = exports$1.loadInsightsPlugin = exports$1.registerInsightsPlugin = exports$1.Logs = exports$1.NullTracingState = exports$1.OTEL_PI_KEY = exports$1.withSpan = exports$1.Traces = exports$1.MetricsDependencyBuilder = exports$1.NullMetric = exports$1.Container = exports$1.Log4jsWrapper = exports$1.Builder = void 0;
12602
+ var builder_1 = requireBuilder();
12603
+ Object.defineProperty(exports$1, "Builder", { enumerable: true, get: function () { return builder_1.Builder; } });
12604
+ var log4jsWrapper_1 = log4jsWrapper;
12605
+ Object.defineProperty(exports$1, "Log4jsWrapper", { enumerable: true, get: function () { return log4jsWrapper_1.Log4jsWrapper; } });
12606
+ var container_1 = container;
12607
+ Object.defineProperty(exports$1, "Container", { enumerable: true, get: function () { return container_1.Container; } });
12608
+ var null_1 = _null$1;
12609
+ Object.defineProperty(exports$1, "NullMetric", { enumerable: true, get: function () { return null_1.NullMetric; } });
12610
+ var metricsDependencyBuilder_1 = metricsDependencyBuilder;
12611
+ Object.defineProperty(exports$1, "MetricsDependencyBuilder", { enumerable: true, get: function () { return metricsDependencyBuilder_1.MetricsDependencyBuilder; } });
12612
+ const traces_1 = __importStar(requireTraces());
12613
+ exports$1.Traces = traces_1.default;
12614
+ Object.defineProperty(exports$1, "withSpan", { enumerable: true, get: function () { return traces_1.withSpan; } });
12615
+ exports$1.OTEL_PI_KEY = "__interopIOTracePropagationInfo";
12616
+ const nullTracingState_1 = __importDefault(nullTracingState);
12617
+ exports$1.NullTracingState = nullTracingState_1.default;
12618
+ var logs_1 = logs;
12619
+ Object.defineProperty(exports$1, "Logs", { enumerable: true, get: function () { return logs_1.Logs; } });
12620
+ const pluginLoader_1 = pluginLoader;
12621
+ Object.defineProperty(exports$1, "registerInsightsPlugin", { enumerable: true, get: function () { return pluginLoader_1.registerInsightsPlugin; } });
12622
+ Object.defineProperty(exports$1, "loadInsightsPlugin", { enumerable: true, get: function () { return pluginLoader_1.loadInsightsPlugin; } });
12623
+ const isNode_1 = isNode$1;
12624
+ Object.defineProperty(exports$1, "isNode", { enumerable: true, get: function () { return isNode_1.isNode; } });
12625
+ const safe_stringify_1 = safeStringify$1;
12626
+ Object.defineProperty(exports$1, "safeStringify", { enumerable: true, get: function () { return safe_stringify_1.safeStringify; } });
12627
+ const otelUtils_1 = otelUtils;
12628
+ Object.defineProperty(exports$1, "getOTELData", { enumerable: true, get: function () { return otelUtils_1.getOTELData; } });
12629
+ Object.defineProperty(exports$1, "flattenOtelAtributes", { enumerable: true, get: function () { return otelUtils_1.flattenOtelAtributes; } });
12630
+ Object.defineProperty(exports$1, "extractFilteringContextFromArgs", { enumerable: true, get: function () { return otelUtils_1.extractFilteringContextFromArgs; } });
12631
+ Object.defineProperty(exports$1, "deep_value", { enumerable: true, get: function () { return otelUtils_1.deep_value; } });
12632
+ if (typeof Promise !== "undefined") {
12633
+ Promise.allSettled = Promise.allSettled || ((promises) => Promise.all(promises.map((p) => p
12634
+ .then((value) => ({
12635
+ status: "fulfilled",
12636
+ value
12637
+ }))
12638
+ .catch((reason) => ({
12639
+ status: "rejected",
12640
+ reason
12641
+ })))));
12642
+ }
12643
+ var SpanStatusCode;
12644
+ (function (SpanStatusCode) {
12645
+ /**
12646
+ * The default status.
12647
+ */
12648
+ SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET";
12649
+ /**
12650
+ * The operation has been validated by an Application developer or
12651
+ * Operator to have completed successfully.
12652
+ */
12653
+ SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK";
12654
+ /**
12655
+ * The operation contains an error.
12656
+ */
12657
+ SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR";
12658
+ })(SpanStatusCode || (SpanStatusCode = {}));
12659
+ exports$1.SpanStatusCode = SpanStatusCode;
12660
+
12661
+ } (dist));
12662
+ return dist;
12663
+ }
12664
+
12665
+ var distExports = requireDist();
12666
+
12667
+ function setInsightsAttributes(settings, ext, glue42gd, nodeStartingContext) {
12668
+ let applicationName = settings.applicationName ?? "unknown-app";
12669
+ if (glue42gd) {
12670
+ applicationName = settings.applicationName ?? glue42gd?.appName ?? applicationName;
12671
+ }
12672
+ if (nodeStartingContext) {
12673
+ applicationName = settings.applicationName ?? nodeStartingContext.applicationConfig.name ?? applicationName;
12674
+ }
12675
+ settings.applicationName = applicationName;
12676
+ if (settings.traces?.closeTrace) {
12677
+ glue42gd?.addCloseHandler(() => distExports.Traces.withSpan("interopio.api.application.close", () => { }));
12678
+ }
12679
+ const sid = glue42gd?.sid;
12680
+ const user = glue42gd?.user;
12681
+ const osUser = (Utils.isNode() && process?.env?.USERNAME) ?? glue42gd?.env?.windowsUserName;
12682
+ const machine = (Utils.isNode() && process?.env?.COMPUTERNAME) ?? glue42gd?.env?.machineName;
12683
+ const env = nodeStartingContext?.env ?? glue42gd?.env?.env;
12684
+ const region = nodeStartingContext?.region ?? glue42gd?.env?.region;
12685
+ const appInstanceId = nodeStartingContext?.instanceId ?? glue42gd?.appInstanceId ?? "";
12686
+ const windowId = glue42gd?.windowId;
12687
+ const extraInsightsContext = {
12688
+ interopioCoreVersion: version,
12689
+ interopioLibVersion: ext.version || version,
12690
+ host: "io.api",
12691
+ tracingAppName: applicationName,
12692
+ tracingAppInstanceId: appInstanceId,
12693
+ user,
12694
+ osUser,
12695
+ machine,
12696
+ env,
12697
+ region,
12698
+ windowId,
12699
+ sid
12700
+ };
12701
+ let providedAdditionalResourceAttributesFunc = settings.additionalResourceAttributes;
12702
+ if (typeof providedAdditionalResourceAttributesFunc !== "function") {
12703
+ const providedAdditionalResourceAttributes = settings.additionalResourceAttributes;
12704
+ providedAdditionalResourceAttributesFunc = () => providedAdditionalResourceAttributes;
12705
+ }
12706
+ settings.additionalResourceAttributes = () => ({
12707
+ ...extraInsightsContext,
12708
+ ...providedAdditionalResourceAttributesFunc(),
12709
+ });
12710
+ }
12711
+ function setDefaultTraceFilters(settings) {
12712
+ if (!settings.traces) {
12713
+ return;
12714
+ }
12715
+ settings.traces.defaultFilters ??= [];
12716
+ settings.traces.defaultFilters.push({
12717
+ "source": "interopio.api.instrumentation.fetch",
12718
+ "canBeRoot": false
12719
+ });
12720
+ settings.traces.defaultFilters.push({
12721
+ "source": "interopio.api.instrumentation.xhr",
12722
+ "canBeRoot": false
12723
+ });
12724
+ settings.traces.defaultFilters.push({
12725
+ "source": "interopio.api.prefs",
12726
+ "canBeRoot": false
12727
+ });
12728
+ settings.traces.defaultFilters.push({
12729
+ "source": "interopio.api.layouts",
12730
+ "canBeRoot": false
12731
+ });
12732
+ settings.traces.defaultFilters.push({
12733
+ "source": "interopio.api.windows",
12734
+ "canBeRoot": false
12735
+ });
12736
+ settings.traces.defaultFilters.push({
12737
+ "source": "interopio.api.interop",
12738
+ "context": {
12739
+ "stream": "#^t42[.].*"
12740
+ },
12741
+ "canBeRoot": false,
12742
+ "enabled": false
12743
+ });
12744
+ settings.traces.defaultFilters.push({
12745
+ "source": "interopio.api.interop",
12746
+ "context": {
12747
+ "stream": "apps.event"
12748
+ },
12749
+ "canBeRoot": false,
12750
+ "enabled": false
12751
+ });
12752
+ settings.traces.defaultFilters.push({
12753
+ "source": "interopio.api.interop",
12754
+ "context": {
12755
+ "name": "#^t42[.].*"
12756
+ },
12757
+ "canBeRoot": false,
12758
+ "enabled": false
12759
+ });
12760
+ settings.traces.defaultFilters.push({
12761
+ "source": "interopio.api.interop",
12762
+ "context": {
12763
+ "name": "apps.event"
12764
+ },
12765
+ "canBeRoot": false,
12766
+ "enabled": false
12767
+ });
12768
+ settings.traces.defaultFilters.push({
12769
+ "source": "interopio.api.interop",
12770
+ "context": {
12771
+ "method": "apps.command"
12772
+ },
12773
+ "canBeRoot": false
12774
+ });
12775
+ settings.traces.defaultFilters.push({
12776
+ "source": "interopio.api.interop",
12777
+ "context": {
12778
+ "method": "#^t42[.].*"
12779
+ },
12780
+ "canBeRoot": false
12781
+ });
12782
+ settings.traces.defaultFilters.push({
12783
+ "source": "interopio.api.contexts",
12784
+ "context": {
12785
+ "context": "___insights_pi_storage___"
12786
+ },
12787
+ "enabled": false
12788
+ });
12789
+ settings.traces.defaultFilters.push({
12790
+ "source": "interopio.api.contexts",
12791
+ "context": {
12792
+ "context": "#^t42[.].*"
12793
+ },
12794
+ "canBeRoot": false
12795
+ });
12796
+ settings.traces.defaultFilters.push({
12797
+ "source": "interopio.api.contexts",
12798
+ "context": {
12799
+ "context": "#^__.*"
12800
+ },
12801
+ "canBeRoot": false
12802
+ });
12803
+ settings.traces.defaultFilters.push({
12804
+ "source": "interopio.api.appManager",
12805
+ "canBeRoot": false
12806
+ });
12807
+ settings.traces.defaultFilters.push({
12808
+ "source": "interopio.api.notifications",
12809
+ "canBeRoot": false
12810
+ });
12811
+ }
12812
+
12813
+ function prepareConfig (configuration, ext, glue42gd) {
12814
+ let nodeStartingContext;
12815
+ if (Utils.isNode()) {
12816
+ const startingContextString = process.env._GD_STARTING_CONTEXT_;
12817
+ if (startingContextString) {
12818
+ try {
12819
+ nodeStartingContext = JSON.parse(startingContextString);
12820
+ }
12821
+ catch {
12822
+ }
12823
+ }
12824
+ }
12825
+ function getConnection() {
12826
+ const gwConfig = configuration.gateway;
12827
+ const protocolVersion = gwConfig?.protocolVersion ?? 3;
12828
+ const reconnectInterval = gwConfig?.reconnectInterval;
12829
+ const reconnectAttempts = gwConfig?.reconnectAttempts;
12830
+ const defaultWs = "ws://localhost:8385";
12831
+ let ws = gwConfig?.ws;
12832
+ const sharedWorker = gwConfig?.sharedWorker;
12833
+ const inproc = gwConfig?.inproc;
12834
+ const webPlatform = gwConfig?.webPlatform ?? undefined;
12835
+ if (glue42gd) {
12836
+ ws = glue42gd.gwURL;
12837
+ }
12838
+ if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwURL) {
12839
+ ws = nodeStartingContext.gwURL;
12840
+ }
12841
+ if (!ws && !sharedWorker && !inproc) {
12842
+ ws = defaultWs;
12843
+ }
12844
+ let instanceId;
12845
+ let windowId;
12846
+ let pid;
12847
+ let environment;
12848
+ let region;
12849
+ const appName = getApplication();
12850
+ let uniqueAppName = appName;
12851
+ if (typeof glue42gd !== "undefined") {
12852
+ windowId = glue42gd.windowId;
12853
+ pid = glue42gd.pid;
12854
+ if (glue42gd.env) {
12855
+ environment = glue42gd.env.env;
12856
+ region = glue42gd.env.region;
12857
+ }
12858
+ uniqueAppName = glue42gd.application ?? "glue-app";
12859
+ instanceId = glue42gd.appInstanceId;
12860
+ }
12861
+ else if (Utils.isNode()) {
12862
+ pid = process.pid;
12863
+ if (nodeStartingContext) {
12864
+ environment = nodeStartingContext.env;
12865
+ region = nodeStartingContext.region;
12866
+ instanceId = nodeStartingContext.instanceId;
12867
+ }
12868
+ }
12869
+ else if (typeof window?.glue42electron !== "undefined") {
12870
+ windowId = window?.glue42electron.instanceId;
12871
+ pid = window?.glue42electron.pid;
12872
+ environment = window?.glue42electron.env;
12873
+ region = window?.glue42electron.region;
12874
+ uniqueAppName = window?.glue42electron.application ?? "glue-app";
12875
+ instanceId = window?.glue42electron.instanceId;
12876
+ }
12877
+ else ;
12878
+ const replaySpecs = configuration.gateway?.replaySpecs ?? [];
12879
+ replaySpecs.push(ContextMessageReplaySpec);
12880
+ let identity = {
12881
+ application: uniqueAppName,
12882
+ applicationName: appName,
12883
+ windowId,
12884
+ instance: instanceId,
12885
+ process: pid,
12886
+ region,
12887
+ environment,
12888
+ api: ext.version || version
12889
+ };
12890
+ if (configuration.identity) {
12891
+ identity = Object.assign(identity, configuration.identity);
12892
+ }
12893
+ return {
12894
+ identity,
12895
+ reconnectInterval,
12896
+ ws,
12897
+ sharedWorker,
12898
+ webPlatform,
12899
+ inproc,
12900
+ protocolVersion,
12901
+ reconnectAttempts,
12902
+ replaySpecs,
12903
+ };
12904
+ }
12905
+ function getContexts() {
12906
+ const defaultConfig = {
12907
+ reAnnounceKnownContexts: true,
12908
+ subscribeOnUpdate: true,
12909
+ subscribeOnGet: true,
12910
+ onlyReAnnounceSubscribedContexts: true
12911
+ };
12912
+ if (typeof configuration.contexts === "undefined") {
12913
+ return defaultConfig;
12914
+ }
12915
+ if (typeof configuration.contexts === "boolean" && configuration.contexts) {
12916
+ return defaultConfig;
12917
+ }
12918
+ if (typeof configuration.contexts === "object") {
12919
+ return { ...defaultConfig, ...configuration.contexts };
12920
+ }
12921
+ return false;
12922
+ }
12923
+ function getApplication() {
12924
+ if (configuration.application) {
12925
+ return configuration.application;
12926
+ }
12927
+ if (glue42gd) {
12928
+ return glue42gd.applicationName;
12929
+ }
12930
+ if (typeof window !== "undefined" && typeof window.glue42electron !== "undefined") {
12931
+ return window.glue42electron.application;
12932
+ }
12933
+ const uid = nanoid(10);
12934
+ if (Utils.isNode()) {
12935
+ if (nodeStartingContext) {
12936
+ return nodeStartingContext.applicationConfig.name;
12937
+ }
12938
+ return "NodeJS" + uid;
12939
+ }
12940
+ if (typeof window !== "undefined" && typeof document !== "undefined") {
12941
+ return document.title + ` (${uid})`;
12942
+ }
12943
+ return uid;
12944
+ }
12945
+ async function getInsights(iodesktop, interop, logger) {
12946
+ const configProp = configuration.insights;
12947
+ if (typeof configProp !== "object" && typeof configProp !== "boolean" && typeof configProp !== "undefined") {
12948
+ throw new Error("insights/otel property should be boolean, object or unspecified");
12949
+ }
12950
+ if (configProp === false) {
12951
+ return { enabled: false };
12952
+ }
12953
+ let gdConfig;
12954
+ if (iodesktop) {
12955
+ gdConfig = iodesktop.insights;
12956
+ }
12957
+ else if (Utils.isNode() && (configuration?.insights !== false &&
12958
+ configuration?.insights?.enabled !== false &&
12959
+ configuration?.insights?.requestSettings !== false)) {
12960
+ gdConfig = (await interop?.invoke("T42.Otel.GetConfig", undefined, nodeStartingContext ? { environment: nodeStartingContext.env, region: nodeStartingContext.region } : undefined, { waitTimeoutMs: 0 })
12961
+ .then(result => result.returned)
12962
+ .catch(err => logger?.warn("Unable to retrieve base io.Insights settings: " +
12963
+ (err?.message ?? err))));
12964
+ }
12965
+ if (gdConfig &&
12966
+ (iodesktop ||
12967
+ nodeStartingContext ||
12968
+ (Utils.isNode() && (typeof configProp === "boolean" || !configProp?.platformInstance)))) {
12969
+ gdConfig = {
12970
+ ...gdConfig,
12971
+ metrics: {
12972
+ ...gdConfig?.metrics,
12973
+ enabled: !!gdConfig?.metrics?.enabled,
12974
+ platformMetricsEnabled: false
12975
+ }
12976
+ };
12977
+ }
12978
+ let settings;
12979
+ if (configProp === true || typeof configProp === "undefined") {
12980
+ settings = gdConfig ?? { enabled: false };
12981
+ }
12982
+ else {
12983
+ settings = deepMerge(gdConfig || {}, configProp, { isMergeableObject: isPlainObject$2 });
12984
+ }
12985
+ setInsightsAttributes(settings, ext, glue42gd, nodeStartingContext);
12986
+ if (settings.traces?.enabled) {
12987
+ setDefaultTraceFilters(settings);
12988
+ }
12989
+ return settings;
12990
+ }
12991
+ function getAuth() {
12992
+ if (typeof configuration.auth === "string") {
12993
+ return {
12994
+ token: configuration.auth
12995
+ };
12996
+ }
12997
+ if (configuration.auth) {
12998
+ return configuration.auth;
12999
+ }
13000
+ if (Utils.isNode() && nodeStartingContext && nodeStartingContext.gwToken) {
13001
+ return {
13002
+ gatewayToken: nodeStartingContext.gwToken
13003
+ };
13004
+ }
13005
+ if (configuration.gateway?.webPlatform) {
13006
+ return {
13007
+ username: "glue42",
13008
+ password: ""
13009
+ };
13010
+ }
13011
+ }
13012
+ function getLogger() {
13013
+ let config = configuration.logger;
13014
+ const defaultLevel = "warn";
13015
+ if (!config) {
13016
+ config = defaultLevel;
13017
+ }
13018
+ let gdConsoleLevel;
13019
+ if (glue42gd) {
13020
+ gdConsoleLevel = glue42gd.consoleLogLevel;
13021
+ }
13022
+ if (typeof config === "string") {
13023
+ return { console: gdConsoleLevel ?? config, publish: defaultLevel };
13024
+ }
13025
+ return {
13026
+ console: gdConsoleLevel ?? config.console ?? defaultLevel,
13027
+ publish: config.publish ?? defaultLevel
13028
+ };
13029
+ }
13030
+ const connection = getConnection();
13031
+ let application = getApplication();
13032
+ if (typeof window !== "undefined") {
13033
+ const windowAsAny = window;
13034
+ const containerApplication = windowAsAny.htmlContainer ?
13035
+ `${windowAsAny.htmlContainer.containerName}.${windowAsAny.htmlContainer.application}` :
13036
+ windowAsAny?.glue42gd?.application;
10988
13037
  if (containerApplication) {
10989
13038
  application = containerApplication;
10990
13039
  }
@@ -10999,10 +13048,40 @@
10999
13048
  contexts: getContexts(),
11000
13049
  version: ext.version || version,
11001
13050
  libs: ext.libs ?? [],
11002
- customLogger: configuration.customLogger
13051
+ customLogger: configuration.customLogger,
13052
+ getInsights
11003
13053
  };
11004
13054
  }
11005
13055
 
13056
+ /******************************************************************************
13057
+ Copyright (c) Microsoft Corporation.
13058
+
13059
+ Permission to use, copy, modify, and/or distribute this software for any
13060
+ purpose with or without fee is hereby granted.
13061
+
13062
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
13063
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13064
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
13065
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13066
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13067
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13068
+ PERFORMANCE OF THIS SOFTWARE.
13069
+ ***************************************************************************** */
13070
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
13071
+
13072
+
13073
+ function __decorate(decorators, target, key, desc) {
13074
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
13075
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
13076
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
13077
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
13078
+ }
13079
+
13080
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
13081
+ var e = new Error(message);
13082
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
13083
+ };
13084
+
11006
13085
  class GW3ContextData {
11007
13086
  name;
11008
13087
  contextId;
@@ -11065,7 +13144,7 @@
11065
13144
  */
11066
13145
  lodash_clonedeep.exports;
11067
13146
 
11068
- (function (module, exports) {
13147
+ (function (module, exports$1) {
11069
13148
  /** Used as the size to enable large array optimizations. */
11070
13149
  var LARGE_ARRAY_SIZE = 200;
11071
13150
 
@@ -11146,7 +13225,7 @@
11146
13225
  var root = freeGlobal || freeSelf || Function('return this')();
11147
13226
 
11148
13227
  /** Detect free variable `exports`. */
11149
- var freeExports = exports && !exports.nodeType && exports;
13228
+ var freeExports = exports$1 && !exports$1.nodeType && exports$1;
11150
13229
 
11151
13230
  /** Detect free variable `module`. */
11152
13231
  var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module;
@@ -12846,6 +14925,7 @@
12846
14925
  delete context[key];
12847
14926
  });
12848
14927
  }
14928
+ distExports.Traces.removePropagationInfo(context);
12849
14929
  return context;
12850
14930
  }
12851
14931
  catch (e) {
@@ -13052,6 +15132,11 @@
13052
15132
  if (name in this._creationPromises) {
13053
15133
  return this._creationPromises[name];
13054
15134
  }
15135
+ const ts = distExports.Traces.currentTracingState;
15136
+ ts.addData("INFO", { context: name });
15137
+ ts.addData("DIAGNOSTIC", { data });
15138
+ data = deepClone(data);
15139
+ ts.injectPropagationInfo(data);
13055
15140
  this._creationPromises[name] =
13056
15141
  this._gw3Session
13057
15142
  .send({
@@ -13087,15 +15172,21 @@
13087
15172
  if (delta) {
13088
15173
  delta = deepClone(delta);
13089
15174
  }
15175
+ const ts = distExports.Traces.currentTracingState;
13090
15176
  if (name in this._creationPromises) {
13091
15177
  await this._creationPromises[name];
15178
+ distExports.Traces.currentTracingState = ts;
13092
15179
  }
13093
15180
  const contextData = this._contextNameToData[name];
15181
+ ts.addData("DIAGNOSTIC", { data: contextData });
15182
+ ts.addData("DEBUG", { delta });
13094
15183
  if (!contextData || !contextData.isAnnounced) {
13095
15184
  await this.createContext(name, delta);
13096
15185
  return;
13097
15186
  }
13098
15187
  const currentContext = await this.get(contextData.name);
15188
+ distExports.Traces.currentTracingState = ts;
15189
+ distExports.Traces.removePropagationInfo(currentContext);
13099
15190
  const calculatedDelta = this.setPathSupported ?
13100
15191
  this.calculateContextDeltaV2(currentContext, delta) :
13101
15192
  this.calculateContextDeltaV1(currentContext, delta);
@@ -13105,13 +15196,16 @@
13105
15196
  && !calculatedDelta.commands?.length) {
13106
15197
  return Promise.resolve();
13107
15198
  }
15199
+ const calculatedDeltaWithPropagationInfo = deepClone(calculatedDelta);
15200
+ ts.injectPropagationInfo(calculatedDeltaWithPropagationInfo);
13108
15201
  const gwResponse = await this._gw3Session
13109
15202
  .send({
13110
15203
  type: GW_MESSAGE_UPDATE_CONTEXT,
13111
15204
  domain: "global",
13112
15205
  context_id: contextData.contextId,
13113
- delta: calculatedDelta,
15206
+ delta: calculatedDeltaWithPropagationInfo,
13114
15207
  }, {}, { skipPeerId: false });
15208
+ distExports.Traces.currentTracingState = ts;
13115
15209
  if (this._subscribeOnUpdate &&
13116
15210
  !contextData.sentExplicitSubscription &&
13117
15211
  !contextData.activityId) {
@@ -13121,6 +15215,7 @@
13121
15215
  contextData.sentExplicitSubscription ||
13122
15216
  contextData.activityId) {
13123
15217
  await contextData.snapshotPromise;
15218
+ distExports.Traces.currentTracingState = ts;
13124
15219
  this.handleUpdated(contextData, calculatedDelta, {
13125
15220
  updaterId: gwResponse.peer_id
13126
15221
  });
@@ -13130,10 +15225,14 @@
13130
15225
  if (data) {
13131
15226
  data = deepClone(data);
13132
15227
  }
15228
+ const ts = distExports.Traces.currentTracingState;
13133
15229
  if (name in this._creationPromises) {
13134
15230
  await this._creationPromises[name];
15231
+ distExports.Traces.currentTracingState = ts;
13135
15232
  }
13136
15233
  const contextData = this._contextNameToData[name];
15234
+ ts.addData("DIAGNOSTIC", { data: contextData });
15235
+ ts.injectPropagationInfo(data);
13137
15236
  if (!contextData || !contextData.isAnnounced) {
13138
15237
  return this.createContext(name, data);
13139
15238
  }
@@ -13144,6 +15243,7 @@
13144
15243
  context_id: contextData.contextId,
13145
15244
  delta: { reset: data },
13146
15245
  }, {}, { skipPeerId: false });
15246
+ distExports.Traces.currentTracingState = ts;
13147
15247
  if (this._subscribeOnUpdate &&
13148
15248
  !contextData.sentExplicitSubscription &&
13149
15249
  !contextData.activityId) {
@@ -13164,21 +15264,30 @@
13164
15264
  }
13165
15265
  setPath(name, path, value) {
13166
15266
  if (!this.setPathSupported) {
13167
- return Promise.reject("glue.contexts.setPath operation is not supported, use Glue42 3.10 or later");
15267
+ return Promise.reject(new Error("contexts.setPath operation is not supported, use version 3.10 or later"));
13168
15268
  }
13169
15269
  return this.setPaths(name, [{ path, value }]);
13170
15270
  }
13171
15271
  async setPaths(name, pathValues) {
13172
15272
  if (!this.setPathSupported) {
13173
- return Promise.reject("glue.contexts.setPaths operation is not supported, use Glue42 3.10 or later");
15273
+ return Promise.reject(new Error("contexts.setPaths operation is not supported, use version 3.10 or later"));
13174
15274
  }
13175
15275
  if (pathValues) {
13176
15276
  pathValues = deepClone(pathValues);
13177
15277
  }
15278
+ const ts = distExports.Traces.currentTracingState;
13178
15279
  if (name in this._creationPromises) {
13179
15280
  await this._creationPromises[name];
15281
+ distExports.Traces.currentTracingState = ts;
13180
15282
  }
13181
15283
  const contextData = this._contextNameToData[name];
15284
+ ts.addData("DIAGNOSTIC", { data: contextData });
15285
+ ts.addData("DEBUG", { pathValues });
15286
+ const injectionCarrier = { [distExports.OTEL_PI_KEY]: undefined };
15287
+ ts.injectPropagationInfo(injectionCarrier);
15288
+ if (injectionCarrier[distExports.OTEL_PI_KEY]) {
15289
+ pathValues.push({ path: distExports.OTEL_PI_KEY, value: injectionCarrier[distExports.OTEL_PI_KEY] });
15290
+ }
13182
15291
  if (!contextData || !contextData.isAnnounced) {
13183
15292
  const obj = {};
13184
15293
  for (const pathValue of pathValues) {
@@ -13202,6 +15311,7 @@
13202
15311
  context_id: contextData.contextId,
13203
15312
  delta: { commands }
13204
15313
  }, {}, { skipPeerId: false });
15314
+ distExports.Traces.currentTracingState = ts;
13205
15315
  if (this._subscribeOnUpdate &&
13206
15316
  !contextData.sentExplicitSubscription &&
13207
15317
  !contextData.activityId) {
@@ -13211,6 +15321,7 @@
13211
15321
  contextData.sentExplicitSubscription ||
13212
15322
  contextData.activityId) {
13213
15323
  await contextData.snapshotPromise;
15324
+ distExports.Traces.currentTracingState = ts;
13214
15325
  this.handleUpdated(contextData, {
13215
15326
  added: {},
13216
15327
  removed: [],
@@ -13222,19 +15333,23 @@
13222
15333
  }
13223
15334
  }
13224
15335
  async get(name) {
15336
+ const ts = distExports.Traces.currentTracingState;
15337
+ ts.addData("INFO", { context: name });
13225
15338
  if (name in this._creationPromises) {
13226
15339
  await this._creationPromises[name];
15340
+ distExports.Traces.currentTracingState = ts;
13227
15341
  }
13228
15342
  const contextData = this._contextNameToData[name];
13229
15343
  if (!contextData || !contextData.isAnnounced) {
13230
15344
  if (!contextData && this._subscribeOnGet) {
13231
- this.subscribe(name, () => { });
15345
+ this.subscribeInner(name, () => { });
13232
15346
  }
13233
15347
  return Promise.resolve({});
13234
15348
  }
13235
15349
  if (contextData && !contextData.sentExplicitSubscription) {
13236
15350
  return new Promise((resolve, reject) => {
13237
- this.subscribe(name, (data, _d, _r, un) => {
15351
+ this.subscribeInner(name, (data, _d, _r, un) => {
15352
+ distExports.Traces.removePropagationInfo(data);
13238
15353
  if (!this._subscribeOnGet) {
13239
15354
  this.unsubscribe(un);
13240
15355
  }
@@ -13250,15 +15365,18 @@
13250
15365
  }
13251
15366
  await contextData.snapshotPromise;
13252
15367
  const context = contextData?.context ?? {};
15368
+ distExports.Traces.removePropagationInfo(context);
13253
15369
  return Promise.resolve(deepClone(context));
13254
15370
  }
13255
15371
  isInvalidContextError(e) {
13256
15372
  return e.reason_uri === this.ERROR_URI_INVALID_CONTEXT
13257
15373
  || (e.reason_uri === this.ERROR_URI_FAILURE && e.reason?.startsWith("Unable to find context with id"));
13258
15374
  }
13259
- async subscribe(name, callback, subscriptionKey) {
15375
+ async subscribeInner(name, callback, subscriptionKey) {
15376
+ const ts = distExports.Traces.currentTracingState;
13260
15377
  if (name in this._creationPromises) {
13261
15378
  await this._creationPromises[name];
15379
+ distExports.Traces.currentTracingState = ts;
13262
15380
  }
13263
15381
  const thisCallbackSubscriptionNumber = typeof subscriptionKey === "undefined" ? this._nextCallbackSubscriptionNumber : subscriptionKey;
13264
15382
  if (typeof subscriptionKey === "undefined") {
@@ -13306,6 +15424,23 @@
13306
15424
  return Promise.resolve(thisCallbackSubscriptionNumber);
13307
15425
  }
13308
15426
  }
15427
+ async subscribe(name, callback, subscriptionKey) {
15428
+ const contextExists = this.all().includes(name);
15429
+ const ts = distExports.Traces.currentTracingState;
15430
+ ts.addData("INFO", { context: name, contextExists });
15431
+ const wrappedCallback = async (...args) => {
15432
+ return distExports.withSpan("interopio.api.contexts.bridge.subscribe.callback", { context: name }, args?.[5], (cbts) => {
15433
+ distExports.Traces.removePropagationInfo(args?.[0]);
15434
+ distExports.Traces.removePropagationInfo(args?.[1]);
15435
+ cbts.addData("INFO", { context: name });
15436
+ cbts.addData("DEBUG", { delta: args?.[1] });
15437
+ cbts.addData("DEBUG", { removed: args?.[2] });
15438
+ cbts.addData("DIAGNOSTIC", { data: args?.[0] });
15439
+ return callback(args?.[0], args?.[1], args?.[2], args?.[3], args?.[4]);
15440
+ });
15441
+ };
15442
+ return this.subscribeInner(name, wrappedCallback, subscriptionKey);
15443
+ }
13309
15444
  unsubscribe(subscriptionKey, keepInSubscriptionsCache) {
13310
15445
  if (!keepInSubscriptionsCache) {
13311
15446
  this._contextsSubscriptionsCache = this._contextsSubscriptionsCache.filter(x => x.subKey !== subscriptionKey);
@@ -13336,8 +15471,11 @@
13336
15471
  }
13337
15472
  }
13338
15473
  async destroy(name) {
15474
+ const ts = distExports.Traces.currentTracingState;
15475
+ ts.addData("INFO", { context: name });
13339
15476
  if (name in this._creationPromises) {
13340
15477
  await this._creationPromises[name];
15478
+ distExports.Traces.currentTracingState = ts;
13341
15479
  }
13342
15480
  const contextData = this._contextNameToData[name];
13343
15481
  const contextId = contextData?.contextId;
@@ -13475,7 +15613,7 @@
13475
15613
  if (justSeen ||
13476
15614
  !deepEqual(contextData.context, oldContext) ||
13477
15615
  updatedMessageType === GW_MESSAGE_SUBSCRIBED_CONTEXT) {
13478
- this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta, { updaterId: contextUpdatedMsg.updater_id });
15616
+ this.invokeUpdateCallbacks(contextData, contextUpdatedMsg.delta ?? contextUpdatedMsg.data, { updaterId: contextUpdatedMsg.updater_id });
13479
15617
  }
13480
15618
  }
13481
15619
  invokeUpdateCallbacks(contextData, delta, extraData) {
@@ -13499,7 +15637,12 @@
13499
15637
  if (contextData.updateCallbacks.hasOwnProperty(updateCallbackIndex)) {
13500
15638
  try {
13501
15639
  const updateCallback = contextData.updateCallbacks[updateCallbackIndex];
13502
- updateCallback(deepClone(contextData.context), deepClone(Object.assign({}, delta.added || {}, delta.updated || {}, delta.reset || {})), delta.removed, parseInt(updateCallbackIndex, 10), extraData);
15640
+ const deltaArg = deepClone({
15641
+ ...delta.added,
15642
+ ...delta.updated,
15643
+ ...delta.reset
15644
+ });
15645
+ updateCallback(deepClone(contextData.context), deltaArg, delta.removed, parseInt(updateCallbackIndex, 10), extraData, distExports.Traces.extractPropagationInfo(delta));
13503
15646
  }
13504
15647
  catch (err) {
13505
15648
  this._logger.debug("callback error: " + JSON.stringify(err));
@@ -13679,6 +15822,27 @@
13679
15822
  return new Promise((resolve) => setTimeout(() => resolve(), 0));
13680
15823
  }
13681
15824
  }
15825
+ __decorate([
15826
+ distExports.withSpan("interopio.api.contexts.bridge.create", { argMapping: ["context"] })
15827
+ ], GW3Bridge.prototype, "createContext", null);
15828
+ __decorate([
15829
+ distExports.withSpan("interopio.api.contexts.bridge.update", { argMapping: ["context"] })
15830
+ ], GW3Bridge.prototype, "update", null);
15831
+ __decorate([
15832
+ distExports.withSpan("interopio.api.contexts.bridge.set", { argMapping: ["context"] })
15833
+ ], GW3Bridge.prototype, "set", null);
15834
+ __decorate([
15835
+ distExports.withSpan("interopio.api.contexts.bridge.setPaths", { argMapping: ["context"] })
15836
+ ], GW3Bridge.prototype, "setPaths", null);
15837
+ __decorate([
15838
+ distExports.withSpan("interopio.api.contexts.bridge.get", { argMapping: ["context"] })
15839
+ ], GW3Bridge.prototype, "get", null);
15840
+ __decorate([
15841
+ distExports.withSpan("interopio.api.contexts.bridge.subscribe", { argMapping: ["context"] })
15842
+ ], GW3Bridge.prototype, "subscribe", null);
15843
+ __decorate([
15844
+ distExports.withSpan("interopio.api.contexts.bridge.destroy", { argMapping: ["context"] })
15845
+ ], GW3Bridge.prototype, "destroy", null);
13682
15846
 
13683
15847
  class ContextsModule {
13684
15848
  initTime;
@@ -13766,6 +15930,21 @@
13766
15930
  }
13767
15931
  }
13768
15932
  }
15933
+ __decorate([
15934
+ distExports.withSpan("interopio.api.contexts.module.update", { argMapping: ["context"] })
15935
+ ], ContextsModule.prototype, "update", null);
15936
+ __decorate([
15937
+ distExports.withSpan("interopio.api.contexts.module.set", { argMapping: ["context"] })
15938
+ ], ContextsModule.prototype, "set", null);
15939
+ __decorate([
15940
+ distExports.withSpan("interopio.api.contexts.module.setPaths", { argMapping: ["context"] })
15941
+ ], ContextsModule.prototype, "setPaths", null);
15942
+ __decorate([
15943
+ distExports.withSpan("interopio.api.contexts.module.subscribe", { argMapping: ["context"] })
15944
+ ], ContextsModule.prototype, "subscribe", null);
15945
+ __decorate([
15946
+ distExports.withSpan("interopio.api.contexts.module.destroy", { argMapping: ["context"] })
15947
+ ], ContextsModule.prototype, "destroy", null);
13769
15948
 
13770
15949
  function promisify (promise, successCallback, errorCallback) {
13771
15950
  if (typeof successCallback !== "function" && typeof errorCallback !== "function") {
@@ -14584,7 +16763,7 @@
14584
16763
  const providedType = typeof input;
14585
16764
  return providedType === "function" ?
14586
16765
  anyJson() :
14587
- fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${typeof providedType}`);
16766
+ fail$1(`The provided argument as ${propDescription} should be of type function, provided: ${providedType}`);
14588
16767
  };
14589
16768
  const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
14590
16769
  const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number or 0");
@@ -14641,6 +16820,9 @@
14641
16820
  this.configuration = configuration;
14642
16821
  }
14643
16822
  subscribe(method, options, successCallback, errorCallback, existingSub) {
16823
+ const ts = distExports.Traces.currentTracingState;
16824
+ ts.addData("INFO", { stream: Utils.getMethodName(method) });
16825
+ ts.addData("INFO", { options });
14644
16826
  const callProtocolSubscribe = (targetServers, stream, successProxy, errorProxy) => {
14645
16827
  options.methodResponseTimeout = options.methodResponseTimeout ?? options.waitTimeoutMs;
14646
16828
  this.protocol.client.subscribe(stream, options, targetServers, successProxy, errorProxy, existingSub);
@@ -14765,6 +16947,10 @@
14765
16947
  });
14766
16948
  }
14767
16949
  async invoke(methodFilter, argumentObj, target, additionalOptions, success, error) {
16950
+ const ts = distExports.Traces.currentTracingState;
16951
+ ts.addData("INFO", { method: Utils.getMethodName(methodFilter) });
16952
+ ts.addData("INFO", { target, additionalOptions });
16953
+ ts.addData("DIAGNOSTIC", { arguments: argumentObj });
14768
16954
  const getInvokePromise = async () => {
14769
16955
  const methodDefinition = typeof methodFilter === "string" ? { name: methodFilter } : { ...methodFilter };
14770
16956
  if (!argumentObj) {
@@ -14825,23 +17011,10 @@
14825
17011
  return Promise.reject(this.generateInvalidInputInvocationResult(message, methodDefinition, argumentObj));
14826
17012
  }
14827
17013
  }
14828
- const timeout = additionalOptions.methodResponseTimeoutMs;
17014
+ const timeout = additionalOptions.methodResponseTimeoutMs ?? 30000;
14829
17015
  const additionalOptionsCopy = additionalOptions;
14830
- const invokePromises = serversMethodMap.map((serversMethodPair) => {
14831
- const invId = nanoid(10);
14832
- const method = serversMethodPair.methods[0];
14833
- const server = serversMethodPair.server;
14834
- const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy);
14835
- return Promise.race([
14836
- invokePromise,
14837
- rejectAfter(timeout, invokePromise, {
14838
- invocationId: invId,
14839
- message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`,
14840
- status: InvokeStatus.Error,
14841
- })
14842
- ]);
14843
- });
14844
- const invocationMessages = await Promise.all(invokePromises);
17016
+ const serverInvokePromises = serversMethodMap.map((smp) => this.getServerInvokePromise(smp.methods[0], smp.server, argumentObj, additionalOptionsCopy, timeout));
17017
+ const invocationMessages = await Promise.all(serverInvokePromises);
14845
17018
  const results = this.getInvocationResultObj(invocationMessages, methodDefinition, argumentObj);
14846
17019
  const allRejected = invocationMessages.every((result) => result.status === InvokeStatus.Error);
14847
17020
  if (allRejected) {
@@ -14851,6 +17024,27 @@
14851
17024
  };
14852
17025
  return promisify(getInvokePromise(), success, error);
14853
17026
  }
17027
+ async getServerInvokePromise(method, server, argumentObj, additionalOptionsCopy, timeout) {
17028
+ const invId = nanoid(10);
17029
+ const ts = distExports.Traces.currentTracingState;
17030
+ if (argumentObj) {
17031
+ argumentObj = deepClone(argumentObj);
17032
+ ts.injectPropagationInfo(argumentObj);
17033
+ }
17034
+ ts.addData("INFO", { "server": server?.id, instance: server?.instance });
17035
+ ts.addData("INFO", { "invocationId": invId });
17036
+ const invokePromise = this.protocol.client.invoke(invId, method, argumentObj, server, additionalOptionsCopy);
17037
+ const returnValue = await Promise.race([
17038
+ invokePromise,
17039
+ rejectAfter(timeout, invokePromise, {
17040
+ invocationId: invId,
17041
+ message: `Invocation timeout (${timeout} ms) reached for method name: ${method?.name}, target instance: ${JSON.stringify(server.instance)}, options: ${JSON.stringify(additionalOptionsCopy)}`,
17042
+ status: InvokeStatus.Error,
17043
+ })
17044
+ ]);
17045
+ ts.addData("DIAGNOSTIC", { returnValue });
17046
+ return returnValue;
17047
+ }
14854
17048
  generateInvalidInputInvocationResult(message, methodDefinition, argumentObj) {
14855
17049
  const method = {
14856
17050
  ...methodDefinition,
@@ -14867,6 +17061,7 @@
14867
17061
  return this.getInvocationResultObj([invokeResultMessage], method, argumentObj);
14868
17062
  }
14869
17063
  getInvocationResultObj(invocationResults, method, calledWith) {
17064
+ distExports.Traces.removePropagationInfo(calledWith);
14870
17065
  const all_return_values = invocationResults
14871
17066
  .filter((invokeMessage) => invokeMessage.status === InvokeStatus.Success)
14872
17067
  .reduce((allValues, currentValue) => {
@@ -15070,6 +17265,15 @@
15070
17265
  return this.filterByTarget(target, serversMethodMap);
15071
17266
  }
15072
17267
  }
17268
+ __decorate([
17269
+ distExports.withSpan("interopio.api.interop.stream.subscribe", { argMapping: (methodDefinition) => ({ stream: Utils.getMethodName(methodDefinition) }) })
17270
+ ], Client.prototype, "subscribe", null);
17271
+ __decorate([
17272
+ distExports.withSpan("interopio.api.interop.invoke", { argMapping: (methodDefinition) => ({ method: Utils.getMethodName(methodDefinition) }) })
17273
+ ], Client.prototype, "invoke", null);
17274
+ __decorate([
17275
+ distExports.withSpan("interopio.api.interop.invoke.server", { argMapping: { "0.name": "method" } })
17276
+ ], Client.prototype, "getServerInvokePromise", null);
15073
17277
 
15074
17278
  class ServerSubscription {
15075
17279
  protocol;
@@ -15235,9 +17439,9 @@
15235
17439
  flags: def2.flags?.metadata,
15236
17440
  };
15237
17441
  }
15238
- close() {
17442
+ async close() {
15239
17443
  this._protocol.server.closeAllSubscriptions(this._repoMethod);
15240
- this._server.unregister(this._repoMethod.definition, true);
17444
+ return this._server.unregister(this._repoMethod.definition, true);
15241
17445
  }
15242
17446
  push(data, branches) {
15243
17447
  if (typeof branches !== "string" && !Array.isArray(branches) && branches !== undefined) {
@@ -15246,12 +17450,23 @@
15246
17450
  if (typeof data !== "object") {
15247
17451
  throw new Error("Invalid arguments. Data must be an object.");
15248
17452
  }
17453
+ const ts = distExports.Traces.currentTracingState;
17454
+ ts.addData("INFO", { stream: this?.name, branches });
17455
+ ts.addData("DIAGNOSTIC", { data });
17456
+ data = deepClone(data);
17457
+ ts.injectPropagationInfo(data);
15249
17458
  this._protocol.server.pushData(this._repoMethod, data, branches);
15250
17459
  }
15251
17460
  updateRepoMethod(repoMethod) {
15252
17461
  this._repoMethod = repoMethod;
15253
17462
  }
15254
17463
  }
17464
+ __decorate([
17465
+ distExports.withSpan("interopio.api.interop.stream.close", { thisMapping: { name: "stream" } })
17466
+ ], ServerStream.prototype, "close", null);
17467
+ __decorate([
17468
+ distExports.withSpan("interopio.api.interop.stream.push", { thisMapping: { name: "stream" } })
17469
+ ], ServerStream.prototype, "push", null);
15255
17470
 
15256
17471
  class Server {
15257
17472
  protocol;
@@ -15326,14 +17541,18 @@
15326
17541
  if (!methodDefinition) {
15327
17542
  return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");
15328
17543
  }
17544
+ const ts = distExports.Traces.currentTracingState;
17545
+ ts.addData("INFO", { method: Utils.getMethodName(methodDefinition) });
15329
17546
  if (typeof callback !== "function") {
15330
- return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`);
17547
+ return Promise.reject(`The second parameter must be a callback function. Method: ${Utils.getMethodName(methodDefinition)}`);
15331
17548
  }
15332
17549
  const wrappedCallbackFunction = async (context, resultCallback) => {
15333
17550
  try {
15334
17551
  const result = callback(context.args, context.instance);
15335
17552
  if (result && typeof result.then === "function") {
17553
+ const cbts = distExports.Traces.currentTracingState;
15336
17554
  const resultValue = await result;
17555
+ distExports.Traces.currentTracingState = cbts;
15337
17556
  resultCallback(undefined, resultValue);
15338
17557
  }
15339
17558
  else {
@@ -15351,8 +17570,10 @@
15351
17570
  if (!methodDefinition) {
15352
17571
  return Promise.reject("Method definition is required. Please, provide either a unique string for a method name or a “methodDefinition” object with a required “name” property.");
15353
17572
  }
17573
+ const ts = distExports.Traces.currentTracingState;
17574
+ ts.addData("INFO", { method: Utils.getMethodName(methodDefinition) });
15354
17575
  if (typeof callback !== "function") {
15355
- return Promise.reject(`The second parameter must be a callback function. Method: ${typeof methodDefinition === "string" ? methodDefinition : methodDefinition.name}`);
17576
+ return Promise.reject(`The second parameter must be a callback function. Method: ${Utils.getMethodName(methodDefinition)}`);
15356
17577
  }
15357
17578
  const wrappedCallback = async (context, resultCallback) => {
15358
17579
  try {
@@ -15390,6 +17611,8 @@
15390
17611
  if (methodFilter === undefined) {
15391
17612
  return Promise.reject("Please, provide either a unique string for a name or an object containing a “name” property.");
15392
17613
  }
17614
+ const ts = distExports.Traces.currentTracingState;
17615
+ ts.addData("INFO", { method: Utils.getMethodName(methodFilter) });
15393
17616
  if (typeof methodFilter === "function") {
15394
17617
  await this.unregisterWithPredicate(methodFilter, forStream);
15395
17618
  return;
@@ -15479,33 +17702,62 @@
15479
17702
  });
15480
17703
  }
15481
17704
  onMethodInvoked(methodToExecute, invocationId, invocationArgs) {
15482
- if (!methodToExecute || !methodToExecute.theFunction) {
15483
- return;
15484
- }
15485
- methodToExecute.theFunction(invocationArgs, (err, result) => {
15486
- if (err !== undefined && err !== null) {
15487
- if (err.message && typeof err.message === "string") {
15488
- err = err.message;
15489
- }
15490
- else if (typeof err !== "string") {
15491
- try {
15492
- err = JSON.stringify(err);
17705
+ const propagationInfo = distExports.Traces.extractPropagationInfo(invocationArgs.args, true);
17706
+ distExports.withSpan("interopio.api.interop.register.callback", { method: methodToExecute?.definition?.name }, propagationInfo, (ts) => {
17707
+ ts.addData("INFO", { method: methodToExecute?.definition?.name });
17708
+ ts.addData("INFO", { invocationId });
17709
+ ts.addData("INFO", { invoker: invocationArgs?.instance });
17710
+ ts.addData("DIAGNOSTIC", { arguments: invocationArgs?.args });
17711
+ if (!methodToExecute || !methodToExecute.theFunction) {
17712
+ ts.status = { code: distExports.SpanStatusCode.ERROR, message: "Required argument 'methodToExecute' is missing." };
17713
+ return;
17714
+ }
17715
+ let resolveWithSpanCallback;
17716
+ const withSpanCallbackPromise = new Promise(resolve => {
17717
+ resolveWithSpanCallback = resolve;
17718
+ });
17719
+ methodToExecute.theFunction(invocationArgs, (err, result) => {
17720
+ if (err !== undefined && err !== null) {
17721
+ if (err.message && typeof err.message === "string") {
17722
+ err = err.message;
15493
17723
  }
15494
- catch (unStrException) {
15495
- err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`;
17724
+ else if (typeof err !== "string") {
17725
+ try {
17726
+ err = JSON.stringify(err);
17727
+ }
17728
+ catch (unStrException) {
17729
+ err = `un-stringifyable error in onMethodInvoked! Top level prop names: ${Object.keys(err)}`;
17730
+ }
15496
17731
  }
17732
+ ts.status = { code: distExports.SpanStatusCode.ERROR, message: err };
17733
+ ts.recordException(err);
15497
17734
  }
15498
- }
15499
- if (!result) {
15500
- result = {};
15501
- }
15502
- else if (typeof result !== "object" || Array.isArray(result)) {
15503
- result = { _value: result };
15504
- }
15505
- this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result);
17735
+ if (!result) {
17736
+ result = {};
17737
+ }
17738
+ else if (typeof result !== "object" || Array.isArray(result)) {
17739
+ result = { _value: result };
17740
+ }
17741
+ ts.addData("DIAGNOSTIC", { returnValue: result });
17742
+ this.protocol.server.methodInvocationResult(methodToExecute, invocationId, err, result);
17743
+ resolveWithSpanCallback();
17744
+ });
17745
+ return withSpanCallbackPromise;
15506
17746
  });
15507
17747
  }
15508
17748
  }
17749
+ __decorate([
17750
+ distExports.withSpan("interopio.api.interop.stream.create", { argMapping: (methodDefinition) => ({ stream: Utils.getMethodName(methodDefinition) }) })
17751
+ ], Server.prototype, "createStream", null);
17752
+ __decorate([
17753
+ distExports.withSpan("interopio.api.interop.register", { argMapping: (methodDefinition) => ({ method: Utils.getMethodName(methodDefinition) }) })
17754
+ ], Server.prototype, "register", null);
17755
+ __decorate([
17756
+ distExports.withSpan("interopio.api.interop.register.async", { argMapping: (methodDefinition) => ({ method: Utils.getMethodName(methodDefinition) }) })
17757
+ ], Server.prototype, "registerAsync", null);
17758
+ __decorate([
17759
+ distExports.withSpan("interopio.api.interop.unregister", { argMapping: (methodDefinition) => ({ method: Utils.getMethodName(methodDefinition) }) })
17760
+ ], Server.prototype, "unregister", null);
15509
17761
 
15510
17762
  class InstanceWrapper {
15511
17763
  wrapped = {};
@@ -16342,6 +18594,7 @@
16342
18594
  session.on("subscription-cancelled", this.handleSubscriptionCancelled);
16343
18595
  }
16344
18596
  subscribe(streamingMethod, params, targetServers, success, error, existingSub) {
18597
+ distExports.Traces.removePropagationInfo(params.arguments);
16345
18598
  if (targetServers.length === 0) {
16346
18599
  error({
16347
18600
  method: streamingMethod,
@@ -16477,7 +18730,7 @@
16477
18730
  "{}";
16478
18731
  pendingSub.error({
16479
18732
  message: ERR_MSG_SUB_REJECTED + reason + " Called with:" + callArgs,
16480
- called_with: pendingSub.params.arguments,
18733
+ called_with: distExports.Traces.removePropagationInfo(pendingSub.params.arguments),
16481
18734
  method: pendingSub.method,
16482
18735
  });
16483
18736
  }
@@ -16545,7 +18798,7 @@
16545
18798
  const isPrivateData = msg.oob;
16546
18799
  const sendingServerId = trackedServersFound[0].serverId;
16547
18800
  const server = this.repository.getServerById(sendingServerId);
16548
- const receivedStreamData = () => {
18801
+ const getReceivedStreamData = () => {
16549
18802
  return {
16550
18803
  data: msg.data,
16551
18804
  server: server?.instance ?? {},
@@ -16556,16 +18809,29 @@
16556
18809
  };
16557
18810
  const onDataHandlers = subscription.handlers.onData;
16558
18811
  const queuedData = subscription.queued.data;
16559
- if (onDataHandlers.length > 0) {
16560
- onDataHandlers.forEach((callback) => {
16561
- if (typeof callback === "function") {
16562
- callback(receivedStreamData());
16563
- }
16564
- });
16565
- }
16566
- else {
16567
- queuedData.push(receivedStreamData());
16568
- }
18812
+ const rsd = getReceivedStreamData();
18813
+ const pi = distExports.Traces.extractPropagationInfo(rsd.data, true);
18814
+ const methodName = subscription?.method?.name;
18815
+ distExports.withSpan("interopio.api.interop.stream.onData", {
18816
+ method: methodName,
18817
+ stream: methodName
18818
+ }, pi, () => {
18819
+ const ts = distExports.Traces.currentTracingState;
18820
+ ts.addData("INFO", { method: methodName });
18821
+ ts.addData("INFO", { stream: methodName });
18822
+ ts.addData("INFO", { handlerCount: onDataHandlers?.length });
18823
+ ts.addData("DIAGNOSTIC", { data: rsd });
18824
+ if (onDataHandlers.length > 0) {
18825
+ onDataHandlers.forEach((callback) => {
18826
+ if (typeof callback === "function") {
18827
+ callback(deepClone(rsd));
18828
+ }
18829
+ });
18830
+ }
18831
+ else {
18832
+ queuedData.push(deepClone(rsd));
18833
+ }
18834
+ });
16569
18835
  };
16570
18836
  handleSubscriptionCancelled = (msg) => {
16571
18837
  const subLocalKey = this.subscriptionIdToLocalKeyMap[msg.subscription_id];
@@ -16963,7 +19229,16 @@
16963
19229
  return this.readyPromise;
16964
19230
  }
16965
19231
  publish = (topic, data, options) => {
19232
+ this.publishCore(topic, data, options);
19233
+ };
19234
+ publishCore(topic, data, options) {
16966
19235
  const { routingKey, target } = options || {};
19236
+ const ts = distExports.Traces.currentTracingState;
19237
+ ts.addData("INFO", { topic });
19238
+ ts.addData("DIAGNOSTIC", { data });
19239
+ ts.addData("INFO", { routingKey, target });
19240
+ data = deepClone(data);
19241
+ ts.injectPropagationInfo(data);
16967
19242
  const args = this.removeEmptyValues({
16968
19243
  type: "publish",
16969
19244
  topic,
@@ -16976,10 +19251,17 @@
16976
19251
  .catch((err) => {
16977
19252
  this.logger.error(`Failed to publish message to topic ${topic} with routing key ${routingKey} for ${JSON.stringify(target)}: ${JSON.stringify(err)}`);
16978
19253
  });
16979
- };
19254
+ }
19255
+ ;
16980
19256
  subscribe = (topic, callback, options) => {
19257
+ return this.subscribeCore(topic, callback, options);
19258
+ };
19259
+ subscribeCore(topic, callback, options) {
16981
19260
  return new Promise((resolve, reject) => {
16982
19261
  const { routingKey, target } = options || {};
19262
+ const ts = distExports.Traces.currentTracingState;
19263
+ ts.addData("INFO", { topic });
19264
+ ts.addData("INFO", { routingKey, target });
16983
19265
  const args = this.removeEmptyValues({
16984
19266
  type: "subscribe",
16985
19267
  topic,
@@ -16990,7 +19272,16 @@
16990
19272
  this.session.send(args)
16991
19273
  .then((response) => {
16992
19274
  const { subscription_id } = response;
16993
- this.subscriptions.push({ subscription_id, topic, callback, source: target });
19275
+ ts.addData("INFO", { subscription_id });
19276
+ const tracedCallback = function (...tracedCallbackArgs) {
19277
+ const propagationInfo = distExports.Traces.extractPropagationInfo(tracedCallbackArgs?.[0], true);
19278
+ distExports.withSpan("interopio.api.bus.subscribe.callback", { topic }, propagationInfo, (cbts) => {
19279
+ cbts.addData("INFO", { topic, subscription_id });
19280
+ cbts.addData("DIAGNOSTIC", { data: tracedCallbackArgs?.[0] });
19281
+ callback.apply(this, tracedCallbackArgs);
19282
+ });
19283
+ };
19284
+ this.subscriptions.push({ subscription_id, topic, callback: tracedCallback, source: target });
16994
19285
  resolve({
16995
19286
  unsubscribe: () => {
16996
19287
  this.session.send({ type: "unsubscribe", subscription_id, peer_id: this.peerId })
@@ -17005,7 +19296,8 @@
17005
19296
  })
17006
19297
  .catch((error) => reject(error));
17007
19298
  });
17008
- };
19299
+ }
19300
+ ;
17009
19301
  watchOnEvent = () => {
17010
19302
  this.session.on("event", (args) => {
17011
19303
  const { data, subscription_id } = args;
@@ -17043,10 +19335,74 @@
17043
19335
  return allMatch;
17044
19336
  }
17045
19337
  }
19338
+ __decorate([
19339
+ distExports.withSpan("interopio.api.bus.publish", { argMapping: ["topic"] })
19340
+ ], MessageBus.prototype, "publishCore", null);
19341
+ __decorate([
19342
+ distExports.withSpan("interopio.api.bus.subscribe", { argMapping: ["topic"] })
19343
+ ], MessageBus.prototype, "subscribeCore", null);
19344
+
19345
+ function replaceComplexProperties(obj) {
19346
+ if (isPrimitiveOrFunction(obj)) {
19347
+ return;
19348
+ }
19349
+ for (const prop in obj) {
19350
+ if (!obj.hasOwnProperty(prop)) {
19351
+ continue;
19352
+ }
19353
+ const value = obj[prop];
19354
+ if (isPrimitiveOrFunction(value)) {
19355
+ continue;
19356
+ }
19357
+ if (isPlainObject$2(value) || Array.isArray(value)) {
19358
+ replaceComplexProperties(value);
19359
+ continue;
19360
+ }
19361
+ obj[prop] = value?.constructor?.name || value.toString();
19362
+ }
19363
+ }
19364
+ function isPrimitiveOrFunction(obj) {
19365
+ if (!obj) {
19366
+ return true;
19367
+ }
19368
+ if (obj !== Object(obj)) {
19369
+ return true;
19370
+ }
19371
+ if (typeof obj === "function") {
19372
+ return true;
19373
+ }
19374
+ return false;
19375
+ }
19376
+
19377
+ async function loadInsightsPlugins(logger, settings) {
19378
+ try {
19379
+ (await Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder; })).init();
19380
+ }
19381
+ catch {
19382
+ logger.warn("@interopio/insights-base plugin failed to load, insights will be disabled");
19383
+ }
19384
+ if (settings.metrics?.enabled) {
19385
+ try {
19386
+ (await Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder; })).init();
19387
+ }
19388
+ catch {
19389
+ logger.warn("@interopio/insights-metrics plugin failed to load, insights metrics functionality will be disabled");
19390
+ }
19391
+ }
19392
+ if (settings.traces?.enabled) {
19393
+ try {
19394
+ (await Promise.resolve().then(function () { return _rollup_plugin_ignore_empty_module_placeholder; })).init();
19395
+ }
19396
+ catch {
19397
+ logger.warn("@interopio/insights-traces plugin failed to load, insights traces functionality will be disabled");
19398
+ }
19399
+ }
19400
+ }
17046
19401
 
17047
19402
  const IOConnectCoreFactory = (userConfig, ext) => {
17048
19403
  const iodesktop = typeof window === "object" ? (window.iodesktop ?? window.glue42gd) : undefined;
17049
19404
  const preloadPromise = typeof window === "object" ? (window.gdPreloadPromise ?? Promise.resolve()) : Promise.resolve();
19405
+ const glueReadyPromiseWrapper = new PromiseWrapper();
17050
19406
  const glueInitTimer = timer("glue");
17051
19407
  userConfig = userConfig || {};
17052
19408
  ext = ext || {};
@@ -17057,6 +19413,7 @@
17057
19413
  let _metrics;
17058
19414
  let _contexts;
17059
19415
  let _bus;
19416
+ let _insights;
17060
19417
  let _allowTrace;
17061
19418
  const libs = {};
17062
19419
  function registerLib(name, inner, t) {
@@ -17220,6 +19577,43 @@
17220
19577
  registerLib("bus", _bus, initTimer);
17221
19578
  return Promise.resolve();
17222
19579
  }
19580
+ async function setupInsights(interop) {
19581
+ const initTimer = timer("insights");
19582
+ const settings = await internalConfig.getInsights(iodesktop, interop, _logger);
19583
+ internalConfig.insights = settings;
19584
+ try {
19585
+ const builder = new distExports.Builder();
19586
+ const insightsLogger = _logger.subLogger("insights");
19587
+ if (settings.enabled) {
19588
+ await loadInsightsPlugins(insightsLogger, settings);
19589
+ }
19590
+ builder.withSettings(settings);
19591
+ builder.withLogger(new distExports.Log4jsWrapper(insightsLogger));
19592
+ builder.withMetrics();
19593
+ const INSIGHTS_PI_STORAGE = "___insights_pi_storage___";
19594
+ builder.withTraces()
19595
+ .withTraceLogger(new distExports.Log4jsWrapper(insightsLogger.subLogger("traces")))
19596
+ .withPropagationInfoStorage((source, pi) => _contexts?.update(INSIGHTS_PI_STORAGE, { [source.replace(/[.]/g, "_!_")]: { pi } }), (source) => _contexts?.get(INSIGHTS_PI_STORAGE)?.then(x => x[source.replace(/[.]/g, "_!_")]?.pi) ?? Promise.resolve(null));
19597
+ const container = builder.build();
19598
+ await container.start();
19599
+ registerLib("insights", container, initTimer);
19600
+ distExports.Traces.withSpan("interopio.api.startup", () => glueReadyPromiseWrapper.promise);
19601
+ _insights = container;
19602
+ return Promise.resolve();
19603
+ }
19604
+ catch (e) {
19605
+ initTimer.stop();
19606
+ _logger?.error("Error initializing insights", e);
19607
+ if (settings.failOnInitError) {
19608
+ throw e;
19609
+ }
19610
+ return Promise.resolve();
19611
+ }
19612
+ finally {
19613
+ replaceComplexProperties(internalConfig?.insights);
19614
+ replaceComplexProperties(userConfig?.insights);
19615
+ }
19616
+ }
17223
19617
  function setupExternalLibs(externalLibs) {
17224
19618
  try {
17225
19619
  externalLibs.forEach((lib) => {
@@ -17267,6 +19661,7 @@
17267
19661
  connection: _connection,
17268
19662
  metrics: _metrics,
17269
19663
  contexts: _contexts,
19664
+ insights: _insights,
17270
19665
  bus: _bus,
17271
19666
  version: internalConfig.version,
17272
19667
  userConfig,
@@ -17335,6 +19730,7 @@
17335
19730
  agmAny.server_method_aded = deprecatedDecorator(glue.agm.serverMethodAdded, "server_method_aded", "serverMethodAdded");
17336
19731
  agmAny.server_method_removed = deprecatedDecorator(glue.agm.serverMethodRemoved, "server_method_removed", "serverMethodRemoved");
17337
19732
  }
19733
+ glueReadyPromiseWrapper.resolve();
17338
19734
  return glue;
17339
19735
  }
17340
19736
  async function registerInstanceIfNeeded() {
@@ -17358,12 +19754,14 @@
17358
19754
  .then(() => Promise.all([setupMetrics(), setupInterop(), setupContexts(), setupBus()]))
17359
19755
  .then(() => _interop.readyPromise)
17360
19756
  .then(() => registerInstanceIfNeeded())
19757
+ .then(() => setupInsights(_interop))
17361
19758
  .then(() => {
17362
19759
  return setupExternalLibs(internalConfig.libs || []);
17363
19760
  })
17364
19761
  .then(waitForLibs)
17365
19762
  .then(constructGlueObject)
17366
19763
  .catch((err) => {
19764
+ glueReadyPromiseWrapper.reject({ err });
17367
19765
  return Promise.reject({
17368
19766
  err,
17369
19767
  libs
@@ -17393,6 +19791,10 @@
17393
19791
  }
17394
19792
  iOConnectBrowserFactory.version = version$1;
17395
19793
 
19794
+ var _rollup_plugin_ignore_empty_module_placeholder = /*#__PURE__*/Object.freeze({
19795
+ __proto__: null
19796
+ });
19797
+
17396
19798
  return iOConnectBrowserFactory;
17397
19799
 
17398
19800
  }));