@trackunit/iris-app-runtime-core 0.3.50 → 0.3.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -3,7 +3,6 @@
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
5
  var irisAppRuntimeCoreApi = require('@trackunit/iris-app-runtime-core-api');
6
- var penpal = require('penpal');
7
6
 
8
7
  /******************************************************************************
9
8
  Copyright (c) Microsoft Corporation.
@@ -30,324 +29,759 @@ function __awaiter(thisArg, _arguments, P, generator) {
30
29
  });
31
30
  }
32
31
 
33
- /**
34
- * Setup using the subscribedMethods to subscribe to events from the host.
35
- *
36
- * @param subscribedMethods the methods to subscribe to
37
- * @returns { Connection<HostConnectorApi> } the connection to the host
38
- */
39
- const setupHostConnector = (subscribedMethods) => {
40
- var _a;
41
- const methods = Object.assign({ onGlobalSelectionChanged: () => { }, onTokenChanged: () => { }, onAssetSortingStateChanged: () => { } }, subscribedMethods);
42
- const connection = penpal.connectToParent({ methods });
43
- (_a = connection.promise) === null || _a === void 0 ? void 0 : _a.catch(err => {
44
- // TODO consider how to handle this catch
45
- // eslint-disable-next-line no-console
46
- console.log(err);
47
- });
48
- return connection;
49
- };
50
- const hostConnector = setupHostConnector({});
51
- /**
52
- * Gets the host connector.
53
- *
54
- * @returns { Promise<HostConnectorApi> } the connection to the host
55
- */
56
- const getHostConnector = () => {
57
- return hostConnector.promise;
32
+ var MessageType;
33
+ (function (MessageType) {
34
+ MessageType["Call"] = "call";
35
+ MessageType["Reply"] = "reply";
36
+ MessageType["Syn"] = "syn";
37
+ MessageType["SynAck"] = "synAck";
38
+ MessageType["Ack"] = "ack";
39
+ })(MessageType || (MessageType = {}));
40
+ var Resolution;
41
+ (function (Resolution) {
42
+ Resolution["Fulfilled"] = "fulfilled";
43
+ Resolution["Rejected"] = "rejected";
44
+ })(Resolution || (Resolution = {}));
45
+ var ErrorCode;
46
+ (function (ErrorCode) {
47
+ ErrorCode["ConnectionDestroyed"] = "ConnectionDestroyed";
48
+ ErrorCode["ConnectionTimeout"] = "ConnectionTimeout";
49
+ ErrorCode["NoIframeSrc"] = "NoIframeSrc";
50
+ })(ErrorCode || (ErrorCode = {}));
51
+ var NativeErrorName;
52
+ (function (NativeErrorName) {
53
+ NativeErrorName["DataCloneError"] = "DataCloneError";
54
+ })(NativeErrorName || (NativeErrorName = {}));
55
+ var NativeEventType;
56
+ (function (NativeEventType) {
57
+ NativeEventType["Message"] = "message";
58
+ })(NativeEventType || (NativeEventType = {}));
59
+
60
+ var createDestructor = (localName, log) => {
61
+ const callbacks = [];
62
+ let destroyed = false;
63
+ return {
64
+ destroy(error) {
65
+ if (!destroyed) {
66
+ destroyed = true;
67
+ log(`${localName}: Destroying connection`);
68
+ callbacks.forEach((callback) => {
69
+ callback(error);
70
+ });
71
+ }
72
+ },
73
+ onDestroy(callback) {
74
+ destroyed ? callback() : callbacks.push(callback);
75
+ },
76
+ };
58
77
  };
59
78
 
60
- const AnalyticsContextRuntime = {
61
- logPageView: (details) => __awaiter(void 0, void 0, void 0, function* () {
62
- const api = yield getHostConnector();
63
- api.logPageView(details);
64
- }),
65
- logError: (details) => __awaiter(void 0, void 0, void 0, function* () {
66
- const api = yield getHostConnector();
67
- api.logError(details);
68
- }),
69
- logEvent: (eventName, details, nameSupplement) => __awaiter(void 0, void 0, void 0, function* () {
70
- const api = yield getHostConnector();
71
- api.logEvent(eventName, details, nameSupplement);
72
- }),
73
- setUserProperty: (name, data) => __awaiter(void 0, void 0, void 0, function* () {
74
- const api = yield getHostConnector();
75
- api.setUserProperty(name, data);
76
- }),
79
+ var createLogger = (debug) => {
80
+ /**
81
+ * Logs a message if debug is enabled.
82
+ */
83
+ return (...args) => {
84
+ if (debug) {
85
+ console.log('[Penpal]', ...args); // eslint-disable-line no-console
86
+ }
87
+ };
77
88
  };
78
89
 
79
- const AssetRuntime = {
80
- getAssetInfo: () => __awaiter(void 0, void 0, void 0, function* () {
81
- const api = yield getHostConnector();
82
- return api.getAssetInfo();
83
- }),
90
+ /**
91
+ * Converts an error object into a plain object.
92
+ */
93
+ const serializeError = ({ name, message, stack, }) => ({
94
+ name,
95
+ message,
96
+ stack,
97
+ });
98
+ /**
99
+ * Converts a plain object into an error object.
100
+ */
101
+ const deserializeError = (obj) => {
102
+ const deserializedError = new Error();
103
+ // @ts-ignore
104
+ Object.keys(obj).forEach((key) => (deserializedError[key] = obj[key]));
105
+ return deserializedError;
84
106
  };
85
107
 
86
- const AssetSortingRuntime = {
87
- getAssetSortingState: () => __awaiter(void 0, void 0, void 0, function* () {
88
- const api = yield getHostConnector();
89
- return api.getAssetSortingState();
90
- }),
91
- setAssetSortingState: (...args) => __awaiter(void 0, void 0, void 0, function* () {
92
- const api = yield getHostConnector();
93
- return api.setAssetSortingState(...args);
94
- }),
108
+ /**
109
+ * Listens for "call" messages coming from the remote, executes the corresponding method, and
110
+ * responds with the return value.
111
+ */
112
+ var connectCallReceiver = (info, serializedMethods, log) => {
113
+ const { localName, local, remote, originForSending, originForReceiving, } = info;
114
+ let destroyed = false;
115
+ const handleMessageEvent = (event) => {
116
+ if (event.source !== remote || event.data.penpal !== MessageType.Call) {
117
+ return;
118
+ }
119
+ if (originForReceiving !== '*' && event.origin !== originForReceiving) {
120
+ log(`${localName} received message from origin ${event.origin} which did not match expected origin ${originForReceiving}`);
121
+ return;
122
+ }
123
+ const callMessage = event.data;
124
+ const { methodName, args, id } = callMessage;
125
+ log(`${localName}: Received ${methodName}() call`);
126
+ const createPromiseHandler = (resolution) => {
127
+ return (returnValue) => {
128
+ log(`${localName}: Sending ${methodName}() reply`);
129
+ if (destroyed) {
130
+ // It's possible to throw an error here, but it would need to be thrown asynchronously
131
+ // and would only be catchable using window.onerror. This is because the consumer
132
+ // is merely returning a value from their method and not calling any function
133
+ // that they could wrap in a try-catch. Even if the consumer were to catch the error,
134
+ // the value of doing so is questionable. Instead, we'll just log a message.
135
+ log(`${localName}: Unable to send ${methodName}() reply due to destroyed connection`);
136
+ return;
137
+ }
138
+ const message = {
139
+ penpal: MessageType.Reply,
140
+ id,
141
+ resolution,
142
+ returnValue,
143
+ };
144
+ if (resolution === Resolution.Rejected &&
145
+ returnValue instanceof Error) {
146
+ message.returnValue = serializeError(returnValue);
147
+ message.returnValueIsError = true;
148
+ }
149
+ try {
150
+ remote.postMessage(message, originForSending);
151
+ }
152
+ catch (err) {
153
+ // If a consumer attempts to send an object that's not cloneable (e.g., window),
154
+ // we want to ensure the receiver's promise gets rejected.
155
+ if (err.name === NativeErrorName.DataCloneError) {
156
+ const errorReplyMessage = {
157
+ penpal: MessageType.Reply,
158
+ id,
159
+ resolution: Resolution.Rejected,
160
+ returnValue: serializeError(err),
161
+ returnValueIsError: true,
162
+ };
163
+ remote.postMessage(errorReplyMessage, originForSending);
164
+ }
165
+ throw err;
166
+ }
167
+ };
168
+ };
169
+ new Promise((resolve) => resolve(serializedMethods[methodName].apply(serializedMethods, args))).then(createPromiseHandler(Resolution.Fulfilled), createPromiseHandler(Resolution.Rejected));
170
+ };
171
+ local.addEventListener(NativeEventType.Message, handleMessageEvent);
172
+ return () => {
173
+ destroyed = true;
174
+ local.removeEventListener(NativeEventType.Message, handleMessageEvent);
175
+ };
95
176
  };
96
177
 
97
- const CurrentUserRuntime = {
98
- getCurrentUserContext: () => __awaiter(void 0, void 0, void 0, function* () {
99
- const api = yield getHostConnector();
100
- return api.getCurrentUserContext();
101
- }),
102
- getCurrentUserRole: (userIds) => __awaiter(void 0, void 0, void 0, function* () {
103
- const api = yield getHostConnector();
104
- return api.getCurrentUserRole(userIds);
105
- }),
178
+ let id = 0;
179
+ /**
180
+ * @return {number} A unique ID (not universally unique)
181
+ */
182
+ var generateId = () => ++id;
183
+
184
+ const KEY_PATH_DELIMITER = '.';
185
+ const keyPathToSegments = (keyPath) => keyPath ? keyPath.split(KEY_PATH_DELIMITER) : [];
186
+ const segmentsToKeyPath = (segments) => segments.join(KEY_PATH_DELIMITER);
187
+ const createKeyPath = (key, prefix) => {
188
+ const segments = keyPathToSegments(prefix || '');
189
+ segments.push(key);
190
+ return segmentsToKeyPath(segments);
191
+ };
192
+ /**
193
+ * Given a `keyPath`, set it to be `value` on `subject`, creating any intermediate
194
+ * objects along the way.
195
+ *
196
+ * @param {Object} subject The object on which to set value.
197
+ * @param {string} keyPath The key path at which to set value.
198
+ * @param {Object} value The value to store at the given key path.
199
+ * @returns {Object} Updated subject.
200
+ */
201
+ const setAtKeyPath = (subject, keyPath, value) => {
202
+ const segments = keyPathToSegments(keyPath);
203
+ segments.reduce((prevSubject, key, idx) => {
204
+ if (typeof prevSubject[key] === 'undefined') {
205
+ prevSubject[key] = {};
206
+ }
207
+ if (idx === segments.length - 1) {
208
+ prevSubject[key] = value;
209
+ }
210
+ return prevSubject[key];
211
+ }, subject);
212
+ return subject;
213
+ };
214
+ /**
215
+ * Given a dictionary of (nested) keys to function, flatten them to a map
216
+ * from key path to function.
217
+ *
218
+ * @param {Object} methods The (potentially nested) object to serialize.
219
+ * @param {string} prefix A string with which to prefix entries. Typically not intended to be used by consumers.
220
+ * @returns {Object} An map from key path in `methods` to functions.
221
+ */
222
+ const serializeMethods = (methods, prefix) => {
223
+ const flattenedMethods = {};
224
+ Object.keys(methods).forEach((key) => {
225
+ const value = methods[key];
226
+ const keyPath = createKeyPath(key, prefix);
227
+ if (typeof value === 'object') {
228
+ // Recurse into any nested children.
229
+ Object.assign(flattenedMethods, serializeMethods(value, keyPath));
230
+ }
231
+ if (typeof value === 'function') {
232
+ // If we've found a method, expose it.
233
+ flattenedMethods[keyPath] = value;
234
+ }
235
+ });
236
+ return flattenedMethods;
237
+ };
238
+ /**
239
+ * Given a map of key paths to functions, unpack the key paths to an object.
240
+ *
241
+ * @param {Object} flattenedMethods A map of key paths to functions to unpack.
242
+ * @returns {Object} A (potentially nested) map of functions.
243
+ */
244
+ const deserializeMethods = (flattenedMethods) => {
245
+ const methods = {};
246
+ for (const keyPath in flattenedMethods) {
247
+ setAtKeyPath(methods, keyPath, flattenedMethods[keyPath]);
248
+ }
249
+ return methods;
106
250
  };
107
251
 
108
- /**
109
- * Get the value of a custom field from a raw value.
110
- *
111
- * @param customFieldDefinition the definition of the custom field
112
- * @param newValue the new value to set
113
- * @returns { CustomFieldValue } an updated CustomFieldValue
114
- */
115
- const getCustomFieldValueFromRawValue = (customFieldDefinition, newValue) => {
116
- if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.BOOLEAN) {
117
- return {
118
- booleanValue: newValue ? true : false,
119
- type: irisAppRuntimeCoreApi.CustomFieldType.BOOLEAN,
120
- };
121
- }
122
- else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.DATE) {
123
- return {
124
- dateValue: getDateValue(newValue),
125
- type: irisAppRuntimeCoreApi.CustomFieldType.DATE,
126
- };
127
- }
128
- else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.DROPDOWN) {
129
- const stringArrayValue = [];
130
- if (Array.isArray(newValue)) {
131
- newValue.forEach(item => {
132
- if (typeof item === "string") {
133
- stringArrayValue.push(item);
134
- }
135
- else {
136
- stringArrayValue.push(item === null || item === void 0 ? void 0 : item.value);
137
- }
138
- });
139
- }
140
- else {
141
- if (typeof newValue === "string") {
142
- stringArrayValue.push(newValue);
143
- }
144
- else if (typeof newValue === "object") {
145
- stringArrayValue.push(newValue === null || newValue === void 0 ? void 0 : newValue.value);
146
- }
147
- }
148
- return {
149
- stringArrayValue: stringArrayValue,
150
- type: irisAppRuntimeCoreApi.CustomFieldType.DROPDOWN,
151
- };
152
- }
153
- else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.EMAIL) {
154
- return {
155
- stringValue: getStringValue(newValue),
156
- type: irisAppRuntimeCoreApi.CustomFieldType.EMAIL,
157
- };
158
- }
159
- else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.NUMBER) {
160
- let value = customFieldDefinition.isInteger
161
- ? parseInt(newValue)
162
- : parseFloat(newValue);
163
- if (isNaN(value)) {
164
- value = null;
165
- }
166
- return {
167
- numberValue: value,
168
- type: irisAppRuntimeCoreApi.CustomFieldType.NUMBER,
169
- };
170
- }
171
- else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.PHONE_NUMBER) {
172
- return {
173
- stringValue: getStringValue(newValue),
174
- type: irisAppRuntimeCoreApi.CustomFieldType.PHONE_NUMBER,
175
- };
176
- }
177
- else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.STRING) {
178
- return {
179
- stringValue: getStringValue(newValue),
180
- type: irisAppRuntimeCoreApi.CustomFieldType.STRING,
181
- };
182
- }
183
- else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.WEB_ADDRESS) {
184
- return {
185
- stringValue: getStringValue(newValue),
186
- type: irisAppRuntimeCoreApi.CustomFieldType.WEB_ADDRESS,
187
- };
188
- }
189
- throw new Error("Unsupported custom field type");
190
- };
191
- /**
192
- * Convert the received value to a string
193
- */
194
- const getStringValue = (value) => {
195
- const stringValue = value;
196
- if (stringValue === null || stringValue === undefined) {
197
- return null;
198
- }
199
- else if (stringValue.trim().length === 0) {
200
- return null;
201
- }
202
- else {
203
- return stringValue.trim();
204
- }
205
- };
206
- /**
207
- * Format the received value to a date string
208
- * yyyy-mm-dd
209
- */
210
- const getDateValue = (value) => {
211
- const date = new Date(value);
212
- const day = date.toLocaleString("en-US", { day: "2-digit" });
213
- const month = date.toLocaleString("en-US", { month: "2-digit" });
214
- const year = date.toLocaleString("en-US", { year: "numeric" });
215
- return `${year}-${month}-${day}`;
216
- };
217
- const CustomFieldRuntime = {
218
- getCustomFieldsFor: (entity) => __awaiter(void 0, void 0, void 0, function* () {
219
- const api = yield getHostConnector();
220
- return api.getCustomFieldsFor(entity);
221
- }),
222
- setCustomFieldsFor: (entity, values) => __awaiter(void 0, void 0, void 0, function* () {
223
- const api = yield getHostConnector();
224
- return api.setCustomFieldsFor(entity, values);
225
- }),
226
- setCustomFieldsFromFormData: (entity, formData, originalDefinitions) => __awaiter(void 0, void 0, void 0, function* () {
227
- const api = yield getHostConnector();
228
- const values = [];
229
- Object.keys(formData).forEach(key => {
230
- var _a;
231
- const found = (_a = originalDefinitions.find(originalDefinition => originalDefinition.definition.key === key)) === null || _a === void 0 ? void 0 : _a.definition;
232
- if (found) {
233
- values.push({
234
- definitionKey: key,
235
- value: getCustomFieldValueFromRawValue(found, formData[key]),
236
- });
237
- }
238
- else {
239
- throw new Error("Unsupported custom field type: " + key);
240
- }
241
- });
242
- return api.setCustomFieldsFor(entity, values);
243
- }),
252
+ /**
253
+ * Augments an object with methods that match those defined by the remote. When these methods are
254
+ * called, a "call" message will be sent to the remote, the remote's corresponding method will be
255
+ * executed, and the method's return value will be returned via a message.
256
+ * @param {Object} callSender Sender object that should be augmented with methods.
257
+ * @param {Object} info Information about the local and remote windows.
258
+ * @param {Array} methodKeyPaths Key paths of methods available to be called on the remote.
259
+ * @param {Promise} destructionPromise A promise resolved when destroy() is called on the penpal
260
+ * connection.
261
+ * @returns {Object} The call sender object with methods that may be called.
262
+ */
263
+ var connectCallSender = (callSender, info, methodKeyPaths, destroyConnection, log) => {
264
+ const { localName, local, remote, originForSending, originForReceiving, } = info;
265
+ let destroyed = false;
266
+ log(`${localName}: Connecting call sender`);
267
+ const createMethodProxy = (methodName) => {
268
+ return (...args) => {
269
+ log(`${localName}: Sending ${methodName}() call`);
270
+ // This handles the case where the iframe has been removed from the DOM
271
+ // (and therefore its window closed), the consumer has not yet
272
+ // called destroy(), and the user calls a method exposed by
273
+ // the remote. We detect the iframe has been removed and force
274
+ // a destroy() immediately so that the consumer sees the error saying
275
+ // the connection has been destroyed. We wrap this check in a try catch
276
+ // because Edge throws an "Object expected" error when accessing
277
+ // contentWindow.closed on a contentWindow from an iframe that's been
278
+ // removed from the DOM.
279
+ let iframeRemoved;
280
+ try {
281
+ if (remote.closed) {
282
+ iframeRemoved = true;
283
+ }
284
+ }
285
+ catch (e) {
286
+ iframeRemoved = true;
287
+ }
288
+ if (iframeRemoved) {
289
+ destroyConnection();
290
+ }
291
+ if (destroyed) {
292
+ const error = new Error(`Unable to send ${methodName}() call due ` + `to destroyed connection`);
293
+ error.code = ErrorCode.ConnectionDestroyed;
294
+ throw error;
295
+ }
296
+ return new Promise((resolve, reject) => {
297
+ const id = generateId();
298
+ const handleMessageEvent = (event) => {
299
+ if (event.source !== remote ||
300
+ event.data.penpal !== MessageType.Reply ||
301
+ event.data.id !== id) {
302
+ return;
303
+ }
304
+ if (originForReceiving !== '*' &&
305
+ event.origin !== originForReceiving) {
306
+ log(`${localName} received message from origin ${event.origin} which did not match expected origin ${originForReceiving}`);
307
+ return;
308
+ }
309
+ const replyMessage = event.data;
310
+ log(`${localName}: Received ${methodName}() reply`);
311
+ local.removeEventListener(NativeEventType.Message, handleMessageEvent);
312
+ let returnValue = replyMessage.returnValue;
313
+ if (replyMessage.returnValueIsError) {
314
+ returnValue = deserializeError(returnValue);
315
+ }
316
+ (replyMessage.resolution === Resolution.Fulfilled ? resolve : reject)(returnValue);
317
+ };
318
+ local.addEventListener(NativeEventType.Message, handleMessageEvent);
319
+ const callMessage = {
320
+ penpal: MessageType.Call,
321
+ id,
322
+ methodName,
323
+ args,
324
+ };
325
+ remote.postMessage(callMessage, originForSending);
326
+ });
327
+ };
328
+ };
329
+ // Wrap each method in a proxy which sends it to the corresponding receiver.
330
+ const flattenedMethods = methodKeyPaths.reduce((api, name) => {
331
+ api[name] = createMethodProxy(name);
332
+ return api;
333
+ }, {});
334
+ // Unpack the structure of the provided methods object onto the CallSender, exposing
335
+ // the methods in the same shape they were provided.
336
+ Object.assign(callSender, deserializeMethods(flattenedMethods));
337
+ return () => {
338
+ destroyed = true;
339
+ };
340
+ };
341
+
342
+ /**
343
+ * Starts a timeout and calls the callback with an error
344
+ * if the timeout completes before the stop function is called.
345
+ */
346
+ var startConnectionTimeout = (timeout, callback) => {
347
+ let timeoutId;
348
+ if (timeout !== undefined) {
349
+ timeoutId = window.setTimeout(() => {
350
+ const error = new Error(`Connection timed out after ${timeout}ms`);
351
+ error.code = ErrorCode.ConnectionTimeout;
352
+ callback(error);
353
+ }, timeout);
354
+ }
355
+ return () => {
356
+ clearTimeout(timeoutId);
357
+ };
358
+ };
359
+
360
+ /**
361
+ * Handles a SYN-ACK handshake message.
362
+ */
363
+ var handleSynAckMessageFactory = (parentOrigin, serializedMethods, destructor, log) => {
364
+ const { destroy, onDestroy } = destructor;
365
+ return (event) => {
366
+ let originQualifies = parentOrigin instanceof RegExp
367
+ ? parentOrigin.test(event.origin)
368
+ : parentOrigin === '*' || parentOrigin === event.origin;
369
+ if (!originQualifies) {
370
+ log(`Child: Handshake - Received SYN-ACK from origin ${event.origin} which did not match expected origin ${parentOrigin}`);
371
+ return;
372
+ }
373
+ log('Child: Handshake - Received SYN-ACK, responding with ACK');
374
+ // If event.origin is "null", the remote protocol is file: or data: and we
375
+ // must post messages with "*" as targetOrigin when sending messages.
376
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage#Using_window.postMessage_in_extensions
377
+ const originForSending = event.origin === 'null' ? '*' : event.origin;
378
+ const ackMessage = {
379
+ penpal: MessageType.Ack,
380
+ methodNames: Object.keys(serializedMethods),
381
+ };
382
+ window.parent.postMessage(ackMessage, originForSending);
383
+ const info = {
384
+ localName: 'Child',
385
+ local: window,
386
+ remote: window.parent,
387
+ originForSending,
388
+ originForReceiving: event.origin,
389
+ };
390
+ const destroyCallReceiver = connectCallReceiver(info, serializedMethods, log);
391
+ onDestroy(destroyCallReceiver);
392
+ const callSender = {};
393
+ const destroyCallSender = connectCallSender(callSender, info, event.data.methodNames, destroy, log);
394
+ onDestroy(destroyCallSender);
395
+ return callSender;
396
+ };
397
+ };
398
+
399
+ const areGlobalsAccessible = () => {
400
+ try {
401
+ clearTimeout();
402
+ }
403
+ catch (e) {
404
+ return false;
405
+ }
406
+ return true;
407
+ };
408
+ /**
409
+ * Attempts to establish communication with the parent window.
410
+ */
411
+ var connectToParent = (options = {}) => {
412
+ const { parentOrigin = '*', methods = {}, timeout, debug = false } = options;
413
+ const log = createLogger(debug);
414
+ const destructor = createDestructor('Child', log);
415
+ const { destroy, onDestroy } = destructor;
416
+ const serializedMethods = serializeMethods(methods);
417
+ const handleSynAckMessage = handleSynAckMessageFactory(parentOrigin, serializedMethods, destructor, log);
418
+ const sendSynMessage = () => {
419
+ log('Child: Handshake - Sending SYN');
420
+ const synMessage = { penpal: MessageType.Syn };
421
+ const parentOriginForSyn = parentOrigin instanceof RegExp ? '*' : parentOrigin;
422
+ window.parent.postMessage(synMessage, parentOriginForSyn);
423
+ };
424
+ const promise = new Promise((resolve, reject) => {
425
+ const stopConnectionTimeout = startConnectionTimeout(timeout, destroy);
426
+ const handleMessage = (event) => {
427
+ // Under niche scenarios, we get into this function after
428
+ // the iframe has been removed from the DOM. In Edge, this
429
+ // results in "Object expected" errors being thrown when we
430
+ // try to access properties on window (global properties).
431
+ // For this reason, we try to access a global up front (clearTimeout)
432
+ // and if it fails we can assume the iframe has been removed
433
+ // and we ignore the message event.
434
+ if (!areGlobalsAccessible()) {
435
+ return;
436
+ }
437
+ if (event.source !== parent || !event.data) {
438
+ return;
439
+ }
440
+ if (event.data.penpal === MessageType.SynAck) {
441
+ const callSender = handleSynAckMessage(event);
442
+ if (callSender) {
443
+ window.removeEventListener(NativeEventType.Message, handleMessage);
444
+ stopConnectionTimeout();
445
+ resolve(callSender);
446
+ }
447
+ }
448
+ };
449
+ window.addEventListener(NativeEventType.Message, handleMessage);
450
+ sendSynMessage();
451
+ onDestroy((error) => {
452
+ window.removeEventListener(NativeEventType.Message, handleMessage);
453
+ if (error) {
454
+ reject(error);
455
+ }
456
+ });
457
+ });
458
+ return {
459
+ promise,
460
+ destroy() {
461
+ // Don't allow consumer to pass an error into destroy.
462
+ destroy();
463
+ },
464
+ };
465
+ };
466
+
467
+ /**
468
+ * Setup using the subscribedMethods to subscribe to events from the host.
469
+ *
470
+ * @param subscribedMethods the methods to subscribe to
471
+ * @returns { Connection<HostConnectorApi> } the connection to the host
472
+ */
473
+ const setupHostConnector = (subscribedMethods) => {
474
+ var _a;
475
+ const methods = Object.assign({ onGlobalSelectionChanged: () => { }, onTokenChanged: () => { }, onAssetSortingStateChanged: () => { } }, subscribedMethods);
476
+ const connection = connectToParent({ methods });
477
+ (_a = connection.promise) === null || _a === void 0 ? void 0 : _a.catch(err => {
478
+ // TODO consider how to handle this catch
479
+ // eslint-disable-next-line no-console
480
+ console.log(err);
481
+ });
482
+ return connection;
483
+ };
484
+ const hostConnector = setupHostConnector({});
485
+ /**
486
+ * Gets the host connector.
487
+ *
488
+ * @returns { Promise<HostConnectorApi> } the connection to the host
489
+ */
490
+ const getHostConnector = () => {
491
+ return hostConnector.promise;
492
+ };
493
+
494
+ const AnalyticsContextRuntime = {
495
+ logPageView: (details) => __awaiter(void 0, void 0, void 0, function* () {
496
+ const api = yield getHostConnector();
497
+ api.logPageView(details);
498
+ }),
499
+ logError: (details) => __awaiter(void 0, void 0, void 0, function* () {
500
+ const api = yield getHostConnector();
501
+ api.logError(details);
502
+ }),
503
+ logEvent: (eventName, details, nameSupplement) => __awaiter(void 0, void 0, void 0, function* () {
504
+ const api = yield getHostConnector();
505
+ api.logEvent(eventName, details, nameSupplement);
506
+ }),
507
+ setUserProperty: (name, data) => __awaiter(void 0, void 0, void 0, function* () {
508
+ const api = yield getHostConnector();
509
+ api.setUserProperty(name, data);
510
+ }),
511
+ };
512
+
513
+ const AssetRuntime = {
514
+ getAssetInfo: () => __awaiter(void 0, void 0, void 0, function* () {
515
+ const api = yield getHostConnector();
516
+ return api.getAssetInfo();
517
+ }),
518
+ };
519
+
520
+ const AssetSortingRuntime = {
521
+ getAssetSortingState: () => __awaiter(void 0, void 0, void 0, function* () {
522
+ const api = yield getHostConnector();
523
+ return api.getAssetSortingState();
524
+ }),
525
+ setAssetSortingState: (...args) => __awaiter(void 0, void 0, void 0, function* () {
526
+ const api = yield getHostConnector();
527
+ return api.setAssetSortingState(...args);
528
+ }),
529
+ };
530
+
531
+ const CurrentUserRuntime = {
532
+ getCurrentUserContext: () => __awaiter(void 0, void 0, void 0, function* () {
533
+ const api = yield getHostConnector();
534
+ return api.getCurrentUserContext();
535
+ }),
536
+ getCurrentUserRole: (userIds) => __awaiter(void 0, void 0, void 0, function* () {
537
+ const api = yield getHostConnector();
538
+ return api.getCurrentUserRole(userIds);
539
+ }),
540
+ };
541
+
542
+ /**
543
+ * Get the value of a custom field from a raw value.
544
+ *
545
+ * @param customFieldDefinition the definition of the custom field
546
+ * @param newValue the new value to set
547
+ * @returns { CustomFieldValue } an updated CustomFieldValue
548
+ */
549
+ const getCustomFieldValueFromRawValue = (customFieldDefinition, newValue) => {
550
+ if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.BOOLEAN) {
551
+ return {
552
+ booleanValue: newValue ? true : false,
553
+ type: irisAppRuntimeCoreApi.CustomFieldType.BOOLEAN,
554
+ };
555
+ }
556
+ else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.DATE) {
557
+ return {
558
+ dateValue: getDateValue(newValue),
559
+ type: irisAppRuntimeCoreApi.CustomFieldType.DATE,
560
+ };
561
+ }
562
+ else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.DROPDOWN) {
563
+ const stringArrayValue = [];
564
+ if (Array.isArray(newValue)) {
565
+ newValue.forEach(item => {
566
+ if (typeof item === "string") {
567
+ stringArrayValue.push(item);
568
+ }
569
+ else {
570
+ stringArrayValue.push(item === null || item === void 0 ? void 0 : item.value);
571
+ }
572
+ });
573
+ }
574
+ else {
575
+ if (typeof newValue === "string") {
576
+ stringArrayValue.push(newValue);
577
+ }
578
+ else if (typeof newValue === "object") {
579
+ stringArrayValue.push(newValue === null || newValue === void 0 ? void 0 : newValue.value);
580
+ }
581
+ }
582
+ return {
583
+ stringArrayValue: stringArrayValue,
584
+ type: irisAppRuntimeCoreApi.CustomFieldType.DROPDOWN,
585
+ };
586
+ }
587
+ else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.EMAIL) {
588
+ return {
589
+ stringValue: getStringValue(newValue),
590
+ type: irisAppRuntimeCoreApi.CustomFieldType.EMAIL,
591
+ };
592
+ }
593
+ else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.NUMBER) {
594
+ let value = customFieldDefinition.isInteger
595
+ ? parseInt(newValue)
596
+ : parseFloat(newValue);
597
+ if (isNaN(value)) {
598
+ value = null;
599
+ }
600
+ return {
601
+ numberValue: value,
602
+ type: irisAppRuntimeCoreApi.CustomFieldType.NUMBER,
603
+ };
604
+ }
605
+ else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.PHONE_NUMBER) {
606
+ return {
607
+ stringValue: getStringValue(newValue),
608
+ type: irisAppRuntimeCoreApi.CustomFieldType.PHONE_NUMBER,
609
+ };
610
+ }
611
+ else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.STRING) {
612
+ return {
613
+ stringValue: getStringValue(newValue),
614
+ type: irisAppRuntimeCoreApi.CustomFieldType.STRING,
615
+ };
616
+ }
617
+ else if (customFieldDefinition.type === irisAppRuntimeCoreApi.CustomFieldType.WEB_ADDRESS) {
618
+ return {
619
+ stringValue: getStringValue(newValue),
620
+ type: irisAppRuntimeCoreApi.CustomFieldType.WEB_ADDRESS,
621
+ };
622
+ }
623
+ throw new Error("Unsupported custom field type");
624
+ };
625
+ /**
626
+ * Convert the received value to a string
627
+ */
628
+ const getStringValue = (value) => {
629
+ const stringValue = value;
630
+ if (stringValue === null || stringValue === undefined) {
631
+ return null;
632
+ }
633
+ else if (stringValue.trim().length === 0) {
634
+ return null;
635
+ }
636
+ else {
637
+ return stringValue.trim();
638
+ }
639
+ };
640
+ /**
641
+ * Format the received value to a date string
642
+ * yyyy-mm-dd
643
+ */
644
+ const getDateValue = (value) => {
645
+ const date = new Date(value);
646
+ const day = date.toLocaleString("en-US", { day: "2-digit" });
647
+ const month = date.toLocaleString("en-US", { month: "2-digit" });
648
+ const year = date.toLocaleString("en-US", { year: "numeric" });
649
+ return `${year}-${month}-${day}`;
650
+ };
651
+ const CustomFieldRuntime = {
652
+ getCustomFieldsFor: (entity) => __awaiter(void 0, void 0, void 0, function* () {
653
+ const api = yield getHostConnector();
654
+ return api.getCustomFieldsFor(entity);
655
+ }),
656
+ setCustomFieldsFor: (entity, values) => __awaiter(void 0, void 0, void 0, function* () {
657
+ const api = yield getHostConnector();
658
+ return api.setCustomFieldsFor(entity, values);
659
+ }),
660
+ setCustomFieldsFromFormData: (entity, formData, originalDefinitions) => __awaiter(void 0, void 0, void 0, function* () {
661
+ const api = yield getHostConnector();
662
+ const values = [];
663
+ Object.keys(formData).forEach(key => {
664
+ var _a;
665
+ const found = (_a = originalDefinitions.find(originalDefinition => originalDefinition.definition.key === key)) === null || _a === void 0 ? void 0 : _a.definition;
666
+ if (found) {
667
+ values.push({
668
+ definitionKey: key,
669
+ value: getCustomFieldValueFromRawValue(found, formData[key]),
670
+ });
671
+ }
672
+ else {
673
+ throw new Error("Unsupported custom field type: " + key);
674
+ }
675
+ });
676
+ return api.setCustomFieldsFor(entity, values);
677
+ }),
244
678
  };
245
679
 
246
- const EnvironmentRuntime = {
247
- getEnvironmentContext: () => __awaiter(void 0, void 0, void 0, function* () {
248
- const api = yield getHostConnector();
249
- return api.getEnvironmentContext();
250
- }),
680
+ const EnvironmentRuntime = {
681
+ getEnvironmentContext: () => __awaiter(void 0, void 0, void 0, function* () {
682
+ const api = yield getHostConnector();
683
+ return api.getEnvironmentContext();
684
+ }),
251
685
  };
252
686
 
253
- const GlobalSelectionRuntime = {
254
- getGlobalSelection: () => __awaiter(void 0, void 0, void 0, function* () {
255
- const api = yield getHostConnector();
256
- return api.getGlobalSelectionContext();
257
- }),
687
+ const GlobalSelectionRuntime = {
688
+ getGlobalSelection: () => __awaiter(void 0, void 0, void 0, function* () {
689
+ const api = yield getHostConnector();
690
+ return api.getGlobalSelectionContext();
691
+ }),
258
692
  };
259
693
 
260
- const OemBrandingContextRuntime = {
261
- getOemBrandingContextRuntime: () => __awaiter(void 0, void 0, void 0, function* () {
262
- const api = yield getHostConnector();
263
- return {
264
- getOemImage: api.getOemImage,
265
- getOemBranding: api.getOemBranding,
266
- };
267
- }),
694
+ const OemBrandingContextRuntime = {
695
+ getOemBrandingContextRuntime: () => __awaiter(void 0, void 0, void 0, function* () {
696
+ const api = yield getHostConnector();
697
+ return {
698
+ getOemImage: api.getOemImage,
699
+ getOemBranding: api.getOemBranding,
700
+ };
701
+ }),
268
702
  };
269
703
 
270
- const NavigationRuntime = {
271
- setDeepLink: (props) => __awaiter(void 0, void 0, void 0, function* () {
272
- const api = yield getHostConnector();
273
- return api.setDeepLink(props);
274
- }),
275
- gotoAssetHome: (assetId, options) => __awaiter(void 0, void 0, void 0, function* () {
276
- const api = yield getHostConnector();
277
- return api.gotoAssetHome(assetId, options);
278
- }),
279
- gotoSiteHome: (siteId, options) => __awaiter(void 0, void 0, void 0, function* () {
280
- const api = yield getHostConnector();
281
- return api.gotoSiteHome(siteId, options);
282
- }),
704
+ const NavigationRuntime = {
705
+ setDeepLink: (props) => __awaiter(void 0, void 0, void 0, function* () {
706
+ const api = yield getHostConnector();
707
+ return api.setDeepLink(props);
708
+ }),
709
+ gotoAssetHome: (assetId, options) => __awaiter(void 0, void 0, void 0, function* () {
710
+ const api = yield getHostConnector();
711
+ return api.gotoAssetHome(assetId, options);
712
+ }),
713
+ gotoSiteHome: (siteId, options) => __awaiter(void 0, void 0, void 0, function* () {
714
+ const api = yield getHostConnector();
715
+ return api.gotoSiteHome(siteId, options);
716
+ }),
283
717
  };
284
718
 
285
- const ParamsRuntime = {
286
- getAppName: () => __awaiter(void 0, void 0, void 0, function* () {
287
- const api = yield getHostConnector();
288
- return api.getAppName();
289
- }),
290
- getOrgName: () => __awaiter(void 0, void 0, void 0, function* () {
291
- const api = yield getHostConnector();
292
- return api.getOrgName();
293
- }),
294
- getExtensionName: () => __awaiter(void 0, void 0, void 0, function* () {
295
- const api = yield getHostConnector();
296
- return api.getExtensionName();
297
- }),
719
+ const ParamsRuntime = {
720
+ getAppName: () => __awaiter(void 0, void 0, void 0, function* () {
721
+ const api = yield getHostConnector();
722
+ return api.getAppName();
723
+ }),
724
+ getOrgName: () => __awaiter(void 0, void 0, void 0, function* () {
725
+ const api = yield getHostConnector();
726
+ return api.getOrgName();
727
+ }),
728
+ getExtensionName: () => __awaiter(void 0, void 0, void 0, function* () {
729
+ const api = yield getHostConnector();
730
+ return api.getExtensionName();
731
+ }),
298
732
  };
299
733
 
300
- const RestRuntime = {
301
- apiHost: "https://API_HOST",
302
- request(path, method, requestParams, body, bodyType, secureByDefault) {
303
- return __awaiter(this, void 0, void 0, function* () {
304
- const api = yield getHostConnector();
305
- return api.requestTrackunitRestApi(path, method, requestParams, body, bodyType, secureByDefault);
306
- });
307
- },
734
+ const RestRuntime = {
735
+ apiHost: "https://API_HOST",
736
+ request(path, method, requestParams, body, bodyType, secureByDefault) {
737
+ return __awaiter(this, void 0, void 0, function* () {
738
+ const api = yield getHostConnector();
739
+ return api.requestTrackunitRestApi(path, method, requestParams, body, bodyType, secureByDefault);
740
+ });
741
+ },
308
742
  };
309
743
 
310
- const SiteRuntime = {
311
- getSiteInfo: () => __awaiter(void 0, void 0, void 0, function* () {
312
- const api = yield getHostConnector();
313
- return api.getSiteInfo();
314
- }),
744
+ const SiteRuntime = {
745
+ getSiteInfo: () => __awaiter(void 0, void 0, void 0, function* () {
746
+ const api = yield getHostConnector();
747
+ return api.getSiteInfo();
748
+ }),
315
749
  };
316
750
 
317
- const ToastRuntime = {
318
- addToast(toast) {
319
- var _a, _b;
320
- return __awaiter(this, void 0, void 0, function* () {
321
- const api = yield getHostConnector();
322
- return api
323
- .addToast(Object.assign(Object.assign({}, toast), { primaryAction: (_a = toast.primaryAction) === null || _a === void 0 ? void 0 : _a.label, secondaryAction: (_b = toast.secondaryAction) === null || _b === void 0 ? void 0 : _b.label }))
324
- .then(res => {
325
- var _a, _b, _c, _d;
326
- switch (res) {
327
- case "primaryAction":
328
- (_b = (_a = toast.primaryAction) === null || _a === void 0 ? void 0 : _a.onClick) === null || _b === void 0 ? void 0 : _b.call(_a);
329
- break;
330
- case "secondaryAction":
331
- (_d = (_c = toast.secondaryAction) === null || _c === void 0 ? void 0 : _c.onClick) === null || _d === void 0 ? void 0 : _d.call(_c);
332
- break;
333
- }
334
- });
335
- });
336
- },
751
+ const ToastRuntime = {
752
+ addToast(toast) {
753
+ var _a, _b;
754
+ return __awaiter(this, void 0, void 0, function* () {
755
+ const api = yield getHostConnector();
756
+ return api
757
+ .addToast(Object.assign(Object.assign({}, toast), { primaryAction: (_a = toast.primaryAction) === null || _a === void 0 ? void 0 : _a.label, secondaryAction: (_b = toast.secondaryAction) === null || _b === void 0 ? void 0 : _b.label }))
758
+ .then(res => {
759
+ var _a, _b, _c, _d;
760
+ switch (res) {
761
+ case "primaryAction":
762
+ (_b = (_a = toast.primaryAction) === null || _a === void 0 ? void 0 : _a.onClick) === null || _b === void 0 ? void 0 : _b.call(_a);
763
+ break;
764
+ case "secondaryAction":
765
+ (_d = (_c = toast.secondaryAction) === null || _c === void 0 ? void 0 : _c.onClick) === null || _d === void 0 ? void 0 : _d.call(_c);
766
+ break;
767
+ }
768
+ });
769
+ });
770
+ },
337
771
  };
338
772
 
339
- const TokenRuntime = {
340
- getTokenContext: () => __awaiter(void 0, void 0, void 0, function* () {
341
- const api = yield getHostConnector();
342
- return api.getTokenContext();
343
- }),
773
+ const TokenRuntime = {
774
+ getTokenContext: () => __awaiter(void 0, void 0, void 0, function* () {
775
+ const api = yield getHostConnector();
776
+ return api.getTokenContext();
777
+ }),
344
778
  };
345
779
 
346
- const UserSubscriptionRuntime = {
347
- getUserSubscriptionContext: () => __awaiter(void 0, void 0, void 0, function* () {
348
- const api = yield getHostConnector();
349
- return api.getUserSubscriptionContext();
350
- }),
780
+ const UserSubscriptionRuntime = {
781
+ getUserSubscriptionContext: () => __awaiter(void 0, void 0, void 0, function* () {
782
+ const api = yield getHostConnector();
783
+ return api.getUserSubscriptionContext();
784
+ }),
351
785
  };
352
786
 
353
787
  exports.AnalyticsContextRuntime = AnalyticsContextRuntime;