@adobe/uix-guest 1.0.0 → 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -1 +1 @@
1
- {"version":3,"file":"guest-server.d.ts","sourceRoot":"","sources":["../src/guest-server.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEhC;;;;;;;;;;GAUG;AACH,qBAAa,WAAW,CAAC,QAAQ,SAAS,SAAS,CAAE,SAAQ,KAAK,CAAC,QAAQ,CAAC;IAC1E,OAAO,CAAC,YAAY,CAAW;IAC/B,QAAQ,EAAE,aAAa,CAAC;IACxB,SAAS,CAAC,eAAe;;;;;;;;;;;;;;;IAOzB;;OAEG;IACH,aAAa,EAAE,aAAa,CAAC;IAC7B;;OAEG;IACH,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC;IAC9B;;;;;;;OAOG;IACG,QAAQ,CAAC,kBAAkB,EAAE,QAAQ,EAAE,QAAQ,EAAE,aAAa;CAKrE"}
1
+ {"version":3,"file":"guest-server.d.ts","sourceRoot":"","sources":["../src/guest-server.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAEhC;;;;;;;;;;GAUG;AACH,qBAAa,WAAW,CAAC,QAAQ,SAAS,SAAS,CAAE,SAAQ,KAAK,CAAC,QAAQ,CAAC;IAC1E,OAAO,CAAC,YAAY,CAAW;IAC/B,QAAQ,EAAE,aAAa,CAAC;IACxB,SAAS,CAAC,eAAe;;;;;;;;;;;;;;;IAOzB;;OAEG;IACH,aAAa,EAAE,aAAa,CAAC;IAC7B;;OAEG;IACH,IAAI,EAAE,KAAK,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,CAAC;IAC9B;;;;;;;OAOG;IACG,QAAQ,CAAC,kBAAkB,EAAE,QAAQ,EAAE,QAAQ,EAAE,aAAa;CAQrE"}
@@ -1 +1 @@
1
- {"version":3,"file":"guest-ui.d.ts","sourceRoot":"","sources":["../src/guest-ui.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,UAAU,EACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,KAAK,EACL,WAAW,EACX,uBAAuB,EACvB,mBAAmB,EACnB,uBAAuB,EACvB,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AACH,qBAAa,OAAO,CAAC,KAAK,SAAS,UAAU,CAAE,SAAQ,KAAK,CAAC,KAAK,CAAC;IACjE;;OAEG;gBACS,MAAM,EAAE,WAAW;IAqB/B;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAkB/B;;;OAGG;IACI,aAAa,EAAE,uBAAuB,CAAC;IAC9C;;;OAGG;IACI,aAAa,EAAE,uBAAuB,CAAC;IAC9C;;;OAGG;IACI,SAAS,EAAE,mBAAmB,CAAC;IACtC;;;OAGG;IACI,KAAK,EAAE,eAAe,CAAC;IAC9B;;OAEG;IACH,IAAI,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC;IAC5B,SAAS,CAAC,cAAc,EAAG,gBAAgB,CAAC,gBAAgB,CAAC,CAAC;CAC/D"}
1
+ {"version":3,"file":"guest-ui.d.ts","sourceRoot":"","sources":["../src/guest-ui.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,UAAU,EACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,KAAK,EACL,WAAW,EACX,uBAAuB,EACvB,mBAAmB,EACnB,uBAAuB,EACvB,eAAe,EAChB,MAAM,SAAS,CAAC;AAEjB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoEG;AACH,qBAAa,OAAO,CAAC,KAAK,SAAS,UAAU,CAAE,SAAQ,KAAK,CAAC,KAAK,CAAC;IACjE;;OAEG;gBACS,MAAM,EAAE,WAAW;IAqB/B;;OAEG;IACH,OAAO,CAAC,uBAAuB;IAoB/B;;;OAGG;IACI,aAAa,EAAE,uBAAuB,CAAC;IAC9C;;;OAGG;IACI,aAAa,EAAE,uBAAuB,CAAC;IAC9C;;;OAGG;IACI,SAAS,EAAE,mBAAmB,CAAC;IACtC;;;OAGG;IACI,KAAK,EAAE,eAAe,CAAC;IAC9B;;OAEG;IACH,IAAI,EAAE,cAAc,CAAC,KAAK,CAAC,CAAC;IAC5B,SAAS,CAAC,cAAc,EAAG,gBAAgB,CAAC,gBAAgB,CAAC,CAAC;CAC/D"}
@@ -495,7 +495,7 @@ var AdobeUIXGuest = (() => {
495
495
  });
496
496
  }
497
497
  var NS_ROOT = "_$pg";
498
- var VERSION = "1.0.0";
498
+ var VERSION = "1.0.1";
499
499
  var INIT_CALLBACK = `${NS_ROOT}_init_cb`;
500
500
  function isPlainObject(value) {
501
501
  if (!value || typeof value !== "object") {
@@ -1563,11 +1563,13 @@ Message must be an object with "${NS_ROOT}" property, which must be an object wi
1563
1563
  let margin = 0;
1564
1564
  for (let i = 0; i < elems.length; i++) {
1565
1565
  const style = elems[i].currentStyle || window.getComputedStyle(elems[i]);
1566
- if (style.marginTop !== "0px") {
1567
- margin = margin + parseInt(style.marginTop);
1566
+ const marginTop = parseInt(style.marginTop);
1567
+ const marginBottom = parseInt(style.marginBottom);
1568
+ if (marginTop > 0) {
1569
+ margin = margin + marginTop;
1568
1570
  }
1569
- if (style.marginBottom !== "0px") {
1570
- margin = margin + parseInt(style.marginBottom);
1571
+ if (marginBottom > 0) {
1572
+ margin = margin + marginBottom;
1571
1573
  }
1572
1574
  }
1573
1575
  return margin;
@@ -1593,7 +1595,10 @@ Message must be an object with "${NS_ROOT}" property, which must be an object wi
1593
1595
  */
1594
1596
  async register(implementedMethods, metadata) {
1595
1597
  this.localMethods = implementedMethods;
1596
- this.metadata = metadata;
1598
+ this.metadata = {
1599
+ ...metadata,
1600
+ extensionId: this.id
1601
+ };
1597
1602
  return this._connect();
1598
1603
  }
1599
1604
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../node_modules/eventemitter3/index.js","../../../uix-core/src/debuglog.ts","../../../uix-core/src/debug-emitter.ts","../../../uix-core/src/emitter.ts","../../../uix-core/src/namespace-proxy.ts","../../../uix-core/src/constants.ts","../../../uix-core/src/value-assertions.ts","../../../uix-core/src/message-wrapper.ts","../../../uix-core/src/object-walker.ts","../../../uix-core/src/rpc/call-receiver.ts","../../../uix-core/src/rpc/call-sender.ts","../../../uix-core/src/remote-subject.ts","../../../uix-core/src/object-simulator.ts","../../../uix-core/src/promises/timed.ts","../../../uix-core/src/tickets.ts","../../../uix-core/src/tunnel/tunnel.ts","../../../uix-core/src/tunnel/tunnel-messenger.ts","../../../uix-core/src/cross-realm-object.ts","../../../uix-core/src/logging-formatters.ts","../../../uix-core/src/promises/wait.ts","../../src/index.ts","../../src/guest.ts","../../src/debug-guest.ts","../../src/guest-ui.ts","../../src/guest-server.ts"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","/**\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * Fancy looking console decorator.\n * @hidden\n * @internal\n */\n\n/** @internal */\nconst isDarkMode = () =>\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-color-scheme: dark)\").matches;\n\n/** @internal */\ntype Layout = {\n padX: number;\n padY: number;\n rounded: number;\n fontSize: number;\n emphasis: Style;\n};\n/** @internal */\ntype HexColor = `#${string}` | \"transparent\";\n/** @internal */\ntype Color = {\n text: HexColor;\n bg: HexColor;\n hilight: HexColor;\n shadow: HexColor;\n};\n/** @internal */\ntype ThemeSpec = Color & Layout;\n\n/** @internal */\nconst Layouts: Record<string, Layout> = {\n medium: {\n padX: 5,\n padY: 3,\n rounded: 4,\n fontSize: 100,\n emphasis: \"font-weight: bold;\",\n },\n small: {\n padX: 3,\n padY: 1,\n rounded: 2,\n fontSize: 95,\n emphasis: \"font-style: italic;\",\n },\n};\n\n/** @internal */\nconst Colors: Record<string, Color> = {\n yellow: {\n text: \"#333333\",\n bg: \"#EBD932\",\n hilight: \"#F7E434\",\n shadow: \"#D1C12C\",\n },\n green: {\n text: \"#333333\",\n bg: \"#96EB5E\",\n hilight: \"#9EF763\",\n shadow: \"#85D154\",\n },\n blue: {\n text: \"#333333\",\n bg: \"#8DD0EB\",\n hilight: \"#88F0F7\",\n shadow: \"#74AED4\",\n },\n gray: isDarkMode()\n ? {\n text: \"#eeeeee\",\n bg: \"transparent\",\n hilight: \"#cecece\",\n shadow: \"#cecece\",\n }\n : {\n text: \"#333333\",\n bg: \"#eeeeee\",\n hilight: \"#f6f6f6\",\n shadow: \"#cecece\",\n },\n};\n\n/** @internal */\ntype ThemeTag = `${keyof typeof Colors} ${keyof typeof Layouts}`;\n\n/**\n * @internal\n */\nexport type Theme = ThemeSpec | ThemeTag;\n\n/** @internal */\ntype LogDecorator = (...args: unknown[]) => unknown[];\n\n/** @internal */\ntype Style = `${string};`;\n\nfunction memoizeUnary<T, U>(fn: (arg: T) => U): typeof fn {\n const cache: Map<T, U> = new Map();\n return (arg) => {\n if (!cache.has(arg)) {\n const result = fn(arg);\n cache.set(arg, result);\n if (cache.size > 100) {\n cache.delete(cache.keys().next().value as T);\n }\n return result;\n }\n return cache.get(arg);\n };\n}\n\nconst toTheme = memoizeUnary((theme: Theme): ThemeSpec => {\n if (typeof theme === \"string\") {\n const [color, size] = theme.split(\" \");\n return {\n ...Colors[color],\n ...Layouts[size],\n };\n }\n return theme;\n});\n\nconst block: Style = `display: inline-block; border: 1px solid;`;\n\nconst flatten = (side: \"left\" | \"right\"): Style =>\n `padding-${side}: 0px; border-${side}-width: 0px; border-top-${side}-radius: 0px; border-bottom-${side}-radius: 0px;`;\n\nconst toColor = ({ bg, hilight, shadow, text }: Color): Style =>\n `color: ${text}; background: ${bg}; border-color: ${hilight} ${shadow} ${shadow} ${hilight};`;\n\nconst toLayout = ({ fontSize, padY, padX, rounded }: Layout) =>\n `font-size: ${fontSize}%; padding: ${padY}px ${padX}px; border-radius: ${rounded}px;`;\n\nconst toBubbleStyle = memoizeUnary((theme: ThemeSpec): string[] => {\n const base = `${block}${toColor(theme)}${toLayout(theme)}`;\n return [\n `${base}${flatten(\"right\")}`,\n `${base}${flatten(\"left\")}${theme.emphasis}`,\n ] as Style[];\n});\n\nfunction toBubblePrepender(\n bubbleLeft: string,\n bubbleRight: string,\n theme: ThemeSpec\n): LogDecorator {\n const prefix = `%c${bubbleLeft}%c ${bubbleRight}`;\n const [left, right] = toBubbleStyle(theme);\n return (args: unknown[]) => {\n const bubbleArgs = [prefix, left, right];\n if (typeof args[0] === \"string\") {\n bubbleArgs[0] = `${prefix}%c ${args.shift() as string}`;\n bubbleArgs.push(\"\"); // reset style\n }\n return [...bubbleArgs, ...args];\n };\n}\n\n/** @internal */\nconst stateTypes = {\n event: \"️⚡️\",\n} as const;\n\nconst stateDelim = \" ⤻ \";\n\n/** @internal */\ntype DebugState = { type: keyof typeof stateTypes; name: string };\n\n// Serialize to memoize.\nconst getStateFormatter = memoizeUnary((stateJson: string) => {\n const stateStack = JSON.parse(stateJson) as unknown as DebugState[];\n const firstState = stateStack.shift();\n const left = stateTypes[firstState.type];\n const right = [\n firstState.name,\n ...stateStack.map((state) => `${stateTypes[state.type]} ${state.name}`),\n ].join(stateDelim);\n return toBubblePrepender(left, right, toTheme(\"gray small\"));\n});\nconst getStatePrepender = (stateStack: DebugState[]) =>\n getStateFormatter(JSON.stringify(stateStack));\n\nconst overrideMethods = [\"log\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n\nconst identity = <T>(x: T) => x;\n\nconst noop = (): (() => undefined) => undefined;\n\n/**\n * A console, plus some methods to track event lifecycles.\n * @internal\n */\nexport interface DebugLogger extends Console {\n /**\n * Stop all logging; methods do nothing\n * @internal\n */\n detach(): void;\n /**\n * Add an event bubble to the log during handler.\n */\n pushState(state: DebugState): void;\n /**\n * Remove the bubble when event is done dispatching\n */\n popState(): void;\n}\n\n/**\n * Returns a console whose methods autoformat with bubbles.\n * @internal\n */\nexport function _customConsole(\n theme: Theme,\n type: string,\n name: string\n): DebugLogger {\n const prepender = toBubblePrepender(`X${type}`, name, toTheme(theme));\n let statePrepender: LogDecorator = identity as LogDecorator;\n const stateStack: DebugState[] = [];\n const loggerProto: PropertyDescriptorMap = {\n detach: {\n writable: true,\n configurable: true,\n value(this: DebugLogger) {\n overrideMethods.forEach((method) => {\n this[method] = noop;\n });\n },\n },\n pushState: {\n value(state: DebugState) {\n stateStack.push(state);\n statePrepender = getStatePrepender(stateStack);\n },\n },\n popState: {\n value() {\n stateStack.pop();\n statePrepender =\n stateStack.length === 0\n ? (identity as LogDecorator)\n : getStatePrepender(stateStack);\n },\n },\n };\n const customConsole = Object.create(\n console,\n overrideMethods.reduce((out, level) => {\n out[level] = {\n writable: true,\n configurable: true,\n value(...args: unknown[]) {\n console[level](...prepender(statePrepender(args)));\n },\n };\n return out;\n }, loggerProto)\n ) as DebugLogger;\n return customConsole;\n}\n\n/**\n * @internal\n */\nexport const quietConsole = new Proxy(console, {\n get() {\n return noop;\n },\n});\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport { _customConsole, DebugLogger, Theme } from \"./debuglog.js\";\nimport { Emits, Unsubscriber } from \"./types.js\";\n\n/**\n * Adds methods for logging events\n * @internal\n */\nexport interface EmitterDebugLogger extends DebugLogger {\n /**\n * Listen to an event and pass the logger to the handler\n * @internal\n */\n listen(\n type: string,\n listener: (logger: EmitterDebugLogger, ev: CustomEvent) => unknown\n ): this;\n}\n\n/**\n * Debugger for EventTarget objects like Hosts, Ports and Guests, which\n * patches dispatchEvent to log events\n * Adapter to attach console logging listeners to all events on an emitter.\n * @internal\n */\nexport function debugEmitter(\n emitter: Emits,\n opts: {\n theme: Theme;\n type?: string;\n id?: string;\n }\n): EmitterDebugLogger {\n const logger = _customConsole(\n opts.theme,\n opts.type ||\n (Object.getPrototypeOf(emitter) as typeof emitter).constructor.name,\n opts.id || emitter.id\n ) as EmitterDebugLogger;\n const oldDispatch = emitter.dispatchEvent;\n emitter.dispatchEvent = (event) => {\n logger.pushState({ type: \"event\", name: event.type });\n const retVal = oldDispatch.call(emitter, event) as boolean;\n logger.popState();\n return retVal;\n };\n\n const subscriptions: Unsubscriber[] = [];\n\n const oldDetach = logger.detach;\n logger.detach = () => {\n oldDetach.call(logger);\n subscriptions.forEach((unsubscribe) => unsubscribe());\n };\n\n /**\n * Listens and passes a logger to callbacks\n */\n function listen(\n type: string,\n listener: (logger: EmitterDebugLogger, ev: CustomEvent) => unknown\n ) {\n subscriptions.push(\n emitter.addEventListener(type, (event) => listener(logger, event))\n );\n return logger;\n }\n\n logger.listen = listen;\n\n return logger;\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport { Emits, Unsubscriber, NamedEvent } from \"./types.js\";\n\n/**\n * Browser-native {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget | EventTarget}\n * whose {@link Emitter.addEventListener} method returns an anonymous function\n * which unsubscribes the original handler.\n *\n * Also provides typed events via generics. You can create or extend this class\n * to define custom emitters with known event names and signatures.\n *\n * @example\n * ```ts\n * import type { NamedEvent, Emitter } from '@adobe/uix-sdk'\n *\n * class FizzBuzzEmitter extends Emitter<\n * NamedEvent<\"fizz\", { fizzCount: number }> |\n * NamedEvent<\"buzz\", { buzzCount: number }> |\n * NamedEvent<\"fizzbuzz\">\n * > {\n * }\n * ```\n * The `FizzBuzzEmitter` class will now type check its events and event\n * listeners, providing autosuggest in editors.\n *\n * @see [EventTarget - MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget)\n *\n * @public\n */\nexport class Emitter<Events extends NamedEvent>\n extends EventTarget\n implements Emits<Events>\n{\n /**\n * An arbitrary string to uniquely identify this emitter and its events.\n * @public\n */\n id: string;\n constructor(id: string) {\n super();\n this.id = id;\n }\n /**\n * Convenience method to construct and dispatch custom events.\n *\n * @param type - Name of one of the allowed events this can emit\n * @param detail - Object to expose in the {@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail | CustomEvent#detail}\n * property.\n * @public\n */\n protected emit<Event extends Events>(\n type: Event[\"type\"],\n detail: Event[\"detail\"]\n ): void {\n const event = new CustomEvent<typeof detail>(type, { detail });\n this.dispatchEvent(event);\n }\n /**\n * Subscribe to an event and receive an unsubscribe callback.\n * @see [EventTarget.addEventListener - MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)\n *\n * Identical to `EventTarget.addEventListener`, but returns an \"unsubscriber\"\n * function which detaches the listener when invoked. Solves an ergonomic\n * problem with native EventTargets where it's impossible to detach listeners\n * without having a reference to the original handler.\n *\n * @typeParam E - Name of one of the allowed events this can emit\n * @param type - Event type\n * @param listener - Event handler\n * @returns Call to unsubscribe listener.\n */\n addEventListener<\n Type extends Events[\"type\"],\n Event extends Extract<Events, { type: Type }>\n >(type: Type, listener: (ev: Event) => unknown): Unsubscriber {\n super.addEventListener(type, listener);\n return () => super.removeEventListener(type, listener);\n }\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { RemoteHostApis, RemoteMethodInvoker } from \"./types.js\";\n\n/**\n * Build a fake object that turns \"method calls\" into RPC messages\n * The resulting object will recursively make more fake proxies on demand until\n * one of the looked-up properties is invoked as a function.\n * Then it will call the passed `invoke` method with a {@link HostMethodAddress}\n * that can send the method invocation as an RPC message to another realm.\n *\n * @example\n * ```js\n * const invoker = (methodAddress) => console.log(\n * address.path,\n * address.name,\n * address.args\n * );\n * const ns = makeNamespaceProxy(invoker);\n *\n * // looking up any property on the object will work\n *\n * ns.example.builds.method.call.message(\"foo\", 1);\n *\n * // Console will log:\n * ['example','builds','method','call']\n * 'message'\n * [\"foo\", 1]\n *```\n * @internal\n *\n * @param invoke - Callback that receives address\n */\nexport function makeNamespaceProxy<ProxiedApi extends object>(\n invoke: RemoteMethodInvoker<unknown>,\n path: string[] = []\n): RemoteHostApis<ProxiedApi> {\n const handler: ProxyHandler<Record<string, any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n if (!Reflect.has(target, prop)) {\n const next = makeNamespaceProxy(invoke, path.concat(prop));\n Reflect.set(target, prop, next);\n }\n return Reflect.get(target, prop) as unknown;\n } else {\n throw new Error(\n `Cannot look up a symbol ${String(prop)} on a host connection proxy.`\n );\n }\n },\n };\n const target = {} as unknown as RemoteHostApis<ProxiedApi>;\n // Only trap the apply if there's at least two levels of namespace.\n // uix.host() is not a function, and neither is uix.host.bareMethod().\n if (path.length < 2) {\n return new Proxy<RemoteHostApis<ProxiedApi>>(target, handler);\n }\n const invoker = (...args: unknown[]) =>\n invoke({\n path: path.slice(0, -1),\n name: path[path.length - 1],\n args,\n });\n return new Proxy<typeof invoker>(invoker, {\n ...handler,\n apply(target, _, args: unknown[]) {\n return target(...args);\n },\n }) as unknown as typeof target;\n}\n","declare const UIX_SDK_VERSION: string;\ndeclare const UIX_SDK_BUILDMODE: string;\n\n/** @internal */\nexport const NS_ROOT = \"_$pg\";\nexport const VERSION = UIX_SDK_VERSION;\nexport const BUILDMODE = UIX_SDK_BUILDMODE;\nexport const SYM_CLEANUP = Symbol(`${NS_ROOT}_cleanup`);\nexport const SYM_INTERNAL = Symbol(`${NS_ROOT}_internal`);\nexport const INIT_CALLBACK = `${NS_ROOT}_init_cb`;\n","/** @internal */\nexport type Primitive = string | number | boolean;\n\nexport function isPlainObject<T>(value: unknown): value is T & object {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const proto = Reflect.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nexport function isPrimitive(value: unknown): value is Primitive {\n if (!value) {\n return true;\n }\n const theType = typeof value;\n return theType === \"string\" || theType === \"number\" || theType === \"boolean\";\n}\n\nexport function isIterable<T>(value: unknown): value is T[] {\n return Array.isArray(value);\n}\n\nexport function isFunction(value: unknown): value is CallableFunction {\n return typeof value === \"function\";\n}\n\nexport function hasProp(value: unknown, prop: string) {\n return !isPrimitive(value) && Reflect.has(value as object, prop);\n}\n\nexport function isTunnelSource(\n value: unknown\n): value is Window | ServiceWorker {\n return (\n value instanceof Window ||\n value instanceof ServiceWorker ||\n hasProp(value, \"onmessage\")\n );\n}\n\nexport function isIframe(value: unknown): value is HTMLIFrameElement {\n if (!value || isPrimitive(value)) {\n return false;\n }\n const { nodeName } = value as HTMLIFrameElement;\n return typeof nodeName === \"string\" && nodeName.toLowerCase() === \"iframe\";\n}\n\nexport function isObjectWithPrototype<T>(\n value: unknown\n): value is T & { [key: string | symbol]: unknown } {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const proto = Reflect.getPrototypeOf(value);\n return proto !== Object.prototype;\n}\n","import { NS_ROOT } from \"./constants\";\nimport { isPlainObject } from \"./value-assertions\";\n\n/** @internal */\nexport type WrappedMessage<Message extends object> = { [NS_ROOT]: Message };\n\nexport function wrap<Message extends object = object>(\n message: Message\n): WrappedMessage<Message> {\n return { [NS_ROOT]: message };\n}\n\nexport function unwrap<Message extends object>(\n wrappedMessage: WrappedMessage<Message>\n): Message {\n return wrappedMessage[NS_ROOT];\n}\n\nexport function isWrapped<Message extends object = object>(\n item: unknown\n): item is WrappedMessage<Message> {\n if (!isPlainObject(item)) {\n return false;\n }\n const keys = Object.keys(item);\n const hasRoot = keys.includes(NS_ROOT);\n if (hasRoot && keys.length != 1) {\n console.error(\n `malformed tunnel message, should have one prop \"${NS_ROOT}\" at root`,\n item\n );\n return false;\n }\n return hasRoot;\n}\n","import type { WrappedMessage } from \"./message-wrapper\";\nimport type { DefTicket } from \"./tickets\";\nimport {\n Primitive,\n isPlainObject,\n isPrimitive,\n isIterable,\n isObjectWithPrototype,\n} from \"./value-assertions\";\n\n/**\n * Extract keys of T whose values are assignable to U.\n * @internal\n */\ntype ExtractKeys<T, U> = {\n [P in keyof T]: T[P] extends U ? P : never;\n}[keyof T];\n\n/**\n * Convert all functions anywhere in T to async functions.\n * @internal\n */\nexport type Asynced<T> = T extends (...args: infer A) => infer R\n ? (...args: A) => Promise<R>\n : {\n [K in ExtractKeys<\n T,\n Function | object | any[] | [any, any]\n >]: T[K] extends (...args: any) => PromiseLike<any>\n ? T[K]\n : T[K] extends [infer U, infer V]\n ? [Asynced<U>, Asynced<V>]\n : T[K] extends (infer U)[]\n ? Asynced<U>[]\n : T[K] extends (...args: infer A) => infer R\n ? (...args: A) => Promise<R>\n : Asynced<T[K]>;\n };\n\n/** @internal */\nexport type Materialized<T> = T extends Primitive\n ? T\n : // : T extends (...args: infer A) => infer R\n // ? (...args: A) => Promise<R>\n T extends Simulated<infer U>\n ? Asynced<U>\n : Asynced<T>;\n\n/** @internal */\nexport type DefMessage = WrappedMessage<DefTicket>;\n\n/** @internal */\nexport type Simulated<T> = {\n [K in ExtractKeys<T, Function | object>]: T[K] extends (\n ...args: unknown[]\n ) => unknown\n ? DefMessage\n : Simulated<T[K]>;\n};\n\nexport const NOT_TRANSFORMED = Symbol.for(\"NOT_TRANSFORMED\");\nexport const CIRCULAR = \"[[Circular]]\";\n\nexport function transformRecursive<To>(\n transform: (source: unknown, parent?: Object) => To | typeof NOT_TRANSFORMED,\n value: unknown,\n parent?: Object,\n _refs: WeakSet<object> = new WeakSet()\n): To {\n if (isPrimitive(value)) {\n return value as To;\n }\n const transformed = transform(value, parent);\n if (transformed !== NOT_TRANSFORMED) {\n return transformed;\n }\n if (isIterable(value)) {\n const outArray = [];\n for (const item of value) {\n outArray.push(transformRecursive(transform, item, undefined, _refs));\n }\n return outArray as To;\n }\n if (isPlainObject(value)) {\n if (_refs.has(value)) {\n return CIRCULAR as To;\n }\n _refs.add(value);\n const outObj = {};\n for (const key of Reflect.ownKeys(value)) {\n Reflect.set(\n outObj,\n key,\n transformRecursive(transform, Reflect.get(value, key), undefined, _refs)\n );\n }\n return outObj as To;\n }\n if (isObjectWithPrototype(value)) {\n if (_refs.has(value)) {\n return CIRCULAR as To;\n }\n _refs.add(value);\n const getObjectKeys = (obj: Object): (string | symbol)[] => {\n const result: Set<string | symbol> = new Set();\n do {\n if (Reflect.getPrototypeOf(obj) !== null) {\n for (const prop of Object.getOwnPropertyNames(obj)) {\n if (prop === \"constructor\") {\n continue;\n }\n result.add(prop);\n }\n }\n } while ((obj = Reflect.getPrototypeOf(obj)));\n\n return [...result];\n };\n const outObj = {};\n const properties = getObjectKeys(value);\n for (const key of properties) {\n Reflect.set(\n outObj,\n key,\n transformRecursive(transform, Reflect.get(value, key), value, _refs)\n );\n }\n return outObj as To;\n }\n\n throw new Error(`Bad value! ${Object.prototype.toString.call(value)}`);\n}\n","import type { CallArgsTicket, DefTicket } from \"../tickets\";\nimport type { RemoteSubject } from \"../remote-subject\";\n\nexport function receiveCalls(\n fn: CallableFunction,\n ticket: DefTicket,\n remote: WeakRef<RemoteSubject>\n) {\n const responder = async ({ fnId, callId, args }: CallArgsTicket) => {\n /* istanbul ignore next: should never happen */\n try {\n const value = await fn(...args);\n remote.deref().respond({\n fnId,\n callId,\n value,\n status: \"resolve\",\n });\n } catch (error) {\n remote.deref().respond({\n fnId,\n callId,\n status: \"reject\",\n error,\n });\n }\n };\n return remote.deref().onCall(ticket, responder);\n}\n","import type { CallArgsTicket, DefTicket } from \"../tickets\";\nimport type { RemoteSubject } from \"../remote-subject\";\n\ntype RejectionPool = Set<(e: Error) => unknown>;\n\nclass DisconnectionError extends Error {\n constructor() {\n super(\n \"Function belongs to a simulated remote object which has been disconnected! The tunnel may have been destroyed by page navigation or reload.\"\n );\n }\n}\n\nfunction dispatch(\n subject: RemoteSubject,\n callTicket: CallArgsTicket,\n rejectionPool: RejectionPool,\n resolve: { (value: unknown): void; (arg0: any): void },\n reject: { (reason?: string): void; (arg0: any): void }\n) {\n subject.onRespond(callTicket, (responseTicket) => {\n rejectionPool.delete(reject);\n if (responseTicket.status === \"resolve\") {\n resolve(responseTicket.value);\n } else {\n reject(responseTicket.error);\n }\n });\n subject.send(callTicket);\n}\n\nexport function makeCallSender(\n { fnId }: DefTicket,\n subjectRef: WeakRef<RemoteSubject>\n) {\n let callCounter = 0;\n const rejectionPool: RejectionPool = new Set();\n let sender = function (...args: unknown[]) {\n return new Promise((resolve, reject) => {\n rejectionPool.add(reject);\n const callId = ++callCounter;\n const callTicket: CallArgsTicket = {\n fnId,\n callId,\n args,\n };\n return dispatch(\n subjectRef.deref(),\n callTicket,\n rejectionPool,\n resolve,\n reject\n );\n });\n };\n const destroy = () => {\n subjectRef = null;\n sender = () => {\n throw new DisconnectionError();\n };\n for (const reject of rejectionPool) {\n reject(new DisconnectionError());\n }\n rejectionPool.clear();\n };\n subjectRef.deref().onDestroyed(destroy);\n const facade = async function (...args: unknown[]) {\n return sender(...args);\n };\n Object.defineProperty(facade, \"name\", { value: fnId });\n return facade;\n}\n","import type {\n CallArgsTicket,\n CallTicket,\n DefTicket,\n RejectTicket,\n ResolveTicket,\n RespondTicket,\n CleanupTicket,\n} from \"./tickets\";\nimport type { Materialized, Simulated } from \"./object-walker\";\nimport EventEmitter from \"eventemitter3\";\n\ntype EvTypeDef = `${string}_f`;\ntype EvTypeGC = `${string}_g`;\ntype EvTypeCall = `${string}_c`;\ntype EvTypeRespond = `${string}_r`;\ntype EvTypeDestroyed = \"destroyed\";\ntype EvTypeConnected = \"connected\";\ntype EvTypeError = \"error\";\n\ntype RemoteDefEvent = {\n type: EvTypeDef;\n payload: DefTicket;\n};\ntype RemoteCallEvent = {\n type: EvTypeCall;\n payload: CallArgsTicket;\n};\ntype RemoteResolveEvent = {\n type: EvTypeRespond;\n payload: ResolveTicket;\n};\ntype RemoteRejectEvent = {\n type: EvTypeRespond;\n payload: RejectTicket;\n};\ntype RemoteCleanupEvent = {\n type: EvTypeGC;\n payload: CleanupTicket;\n};\ntype RemoteReconnectedEvent = {\n type: EvTypeConnected;\n payload: void;\n};\ntype RemoteDestroyedEvent = {\n type: EvTypeDestroyed;\n payload: void;\n};\ntype RemoteErrorEvent = {\n type: EvTypeError;\n payload: Error;\n};\n\nexport type RemoteEvents =\n | RemoteDefEvent\n | RemoteCallEvent\n | RemoteResolveEvent\n | RemoteRejectEvent\n | RemoteCleanupEvent\n | RemoteReconnectedEvent\n | RemoteDestroyedEvent\n | RemoteErrorEvent;\n\ntype Simulates = <T>(localObject: T) => Simulated<T>;\ntype Materializes = <T>(simulatedObject: T) => Materialized<T>;\n\nexport interface Simulator {\n // #region Properties\n\n materialize: Materializes;\n simulate: Simulates;\n\n // #endregion Properties\n}\n\ntype Mapper = Simulates | Materializes;\n\nexport class RemoteSubject {\n // #region Properties\n\n private emitter: EventEmitter;\n private simulator: Simulator;\n\n // #endregion Properties\n\n // #region Constructors\n\n constructor(emitter: EventEmitter, simulator: Simulator) {\n this.emitter = emitter;\n this.simulator = simulator;\n }\n\n // #endregion Constructors\n\n // #region Public Methods\n\n notifyCleanup(ticket: DefTicket) {\n return this.emitter.emit(`${ticket.fnId}_g`, {});\n }\n\n notifyConnect() {\n return this.emitter.emit(\"connected\");\n }\n\n notifyDestroy() {\n return this.emitter.emit(\"destroyed\");\n }\n\n onCall(ticket: DefTicket, handler: (ticket: CallArgsTicket) => void) {\n return this.subscribe(`${ticket.fnId}_c`, (ticket: CallArgsTicket) =>\n handler(this.processCallTicket(ticket, this.simulator.materialize))\n );\n }\n\n onConnected(handler: () => void) {\n return this.subscribe(\"connected\", handler);\n }\n\n onDestroyed(handler: () => void) {\n return this.subscribe(\"destroyed\", handler);\n }\n\n onOutOfScope(ticket: DefTicket, handler: () => void) {\n return this.subscribeOnce(`${ticket.fnId}_g`, handler);\n }\n\n onRespond(ticket: CallTicket, handler: (ticket: RespondTicket) => void) {\n const fnAndCall = `${ticket.fnId}${ticket.callId}`;\n return this.subscribeOnce(`${fnAndCall}_r`, (ticket: RespondTicket) =>\n handler(this.processResponseTicket(ticket, this.simulator.materialize))\n );\n }\n\n respond(ticket: RespondTicket) {\n const fnAndCall = `${ticket.fnId}${ticket.callId}`;\n return this.emitter.emit(\n `${fnAndCall}_r`,\n this.processResponseTicket(ticket, this.simulator.simulate)\n );\n }\n\n send(ticket: CallArgsTicket) {\n return this.emitter.emit(\n `${ticket.fnId}_c`,\n this.processCallTicket(ticket, this.simulator.simulate)\n );\n }\n\n // #endregion Public Methods\n\n // #region Private Methods\n\n private processCallTicket(\n { args, ...ticket }: CallArgsTicket,\n mapper: Mapper\n ) {\n return {\n ...ticket,\n args: args.map(mapper),\n };\n }\n\n private processResponseTicket(ticket: RespondTicket, mapper: Mapper) {\n return ticket.status === \"resolve\"\n ? { ...ticket, value: mapper(ticket.value) }\n : ticket;\n }\n\n private subscribe(type: string, handler: (arg: unknown) => void) {\n this.emitter.on(type, handler);\n return () => {\n this.emitter.off(type, handler);\n };\n }\n\n private subscribeOnce(type: string, handler: (arg: unknown) => void) {\n const once = (arg: unknown) => {\n this.emitter.off(type, once);\n handler(arg);\n };\n return this.subscribe(type, once);\n }\n\n // #endregion Private Methods\n}\n","import { isWrapped, unwrap, wrap } from \"./message-wrapper\";\nimport EventEmitter from \"eventemitter3\";\nimport type { DefMessage, Materialized, Simulated } from \"./object-walker\";\nimport { NOT_TRANSFORMED, transformRecursive } from \"./object-walker\";\nimport { makeCallSender, receiveCalls } from \"./rpc\";\nimport type { Simulator } from \"./remote-subject\";\nimport { RemoteSubject } from \"./remote-subject\";\nimport type { DefTicket } from \"./tickets\";\nimport { hasProp } from \"./value-assertions\";\n\nfunction isDefMessage(value: unknown): value is DefMessage {\n return isWrapped(value) && hasProp(unwrap(value), \"fnId\");\n}\n\nconst bindAll = <T>(inst: T, methods: (keyof T)[]) => {\n for (const methodName of methods) {\n const method = inst[methodName];\n if (typeof method === \"function\") {\n inst[methodName] = method.bind(inst);\n }\n }\n};\n\ninterface CleanupNotifier {\n // #region Public Methods\n\n register(obj: any, heldValue: string, ref?: any): void;\n unregister(ref: any): void;\n\n // #endregion Public Methods\n}\n\ninterface CleanupNotifierConstructor {\n new (callback: (heldValue: unknown) => void): CleanupNotifier;\n}\n\nexport class ObjectSimulator implements Simulator {\n // #region Properties\n\n private cleanupNotifier: CleanupNotifier;\n private fnCounter = 0;\n private receiverTicketCache: WeakMap<CallableFunction, DefTicket> =\n new WeakMap();\n private senderCache: WeakMap<DefTicket, CallableFunction> = new WeakMap();\n\n subject: RemoteSubject;\n\n // #endregion Properties\n\n // #region Constructors\n\n constructor(subject: RemoteSubject, cleanupNotifier: CleanupNotifier) {\n this.cleanupNotifier = cleanupNotifier;\n this.subject = subject;\n\n bindAll(this, [\"makeSender\", \"makeReceiver\", \"simulate\", \"materialize\"]);\n }\n\n // #endregion Constructors\n\n // #region Public Static Methods\n\n static create(\n emitter: EventEmitter,\n Cleanup: CleanupNotifierConstructor\n ): ObjectSimulator {\n let simulator: Simulator;\n // proxy simulator, so as not to have cyclic dependency\n const simulatorInterface: Simulator = {\n simulate: (x) => simulator.simulate(x),\n materialize: (x) => simulator.materialize(x),\n };\n\n const subject = new RemoteSubject(emitter, simulatorInterface);\n\n const cleanupNotifier = new Cleanup((fnId: string) => {\n return subject.notifyCleanup({ fnId });\n });\n\n simulator = new ObjectSimulator(subject, cleanupNotifier);\n\n return simulator as ObjectSimulator;\n }\n\n // #endregion Public Static Methods\n\n // #region Public Methods\n\n makeReceiver(fn: CallableFunction, parent?: Object) {\n if (typeof fn !== \"function\") {\n return NOT_TRANSFORMED;\n }\n let fnTicket = this.receiverTicketCache.get(fn);\n if (!fnTicket) {\n fnTicket = {\n fnId: `${fn.name || \"<anonymous>\"}_${++this.fnCounter}`,\n };\n // Bind function to parent object if it exists\n let boundFunction = fn;\n if (parent) {\n boundFunction = fn.bind(parent);\n }\n const cleanup = receiveCalls(\n boundFunction,\n fnTicket,\n new WeakRef(this.subject)\n );\n this.subject.onOutOfScope(fnTicket, cleanup);\n this.receiverTicketCache.set(boundFunction, fnTicket);\n }\n return wrap(fnTicket);\n }\n\n makeSender(message: unknown) {\n if (!isDefMessage(message)) {\n return NOT_TRANSFORMED;\n }\n const ticket = unwrap(message);\n /* istanbul ignore else: preopt */\n if (!this.senderCache.has(ticket)) {\n const sender = makeCallSender(ticket, new WeakRef(this.subject));\n this.cleanupNotifier.register(sender, ticket.fnId, sender);\n this.senderCache.set(ticket, sender);\n return sender;\n } else {\n return this.senderCache.get(ticket) as CallableFunction;\n }\n }\n\n materialize<T>(simulated: T) {\n return transformRecursive<CallableFunction>(\n this.makeSender,\n simulated\n ) as Materialized<T>;\n }\n\n simulate<T>(localObject: T) {\n return transformRecursive<DefMessage>(\n this.makeReceiver,\n localObject\n ) as Simulated<T>;\n }\n\n // #endregion Public Methods\n}\n","/**\n * Add a timeout to a Promise. The returned Promise will resolve to the value of\n * the original Promise, but if it doesn't resolve within the timeout interval,\n * it will reject with a timeout error.\n *\n * @param describe - Job description to be used in the timeout error\n * @param promise - Original promise to set a timeout for\n * @param timeoutMs - Time to wait (ms) before rejecting\n * @param onReject - Run when promise times out to clean up handles\n * @returns - Promise that rejects with informative error after X milliseconds have passed\n *\n * @internal\n */\nexport function timeoutPromise<T>(\n describe: string | (() => string),\n promise: Promise<T>,\n ms: number,\n onReject?: (e: Error) => void\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const cleanupAndReject = async (e: Error) => {\n try {\n if (onReject) {\n await onReject(e);\n }\n } finally {\n reject(e);\n }\n };\n const timeout = setTimeout(() => {\n cleanupAndReject(\n new Error(\n `${\n typeof describe === \"function\" ? describe() : describe\n } timed out after ${ms}ms`\n )\n );\n }, ms);\n promise\n .then((result) => {\n clearTimeout(timeout);\n resolve(result);\n })\n .catch((e) => {\n clearTimeout(timeout);\n cleanupAndReject(e);\n });\n });\n}\n","import { INIT_CALLBACK } from \"./constants\";\n\nexport interface HandshakeAcceptedTicket {\n // #region Properties\n\n accepts: string;\n version: string;\n\n // #endregion Properties\n}\nexport interface HandshakeOfferedTicket {\n // #region Properties\n\n offers: string;\n version: string;\n\n // #endregion Properties\n}\n\n/** @internal */\nexport interface DefTicket {\n // #region Properties\n\n fnId: string;\n\n // #endregion Properties\n}\nexport interface InitTicket extends DefTicket {\n // #region Properties\n\n fnId: typeof INIT_CALLBACK;\n\n // #endregion Properties\n}\nexport interface CallTicket extends DefTicket {\n // #region Properties\n\n callId: number;\n\n // #endregion Properties\n}\nexport interface CallArgsTicket extends CallTicket {\n // #region Properties\n\n args: any[];\n\n // #endregion Properties\n}\nexport interface ResolveTicket extends CallTicket {\n // #region Properties\n\n status: \"resolve\";\n value: any;\n\n // #endregion Properties\n}\nexport interface RejectTicket extends CallTicket {\n // #region Properties\n\n error: Error;\n status: \"reject\";\n\n // #endregion Properties\n}\nexport type RespondTicket = ResolveTicket | RejectTicket;\n\nexport type CleanupTicket = {};\n\nexport const INIT_TICKET: InitTicket = {\n fnId: INIT_CALLBACK,\n};\n","import EventEmitter from \"eventemitter3\";\nimport { isIframe } from \"../value-assertions\";\nimport { TunnelMessenger } from \"./tunnel-messenger\";\nimport { unwrap } from \"../message-wrapper\";\nimport { quietConsole } from \"../debuglog\";\n\n/**\n * Child iframe will send offer messages to parent at this frequency until one\n * is accepted or the attempt times out.\n * TODO: make configurable if ever necessary\n */\nconst RETRY_MS = 100;\n\n/**\n * Child iframe may unexpectedly close or detach from DOM. It emits no event\n * when this happens, so we must poll it and destroy the tunnel when necessary.\n * TODO: make configurable if ever necessary\n */\nconst STATUSCHECK_MS = 5000;\n\n/**\n * Semi-unique IDs allow multiple parallel connections to handshake on both parent\n * and child iframe. This generates a semi-random 8-char base 36 string.\n */\nconst KEY_BASE = 36;\nconst KEY_LENGTH = 8;\nconst KEY_EXP = KEY_BASE ** KEY_LENGTH;\nconst makeKey = () => Math.round(Math.random() * KEY_EXP).toString(KEY_BASE);\n\n/** @alpha */\nexport interface TunnelConfig {\n // #region Properties\n\n /**\n * To ensure secure communication, target origin must be specified, so the\n * tunnel can't connect to an unauthorized domain. Can be '*' to disable\n * origin checks, but this is discouraged!\n */\n targetOrigin: string;\n /**\n * A Promise for a tunnel will reject if not connected within timeout (ms).\n * @defaultValue 4000\n */\n timeout: number;\n /**\n * Logger instance to use for debugging tunnel connection.\n */\n logger: Console;\n\n // #endregion Properties\n}\n\nconst badTimeout = \"\\n - timeout value must be a number of milliseconds\";\nconst badTargetOrigin =\n \"\\n - targetOrigin must be a valid URL origin or '*' for any origin\";\n\nfunction isFromOrigin(\n event: MessageEvent,\n source: WindowProxy,\n targetOrigin: string\n) {\n try {\n return (\n source === event.source &&\n (targetOrigin === \"*\" || targetOrigin === new URL(event.origin).origin)\n );\n } catch (_) {\n return false;\n }\n}\n\nconst { emit: emitOn } = EventEmitter.prototype;\n\n/**\n * An EventEmitter across two documents. It emits events on the remote document\n * and takes subscribers from the local document.\n * @alpha\n */\nexport class Tunnel extends EventEmitter {\n // #region Properties\n\n private _messagePort: MessagePort;\n\n config: TunnelConfig;\n isConnected: boolean;\n\n // #endregion Properties\n\n // #region Constructors\n\n constructor(config: TunnelConfig) {\n super();\n this.config = config;\n }\n\n // #endregion Constructors\n\n // #region Public Static Methods\n\n /**\n * Create a Tunnel that connects to the page running in the provided iframe.\n *\n * @remarks\n * Returns a Tunnel that listens for connection requests from the page in the\n * provided iframe, which it will send periodically until timeout if that page\n * has called {@link Tunnel.toParent}. If it receives one, the Tunnel will accept the\n * connection and send an exclusive MessagePort to the xrobject on the other\n * end. The tunnel may reconnect if the iframe reloads, in which case it will\n * emit another \"connected\" event.\n *\n * @alpha\n */\n static toIframe(\n target: HTMLIFrameElement,\n options: Partial<TunnelConfig>\n ): Tunnel {\n if (!isIframe(target)) {\n throw new Error(\n `Provided tunnel target is not an iframe! ${Object.prototype.toString.call(\n target\n )}`\n );\n }\n\n const config = Tunnel._normalizeConfig(options);\n const tunnel = new Tunnel(config);\n const messenger = new TunnelMessenger({\n myOrigin: window.location.origin,\n targetOrigin: config.targetOrigin,\n logger: config.logger,\n });\n tunnel.on(\"destroyed\", () =>\n config.logger.log(\n `Tunnel to iframe at ${config.targetOrigin} destroyed!`,\n tunnel,\n target\n )\n );\n tunnel.on(\"connected\", () =>\n config.logger.log(\n `Tunnel to iframe at ${config.targetOrigin} connected!`,\n tunnel,\n target\n )\n );\n tunnel.on(\"error\", (e) =>\n config.logger.log(\n `Tunnel to iframe at ${config.targetOrigin} error!`,\n tunnel,\n target,\n e\n )\n );\n let frameStatusCheck: number;\n let timeout: number;\n const offerListener = (event: MessageEvent) => {\n if (\n !tunnel.isConnected &&\n isFromOrigin(event, target.contentWindow, config.targetOrigin) &&\n messenger.isHandshakeOffer(event.data)\n ) {\n const accepted = messenger.makeAccepted(unwrap(event.data).offers);\n const channel = new MessageChannel();\n target.contentWindow.postMessage(accepted, config.targetOrigin, [\n channel.port1,\n ]);\n tunnel.connect(channel.port2);\n }\n };\n const cleanup = () => {\n clearTimeout(timeout);\n clearInterval(frameStatusCheck);\n window.removeEventListener(\"message\", offerListener);\n };\n timeout = window.setTimeout(() => {\n tunnel.abort(\n new Error(\n `Timed out awaiting initial message from target iframe after ${config.timeout}ms`\n )\n );\n }, config.timeout);\n\n tunnel.on(\"destroyed\", cleanup);\n tunnel.on(\"connected\", () => clearTimeout(timeout));\n\n /**\n * Check if the iframe has been unexpectedly removed from the DOM (for\n * example, by React). Unsubscribe event listeners and destroy tunnel.\n */\n frameStatusCheck = window.setInterval(() => {\n if (!target.isConnected) {\n cleanup();\n if (tunnel.isConnected) {\n const frameDisconnectError = new Error(\n `Tunnel target iframe at ${tunnel.config.targetOrigin} was disconnected from the document!`\n );\n Object.assign(frameDisconnectError, { target });\n tunnel.abort(frameDisconnectError);\n } else {\n tunnel.destroy();\n }\n }\n }, STATUSCHECK_MS);\n\n window.addEventListener(\"message\", offerListener);\n\n return tunnel;\n }\n\n /**\n * Create a Tunnel that connects to the page running in the parent window.\n *\n * @remarks\n * Returns a Tunnel that starts sending connection requests to the parent\n * window, sending them periodically until the window responds with an accept\n * message or the timeout passes. The parent window will accept the request if\n * it calls {@link Tunnel.toIframe}.\n *\n * @alpha\n */\n static toParent(source: WindowProxy, opts: Partial<TunnelConfig>): Tunnel {\n let retrying: number;\n let timeout: number;\n let timedOut = false;\n const key = makeKey();\n const config = Tunnel._normalizeConfig(opts);\n const tunnel = new Tunnel(config);\n tunnel.on(\"destroyed\", () =>\n config.logger.log(`Tunnel ${key} to parent window destroyed!`, tunnel)\n );\n tunnel.on(\"connected\", () =>\n config.logger.log(`Tunnel ${key} to parent window connected!`, tunnel)\n );\n tunnel.on(\"error\", (e) =>\n config.logger.log(`Tunnel ${key} to parent window error!`, tunnel, e)\n );\n const messenger = new TunnelMessenger({\n myOrigin: window.location.origin,\n targetOrigin: config.targetOrigin,\n logger: config.logger,\n });\n const acceptListener = (event: MessageEvent) => {\n if (\n !timedOut &&\n isFromOrigin(event, source, config.targetOrigin) &&\n messenger.isHandshakeAccepting(event.data, key)\n ) {\n cleanup();\n if (!event.ports || !event.ports.length) {\n const portError = new Error(\n \"Received handshake accept message, but it did not include a MessagePort to establish tunnel\"\n );\n tunnel.emitLocal(\"error\", portError);\n return;\n }\n tunnel.connect(event.ports[0]);\n }\n };\n const cleanup = () => {\n clearInterval(retrying);\n clearTimeout(timeout);\n window.removeEventListener(\"message\", acceptListener);\n };\n\n timeout = window.setTimeout(() => {\n if (!timedOut) {\n timedOut = true;\n tunnel.abort(\n new Error(\n `Timed out waiting for initial response from parent after ${config.timeout}ms`\n )\n );\n }\n }, config.timeout);\n\n window.addEventListener(\"message\", acceptListener);\n tunnel.on(\"destroyed\", () => {\n cleanup();\n });\n tunnel.on(\"connected\", () => {\n cleanup();\n });\n\n const sendOffer = () => {\n if (tunnel.isConnected) {\n clearInterval(retrying);\n } else {\n source.postMessage(messenger.makeOffered(key), config.targetOrigin);\n }\n };\n retrying = window.setInterval(sendOffer, RETRY_MS);\n sendOffer();\n\n return tunnel;\n }\n\n // #endregion Public Static Methods\n\n // #region Public Methods\n\n connect(remote: MessagePort) {\n if (this._messagePort) {\n this._messagePort.removeEventListener(\"message\", this._emitFromMessage);\n this._messagePort.close();\n }\n this._messagePort = remote;\n remote.addEventListener(\"message\", this._emitFromMessage);\n this.emitLocal(\"connected\");\n this._messagePort.start();\n this.isConnected = true;\n }\n\n abort(error: Error): void {\n this.emitLocal(\"error\", error);\n this.destroy(error);\n }\n\n destroy(e?: Error): void {\n if (this._messagePort) {\n this._messagePort.close();\n this._messagePort = null;\n this.isConnected = false;\n }\n // don't add the argument to the logging if it doesn't exist; otherwise, on\n // a normal destroy, it logs a confusing \"undefined\"\n const context = e ? [e] : [];\n this.emitLocal(\"destroyed\", ...context);\n // this.removeAllListeners(); // TODO: maybe necessary for memory leaks\n }\n\n emit(type: string | symbol, payload?: unknown): boolean {\n if (!this._messagePort) {\n return false;\n }\n this._messagePort.postMessage({ type, payload });\n return true;\n }\n\n emitLocal = (type: string | symbol, payload?: unknown) => {\n return emitOn.call(this, type, payload);\n };\n\n // #endregion Public Methods\n\n // #region Private Static Methods\n\n private static _normalizeConfig(\n options: Partial<TunnelConfig> = {}\n ): TunnelConfig {\n let errorMessage = \"\";\n const config: Partial<TunnelConfig> = {\n timeout: 4000,\n ...options,\n logger: options.logger || quietConsole,\n };\n\n const timeoutMs = Number(config.timeout);\n if (!Number.isSafeInteger(timeoutMs)) {\n errorMessage += badTimeout;\n }\n if (config.targetOrigin !== \"*\") {\n try {\n new URL(config.targetOrigin);\n } catch (e) {\n errorMessage += badTargetOrigin;\n }\n }\n if (errorMessage) {\n throw new Error(`Invalid tunnel configuration: ${errorMessage}`);\n }\n return config as TunnelConfig;\n }\n\n // #endregion Private Static Methods\n\n // #region Private Methods\n\n private _emitFromMessage = ({ data: { type, payload } }: MessageEvent) => {\n this.emitLocal(type, payload);\n };\n\n // #endregion Private Methods\n}\n","import { NS_ROOT, VERSION } from \"../constants\";\nimport { isPlainObject } from \"../value-assertions\";\nimport { WrappedMessage, isWrapped, wrap, unwrap } from \"../message-wrapper\";\nimport { HandshakeAcceptedTicket, HandshakeOfferedTicket } from \"../tickets\";\n\ntype Handshake = HandshakeAcceptedTicket | HandshakeOfferedTicket;\ntype HandshakeAccepted = WrappedMessage<HandshakeAcceptedTicket>;\ntype HandshakeOffered = WrappedMessage<HandshakeOfferedTicket>;\ntype HandshakeMessage = HandshakeAccepted | HandshakeOffered;\n\ntype ParsedVersion = {\n major: string;\n minor: string;\n patch: string;\n prerelease: string;\n};\n\n/**\n * Due to a bug in release for 0.8.0 and 0.8.11, those versions have the\n * wrong (previous) version number embedded.\n */\nconst VERSION_CORRECTED = {\n \"0.7.0\": \"0.8.0\",\n \"0.8.0\": \"0.8.1\",\n};\n\nfunction getVersionParts(version: string): ParsedVersion {\n const realVersion = VERSION_CORRECTED.hasOwnProperty(version)\n ? VERSION_CORRECTED[version as keyof typeof VERSION_CORRECTED]\n : version;\n const [major, minor = \"UNKNOWN\", suffix = \"UNKNOWN\"] = realVersion.split(\".\");\n const [patch, prerelease = \"\"] = suffix.split(\"-\");\n return { major, minor, patch, prerelease };\n}\nconst thisVersion = getVersionParts(VERSION);\nexport class TunnelMessenger {\n private myOrigin: string;\n private remoteOrigin: string;\n private logger: Console;\n private versionWarnings = new Set<string>();\n constructor(opts: {\n myOrigin: string;\n targetOrigin: string;\n logger: Console;\n }) {\n this.myOrigin = opts.myOrigin;\n this.remoteOrigin =\n opts.targetOrigin === \"*\" ? \"remote document\" : opts.targetOrigin;\n this.logger = opts.logger;\n }\n resetWarnings() {\n this.versionWarnings.clear();\n }\n\n makeAccepted(id: string): HandshakeAccepted {\n return wrap({\n accepts: id,\n version: VERSION,\n });\n }\n makeOffered(id: string): HandshakeOffered {\n return wrap({\n offers: id,\n version: VERSION,\n });\n }\n isHandshakeAccepting(\n message: unknown,\n id: string\n ): message is HandshakeAccepted {\n return (\n this.isHandshake(message) &&\n unwrap(message as HandshakeAccepted).accepts === id\n );\n }\n isHandshakeOffer(message: unknown): message is HandshakeOffered {\n return (\n this.isHandshake(message) &&\n typeof unwrap(message as HandshakeOffered).offers === \"string\"\n );\n }\n isCompatibleVersion(versionString: string) {\n const version = getVersionParts(versionString);\n return (\n version.major === thisVersion.major &&\n version.minor === thisVersion.minor &&\n version.prerelease === thisVersion.prerelease\n );\n }\n isHandshake(message: unknown): message is HandshakeMessage {\n if (!isWrapped(message)) {\n this.logMalformed(message);\n return false;\n }\n const tunnelData: Handshake = unwrap<Handshake>(\n message as HandshakeMessage\n );\n if (\n !isPlainObject(tunnelData) ||\n typeof tunnelData.version !== \"string\" ||\n !(Reflect.has(tunnelData, \"accepts\") || Reflect.has(tunnelData, \"offers\"))\n ) {\n this.logMalformed(message);\n return false;\n }\n const { version } = tunnelData;\n if (\n !this.isCompatibleVersion(version) &&\n !this.versionWarnings.has(version)\n ) {\n this.versionWarnings.add(version);\n this.logger.warn(\n `SDK version mismatch. ${this.myOrigin} is using v${VERSION}, but received message from ${this.remoteOrigin} using SDK v${version}. Extensions may be broken or unresponsive.`\n );\n }\n return true;\n }\n private logMalformed(message: unknown) {\n let inspectedMessage: string;\n try {\n inspectedMessage = JSON.stringify(message, null, 2);\n } catch (_) {\n try {\n inspectedMessage = message.toString();\n } catch (e) {\n inspectedMessage = Object.prototype.toString.call(message);\n }\n }\n this.logger.error(\n `Malformed tunnel message sent from SDK at ${this.remoteOrigin} to ${this.myOrigin}:\n${inspectedMessage}\nMessage must be an object with \"${NS_ROOT}\" property, which must be an object with a \"version\" string and an either an \"accepts\" or \"offers\" property containing an ID string.`\n );\n }\n}\n","import type { WrappedMessage } from \"./message-wrapper\";\nimport { wrap } from \"./message-wrapper\";\nimport { ObjectSimulator } from \"./object-simulator\";\nimport type { Asynced } from \"./object-walker\";\nimport { timeoutPromise } from \"./promises/timed\";\nimport { receiveCalls } from \"./rpc\";\nimport type { InitTicket } from \"./tickets\";\nimport { INIT_TICKET } from \"./tickets\";\nimport type { TunnelConfig } from \"./tunnel\";\nimport { Tunnel } from \"./tunnel\";\n\nconst INIT_MESSAGE: WrappedMessage<InitTicket> = wrap(INIT_TICKET);\n\n/**\n * Representation of an object on the other side of an iframe/window divide\n * between JS runtimes.\n *\n * @remarks\n * At first, xrobject simply returned the proxy to the remote object and did\n * not expose any of the underlying event handling. However, there was no way\n * for a consumer to handle the case where the remote iframe reloaded, which\n * would invalidate all of the simulated objects.\n *\n * This new manager object exposes the {@link Tunnel} object so that consumers\n * can subscribe to the \"api\" event.\n * @alpha\n */\nexport interface CrossRealmObject<ExpectedApi> {\n /**\n * The event emitter that transmits RPC events between remotes. Can be used to\n * listen to \"api\" events, which re-emit the initial remote API after an\n * unexpected reload. Can also be used to manually destroy the xrobject.\n * @internal\n */\n tunnel: Tunnel;\n /**\n * Accessor for the simulated object. Putting the object behind an accessor is\n * a way (we hope) to subtly discourage hanging on to a reference to the\n * object, which will invalidate without the holder of the reference knowing.\n * @internal\n */\n getRemoteApi(): Asynced<ExpectedApi>;\n}\n\nasync function setupApiExchange<T>(\n tunnel: Tunnel,\n apiToSend: unknown\n): Promise<CrossRealmObject<T>> {\n let done = false;\n let remoteApi!: Asynced<T>;\n const xrObject: CrossRealmObject<T> = {\n tunnel,\n getRemoteApi(): Asynced<T> {\n return remoteApi;\n },\n };\n return timeoutPromise(\n \"Initial API exchange\",\n new Promise((resolve, reject) => {\n const simulator = ObjectSimulator.create(tunnel, FinalizationRegistry);\n\n const sendApi = simulator.makeSender(INIT_MESSAGE);\n const apiCallback = (api: Asynced<T>) => {\n remoteApi = api;\n if (!done) {\n done = true;\n resolve(xrObject);\n }\n };\n tunnel.on(\"api\", apiCallback);\n\n const unsubscribe = receiveCalls(\n (api: Asynced<T>) => tunnel.emitLocal(\"api\", api),\n INIT_TICKET,\n new WeakRef(simulator.subject)\n );\n const destroy = (e: Error) => {\n unsubscribe();\n if (!done) {\n done = true;\n if (e) {\n reject(e);\n }\n }\n };\n tunnel.on(\"destroyed\", destroy);\n tunnel.on(\"connected\", () =>\n (sendApi as Function)(apiToSend).catch(destroy)\n );\n }),\n tunnel.config.timeout,\n (e) => {\n tunnel.abort(e);\n }\n );\n}\n\n/**\n * Create a CrossRealmObject in an iframe, simulating objects from the parent window.\n * @alpha\n */\nexport async function connectParentWindow<Expected>(\n tunnelOptions: Partial<TunnelConfig>,\n apiToSend: unknown\n): Promise<CrossRealmObject<Expected>> {\n const tunnel = Tunnel.toParent(window.parent, tunnelOptions);\n return setupApiExchange<Expected>(tunnel, apiToSend);\n}\n\n/**\n * Create a CrossRealmObject simulating objects from the provided iframe runtime.\n * @alpha\n */\nexport async function connectIframe<Expected>(\n frame: HTMLIFrameElement,\n tunnelOptions: Partial<TunnelConfig>,\n apiToSend: unknown\n): Promise<CrossRealmObject<Expected>> {\n const tunnel = Tunnel.toIframe(frame, tunnelOptions);\n return setupApiExchange<Expected>(tunnel, apiToSend);\n}\n","/**\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type { HostMethodAddress } from \"./types\";\nimport { isFunction, isIterable, isPrimitive } from \"./value-assertions\";\n\n/**\n * Try and format any type of value for logging.\n *\n * @privateRemarks\n * **WARNING**: This is an expensive operation due to the JSON.stringify, and\n * should only be done when debugging or in error conditions.\n * @internal\n */\nexport function formatHostMethodArgument(argument: unknown): string {\n try {\n return JSON.stringify(argument, null, 2);\n } catch (e) {\n if (isIterable(argument)) {\n return `Iterable<${argument.length}>`;\n }\n if (isPrimitive(argument) || isFunction(argument)) {\n return `${argument}`;\n }\n return Object.prototype.toString.call(argument);\n }\n}\n\n/**\n * Try and format a remote method call as it would appear during debugging.\n *\n * @privateRemarks\n * **WARNING**: This is an expensive operation due to the JSON.stringify, and\n * should only be done when debugging or in error conditions. This Functions\n * like {@link @adobe/uix-core#timedPromise} which take logging strings also\n * take callbacks for lazy evaluation of debugging messages. Use this only in\n * such callbacks.\n * @internal\n */\nexport function formatHostMethodAddress(address: HostMethodAddress) {\n const path =\n address.path?.length < 1\n ? \"<Missing method path!>\"\n : address.path.join(\".\");\n const name = address.name || \"<Missing method name!>\";\n const args = address.args?.map(formatHostMethodArgument).join(\",\");\n return `host.${path}.${name}(${args})`;\n}\n","/**\n * Promise that resolves after a specific time\n *\n * @internal\n */\nexport function wait(ms: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * @packageDocumentation\n * Tools for UI Extensions meant to run inside extensible apps. Connects\n * Extensions running in their own window contexts with the host app, allowing\n * the host and guest to exchange method, events, and signals.\n *\n * @remarks The core object of this library, which extensions use for\n * communication, is the Guest object. There are two variants of the Guest\n * object {@link GuestServer} for the bootstrap frame which your extension keeps\n * running in the background, and {@link GuestUI} for frames meant to be\n * displayed in the host application. An extension must have one GuestServer\n * frame, and the host app may choose to use one or more GuestUI frames.\n *\n * @example Creating and connecting a GuestServer with {@link register}\n * ```typescript\n * import { register } from \"@adobe/uix-guest\";\n *\n * const server = await register({\n * // Must match extension ID from registry\n * id: \"My Custom View Extension\",\n * // enable logging in dev build\n * debug: process.env.NODE_ENV !== \"production\",\n * // Host can access these methods from its Port to this guest\n * methods: {\n * // Methods must be namespaced by one or more levels\n * myCustomView: {\n * async documentIsViewable(docId) {\n * const doc = await callMyRuntimeAction(docId);\n * return someValidation(doc);\n * },\n * renderView(docId, depth) {\n * // Use a host method\n * const tooltip = await server.host.editor.requestTooltip({\n * type: 'frame',\n * url: new URL(`/show/${docId}`, location).href\n * })\n * }\n * },\n * },\n * })\n * ```\n *\n * @example Connecting to an existing GuestServer with a GuestUI\n * ```typescript\n * import { attach } from \"@adobe/uix-guest\";\n *\n * const ui = await attach({\n * id: \"My Custom View Extension\",\n * })\n *\n * // when editing is done:\n * const saved = await ui.host.editor.saveChanges();\n * if (!saved) {\n * const editorState = ui.sharedContext.get('editorState');\n * if (editorState.tooltips[ui.id].invalid === true) {\n * putGuestUIInInvalidState();\n * }\n * } else {\n * ui.host.editor.dismissTooltip();\n * }\n * ```\n *\n */\nimport type { Guest, GuestConfig } from \"./guest.js\";\nimport { GuestUI } from \"./guest-ui.js\";\nimport { GuestServer } from \"./guest-server.js\";\nimport { GuestApis, GuestMetadata } from \"@adobe/uix-core\";\n\n/**\n * {@inheritdoc GuestConfig}\n * @public\n */\ntype GuestConfigWithMethods<Outgoing extends GuestApis> = GuestConfig & {\n methods: Outgoing;\n metadata?: GuestMetadata;\n};\n\n/**\n * Create and immediately return a {@link GuestServer}.\n *\n * @deprecated Use {@link attach} or {@link register}, which return Promises\n * that resolve once the guest is connected.\n * @public\n */\nexport function createGuest(config: GuestConfig) {\n const guest = new GuestServer(config);\n return guest;\n}\n\n/**\n * Connect to a running {@link GuestServer} to share its context and render UI.\n *\n * @remarks Creates a guest object that shares most of the GuestServer API,\n * except it cannot register its own methods. Use `attach()` in an app or\n * document that is meant to render a UI in the host application; it will have\n * access to the sharedContext object shared by the host and GuestServer.\n *\n * @public\n */\nexport async function attach(config: GuestConfig) {\n const guest = new GuestUI(config);\n await guest._connect();\n return guest;\n}\n\n/**\n * Initiate a connection to the host app and its extension points.\n *\n * @remarks Creates the \"main\" {@link GuestServer}, which runs in the background\n * without UI. Registers methods passed in the `methods` parameter, then\n * resolves the returned Promise with the connected GuestServer object.\n *\n * @public\n */\nexport async function register<Outgoing extends GuestApis>(\n config: GuestConfigWithMethods<Outgoing>\n) {\n const guest = new GuestServer(config);\n guest.register(config.methods, config.metadata);\n return guest;\n}\n\n// backwards compatibility\nexport {\n Guest,\n Guest as BaseGuest,\n GuestUI,\n GuestUI as UIGuest,\n GuestServer,\n GuestServer as PrimaryGuest,\n};\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint @typescript-eslint/no-explicit-any: \"off\" */\nimport type {\n RemoteHostApis,\n HostConnection,\n NamedEvent,\n CrossRealmObject,\n VirtualApi,\n RemoteMethodInvoker,\n HostMethodAddress,\n} from \"@adobe/uix-core\";\nimport {\n Emitter,\n formatHostMethodAddress,\n makeNamespaceProxy,\n connectParentWindow,\n timeoutPromise,\n quietConsole,\n} from \"@adobe/uix-core\";\nimport { debugGuest } from \"./debug-guest.js\";\n\n/**\n * @public\n */\nexport type GuestEvent<\n Type extends string = string,\n Detail = Record<string, unknown>\n> = NamedEvent<\n Type,\n Detail &\n Record<string, unknown> & {\n guest: Guest;\n }\n>;\n\n/**\n * @public\n */\nexport type GuestEventContextChange = GuestEvent<\n \"contextchange\",\n { context: Record<string, unknown> }\n>;\n\n/** @public */\nexport type GuestEventBeforeConnect = GuestEvent<\"beforeconnect\">;\n/** @public */\nexport type GuestEventConnected = GuestEvent<\"connected\">;\n/** @public */\nexport type GuestEventError = GuestEvent<\"error\", { error: Error }>;\n\n/**\n * @public\n */\nexport type GuestEvents =\n | GuestEventContextChange\n | GuestEventBeforeConnect\n | GuestEventConnected\n | GuestEventError;\n\n/**\n * @public\n */\nexport interface GuestConfig {\n /**\n * String slug identifying extension. This may need to use IDs from an\n * external system in the future.\n */\n id: string;\n /**\n * Set debug flags on all libraries that have them, and add loggers to SDK\n * objects. Log a lot to the console.\n */\n debug?: boolean;\n /**\n * Time out and stop trying to reach the host after this many milliseconds\n */\n timeout?: number;\n}\n\n/**\n * A `Map` representing the {@link @adobe/uix-host#HostConfig.sharedContext}\n * object.\n *\n * @remarks While the Host object is a plain JavaScript object. the `sharedContext` in the Guest object implements the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map | Map} interface.\n *\n * @example\n * In the host app window, the Host object shares context:\n * ```javascript\n *host.shareContext({\n * someAuthToken: 'abc'\n *});\n * ```\n *\n * After the `contentchange` event has fired in the guest window:\n * ```javascript\n * guest.sharedContext.get('someAuthToken') === 'abc'\n * ```\n * @public\n */\nexport class SharedContext {\n private _map: Map<string, unknown>;\n constructor(values: Record<string, unknown>) {\n this.reset(values);\n }\n private reset(values: Record<string, unknown>) {\n this._map = new Map(Object.entries(values));\n }\n /**\n * @public\n * Retrieve a copy of a value from the {@link @adobe/uix-host#HostConfig.sharedContext} object. *Note that this is not a reference to any actual objects from the parent. If the parent updates an \"inner object\" inside the SharedContext, that change will not be reflected in the Guest!*\n */\n get(key: string) {\n return this._map.get(key);\n }\n}\n\n/**\n * Generic Guest object, with methods shared by all types of Guest.\n * @internal\n */\nexport class Guest<\n Incoming extends object = VirtualApi\n> extends Emitter<GuestEvents> {\n /**\n * Shared context has been set or updated.\n * @eventProperty\n */\n public contextchange: GuestEventContextChange;\n /**\n * About to attempt connection to the host.\n * @eventProperty\n */\n public beforeconnect: GuestEventBeforeConnect;\n /**\n * Host connection has been established.\n * @eventProperty\n */\n public connected: GuestEventConnected;\n /**\n * Host connection has failed.\n * @eventProperty\n */\n public error: GuestEventError;\n /**\n * {@inheritdoc SharedContext}\n */\n sharedContext: SharedContext;\n /**\n * A guest (extension) configuration\n */\n configuration?: Record<string, unknown>;\n logger: Console = quietConsole;\n\n /**\n * @param config - Initializer for guest object, including ID.\n */\n constructor(config: GuestConfig) {\n super(config.id);\n if (typeof config.timeout === \"number\") {\n this.timeout = config.timeout;\n }\n if (config.debug) {\n this.logger = debugGuest(this);\n }\n this.addEventListener(\"contextchange\", (event) => {\n this.sharedContext = new SharedContext(event.detail.context);\n });\n }\n /**\n * Proxy object for calling methods on the host.\n *\n * @remarks Any APIs exposed to the extension via {@link @adobe/uix-host#Port.provide}\n * can be called on this object. Because these methods are called with RPC,\n * they are all asynchronous, The return types of all Host methods will be\n * Promises which resolve to the value the Host method returns.\n * @public\n */\n host: RemoteHostApis<Incoming> = makeNamespaceProxy<Incoming>(\n async (address) => {\n await this.hostConnectionPromise;\n try {\n const result = await timeoutPromise(\n () => `Calling ${formatHostMethodAddress(address)}`,\n this.invokeAwaiter(\n this.hostConnection.getRemoteApi().invokeHostMethod,\n address\n ),\n 10000\n );\n return result;\n } catch (e) {\n const error =\n e instanceof Error ? e : new Error(e as unknown as string);\n this.logger.error(error);\n throw error;\n }\n }\n );\n\n /**\n * @internal\n */\n private async invokeChecker<T>(\n invoker: RemoteMethodInvoker<unknown>,\n address: HostMethodAddress<unknown[]>\n ): Promise<unknown> {\n try {\n const res = await invoker(address);\n return new Promise((resolve) => resolve(res));\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n return this.invokeChecker(invoker, address);\n }\n }\n\n /**\n * @internal\n */\n private async invokeAwaiter(\n invoker: RemoteMethodInvoker<unknown>,\n address: HostMethodAddress<unknown[]>\n ): Promise<any> {\n const final = setTimeout(() => {\n return new Promise((resolve, reject) =>\n reject(`${address} doesn't exist`)\n );\n }, 20000);\n const res = await this.invokeChecker(invoker, address);\n return new Promise((resolve) => {\n clearTimeout(final);\n return resolve(res);\n }).catch((e) => {\n clearTimeout(final);\n return e;\n });\n }\n private timeout = 20000;\n protected hostConnectionPromise: Promise<CrossRealmObject<HostConnection>>;\n protected hostConnection!: CrossRealmObject<HostConnection>;\n /** @internal */\n protected getLocalMethods() {\n return {\n emit: (...args: Parameters<typeof this.emit>) => {\n this.logger.log(`Event \"${args[0]}\" emitted from host`);\n this.emit(...args);\n },\n };\n }\n /**\n * Accept a connection from the Host.\n * @returns A Promise that resolves when the Host has established a connection.\n * @deprecated It is preferable to use {@link register} for primary frames,\n * and {@link attach} for UI frames and other secondary frames, than to\n * instantiate a Guest and then call `.connect()` on it. The latter style\n * returns an object that cannot be used until it is connected, and therefore\n * risks errors.\n * @public\n */\n async connect() {\n return this._connect();\n }\n\n /**\n * @internal\n */\n async _connect() {\n this.emit(\"beforeconnect\", { guest: this });\n try {\n const hostConnectionPromise = connectParentWindow<HostConnection>(\n {\n targetOrigin: \"*\",\n timeout: this.timeout,\n logger: this.logger,\n },\n this.getLocalMethods()\n );\n\n this.hostConnectionPromise = hostConnectionPromise;\n this.hostConnection = await this.hostConnectionPromise;\n this.emit(\"connected\", { guest: this });\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"Connection failed!\", e);\n throw e;\n }\n try {\n this.sharedContext = new SharedContext(\n await this.hostConnection.getRemoteApi().getSharedContext()\n );\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"getSharedContext failed!\", e);\n throw e;\n }\n try {\n this.configuration = await this.hostConnection\n .getRemoteApi()\n .getConfiguration();\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"getConfiguration failed!\", e);\n throw e;\n }\n }\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * Adapter to attach console logging listeners to a Guest running in a frame/\n * @internal @preapproved\n */\nimport { debugEmitter, Emits, EmitterDebugLogger } from \"@adobe/uix-core\";\nimport { GuestEvents } from \"./guest\";\n\nexport function debugGuest(guest: Emits<GuestEvents>): EmitterDebugLogger {\n return debugEmitter(guest, {\n theme: \"yellow medium\",\n type: \"Guest\",\n })\n .listen(\"beforeconnect\", (log, { detail: { guest } }) => {\n log.info(guest);\n })\n .listen(\"connecting\", (log, { detail: { connection } }) => {\n log.info(connection);\n })\n .listen(\"connected\", (log, { detail: { guest } }) => {\n log.info(guest);\n })\n .listen(\"error\", (log, { detail: { error, guest } }) => {\n log.error(\n \"❌ Failed to connect! %s\",\n (error as Error).message,\n guest,\n error\n );\n });\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type {\n CrossRealmObject,\n RemoteHostApis,\n UIHostConnection,\n VirtualApi,\n} from \"@adobe/uix-core\";\nimport {\n Guest,\n GuestConfig,\n GuestEventBeforeConnect,\n GuestEventConnected,\n GuestEventContextChange,\n GuestEventError,\n} from \"./guest\";\n\n/**\n * A Guest to be used in an extension-controlled frame, usually to display UI.\n *\n * @typeParam Incoming - Optional interface of host methods. If using\n * TypeScript, supply this type parameter and a promisified version of the\n * interface will be available at {@link Guest.host}\n *\n * @remarks\n * This is the object returned when calling {@link @adobe/uix-guest#attach}. It\n * represents an additional frame or runtime created by the host application, on\n * behalf of the extension's control frame which is running the {@link\n * GuestServer}. It is a \"secondary\" guest object, which a host won't use before\n * the control frame has connected. It exposes a subset of the functionality of\n * the {@link GuestServer}.\n *\n * Unlike the {@link GuestServer}, it cannot register methods or update the\n * {@link Guest.sharedContext}, but it remains in sync with the GuestServer and\n * can access the {@link Guest.sharedContext} of the control frame, as well as\n * any of the published methods on the host.\n *\n * Extensible host apps using the React bindings will likely render GuestUI\n * frames using the {@link @adobe/uix-host-react#GuestUIFrame} component.\n *\n * @example\n * When an extensible app renders this page, {@link @adobe/uix-guest#attach}\n * creates a GuestUI. Once it attaches to the host, it\n * ```javascript\n * import React, { useEffect, useState } from \"react\";\n * import { attach } from \"@adobe/uix-guest\";\n * import { Tooltip } from \"./tooltip\";\n *\n * export default function PopupOverlay(props) {\n * // how large am I?\n * const [dimensions, setDimensions] = useState(\n * document.body.getBoundingClientRect()\n * );\n * // if possible, use language preloaded in query parameters\n * const [language, setLanguage] = useState(props.params.lang)\n *\n * // attach only once, in a useEffect\n * useEffect(() => {\n * attach({\n * id: \"my-extension-id\",\n * debug: true,\n * })\n * .then(guestUI => {\n * // this event fires whenever the host, or the control frame, changes\n * // any sharedContext value\n * guestUI.addEventListener(\"contextchange\", ({ detail: { context }}) => {\n * setLanguage(context.lang)\n * });\n * // how large does the host want me to be?\n * return guestUI.host.tooltips.getDimensions()\n * .then(setDimensions)\n * })\n * .catch((e) => {\n * console.error(\"ui attach failed\", e);\n * });\n * }, []);\n * // render UI! Due to the setup and useState, this component will re-render\n * // once attach() is complete.\n * return (\n * <Tooltip {...props.params} lang={language} dimensions={dimensions} />\n * );\n * }\n * ```\n *\n * @public\n */\nexport class GuestUI<IHost extends VirtualApi> extends Guest<IHost> {\n /**\n * {@inheritDoc Guest.\"constructor\"}\n */\n constructor(config: GuestConfig) {\n super(config);\n this.addEventListener(\"connected\", () => {\n const resizeObserver = new ResizeObserver((entries) => {\n const doc = entries.find((entry) => entry.target === document.body);\n const borderBoxSize = doc.borderBoxSize.length\n ? doc.borderBoxSize[0]\n : (doc.borderBoxSize as unknown as ResizeObserverSize);\n this.hostConnection.getRemoteApi().onIframeResize({\n height:\n borderBoxSize.blockSize +\n this.calculateChildrenMargin(doc.target.querySelectorAll(\"*\")),\n width: borderBoxSize.inlineSize,\n });\n });\n resizeObserver.observe(document.body);\n });\n\n this.logger.log(\"Will add resize observer on connect\");\n }\n\n /**\n * @internal\n */\n private calculateChildrenMargin(elems: NodeListOf<any>): number {\n let margin = 0;\n\n for (let i = 0; i < elems.length; i++) {\n const style = elems[i].currentStyle || window.getComputedStyle(elems[i]);\n\n if (style.marginTop !== \"0px\") {\n margin = margin + parseInt(style.marginTop);\n }\n\n if (style.marginBottom !== \"0px\") {\n margin = margin + parseInt(style.marginBottom);\n }\n }\n\n return margin;\n }\n\n /**\n * {@inheritDoc Guest.contextchange}\n * @eventProperty\n */\n public contextchange: GuestEventContextChange;\n /**\n * {@inheritDoc Guest.beforeconnect}\n * @eventProperty\n */\n public beforeconnect: GuestEventBeforeConnect;\n /**\n * {@inheritDoc Guest.connected}\n * @eventProperty\n */\n public connected: GuestEventConnected;\n /**\n * {@inheritDoc Guest.error}\n * @eventProperty\n */\n public error: GuestEventError;\n /**\n * {@inheritDoc Guest.host}\n */\n host: RemoteHostApis<IHost>;\n protected hostConnection!: CrossRealmObject<UIHostConnection>;\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type { GuestApis, GuestMetadata } from \"@adobe/uix-core\";\nimport type { SharedContext } from \"./guest\";\nimport { Guest } from \"./guest\";\n\n/**\n * A Guest to be used in the \"main\" or primary frame of an extension, the frame\n * the Host loads first.\n *\n * @remarks This is the Guest object returned from {@link register}. It can\n * expose internal methods to the Host via the {@link GuestServer.register}\n * method.\n *\n *\n * @public\n */\nexport class GuestServer<Outgoing extends GuestApis> extends Guest<Outgoing> {\n private localMethods: Outgoing;\n metadata: GuestMetadata;\n protected getLocalMethods() {\n return {\n ...super.getLocalMethods(),\n apis: this.localMethods,\n metadata: this.metadata,\n };\n }\n /**\n * {@inheritDoc BaseGuest.sharedContext}\n */\n sharedContext: SharedContext;\n /**\n * {@inheritdoc BaseGuest.host}\n */\n host: Guest<Outgoing>[\"host\"];\n /**\n * Pass an interface of methods which Host may call as callbacks.\n *\n * @remarks It is preferable to use {@link register} to obtain a guest object\n * and register local methods in one step. The returned guest object will be\n * pre-registered and connected.\n * @public\n */\n async register(implementedMethods: Outgoing, metadata: GuestMetadata) {\n this.localMethods = implementedMethods;\n this.metadata = metadata;\n return this._connect();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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ACA;AACA,UAAM,QAAQ,IAAI,YAAY,MAAM;AACpC,UAAM,SAAS,OAAO,SAAS,OAAO,QAAQ;AAC9C,WAAO;AAAA,EACT;","names":["__commonJS","exports","module","EventEmitter","quietConsole","debugEmitter","Emitter","makeNamespaceProxy","target","timeoutPromise","connectParentWindow","formatHostMethodAddress","import_uix_core","guest","Guest","Guest","Guest"]}
1
+ {"version":3,"sources":["../../../../node_modules/eventemitter3/index.js","../../../uix-core/src/debuglog.ts","../../../uix-core/src/debug-emitter.ts","../../../uix-core/src/emitter.ts","../../../uix-core/src/namespace-proxy.ts","../../../uix-core/src/constants.ts","../../../uix-core/src/value-assertions.ts","../../../uix-core/src/message-wrapper.ts","../../../uix-core/src/object-walker.ts","../../../uix-core/src/rpc/call-receiver.ts","../../../uix-core/src/rpc/call-sender.ts","../../../uix-core/src/remote-subject.ts","../../../uix-core/src/object-simulator.ts","../../../uix-core/src/promises/timed.ts","../../../uix-core/src/tickets.ts","../../../uix-core/src/tunnel/tunnel.ts","../../../uix-core/src/tunnel/tunnel-messenger.ts","../../../uix-core/src/cross-realm-object.ts","../../../uix-core/src/logging-formatters.ts","../../../uix-core/src/promises/wait.ts","../../src/index.ts","../../src/guest.ts","../../src/debug-guest.ts","../../src/guest-ui.ts","../../src/guest-server.ts"],"sourcesContent":["'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","/**\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * Fancy looking console decorator.\n * @hidden\n * @internal\n */\n\n/** @internal */\nconst isDarkMode = () =>\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(prefers-color-scheme: dark)\").matches;\n\n/** @internal */\ntype Layout = {\n padX: number;\n padY: number;\n rounded: number;\n fontSize: number;\n emphasis: Style;\n};\n/** @internal */\ntype HexColor = `#${string}` | \"transparent\";\n/** @internal */\ntype Color = {\n text: HexColor;\n bg: HexColor;\n hilight: HexColor;\n shadow: HexColor;\n};\n/** @internal */\ntype ThemeSpec = Color & Layout;\n\n/** @internal */\nconst Layouts: Record<string, Layout> = {\n medium: {\n padX: 5,\n padY: 3,\n rounded: 4,\n fontSize: 100,\n emphasis: \"font-weight: bold;\",\n },\n small: {\n padX: 3,\n padY: 1,\n rounded: 2,\n fontSize: 95,\n emphasis: \"font-style: italic;\",\n },\n};\n\n/** @internal */\nconst Colors: Record<string, Color> = {\n yellow: {\n text: \"#333333\",\n bg: \"#EBD932\",\n hilight: \"#F7E434\",\n shadow: \"#D1C12C\",\n },\n green: {\n text: \"#333333\",\n bg: \"#96EB5E\",\n hilight: \"#9EF763\",\n shadow: \"#85D154\",\n },\n blue: {\n text: \"#333333\",\n bg: \"#8DD0EB\",\n hilight: \"#88F0F7\",\n shadow: \"#74AED4\",\n },\n gray: isDarkMode()\n ? {\n text: \"#eeeeee\",\n bg: \"transparent\",\n hilight: \"#cecece\",\n shadow: \"#cecece\",\n }\n : {\n text: \"#333333\",\n bg: \"#eeeeee\",\n hilight: \"#f6f6f6\",\n shadow: \"#cecece\",\n },\n};\n\n/** @internal */\ntype ThemeTag = `${keyof typeof Colors} ${keyof typeof Layouts}`;\n\n/**\n * @internal\n */\nexport type Theme = ThemeSpec | ThemeTag;\n\n/** @internal */\ntype LogDecorator = (...args: unknown[]) => unknown[];\n\n/** @internal */\ntype Style = `${string};`;\n\nfunction memoizeUnary<T, U>(fn: (arg: T) => U): typeof fn {\n const cache: Map<T, U> = new Map();\n return (arg) => {\n if (!cache.has(arg)) {\n const result = fn(arg);\n cache.set(arg, result);\n if (cache.size > 100) {\n cache.delete(cache.keys().next().value as T);\n }\n return result;\n }\n return cache.get(arg);\n };\n}\n\nconst toTheme = memoizeUnary((theme: Theme): ThemeSpec => {\n if (typeof theme === \"string\") {\n const [color, size] = theme.split(\" \");\n return {\n ...Colors[color],\n ...Layouts[size],\n };\n }\n return theme;\n});\n\nconst block: Style = `display: inline-block; border: 1px solid;`;\n\nconst flatten = (side: \"left\" | \"right\"): Style =>\n `padding-${side}: 0px; border-${side}-width: 0px; border-top-${side}-radius: 0px; border-bottom-${side}-radius: 0px;`;\n\nconst toColor = ({ bg, hilight, shadow, text }: Color): Style =>\n `color: ${text}; background: ${bg}; border-color: ${hilight} ${shadow} ${shadow} ${hilight};`;\n\nconst toLayout = ({ fontSize, padY, padX, rounded }: Layout) =>\n `font-size: ${fontSize}%; padding: ${padY}px ${padX}px; border-radius: ${rounded}px;`;\n\nconst toBubbleStyle = memoizeUnary((theme: ThemeSpec): string[] => {\n const base = `${block}${toColor(theme)}${toLayout(theme)}`;\n return [\n `${base}${flatten(\"right\")}`,\n `${base}${flatten(\"left\")}${theme.emphasis}`,\n ] as Style[];\n});\n\nfunction toBubblePrepender(\n bubbleLeft: string,\n bubbleRight: string,\n theme: ThemeSpec\n): LogDecorator {\n const prefix = `%c${bubbleLeft}%c ${bubbleRight}`;\n const [left, right] = toBubbleStyle(theme);\n return (args: unknown[]) => {\n const bubbleArgs = [prefix, left, right];\n if (typeof args[0] === \"string\") {\n bubbleArgs[0] = `${prefix}%c ${args.shift() as string}`;\n bubbleArgs.push(\"\"); // reset style\n }\n return [...bubbleArgs, ...args];\n };\n}\n\n/** @internal */\nconst stateTypes = {\n event: \"️⚡️\",\n} as const;\n\nconst stateDelim = \" ⤻ \";\n\n/** @internal */\ntype DebugState = { type: keyof typeof stateTypes; name: string };\n\n// Serialize to memoize.\nconst getStateFormatter = memoizeUnary((stateJson: string) => {\n const stateStack = JSON.parse(stateJson) as unknown as DebugState[];\n const firstState = stateStack.shift();\n const left = stateTypes[firstState.type];\n const right = [\n firstState.name,\n ...stateStack.map((state) => `${stateTypes[state.type]} ${state.name}`),\n ].join(stateDelim);\n return toBubblePrepender(left, right, toTheme(\"gray small\"));\n});\nconst getStatePrepender = (stateStack: DebugState[]) =>\n getStateFormatter(JSON.stringify(stateStack));\n\nconst overrideMethods = [\"log\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n\nconst identity = <T>(x: T) => x;\n\nconst noop = (): (() => undefined) => undefined;\n\n/**\n * A console, plus some methods to track event lifecycles.\n * @internal\n */\nexport interface DebugLogger extends Console {\n /**\n * Stop all logging; methods do nothing\n * @internal\n */\n detach(): void;\n /**\n * Add an event bubble to the log during handler.\n */\n pushState(state: DebugState): void;\n /**\n * Remove the bubble when event is done dispatching\n */\n popState(): void;\n}\n\n/**\n * Returns a console whose methods autoformat with bubbles.\n * @internal\n */\nexport function _customConsole(\n theme: Theme,\n type: string,\n name: string\n): DebugLogger {\n const prepender = toBubblePrepender(`X${type}`, name, toTheme(theme));\n let statePrepender: LogDecorator = identity as LogDecorator;\n const stateStack: DebugState[] = [];\n const loggerProto: PropertyDescriptorMap = {\n detach: {\n writable: true,\n configurable: true,\n value(this: DebugLogger) {\n overrideMethods.forEach((method) => {\n this[method] = noop;\n });\n },\n },\n pushState: {\n value(state: DebugState) {\n stateStack.push(state);\n statePrepender = getStatePrepender(stateStack);\n },\n },\n popState: {\n value() {\n stateStack.pop();\n statePrepender =\n stateStack.length === 0\n ? (identity as LogDecorator)\n : getStatePrepender(stateStack);\n },\n },\n };\n const customConsole = Object.create(\n console,\n overrideMethods.reduce((out, level) => {\n out[level] = {\n writable: true,\n configurable: true,\n value(...args: unknown[]) {\n console[level](...prepender(statePrepender(args)));\n },\n };\n return out;\n }, loggerProto)\n ) as DebugLogger;\n return customConsole;\n}\n\n/**\n * @internal\n */\nexport const quietConsole = new Proxy(console, {\n get() {\n return noop;\n },\n});\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport { _customConsole, DebugLogger, Theme } from \"./debuglog.js\";\nimport { Emits, Unsubscriber } from \"./types.js\";\n\n/**\n * Adds methods for logging events\n * @internal\n */\nexport interface EmitterDebugLogger extends DebugLogger {\n /**\n * Listen to an event and pass the logger to the handler\n * @internal\n */\n listen(\n type: string,\n listener: (logger: EmitterDebugLogger, ev: CustomEvent) => unknown\n ): this;\n}\n\n/**\n * Debugger for EventTarget objects like Hosts, Ports and Guests, which\n * patches dispatchEvent to log events\n * Adapter to attach console logging listeners to all events on an emitter.\n * @internal\n */\nexport function debugEmitter(\n emitter: Emits,\n opts: {\n theme: Theme;\n type?: string;\n id?: string;\n }\n): EmitterDebugLogger {\n const logger = _customConsole(\n opts.theme,\n opts.type ||\n (Object.getPrototypeOf(emitter) as typeof emitter).constructor.name,\n opts.id || emitter.id\n ) as EmitterDebugLogger;\n const oldDispatch = emitter.dispatchEvent;\n emitter.dispatchEvent = (event) => {\n logger.pushState({ type: \"event\", name: event.type });\n const retVal = oldDispatch.call(emitter, event) as boolean;\n logger.popState();\n return retVal;\n };\n\n const subscriptions: Unsubscriber[] = [];\n\n const oldDetach = logger.detach;\n logger.detach = () => {\n oldDetach.call(logger);\n subscriptions.forEach((unsubscribe) => unsubscribe());\n };\n\n /**\n * Listens and passes a logger to callbacks\n */\n function listen(\n type: string,\n listener: (logger: EmitterDebugLogger, ev: CustomEvent) => unknown\n ) {\n subscriptions.push(\n emitter.addEventListener(type, (event) => listener(logger, event))\n );\n return logger;\n }\n\n logger.listen = listen;\n\n return logger;\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport { Emits, Unsubscriber, NamedEvent } from \"./types.js\";\n\n/**\n * Browser-native {@link https://developer.mozilla.org/en-US/docs/Web/API/EventTarget | EventTarget}\n * whose {@link Emitter.addEventListener} method returns an anonymous function\n * which unsubscribes the original handler.\n *\n * Also provides typed events via generics. You can create or extend this class\n * to define custom emitters with known event names and signatures.\n *\n * @example\n * ```ts\n * import type { NamedEvent, Emitter } from '@adobe/uix-sdk'\n *\n * class FizzBuzzEmitter extends Emitter<\n * NamedEvent<\"fizz\", { fizzCount: number }> |\n * NamedEvent<\"buzz\", { buzzCount: number }> |\n * NamedEvent<\"fizzbuzz\">\n * > {\n * }\n * ```\n * The `FizzBuzzEmitter` class will now type check its events and event\n * listeners, providing autosuggest in editors.\n *\n * @see [EventTarget - MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget)\n *\n * @public\n */\nexport class Emitter<Events extends NamedEvent>\n extends EventTarget\n implements Emits<Events>\n{\n /**\n * An arbitrary string to uniquely identify this emitter and its events.\n * @public\n */\n id: string;\n constructor(id: string) {\n super();\n this.id = id;\n }\n /**\n * Convenience method to construct and dispatch custom events.\n *\n * @param type - Name of one of the allowed events this can emit\n * @param detail - Object to expose in the {@link https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/detail | CustomEvent#detail}\n * property.\n * @public\n */\n protected emit<Event extends Events>(\n type: Event[\"type\"],\n detail: Event[\"detail\"]\n ): void {\n const event = new CustomEvent<typeof detail>(type, { detail });\n this.dispatchEvent(event);\n }\n /**\n * Subscribe to an event and receive an unsubscribe callback.\n * @see [EventTarget.addEventListener - MDN](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)\n *\n * Identical to `EventTarget.addEventListener`, but returns an \"unsubscriber\"\n * function which detaches the listener when invoked. Solves an ergonomic\n * problem with native EventTargets where it's impossible to detach listeners\n * without having a reference to the original handler.\n *\n * @typeParam E - Name of one of the allowed events this can emit\n * @param type - Event type\n * @param listener - Event handler\n * @returns Call to unsubscribe listener.\n */\n addEventListener<\n Type extends Events[\"type\"],\n Event extends Extract<Events, { type: Type }>\n >(type: Type, listener: (ev: Event) => unknown): Unsubscriber {\n super.addEventListener(type, listener);\n return () => super.removeEventListener(type, listener);\n }\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { RemoteHostApis, RemoteMethodInvoker } from \"./types.js\";\n\n/**\n * Build a fake object that turns \"method calls\" into RPC messages\n * The resulting object will recursively make more fake proxies on demand until\n * one of the looked-up properties is invoked as a function.\n * Then it will call the passed `invoke` method with a {@link HostMethodAddress}\n * that can send the method invocation as an RPC message to another realm.\n *\n * @example\n * ```js\n * const invoker = (methodAddress) => console.log(\n * address.path,\n * address.name,\n * address.args\n * );\n * const ns = makeNamespaceProxy(invoker);\n *\n * // looking up any property on the object will work\n *\n * ns.example.builds.method.call.message(\"foo\", 1);\n *\n * // Console will log:\n * ['example','builds','method','call']\n * 'message'\n * [\"foo\", 1]\n *```\n * @internal\n *\n * @param invoke - Callback that receives address\n */\nexport function makeNamespaceProxy<ProxiedApi extends object>(\n invoke: RemoteMethodInvoker<unknown>,\n path: string[] = []\n): RemoteHostApis<ProxiedApi> {\n const handler: ProxyHandler<Record<string, any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n if (!Reflect.has(target, prop)) {\n const next = makeNamespaceProxy(invoke, path.concat(prop));\n Reflect.set(target, prop, next);\n }\n return Reflect.get(target, prop) as unknown;\n } else {\n throw new Error(\n `Cannot look up a symbol ${String(prop)} on a host connection proxy.`\n );\n }\n },\n };\n const target = {} as unknown as RemoteHostApis<ProxiedApi>;\n // Only trap the apply if there's at least two levels of namespace.\n // uix.host() is not a function, and neither is uix.host.bareMethod().\n if (path.length < 2) {\n return new Proxy<RemoteHostApis<ProxiedApi>>(target, handler);\n }\n const invoker = (...args: unknown[]) =>\n invoke({\n path: path.slice(0, -1),\n name: path[path.length - 1],\n args,\n });\n return new Proxy<typeof invoker>(invoker, {\n ...handler,\n apply(target, _, args: unknown[]) {\n return target(...args);\n },\n }) as unknown as typeof target;\n}\n","declare const UIX_SDK_VERSION: string;\ndeclare const UIX_SDK_BUILDMODE: string;\n\n/** @internal */\nexport const NS_ROOT = \"_$pg\";\nexport const VERSION = UIX_SDK_VERSION;\nexport const BUILDMODE = UIX_SDK_BUILDMODE;\nexport const SYM_CLEANUP = Symbol(`${NS_ROOT}_cleanup`);\nexport const SYM_INTERNAL = Symbol(`${NS_ROOT}_internal`);\nexport const INIT_CALLBACK = `${NS_ROOT}_init_cb`;\n","/** @internal */\nexport type Primitive = string | number | boolean;\n\nexport function isPlainObject<T>(value: unknown): value is T & object {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const proto = Reflect.getPrototypeOf(value);\n return proto === null || proto === Object.prototype;\n}\n\nexport function isPrimitive(value: unknown): value is Primitive {\n if (!value) {\n return true;\n }\n const theType = typeof value;\n return theType === \"string\" || theType === \"number\" || theType === \"boolean\";\n}\n\nexport function isIterable<T>(value: unknown): value is T[] {\n return Array.isArray(value);\n}\n\nexport function isFunction(value: unknown): value is CallableFunction {\n return typeof value === \"function\";\n}\n\nexport function hasProp(value: unknown, prop: string) {\n return !isPrimitive(value) && Reflect.has(value as object, prop);\n}\n\nexport function isTunnelSource(\n value: unknown\n): value is Window | ServiceWorker {\n return (\n value instanceof Window ||\n value instanceof ServiceWorker ||\n hasProp(value, \"onmessage\")\n );\n}\n\nexport function isIframe(value: unknown): value is HTMLIFrameElement {\n if (!value || isPrimitive(value)) {\n return false;\n }\n const { nodeName } = value as HTMLIFrameElement;\n return typeof nodeName === \"string\" && nodeName.toLowerCase() === \"iframe\";\n}\n\nexport function isObjectWithPrototype<T>(\n value: unknown\n): value is T & { [key: string | symbol]: unknown } {\n if (!value || typeof value !== \"object\") {\n return false;\n }\n const proto = Reflect.getPrototypeOf(value);\n return proto !== Object.prototype;\n}\n","import { NS_ROOT } from \"./constants\";\nimport { isPlainObject } from \"./value-assertions\";\n\n/** @internal */\nexport type WrappedMessage<Message extends object> = { [NS_ROOT]: Message };\n\nexport function wrap<Message extends object = object>(\n message: Message\n): WrappedMessage<Message> {\n return { [NS_ROOT]: message };\n}\n\nexport function unwrap<Message extends object>(\n wrappedMessage: WrappedMessage<Message>\n): Message {\n return wrappedMessage[NS_ROOT];\n}\n\nexport function isWrapped<Message extends object = object>(\n item: unknown\n): item is WrappedMessage<Message> {\n if (!isPlainObject(item)) {\n return false;\n }\n const keys = Object.keys(item);\n const hasRoot = keys.includes(NS_ROOT);\n if (hasRoot && keys.length != 1) {\n console.error(\n `malformed tunnel message, should have one prop \"${NS_ROOT}\" at root`,\n item\n );\n return false;\n }\n return hasRoot;\n}\n","import type { WrappedMessage } from \"./message-wrapper\";\nimport type { DefTicket } from \"./tickets\";\nimport {\n Primitive,\n isPlainObject,\n isPrimitive,\n isIterable,\n isObjectWithPrototype,\n} from \"./value-assertions\";\n\n/**\n * Extract keys of T whose values are assignable to U.\n * @internal\n */\ntype ExtractKeys<T, U> = {\n [P in keyof T]: T[P] extends U ? P : never;\n}[keyof T];\n\n/**\n * Convert all functions anywhere in T to async functions.\n * @internal\n */\nexport type Asynced<T> = T extends (...args: infer A) => infer R\n ? (...args: A) => Promise<R>\n : {\n [K in ExtractKeys<\n T,\n Function | object | any[] | [any, any]\n >]: T[K] extends (...args: any) => PromiseLike<any>\n ? T[K]\n : T[K] extends [infer U, infer V]\n ? [Asynced<U>, Asynced<V>]\n : T[K] extends (infer U)[]\n ? Asynced<U>[]\n : T[K] extends (...args: infer A) => infer R\n ? (...args: A) => Promise<R>\n : Asynced<T[K]>;\n };\n\n/** @internal */\nexport type Materialized<T> = T extends Primitive\n ? T\n : // : T extends (...args: infer A) => infer R\n // ? (...args: A) => Promise<R>\n T extends Simulated<infer U>\n ? Asynced<U>\n : Asynced<T>;\n\n/** @internal */\nexport type DefMessage = WrappedMessage<DefTicket>;\n\n/** @internal */\nexport type Simulated<T> = {\n [K in ExtractKeys<T, Function | object>]: T[K] extends (\n ...args: unknown[]\n ) => unknown\n ? DefMessage\n : Simulated<T[K]>;\n};\n\nexport const NOT_TRANSFORMED = Symbol.for(\"NOT_TRANSFORMED\");\nexport const CIRCULAR = \"[[Circular]]\";\n\nexport function transformRecursive<To>(\n transform: (source: unknown, parent?: Object) => To | typeof NOT_TRANSFORMED,\n value: unknown,\n parent?: Object,\n _refs: WeakSet<object> = new WeakSet()\n): To {\n if (isPrimitive(value)) {\n return value as To;\n }\n const transformed = transform(value, parent);\n if (transformed !== NOT_TRANSFORMED) {\n return transformed;\n }\n if (isIterable(value)) {\n const outArray = [];\n for (const item of value) {\n outArray.push(transformRecursive(transform, item, undefined, _refs));\n }\n return outArray as To;\n }\n if (isPlainObject(value)) {\n if (_refs.has(value)) {\n return CIRCULAR as To;\n }\n _refs.add(value);\n const outObj = {};\n for (const key of Reflect.ownKeys(value)) {\n Reflect.set(\n outObj,\n key,\n transformRecursive(transform, Reflect.get(value, key), undefined, _refs)\n );\n }\n return outObj as To;\n }\n if (isObjectWithPrototype(value)) {\n if (_refs.has(value)) {\n return CIRCULAR as To;\n }\n _refs.add(value);\n const getObjectKeys = (obj: Object): (string | symbol)[] => {\n const result: Set<string | symbol> = new Set();\n do {\n if (Reflect.getPrototypeOf(obj) !== null) {\n for (const prop of Object.getOwnPropertyNames(obj)) {\n if (prop === \"constructor\") {\n continue;\n }\n result.add(prop);\n }\n }\n } while ((obj = Reflect.getPrototypeOf(obj)));\n\n return [...result];\n };\n const outObj = {};\n const properties = getObjectKeys(value);\n for (const key of properties) {\n Reflect.set(\n outObj,\n key,\n transformRecursive(transform, Reflect.get(value, key), value, _refs)\n );\n }\n return outObj as To;\n }\n\n throw new Error(`Bad value! ${Object.prototype.toString.call(value)}`);\n}\n","import type { CallArgsTicket, DefTicket } from \"../tickets\";\nimport type { RemoteSubject } from \"../remote-subject\";\n\nexport function receiveCalls(\n fn: CallableFunction,\n ticket: DefTicket,\n remote: WeakRef<RemoteSubject>\n) {\n const responder = async ({ fnId, callId, args }: CallArgsTicket) => {\n /* istanbul ignore next: should never happen */\n try {\n const value = await fn(...args);\n remote.deref().respond({\n fnId,\n callId,\n value,\n status: \"resolve\",\n });\n } catch (error) {\n remote.deref().respond({\n fnId,\n callId,\n status: \"reject\",\n error,\n });\n }\n };\n return remote.deref().onCall(ticket, responder);\n}\n","import type { CallArgsTicket, DefTicket } from \"../tickets\";\nimport type { RemoteSubject } from \"../remote-subject\";\n\ntype RejectionPool = Set<(e: Error) => unknown>;\n\nclass DisconnectionError extends Error {\n constructor() {\n super(\n \"Function belongs to a simulated remote object which has been disconnected! The tunnel may have been destroyed by page navigation or reload.\"\n );\n }\n}\n\nfunction dispatch(\n subject: RemoteSubject,\n callTicket: CallArgsTicket,\n rejectionPool: RejectionPool,\n resolve: { (value: unknown): void; (arg0: any): void },\n reject: { (reason?: string): void; (arg0: any): void }\n) {\n subject.onRespond(callTicket, (responseTicket) => {\n rejectionPool.delete(reject);\n if (responseTicket.status === \"resolve\") {\n resolve(responseTicket.value);\n } else {\n reject(responseTicket.error);\n }\n });\n subject.send(callTicket);\n}\n\nexport function makeCallSender(\n { fnId }: DefTicket,\n subjectRef: WeakRef<RemoteSubject>\n) {\n let callCounter = 0;\n const rejectionPool: RejectionPool = new Set();\n let sender = function (...args: unknown[]) {\n return new Promise((resolve, reject) => {\n rejectionPool.add(reject);\n const callId = ++callCounter;\n const callTicket: CallArgsTicket = {\n fnId,\n callId,\n args,\n };\n return dispatch(\n subjectRef.deref(),\n callTicket,\n rejectionPool,\n resolve,\n reject\n );\n });\n };\n const destroy = () => {\n subjectRef = null;\n sender = () => {\n throw new DisconnectionError();\n };\n for (const reject of rejectionPool) {\n reject(new DisconnectionError());\n }\n rejectionPool.clear();\n };\n subjectRef.deref().onDestroyed(destroy);\n const facade = async function (...args: unknown[]) {\n return sender(...args);\n };\n Object.defineProperty(facade, \"name\", { value: fnId });\n return facade;\n}\n","import type {\n CallArgsTicket,\n CallTicket,\n DefTicket,\n RejectTicket,\n ResolveTicket,\n RespondTicket,\n CleanupTicket,\n} from \"./tickets\";\nimport type { Materialized, Simulated } from \"./object-walker\";\nimport EventEmitter from \"eventemitter3\";\n\ntype EvTypeDef = `${string}_f`;\ntype EvTypeGC = `${string}_g`;\ntype EvTypeCall = `${string}_c`;\ntype EvTypeRespond = `${string}_r`;\ntype EvTypeDestroyed = \"destroyed\";\ntype EvTypeConnected = \"connected\";\ntype EvTypeError = \"error\";\n\ntype RemoteDefEvent = {\n type: EvTypeDef;\n payload: DefTicket;\n};\ntype RemoteCallEvent = {\n type: EvTypeCall;\n payload: CallArgsTicket;\n};\ntype RemoteResolveEvent = {\n type: EvTypeRespond;\n payload: ResolveTicket;\n};\ntype RemoteRejectEvent = {\n type: EvTypeRespond;\n payload: RejectTicket;\n};\ntype RemoteCleanupEvent = {\n type: EvTypeGC;\n payload: CleanupTicket;\n};\ntype RemoteReconnectedEvent = {\n type: EvTypeConnected;\n payload: void;\n};\ntype RemoteDestroyedEvent = {\n type: EvTypeDestroyed;\n payload: void;\n};\ntype RemoteErrorEvent = {\n type: EvTypeError;\n payload: Error;\n};\n\nexport type RemoteEvents =\n | RemoteDefEvent\n | RemoteCallEvent\n | RemoteResolveEvent\n | RemoteRejectEvent\n | RemoteCleanupEvent\n | RemoteReconnectedEvent\n | RemoteDestroyedEvent\n | RemoteErrorEvent;\n\ntype Simulates = <T>(localObject: T) => Simulated<T>;\ntype Materializes = <T>(simulatedObject: T) => Materialized<T>;\n\nexport interface Simulator {\n // #region Properties\n\n materialize: Materializes;\n simulate: Simulates;\n\n // #endregion Properties\n}\n\ntype Mapper = Simulates | Materializes;\n\nexport class RemoteSubject {\n // #region Properties\n\n private emitter: EventEmitter;\n private simulator: Simulator;\n\n // #endregion Properties\n\n // #region Constructors\n\n constructor(emitter: EventEmitter, simulator: Simulator) {\n this.emitter = emitter;\n this.simulator = simulator;\n }\n\n // #endregion Constructors\n\n // #region Public Methods\n\n notifyCleanup(ticket: DefTicket) {\n return this.emitter.emit(`${ticket.fnId}_g`, {});\n }\n\n notifyConnect() {\n return this.emitter.emit(\"connected\");\n }\n\n notifyDestroy() {\n return this.emitter.emit(\"destroyed\");\n }\n\n onCall(ticket: DefTicket, handler: (ticket: CallArgsTicket) => void) {\n return this.subscribe(`${ticket.fnId}_c`, (ticket: CallArgsTicket) =>\n handler(this.processCallTicket(ticket, this.simulator.materialize))\n );\n }\n\n onConnected(handler: () => void) {\n return this.subscribe(\"connected\", handler);\n }\n\n onDestroyed(handler: () => void) {\n return this.subscribe(\"destroyed\", handler);\n }\n\n onOutOfScope(ticket: DefTicket, handler: () => void) {\n return this.subscribeOnce(`${ticket.fnId}_g`, handler);\n }\n\n onRespond(ticket: CallTicket, handler: (ticket: RespondTicket) => void) {\n const fnAndCall = `${ticket.fnId}${ticket.callId}`;\n return this.subscribeOnce(`${fnAndCall}_r`, (ticket: RespondTicket) =>\n handler(this.processResponseTicket(ticket, this.simulator.materialize))\n );\n }\n\n respond(ticket: RespondTicket) {\n const fnAndCall = `${ticket.fnId}${ticket.callId}`;\n return this.emitter.emit(\n `${fnAndCall}_r`,\n this.processResponseTicket(ticket, this.simulator.simulate)\n );\n }\n\n send(ticket: CallArgsTicket) {\n return this.emitter.emit(\n `${ticket.fnId}_c`,\n this.processCallTicket(ticket, this.simulator.simulate)\n );\n }\n\n // #endregion Public Methods\n\n // #region Private Methods\n\n private processCallTicket(\n { args, ...ticket }: CallArgsTicket,\n mapper: Mapper\n ) {\n return {\n ...ticket,\n args: args.map(mapper),\n };\n }\n\n private processResponseTicket(ticket: RespondTicket, mapper: Mapper) {\n return ticket.status === \"resolve\"\n ? { ...ticket, value: mapper(ticket.value) }\n : ticket;\n }\n\n private subscribe(type: string, handler: (arg: unknown) => void) {\n this.emitter.on(type, handler);\n return () => {\n this.emitter.off(type, handler);\n };\n }\n\n private subscribeOnce(type: string, handler: (arg: unknown) => void) {\n const once = (arg: unknown) => {\n this.emitter.off(type, once);\n handler(arg);\n };\n return this.subscribe(type, once);\n }\n\n // #endregion Private Methods\n}\n","import { isWrapped, unwrap, wrap } from \"./message-wrapper\";\nimport EventEmitter from \"eventemitter3\";\nimport type { DefMessage, Materialized, Simulated } from \"./object-walker\";\nimport { NOT_TRANSFORMED, transformRecursive } from \"./object-walker\";\nimport { makeCallSender, receiveCalls } from \"./rpc\";\nimport type { Simulator } from \"./remote-subject\";\nimport { RemoteSubject } from \"./remote-subject\";\nimport type { DefTicket } from \"./tickets\";\nimport { hasProp } from \"./value-assertions\";\n\nfunction isDefMessage(value: unknown): value is DefMessage {\n return isWrapped(value) && hasProp(unwrap(value), \"fnId\");\n}\n\nconst bindAll = <T>(inst: T, methods: (keyof T)[]) => {\n for (const methodName of methods) {\n const method = inst[methodName];\n if (typeof method === \"function\") {\n inst[methodName] = method.bind(inst);\n }\n }\n};\n\ninterface CleanupNotifier {\n // #region Public Methods\n\n register(obj: any, heldValue: string, ref?: any): void;\n unregister(ref: any): void;\n\n // #endregion Public Methods\n}\n\ninterface CleanupNotifierConstructor {\n new (callback: (heldValue: unknown) => void): CleanupNotifier;\n}\n\nexport class ObjectSimulator implements Simulator {\n // #region Properties\n\n private cleanupNotifier: CleanupNotifier;\n private fnCounter = 0;\n private receiverTicketCache: WeakMap<CallableFunction, DefTicket> =\n new WeakMap();\n private senderCache: WeakMap<DefTicket, CallableFunction> = new WeakMap();\n\n subject: RemoteSubject;\n\n // #endregion Properties\n\n // #region Constructors\n\n constructor(subject: RemoteSubject, cleanupNotifier: CleanupNotifier) {\n this.cleanupNotifier = cleanupNotifier;\n this.subject = subject;\n\n bindAll(this, [\"makeSender\", \"makeReceiver\", \"simulate\", \"materialize\"]);\n }\n\n // #endregion Constructors\n\n // #region Public Static Methods\n\n static create(\n emitter: EventEmitter,\n Cleanup: CleanupNotifierConstructor\n ): ObjectSimulator {\n let simulator: Simulator;\n // proxy simulator, so as not to have cyclic dependency\n const simulatorInterface: Simulator = {\n simulate: (x) => simulator.simulate(x),\n materialize: (x) => simulator.materialize(x),\n };\n\n const subject = new RemoteSubject(emitter, simulatorInterface);\n\n const cleanupNotifier = new Cleanup((fnId: string) => {\n return subject.notifyCleanup({ fnId });\n });\n\n simulator = new ObjectSimulator(subject, cleanupNotifier);\n\n return simulator as ObjectSimulator;\n }\n\n // #endregion Public Static Methods\n\n // #region Public Methods\n\n makeReceiver(fn: CallableFunction, parent?: Object) {\n if (typeof fn !== \"function\") {\n return NOT_TRANSFORMED;\n }\n let fnTicket = this.receiverTicketCache.get(fn);\n if (!fnTicket) {\n fnTicket = {\n fnId: `${fn.name || \"<anonymous>\"}_${++this.fnCounter}`,\n };\n // Bind function to parent object if it exists\n let boundFunction = fn;\n if (parent) {\n boundFunction = fn.bind(parent);\n }\n const cleanup = receiveCalls(\n boundFunction,\n fnTicket,\n new WeakRef(this.subject)\n );\n this.subject.onOutOfScope(fnTicket, cleanup);\n this.receiverTicketCache.set(boundFunction, fnTicket);\n }\n return wrap(fnTicket);\n }\n\n makeSender(message: unknown) {\n if (!isDefMessage(message)) {\n return NOT_TRANSFORMED;\n }\n const ticket = unwrap(message);\n /* istanbul ignore else: preopt */\n if (!this.senderCache.has(ticket)) {\n const sender = makeCallSender(ticket, new WeakRef(this.subject));\n this.cleanupNotifier.register(sender, ticket.fnId, sender);\n this.senderCache.set(ticket, sender);\n return sender;\n } else {\n return this.senderCache.get(ticket) as CallableFunction;\n }\n }\n\n materialize<T>(simulated: T) {\n return transformRecursive<CallableFunction>(\n this.makeSender,\n simulated\n ) as Materialized<T>;\n }\n\n simulate<T>(localObject: T) {\n return transformRecursive<DefMessage>(\n this.makeReceiver,\n localObject\n ) as Simulated<T>;\n }\n\n // #endregion Public Methods\n}\n","/**\n * Add a timeout to a Promise. The returned Promise will resolve to the value of\n * the original Promise, but if it doesn't resolve within the timeout interval,\n * it will reject with a timeout error.\n *\n * @param describe - Job description to be used in the timeout error\n * @param promise - Original promise to set a timeout for\n * @param timeoutMs - Time to wait (ms) before rejecting\n * @param onReject - Run when promise times out to clean up handles\n * @returns - Promise that rejects with informative error after X milliseconds have passed\n *\n * @internal\n */\nexport function timeoutPromise<T>(\n describe: string | (() => string),\n promise: Promise<T>,\n ms: number,\n onReject?: (e: Error) => void\n): Promise<T> {\n return new Promise((resolve, reject) => {\n const cleanupAndReject = async (e: Error) => {\n try {\n if (onReject) {\n await onReject(e);\n }\n } finally {\n reject(e);\n }\n };\n const timeout = setTimeout(() => {\n cleanupAndReject(\n new Error(\n `${\n typeof describe === \"function\" ? describe() : describe\n } timed out after ${ms}ms`\n )\n );\n }, ms);\n promise\n .then((result) => {\n clearTimeout(timeout);\n resolve(result);\n })\n .catch((e) => {\n clearTimeout(timeout);\n cleanupAndReject(e);\n });\n });\n}\n","import { INIT_CALLBACK } from \"./constants\";\n\nexport interface HandshakeAcceptedTicket {\n // #region Properties\n\n accepts: string;\n version: string;\n\n // #endregion Properties\n}\nexport interface HandshakeOfferedTicket {\n // #region Properties\n\n offers: string;\n version: string;\n\n // #endregion Properties\n}\n\n/** @internal */\nexport interface DefTicket {\n // #region Properties\n\n fnId: string;\n\n // #endregion Properties\n}\nexport interface InitTicket extends DefTicket {\n // #region Properties\n\n fnId: typeof INIT_CALLBACK;\n\n // #endregion Properties\n}\nexport interface CallTicket extends DefTicket {\n // #region Properties\n\n callId: number;\n\n // #endregion Properties\n}\nexport interface CallArgsTicket extends CallTicket {\n // #region Properties\n\n args: any[];\n\n // #endregion Properties\n}\nexport interface ResolveTicket extends CallTicket {\n // #region Properties\n\n status: \"resolve\";\n value: any;\n\n // #endregion Properties\n}\nexport interface RejectTicket extends CallTicket {\n // #region Properties\n\n error: Error;\n status: \"reject\";\n\n // #endregion Properties\n}\nexport type RespondTicket = ResolveTicket | RejectTicket;\n\nexport type CleanupTicket = {};\n\nexport const INIT_TICKET: InitTicket = {\n fnId: INIT_CALLBACK,\n};\n","import EventEmitter from \"eventemitter3\";\nimport { isIframe } from \"../value-assertions\";\nimport { TunnelMessenger } from \"./tunnel-messenger\";\nimport { unwrap } from \"../message-wrapper\";\nimport { quietConsole } from \"../debuglog\";\n\n/**\n * Child iframe will send offer messages to parent at this frequency until one\n * is accepted or the attempt times out.\n * TODO: make configurable if ever necessary\n */\nconst RETRY_MS = 100;\n\n/**\n * Child iframe may unexpectedly close or detach from DOM. It emits no event\n * when this happens, so we must poll it and destroy the tunnel when necessary.\n * TODO: make configurable if ever necessary\n */\nconst STATUSCHECK_MS = 5000;\n\n/**\n * Semi-unique IDs allow multiple parallel connections to handshake on both parent\n * and child iframe. This generates a semi-random 8-char base 36 string.\n */\nconst KEY_BASE = 36;\nconst KEY_LENGTH = 8;\nconst KEY_EXP = KEY_BASE ** KEY_LENGTH;\nconst makeKey = () => Math.round(Math.random() * KEY_EXP).toString(KEY_BASE);\n\n/** @alpha */\nexport interface TunnelConfig {\n // #region Properties\n\n /**\n * To ensure secure communication, target origin must be specified, so the\n * tunnel can't connect to an unauthorized domain. Can be '*' to disable\n * origin checks, but this is discouraged!\n */\n targetOrigin: string;\n /**\n * A Promise for a tunnel will reject if not connected within timeout (ms).\n * @defaultValue 4000\n */\n timeout: number;\n /**\n * Logger instance to use for debugging tunnel connection.\n */\n logger: Console;\n\n // #endregion Properties\n}\n\nconst badTimeout = \"\\n - timeout value must be a number of milliseconds\";\nconst badTargetOrigin =\n \"\\n - targetOrigin must be a valid URL origin or '*' for any origin\";\n\nfunction isFromOrigin(\n event: MessageEvent,\n source: WindowProxy,\n targetOrigin: string\n) {\n try {\n return (\n source === event.source &&\n (targetOrigin === \"*\" || targetOrigin === new URL(event.origin).origin)\n );\n } catch (_) {\n return false;\n }\n}\n\nconst { emit: emitOn } = EventEmitter.prototype;\n\n/**\n * An EventEmitter across two documents. It emits events on the remote document\n * and takes subscribers from the local document.\n * @alpha\n */\nexport class Tunnel extends EventEmitter {\n // #region Properties\n\n private _messagePort: MessagePort;\n\n config: TunnelConfig;\n isConnected: boolean;\n\n // #endregion Properties\n\n // #region Constructors\n\n constructor(config: TunnelConfig) {\n super();\n this.config = config;\n }\n\n // #endregion Constructors\n\n // #region Public Static Methods\n\n /**\n * Create a Tunnel that connects to the page running in the provided iframe.\n *\n * @remarks\n * Returns a Tunnel that listens for connection requests from the page in the\n * provided iframe, which it will send periodically until timeout if that page\n * has called {@link Tunnel.toParent}. If it receives one, the Tunnel will accept the\n * connection and send an exclusive MessagePort to the xrobject on the other\n * end. The tunnel may reconnect if the iframe reloads, in which case it will\n * emit another \"connected\" event.\n *\n * @alpha\n */\n static toIframe(\n target: HTMLIFrameElement,\n options: Partial<TunnelConfig>\n ): Tunnel {\n if (!isIframe(target)) {\n throw new Error(\n `Provided tunnel target is not an iframe! ${Object.prototype.toString.call(\n target\n )}`\n );\n }\n\n const config = Tunnel._normalizeConfig(options);\n const tunnel = new Tunnel(config);\n const messenger = new TunnelMessenger({\n myOrigin: window.location.origin,\n targetOrigin: config.targetOrigin,\n logger: config.logger,\n });\n tunnel.on(\"destroyed\", () =>\n config.logger.log(\n `Tunnel to iframe at ${config.targetOrigin} destroyed!`,\n tunnel,\n target\n )\n );\n tunnel.on(\"connected\", () =>\n config.logger.log(\n `Tunnel to iframe at ${config.targetOrigin} connected!`,\n tunnel,\n target\n )\n );\n tunnel.on(\"error\", (e) =>\n config.logger.log(\n `Tunnel to iframe at ${config.targetOrigin} error!`,\n tunnel,\n target,\n e\n )\n );\n let frameStatusCheck: number;\n let timeout: number;\n const offerListener = (event: MessageEvent) => {\n if (\n !tunnel.isConnected &&\n isFromOrigin(event, target.contentWindow, config.targetOrigin) &&\n messenger.isHandshakeOffer(event.data)\n ) {\n const accepted = messenger.makeAccepted(unwrap(event.data).offers);\n const channel = new MessageChannel();\n target.contentWindow.postMessage(accepted, config.targetOrigin, [\n channel.port1,\n ]);\n tunnel.connect(channel.port2);\n }\n };\n const cleanup = () => {\n clearTimeout(timeout);\n clearInterval(frameStatusCheck);\n window.removeEventListener(\"message\", offerListener);\n };\n timeout = window.setTimeout(() => {\n tunnel.abort(\n new Error(\n `Timed out awaiting initial message from target iframe after ${config.timeout}ms`\n )\n );\n }, config.timeout);\n\n tunnel.on(\"destroyed\", cleanup);\n tunnel.on(\"connected\", () => clearTimeout(timeout));\n\n /**\n * Check if the iframe has been unexpectedly removed from the DOM (for\n * example, by React). Unsubscribe event listeners and destroy tunnel.\n */\n frameStatusCheck = window.setInterval(() => {\n if (!target.isConnected) {\n cleanup();\n if (tunnel.isConnected) {\n const frameDisconnectError = new Error(\n `Tunnel target iframe at ${tunnel.config.targetOrigin} was disconnected from the document!`\n );\n Object.assign(frameDisconnectError, { target });\n tunnel.abort(frameDisconnectError);\n } else {\n tunnel.destroy();\n }\n }\n }, STATUSCHECK_MS);\n\n window.addEventListener(\"message\", offerListener);\n\n return tunnel;\n }\n\n /**\n * Create a Tunnel that connects to the page running in the parent window.\n *\n * @remarks\n * Returns a Tunnel that starts sending connection requests to the parent\n * window, sending them periodically until the window responds with an accept\n * message or the timeout passes. The parent window will accept the request if\n * it calls {@link Tunnel.toIframe}.\n *\n * @alpha\n */\n static toParent(source: WindowProxy, opts: Partial<TunnelConfig>): Tunnel {\n let retrying: number;\n let timeout: number;\n let timedOut = false;\n const key = makeKey();\n const config = Tunnel._normalizeConfig(opts);\n const tunnel = new Tunnel(config);\n tunnel.on(\"destroyed\", () =>\n config.logger.log(`Tunnel ${key} to parent window destroyed!`, tunnel)\n );\n tunnel.on(\"connected\", () =>\n config.logger.log(`Tunnel ${key} to parent window connected!`, tunnel)\n );\n tunnel.on(\"error\", (e) =>\n config.logger.log(`Tunnel ${key} to parent window error!`, tunnel, e)\n );\n const messenger = new TunnelMessenger({\n myOrigin: window.location.origin,\n targetOrigin: config.targetOrigin,\n logger: config.logger,\n });\n const acceptListener = (event: MessageEvent) => {\n if (\n !timedOut &&\n isFromOrigin(event, source, config.targetOrigin) &&\n messenger.isHandshakeAccepting(event.data, key)\n ) {\n cleanup();\n if (!event.ports || !event.ports.length) {\n const portError = new Error(\n \"Received handshake accept message, but it did not include a MessagePort to establish tunnel\"\n );\n tunnel.emitLocal(\"error\", portError);\n return;\n }\n tunnel.connect(event.ports[0]);\n }\n };\n const cleanup = () => {\n clearInterval(retrying);\n clearTimeout(timeout);\n window.removeEventListener(\"message\", acceptListener);\n };\n\n timeout = window.setTimeout(() => {\n if (!timedOut) {\n timedOut = true;\n tunnel.abort(\n new Error(\n `Timed out waiting for initial response from parent after ${config.timeout}ms`\n )\n );\n }\n }, config.timeout);\n\n window.addEventListener(\"message\", acceptListener);\n tunnel.on(\"destroyed\", () => {\n cleanup();\n });\n tunnel.on(\"connected\", () => {\n cleanup();\n });\n\n const sendOffer = () => {\n if (tunnel.isConnected) {\n clearInterval(retrying);\n } else {\n source.postMessage(messenger.makeOffered(key), config.targetOrigin);\n }\n };\n retrying = window.setInterval(sendOffer, RETRY_MS);\n sendOffer();\n\n return tunnel;\n }\n\n // #endregion Public Static Methods\n\n // #region Public Methods\n\n connect(remote: MessagePort) {\n if (this._messagePort) {\n this._messagePort.removeEventListener(\"message\", this._emitFromMessage);\n this._messagePort.close();\n }\n this._messagePort = remote;\n remote.addEventListener(\"message\", this._emitFromMessage);\n this.emitLocal(\"connected\");\n this._messagePort.start();\n this.isConnected = true;\n }\n\n abort(error: Error): void {\n this.emitLocal(\"error\", error);\n this.destroy(error);\n }\n\n destroy(e?: Error): void {\n if (this._messagePort) {\n this._messagePort.close();\n this._messagePort = null;\n this.isConnected = false;\n }\n // don't add the argument to the logging if it doesn't exist; otherwise, on\n // a normal destroy, it logs a confusing \"undefined\"\n const context = e ? [e] : [];\n this.emitLocal(\"destroyed\", ...context);\n // this.removeAllListeners(); // TODO: maybe necessary for memory leaks\n }\n\n emit(type: string | symbol, payload?: unknown): boolean {\n if (!this._messagePort) {\n return false;\n }\n this._messagePort.postMessage({ type, payload });\n return true;\n }\n\n emitLocal = (type: string | symbol, payload?: unknown) => {\n return emitOn.call(this, type, payload);\n };\n\n // #endregion Public Methods\n\n // #region Private Static Methods\n\n private static _normalizeConfig(\n options: Partial<TunnelConfig> = {}\n ): TunnelConfig {\n let errorMessage = \"\";\n const config: Partial<TunnelConfig> = {\n timeout: 4000,\n ...options,\n logger: options.logger || quietConsole,\n };\n\n const timeoutMs = Number(config.timeout);\n if (!Number.isSafeInteger(timeoutMs)) {\n errorMessage += badTimeout;\n }\n if (config.targetOrigin !== \"*\") {\n try {\n new URL(config.targetOrigin);\n } catch (e) {\n errorMessage += badTargetOrigin;\n }\n }\n if (errorMessage) {\n throw new Error(`Invalid tunnel configuration: ${errorMessage}`);\n }\n return config as TunnelConfig;\n }\n\n // #endregion Private Static Methods\n\n // #region Private Methods\n\n private _emitFromMessage = ({ data: { type, payload } }: MessageEvent) => {\n this.emitLocal(type, payload);\n };\n\n // #endregion Private Methods\n}\n","import { NS_ROOT, VERSION } from \"../constants\";\nimport { isPlainObject } from \"../value-assertions\";\nimport { WrappedMessage, isWrapped, wrap, unwrap } from \"../message-wrapper\";\nimport { HandshakeAcceptedTicket, HandshakeOfferedTicket } from \"../tickets\";\n\ntype Handshake = HandshakeAcceptedTicket | HandshakeOfferedTicket;\ntype HandshakeAccepted = WrappedMessage<HandshakeAcceptedTicket>;\ntype HandshakeOffered = WrappedMessage<HandshakeOfferedTicket>;\ntype HandshakeMessage = HandshakeAccepted | HandshakeOffered;\n\ntype ParsedVersion = {\n major: string;\n minor: string;\n patch: string;\n prerelease: string;\n};\n\n/**\n * Due to a bug in release for 0.8.0 and 0.8.11, those versions have the\n * wrong (previous) version number embedded.\n */\nconst VERSION_CORRECTED = {\n \"0.7.0\": \"0.8.0\",\n \"0.8.0\": \"0.8.1\",\n};\n\nfunction getVersionParts(version: string): ParsedVersion {\n const realVersion = VERSION_CORRECTED.hasOwnProperty(version)\n ? VERSION_CORRECTED[version as keyof typeof VERSION_CORRECTED]\n : version;\n const [major, minor = \"UNKNOWN\", suffix = \"UNKNOWN\"] = realVersion.split(\".\");\n const [patch, prerelease = \"\"] = suffix.split(\"-\");\n return { major, minor, patch, prerelease };\n}\nconst thisVersion = getVersionParts(VERSION);\nexport class TunnelMessenger {\n private myOrigin: string;\n private remoteOrigin: string;\n private logger: Console;\n private versionWarnings = new Set<string>();\n constructor(opts: {\n myOrigin: string;\n targetOrigin: string;\n logger: Console;\n }) {\n this.myOrigin = opts.myOrigin;\n this.remoteOrigin =\n opts.targetOrigin === \"*\" ? \"remote document\" : opts.targetOrigin;\n this.logger = opts.logger;\n }\n resetWarnings() {\n this.versionWarnings.clear();\n }\n\n makeAccepted(id: string): HandshakeAccepted {\n return wrap({\n accepts: id,\n version: VERSION,\n });\n }\n makeOffered(id: string): HandshakeOffered {\n return wrap({\n offers: id,\n version: VERSION,\n });\n }\n isHandshakeAccepting(\n message: unknown,\n id: string\n ): message is HandshakeAccepted {\n return (\n this.isHandshake(message) &&\n unwrap(message as HandshakeAccepted).accepts === id\n );\n }\n isHandshakeOffer(message: unknown): message is HandshakeOffered {\n return (\n this.isHandshake(message) &&\n typeof unwrap(message as HandshakeOffered).offers === \"string\"\n );\n }\n isCompatibleVersion(versionString: string) {\n const version = getVersionParts(versionString);\n return (\n version.major === thisVersion.major &&\n version.minor === thisVersion.minor &&\n version.prerelease === thisVersion.prerelease\n );\n }\n isHandshake(message: unknown): message is HandshakeMessage {\n if (!isWrapped(message)) {\n this.logMalformed(message);\n return false;\n }\n const tunnelData: Handshake = unwrap<Handshake>(\n message as HandshakeMessage\n );\n if (\n !isPlainObject(tunnelData) ||\n typeof tunnelData.version !== \"string\" ||\n !(Reflect.has(tunnelData, \"accepts\") || Reflect.has(tunnelData, \"offers\"))\n ) {\n this.logMalformed(message);\n return false;\n }\n const { version } = tunnelData;\n if (\n !this.isCompatibleVersion(version) &&\n !this.versionWarnings.has(version)\n ) {\n this.versionWarnings.add(version);\n this.logger.warn(\n `SDK version mismatch. ${this.myOrigin} is using v${VERSION}, but received message from ${this.remoteOrigin} using SDK v${version}. Extensions may be broken or unresponsive.`\n );\n }\n return true;\n }\n private logMalformed(message: unknown) {\n let inspectedMessage: string;\n try {\n inspectedMessage = JSON.stringify(message, null, 2);\n } catch (_) {\n try {\n inspectedMessage = message.toString();\n } catch (e) {\n inspectedMessage = Object.prototype.toString.call(message);\n }\n }\n this.logger.error(\n `Malformed tunnel message sent from SDK at ${this.remoteOrigin} to ${this.myOrigin}:\n${inspectedMessage}\nMessage must be an object with \"${NS_ROOT}\" property, which must be an object with a \"version\" string and an either an \"accepts\" or \"offers\" property containing an ID string.`\n );\n }\n}\n","import type { WrappedMessage } from \"./message-wrapper\";\nimport { wrap } from \"./message-wrapper\";\nimport { ObjectSimulator } from \"./object-simulator\";\nimport type { Asynced } from \"./object-walker\";\nimport { timeoutPromise } from \"./promises/timed\";\nimport { receiveCalls } from \"./rpc\";\nimport type { InitTicket } from \"./tickets\";\nimport { INIT_TICKET } from \"./tickets\";\nimport type { TunnelConfig } from \"./tunnel\";\nimport { Tunnel } from \"./tunnel\";\n\nconst INIT_MESSAGE: WrappedMessage<InitTicket> = wrap(INIT_TICKET);\n\n/**\n * Representation of an object on the other side of an iframe/window divide\n * between JS runtimes.\n *\n * @remarks\n * At first, xrobject simply returned the proxy to the remote object and did\n * not expose any of the underlying event handling. However, there was no way\n * for a consumer to handle the case where the remote iframe reloaded, which\n * would invalidate all of the simulated objects.\n *\n * This new manager object exposes the {@link Tunnel} object so that consumers\n * can subscribe to the \"api\" event.\n * @alpha\n */\nexport interface CrossRealmObject<ExpectedApi> {\n /**\n * The event emitter that transmits RPC events between remotes. Can be used to\n * listen to \"api\" events, which re-emit the initial remote API after an\n * unexpected reload. Can also be used to manually destroy the xrobject.\n * @internal\n */\n tunnel: Tunnel;\n /**\n * Accessor for the simulated object. Putting the object behind an accessor is\n * a way (we hope) to subtly discourage hanging on to a reference to the\n * object, which will invalidate without the holder of the reference knowing.\n * @internal\n */\n getRemoteApi(): Asynced<ExpectedApi>;\n}\n\nasync function setupApiExchange<T>(\n tunnel: Tunnel,\n apiToSend: unknown\n): Promise<CrossRealmObject<T>> {\n let done = false;\n let remoteApi!: Asynced<T>;\n const xrObject: CrossRealmObject<T> = {\n tunnel,\n getRemoteApi(): Asynced<T> {\n return remoteApi;\n },\n };\n return timeoutPromise(\n \"Initial API exchange\",\n new Promise((resolve, reject) => {\n const simulator = ObjectSimulator.create(tunnel, FinalizationRegistry);\n\n const sendApi = simulator.makeSender(INIT_MESSAGE);\n const apiCallback = (api: Asynced<T>) => {\n remoteApi = api;\n if (!done) {\n done = true;\n resolve(xrObject);\n }\n };\n tunnel.on(\"api\", apiCallback);\n\n const unsubscribe = receiveCalls(\n (api: Asynced<T>) => tunnel.emitLocal(\"api\", api),\n INIT_TICKET,\n new WeakRef(simulator.subject)\n );\n const destroy = (e: Error) => {\n unsubscribe();\n if (!done) {\n done = true;\n if (e) {\n reject(e);\n }\n }\n };\n tunnel.on(\"destroyed\", destroy);\n tunnel.on(\"connected\", () =>\n (sendApi as Function)(apiToSend).catch(destroy)\n );\n }),\n tunnel.config.timeout,\n (e) => {\n tunnel.abort(e);\n }\n );\n}\n\n/**\n * Create a CrossRealmObject in an iframe, simulating objects from the parent window.\n * @alpha\n */\nexport async function connectParentWindow<Expected>(\n tunnelOptions: Partial<TunnelConfig>,\n apiToSend: unknown\n): Promise<CrossRealmObject<Expected>> {\n const tunnel = Tunnel.toParent(window.parent, tunnelOptions);\n return setupApiExchange<Expected>(tunnel, apiToSend);\n}\n\n/**\n * Create a CrossRealmObject simulating objects from the provided iframe runtime.\n * @alpha\n */\nexport async function connectIframe<Expected>(\n frame: HTMLIFrameElement,\n tunnelOptions: Partial<TunnelConfig>,\n apiToSend: unknown\n): Promise<CrossRealmObject<Expected>> {\n const tunnel = Tunnel.toIframe(frame, tunnelOptions);\n return setupApiExchange<Expected>(tunnel, apiToSend);\n}\n","/**\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type { HostMethodAddress } from \"./types\";\nimport { isFunction, isIterable, isPrimitive } from \"./value-assertions\";\n\n/**\n * Try and format any type of value for logging.\n *\n * @privateRemarks\n * **WARNING**: This is an expensive operation due to the JSON.stringify, and\n * should only be done when debugging or in error conditions.\n * @internal\n */\nexport function formatHostMethodArgument(argument: unknown): string {\n try {\n return JSON.stringify(argument, null, 2);\n } catch (e) {\n if (isIterable(argument)) {\n return `Iterable<${argument.length}>`;\n }\n if (isPrimitive(argument) || isFunction(argument)) {\n return `${argument}`;\n }\n return Object.prototype.toString.call(argument);\n }\n}\n\n/**\n * Try and format a remote method call as it would appear during debugging.\n *\n * @privateRemarks\n * **WARNING**: This is an expensive operation due to the JSON.stringify, and\n * should only be done when debugging or in error conditions. This Functions\n * like {@link @adobe/uix-core#timedPromise} which take logging strings also\n * take callbacks for lazy evaluation of debugging messages. Use this only in\n * such callbacks.\n * @internal\n */\nexport function formatHostMethodAddress(address: HostMethodAddress) {\n const path =\n address.path?.length < 1\n ? \"<Missing method path!>\"\n : address.path.join(\".\");\n const name = address.name || \"<Missing method name!>\";\n const args = address.args?.map(formatHostMethodArgument).join(\",\");\n return `host.${path}.${name}(${args})`;\n}\n","/**\n * Promise that resolves after a specific time\n *\n * @internal\n */\nexport function wait(ms: number) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * @packageDocumentation\n * Tools for UI Extensions meant to run inside extensible apps. Connects\n * Extensions running in their own window contexts with the host app, allowing\n * the host and guest to exchange method, events, and signals.\n *\n * @remarks The core object of this library, which extensions use for\n * communication, is the Guest object. There are two variants of the Guest\n * object {@link GuestServer} for the bootstrap frame which your extension keeps\n * running in the background, and {@link GuestUI} for frames meant to be\n * displayed in the host application. An extension must have one GuestServer\n * frame, and the host app may choose to use one or more GuestUI frames.\n *\n * @example Creating and connecting a GuestServer with {@link register}\n * ```typescript\n * import { register } from \"@adobe/uix-guest\";\n *\n * const server = await register({\n * // Must match extension ID from registry\n * id: \"My Custom View Extension\",\n * // enable logging in dev build\n * debug: process.env.NODE_ENV !== \"production\",\n * // Host can access these methods from its Port to this guest\n * methods: {\n * // Methods must be namespaced by one or more levels\n * myCustomView: {\n * async documentIsViewable(docId) {\n * const doc = await callMyRuntimeAction(docId);\n * return someValidation(doc);\n * },\n * renderView(docId, depth) {\n * // Use a host method\n * const tooltip = await server.host.editor.requestTooltip({\n * type: 'frame',\n * url: new URL(`/show/${docId}`, location).href\n * })\n * }\n * },\n * },\n * })\n * ```\n *\n * @example Connecting to an existing GuestServer with a GuestUI\n * ```typescript\n * import { attach } from \"@adobe/uix-guest\";\n *\n * const ui = await attach({\n * id: \"My Custom View Extension\",\n * })\n *\n * // when editing is done:\n * const saved = await ui.host.editor.saveChanges();\n * if (!saved) {\n * const editorState = ui.sharedContext.get('editorState');\n * if (editorState.tooltips[ui.id].invalid === true) {\n * putGuestUIInInvalidState();\n * }\n * } else {\n * ui.host.editor.dismissTooltip();\n * }\n * ```\n *\n */\nimport type { Guest, GuestConfig } from \"./guest.js\";\nimport { GuestUI } from \"./guest-ui.js\";\nimport { GuestServer } from \"./guest-server.js\";\nimport { GuestApis, GuestMetadata } from \"@adobe/uix-core\";\n\n/**\n * {@inheritdoc GuestConfig}\n * @public\n */\ntype GuestConfigWithMethods<Outgoing extends GuestApis> = GuestConfig & {\n methods: Outgoing;\n metadata?: GuestMetadata;\n};\n\n/**\n * Create and immediately return a {@link GuestServer}.\n *\n * @deprecated Use {@link attach} or {@link register}, which return Promises\n * that resolve once the guest is connected.\n * @public\n */\nexport function createGuest(config: GuestConfig) {\n const guest = new GuestServer(config);\n return guest;\n}\n\n/**\n * Connect to a running {@link GuestServer} to share its context and render UI.\n *\n * @remarks Creates a guest object that shares most of the GuestServer API,\n * except it cannot register its own methods. Use `attach()` in an app or\n * document that is meant to render a UI in the host application; it will have\n * access to the sharedContext object shared by the host and GuestServer.\n *\n * @public\n */\nexport async function attach(config: GuestConfig) {\n const guest = new GuestUI(config);\n await guest._connect();\n return guest;\n}\n\n/**\n * Initiate a connection to the host app and its extension points.\n *\n * @remarks Creates the \"main\" {@link GuestServer}, which runs in the background\n * without UI. Registers methods passed in the `methods` parameter, then\n * resolves the returned Promise with the connected GuestServer object.\n *\n * @public\n */\nexport async function register<Outgoing extends GuestApis>(\n config: GuestConfigWithMethods<Outgoing>\n) {\n const guest = new GuestServer(config);\n guest.register(config.methods, config.metadata);\n return guest;\n}\n\n// backwards compatibility\nexport {\n Guest,\n Guest as BaseGuest,\n GuestUI,\n GuestUI as UIGuest,\n GuestServer,\n GuestServer as PrimaryGuest,\n};\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint @typescript-eslint/no-explicit-any: \"off\" */\nimport type {\n RemoteHostApis,\n HostConnection,\n NamedEvent,\n CrossRealmObject,\n VirtualApi,\n RemoteMethodInvoker,\n HostMethodAddress,\n} from \"@adobe/uix-core\";\nimport {\n Emitter,\n formatHostMethodAddress,\n makeNamespaceProxy,\n connectParentWindow,\n timeoutPromise,\n quietConsole,\n} from \"@adobe/uix-core\";\nimport { debugGuest } from \"./debug-guest.js\";\n\n/**\n * @public\n */\nexport type GuestEvent<\n Type extends string = string,\n Detail = Record<string, unknown>\n> = NamedEvent<\n Type,\n Detail &\n Record<string, unknown> & {\n guest: Guest;\n }\n>;\n\n/**\n * @public\n */\nexport type GuestEventContextChange = GuestEvent<\n \"contextchange\",\n { context: Record<string, unknown> }\n>;\n\n/** @public */\nexport type GuestEventBeforeConnect = GuestEvent<\"beforeconnect\">;\n/** @public */\nexport type GuestEventConnected = GuestEvent<\"connected\">;\n/** @public */\nexport type GuestEventError = GuestEvent<\"error\", { error: Error }>;\n\n/**\n * @public\n */\nexport type GuestEvents =\n | GuestEventContextChange\n | GuestEventBeforeConnect\n | GuestEventConnected\n | GuestEventError;\n\n/**\n * @public\n */\nexport interface GuestConfig {\n /**\n * String slug identifying extension. This may need to use IDs from an\n * external system in the future.\n */\n id: string;\n /**\n * Set debug flags on all libraries that have them, and add loggers to SDK\n * objects. Log a lot to the console.\n */\n debug?: boolean;\n /**\n * Time out and stop trying to reach the host after this many milliseconds\n */\n timeout?: number;\n}\n\n/**\n * A `Map` representing the {@link @adobe/uix-host#HostConfig.sharedContext}\n * object.\n *\n * @remarks While the Host object is a plain JavaScript object. the `sharedContext` in the Guest object implements the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map | Map} interface.\n *\n * @example\n * In the host app window, the Host object shares context:\n * ```javascript\n *host.shareContext({\n * someAuthToken: 'abc'\n *});\n * ```\n *\n * After the `contentchange` event has fired in the guest window:\n * ```javascript\n * guest.sharedContext.get('someAuthToken') === 'abc'\n * ```\n * @public\n */\nexport class SharedContext {\n private _map: Map<string, unknown>;\n constructor(values: Record<string, unknown>) {\n this.reset(values);\n }\n private reset(values: Record<string, unknown>) {\n this._map = new Map(Object.entries(values));\n }\n /**\n * @public\n * Retrieve a copy of a value from the {@link @adobe/uix-host#HostConfig.sharedContext} object. *Note that this is not a reference to any actual objects from the parent. If the parent updates an \"inner object\" inside the SharedContext, that change will not be reflected in the Guest!*\n */\n get(key: string) {\n return this._map.get(key);\n }\n}\n\n/**\n * Generic Guest object, with methods shared by all types of Guest.\n * @internal\n */\nexport class Guest<\n Incoming extends object = VirtualApi\n> extends Emitter<GuestEvents> {\n /**\n * Shared context has been set or updated.\n * @eventProperty\n */\n public contextchange: GuestEventContextChange;\n /**\n * About to attempt connection to the host.\n * @eventProperty\n */\n public beforeconnect: GuestEventBeforeConnect;\n /**\n * Host connection has been established.\n * @eventProperty\n */\n public connected: GuestEventConnected;\n /**\n * Host connection has failed.\n * @eventProperty\n */\n public error: GuestEventError;\n /**\n * {@inheritdoc SharedContext}\n */\n sharedContext: SharedContext;\n /**\n * A guest (extension) configuration\n */\n configuration?: Record<string, unknown>;\n logger: Console = quietConsole;\n\n /**\n * @param config - Initializer for guest object, including ID.\n */\n constructor(config: GuestConfig) {\n super(config.id);\n if (typeof config.timeout === \"number\") {\n this.timeout = config.timeout;\n }\n if (config.debug) {\n this.logger = debugGuest(this);\n }\n this.addEventListener(\"contextchange\", (event) => {\n this.sharedContext = new SharedContext(event.detail.context);\n });\n }\n /**\n * Proxy object for calling methods on the host.\n *\n * @remarks Any APIs exposed to the extension via {@link @adobe/uix-host#Port.provide}\n * can be called on this object. Because these methods are called with RPC,\n * they are all asynchronous, The return types of all Host methods will be\n * Promises which resolve to the value the Host method returns.\n * @public\n */\n host: RemoteHostApis<Incoming> = makeNamespaceProxy<Incoming>(\n async (address) => {\n await this.hostConnectionPromise;\n try {\n const result = await timeoutPromise(\n () => `Calling ${formatHostMethodAddress(address)}`,\n this.invokeAwaiter(\n this.hostConnection.getRemoteApi().invokeHostMethod,\n address\n ),\n 10000\n );\n return result;\n } catch (e) {\n const error =\n e instanceof Error ? e : new Error(e as unknown as string);\n this.logger.error(error);\n throw error;\n }\n }\n );\n\n /**\n * @internal\n */\n private async invokeChecker<T>(\n invoker: RemoteMethodInvoker<unknown>,\n address: HostMethodAddress<unknown[]>\n ): Promise<unknown> {\n try {\n const res = await invoker(address);\n return new Promise((resolve) => resolve(res));\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n return this.invokeChecker(invoker, address);\n }\n }\n\n /**\n * @internal\n */\n private async invokeAwaiter(\n invoker: RemoteMethodInvoker<unknown>,\n address: HostMethodAddress<unknown[]>\n ): Promise<any> {\n const final = setTimeout(() => {\n return new Promise((resolve, reject) =>\n reject(`${address} doesn't exist`)\n );\n }, 20000);\n const res = await this.invokeChecker(invoker, address);\n return new Promise((resolve) => {\n clearTimeout(final);\n return resolve(res);\n }).catch((e) => {\n clearTimeout(final);\n return e;\n });\n }\n private timeout = 20000;\n protected hostConnectionPromise: Promise<CrossRealmObject<HostConnection>>;\n protected hostConnection!: CrossRealmObject<HostConnection>;\n /** @internal */\n protected getLocalMethods() {\n return {\n emit: (...args: Parameters<typeof this.emit>) => {\n this.logger.log(`Event \"${args[0]}\" emitted from host`);\n this.emit(...args);\n },\n };\n }\n /**\n * Accept a connection from the Host.\n * @returns A Promise that resolves when the Host has established a connection.\n * @deprecated It is preferable to use {@link register} for primary frames,\n * and {@link attach} for UI frames and other secondary frames, than to\n * instantiate a Guest and then call `.connect()` on it. The latter style\n * returns an object that cannot be used until it is connected, and therefore\n * risks errors.\n * @public\n */\n async connect() {\n return this._connect();\n }\n\n /**\n * @internal\n */\n async _connect() {\n this.emit(\"beforeconnect\", { guest: this });\n try {\n const hostConnectionPromise = connectParentWindow<HostConnection>(\n {\n targetOrigin: \"*\",\n timeout: this.timeout,\n logger: this.logger,\n },\n this.getLocalMethods()\n );\n\n this.hostConnectionPromise = hostConnectionPromise;\n this.hostConnection = await this.hostConnectionPromise;\n this.emit(\"connected\", { guest: this });\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"Connection failed!\", e);\n throw e;\n }\n try {\n this.sharedContext = new SharedContext(\n await this.hostConnection.getRemoteApi().getSharedContext()\n );\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"getSharedContext failed!\", e);\n throw e;\n }\n try {\n this.configuration = await this.hostConnection\n .getRemoteApi()\n .getConfiguration();\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"getConfiguration failed!\", e);\n throw e;\n }\n }\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * Adapter to attach console logging listeners to a Guest running in a frame/\n * @internal @preapproved\n */\nimport { debugEmitter, Emits, EmitterDebugLogger } from \"@adobe/uix-core\";\nimport { GuestEvents } from \"./guest\";\n\nexport function debugGuest(guest: Emits<GuestEvents>): EmitterDebugLogger {\n return debugEmitter(guest, {\n theme: \"yellow medium\",\n type: \"Guest\",\n })\n .listen(\"beforeconnect\", (log, { detail: { guest } }) => {\n log.info(guest);\n })\n .listen(\"connecting\", (log, { detail: { connection } }) => {\n log.info(connection);\n })\n .listen(\"connected\", (log, { detail: { guest } }) => {\n log.info(guest);\n })\n .listen(\"error\", (log, { detail: { error, guest } }) => {\n log.error(\n \"❌ Failed to connect! %s\",\n (error as Error).message,\n guest,\n error\n );\n });\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type {\n CrossRealmObject,\n RemoteHostApis,\n UIHostConnection,\n VirtualApi,\n} from \"@adobe/uix-core\";\nimport {\n Guest,\n GuestConfig,\n GuestEventBeforeConnect,\n GuestEventConnected,\n GuestEventContextChange,\n GuestEventError,\n} from \"./guest\";\n\n/**\n * A Guest to be used in an extension-controlled frame, usually to display UI.\n *\n * @typeParam Incoming - Optional interface of host methods. If using\n * TypeScript, supply this type parameter and a promisified version of the\n * interface will be available at {@link Guest.host}\n *\n * @remarks\n * This is the object returned when calling {@link @adobe/uix-guest#attach}. It\n * represents an additional frame or runtime created by the host application, on\n * behalf of the extension's control frame which is running the {@link\n * GuestServer}. It is a \"secondary\" guest object, which a host won't use before\n * the control frame has connected. It exposes a subset of the functionality of\n * the {@link GuestServer}.\n *\n * Unlike the {@link GuestServer}, it cannot register methods or update the\n * {@link Guest.sharedContext}, but it remains in sync with the GuestServer and\n * can access the {@link Guest.sharedContext} of the control frame, as well as\n * any of the published methods on the host.\n *\n * Extensible host apps using the React bindings will likely render GuestUI\n * frames using the {@link @adobe/uix-host-react#GuestUIFrame} component.\n *\n * @example\n * When an extensible app renders this page, {@link @adobe/uix-guest#attach}\n * creates a GuestUI. Once it attaches to the host, it\n * ```javascript\n * import React, { useEffect, useState } from \"react\";\n * import { attach } from \"@adobe/uix-guest\";\n * import { Tooltip } from \"./tooltip\";\n *\n * export default function PopupOverlay(props) {\n * // how large am I?\n * const [dimensions, setDimensions] = useState(\n * document.body.getBoundingClientRect()\n * );\n * // if possible, use language preloaded in query parameters\n * const [language, setLanguage] = useState(props.params.lang)\n *\n * // attach only once, in a useEffect\n * useEffect(() => {\n * attach({\n * id: \"my-extension-id\",\n * debug: true,\n * })\n * .then(guestUI => {\n * // this event fires whenever the host, or the control frame, changes\n * // any sharedContext value\n * guestUI.addEventListener(\"contextchange\", ({ detail: { context }}) => {\n * setLanguage(context.lang)\n * });\n * // how large does the host want me to be?\n * return guestUI.host.tooltips.getDimensions()\n * .then(setDimensions)\n * })\n * .catch((e) => {\n * console.error(\"ui attach failed\", e);\n * });\n * }, []);\n * // render UI! Due to the setup and useState, this component will re-render\n * // once attach() is complete.\n * return (\n * <Tooltip {...props.params} lang={language} dimensions={dimensions} />\n * );\n * }\n * ```\n *\n * @public\n */\nexport class GuestUI<IHost extends VirtualApi> extends Guest<IHost> {\n /**\n * {@inheritDoc Guest.\"constructor\"}\n */\n constructor(config: GuestConfig) {\n super(config);\n this.addEventListener(\"connected\", () => {\n const resizeObserver = new ResizeObserver((entries) => {\n const doc = entries.find((entry) => entry.target === document.body);\n const borderBoxSize = doc.borderBoxSize.length\n ? doc.borderBoxSize[0]\n : (doc.borderBoxSize as unknown as ResizeObserverSize);\n this.hostConnection.getRemoteApi().onIframeResize({\n height:\n borderBoxSize.blockSize +\n this.calculateChildrenMargin(doc.target.querySelectorAll(\"*\")),\n width: borderBoxSize.inlineSize,\n });\n });\n resizeObserver.observe(document.body);\n });\n\n this.logger.log(\"Will add resize observer on connect\");\n }\n\n /**\n * @internal\n */\n private calculateChildrenMargin(elems: NodeListOf<any>): number {\n let margin = 0;\n\n for (let i = 0; i < elems.length; i++) {\n const style = elems[i].currentStyle || window.getComputedStyle(elems[i]);\n const marginTop = parseInt(style.marginTop);\n const marginBottom = parseInt(style.marginBottom);\n\n if (marginTop > 0) {\n margin = margin + marginTop;\n }\n\n if (marginBottom > 0) {\n margin = margin + marginBottom;\n }\n }\n\n return margin;\n }\n\n /**\n * {@inheritDoc Guest.contextchange}\n * @eventProperty\n */\n public contextchange: GuestEventContextChange;\n /**\n * {@inheritDoc Guest.beforeconnect}\n * @eventProperty\n */\n public beforeconnect: GuestEventBeforeConnect;\n /**\n * {@inheritDoc Guest.connected}\n * @eventProperty\n */\n public connected: GuestEventConnected;\n /**\n * {@inheritDoc Guest.error}\n * @eventProperty\n */\n public error: GuestEventError;\n /**\n * {@inheritDoc Guest.host}\n */\n host: RemoteHostApis<IHost>;\n protected hostConnection!: CrossRealmObject<UIHostConnection>;\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type { GuestApis, GuestMetadata } from \"@adobe/uix-core\";\nimport type { SharedContext } from \"./guest\";\nimport { Guest } from \"./guest\";\n\n/**\n * A Guest to be used in the \"main\" or primary frame of an extension, the frame\n * the Host loads first.\n *\n * @remarks This is the Guest object returned from {@link register}. It can\n * expose internal methods to the Host via the {@link GuestServer.register}\n * method.\n *\n *\n * @public\n */\nexport class GuestServer<Outgoing extends GuestApis> extends Guest<Outgoing> {\n private localMethods: Outgoing;\n metadata: GuestMetadata;\n protected getLocalMethods() {\n return {\n ...super.getLocalMethods(),\n apis: this.localMethods,\n metadata: this.metadata,\n };\n }\n /**\n * {@inheritDoc BaseGuest.sharedContext}\n */\n sharedContext: SharedContext;\n /**\n * {@inheritdoc BaseGuest.host}\n */\n host: Guest<Outgoing>[\"host\"];\n /**\n * Pass an interface of methods which Host may call as callbacks.\n *\n * @remarks It is preferable to use {@link register} to obtain a guest object\n * and register local methods in one step. The returned guest object will be\n * pre-registered and connected.\n * @public\n */\n async register(implementedMethods: Outgoing, metadata: GuestMetadata) {\n this.localMethods = implementedMethods;\n this.metadata = {\n ...metadata,\n extensionId: this.id,\n };\n return this._connect();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,UAAA,wBAAAA,YAAA;QAEA,4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,UAAM,QAAQ,IAAI,YAAY,MAAM;AACpC,UAAM,SAAS,OAAO,SAAS,OAAO,QAAQ;AAC9C,WAAO;AAAA,EACT;","names":["__commonJS","exports","module","EventEmitter","quietConsole","debugEmitter","Emitter","makeNamespaceProxy","target","timeoutPromise","connectParentWindow","formatHostMethodAddress","import_uix_core","guest","Guest","Guest","Guest"]}
package/dist/index.js CHANGED
@@ -237,11 +237,13 @@ var GuestUI = class extends Guest2 {
237
237
  let margin = 0;
238
238
  for (let i = 0; i < elems.length; i++) {
239
239
  const style = elems[i].currentStyle || window.getComputedStyle(elems[i]);
240
- if (style.marginTop !== "0px") {
241
- margin = margin + parseInt(style.marginTop);
240
+ const marginTop = parseInt(style.marginTop);
241
+ const marginBottom = parseInt(style.marginBottom);
242
+ if (marginTop > 0) {
243
+ margin = margin + marginTop;
242
244
  }
243
- if (style.marginBottom !== "0px") {
244
- margin = margin + parseInt(style.marginBottom);
245
+ if (marginBottom > 0) {
246
+ margin = margin + marginBottom;
245
247
  }
246
248
  }
247
249
  return margin;
@@ -267,7 +269,10 @@ var GuestServer = class extends Guest2 {
267
269
  */
268
270
  async register(implementedMethods, metadata) {
269
271
  this.localMethods = implementedMethods;
270
- this.metadata = metadata;
272
+ this.metadata = {
273
+ ...metadata,
274
+ extensionId: this.id
275
+ };
271
276
  return this._connect();
272
277
  }
273
278
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/guest.ts","../src/debug-guest.ts","../src/guest-ui.ts","../src/guest-server.ts"],"sourcesContent":["/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * @packageDocumentation\n * Tools for UI Extensions meant to run inside extensible apps. Connects\n * Extensions running in their own window contexts with the host app, allowing\n * the host and guest to exchange method, events, and signals.\n *\n * @remarks The core object of this library, which extensions use for\n * communication, is the Guest object. There are two variants of the Guest\n * object {@link GuestServer} for the bootstrap frame which your extension keeps\n * running in the background, and {@link GuestUI} for frames meant to be\n * displayed in the host application. An extension must have one GuestServer\n * frame, and the host app may choose to use one or more GuestUI frames.\n *\n * @example Creating and connecting a GuestServer with {@link register}\n * ```typescript\n * import { register } from \"@adobe/uix-guest\";\n *\n * const server = await register({\n * // Must match extension ID from registry\n * id: \"My Custom View Extension\",\n * // enable logging in dev build\n * debug: process.env.NODE_ENV !== \"production\",\n * // Host can access these methods from its Port to this guest\n * methods: {\n * // Methods must be namespaced by one or more levels\n * myCustomView: {\n * async documentIsViewable(docId) {\n * const doc = await callMyRuntimeAction(docId);\n * return someValidation(doc);\n * },\n * renderView(docId, depth) {\n * // Use a host method\n * const tooltip = await server.host.editor.requestTooltip({\n * type: 'frame',\n * url: new URL(`/show/${docId}`, location).href\n * })\n * }\n * },\n * },\n * })\n * ```\n *\n * @example Connecting to an existing GuestServer with a GuestUI\n * ```typescript\n * import { attach } from \"@adobe/uix-guest\";\n *\n * const ui = await attach({\n * id: \"My Custom View Extension\",\n * })\n *\n * // when editing is done:\n * const saved = await ui.host.editor.saveChanges();\n * if (!saved) {\n * const editorState = ui.sharedContext.get('editorState');\n * if (editorState.tooltips[ui.id].invalid === true) {\n * putGuestUIInInvalidState();\n * }\n * } else {\n * ui.host.editor.dismissTooltip();\n * }\n * ```\n *\n */\nimport type { Guest, GuestConfig } from \"./guest.js\";\nimport { GuestUI } from \"./guest-ui.js\";\nimport { GuestServer } from \"./guest-server.js\";\nimport { GuestApis, GuestMetadata } from \"@adobe/uix-core\";\n\n/**\n * {@inheritdoc GuestConfig}\n * @public\n */\ntype GuestConfigWithMethods<Outgoing extends GuestApis> = GuestConfig & {\n methods: Outgoing;\n metadata?: GuestMetadata;\n};\n\n/**\n * Create and immediately return a {@link GuestServer}.\n *\n * @deprecated Use {@link attach} or {@link register}, which return Promises\n * that resolve once the guest is connected.\n * @public\n */\nexport function createGuest(config: GuestConfig) {\n const guest = new GuestServer(config);\n return guest;\n}\n\n/**\n * Connect to a running {@link GuestServer} to share its context and render UI.\n *\n * @remarks Creates a guest object that shares most of the GuestServer API,\n * except it cannot register its own methods. Use `attach()` in an app or\n * document that is meant to render a UI in the host application; it will have\n * access to the sharedContext object shared by the host and GuestServer.\n *\n * @public\n */\nexport async function attach(config: GuestConfig) {\n const guest = new GuestUI(config);\n await guest._connect();\n return guest;\n}\n\n/**\n * Initiate a connection to the host app and its extension points.\n *\n * @remarks Creates the \"main\" {@link GuestServer}, which runs in the background\n * without UI. Registers methods passed in the `methods` parameter, then\n * resolves the returned Promise with the connected GuestServer object.\n *\n * @public\n */\nexport async function register<Outgoing extends GuestApis>(\n config: GuestConfigWithMethods<Outgoing>\n) {\n const guest = new GuestServer(config);\n guest.register(config.methods, config.metadata);\n return guest;\n}\n\n// backwards compatibility\nexport {\n Guest,\n Guest as BaseGuest,\n GuestUI,\n GuestUI as UIGuest,\n GuestServer,\n GuestServer as PrimaryGuest,\n};\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint @typescript-eslint/no-explicit-any: \"off\" */\nimport type {\n RemoteHostApis,\n HostConnection,\n NamedEvent,\n CrossRealmObject,\n VirtualApi,\n RemoteMethodInvoker,\n HostMethodAddress,\n} from \"@adobe/uix-core\";\nimport {\n Emitter,\n formatHostMethodAddress,\n makeNamespaceProxy,\n connectParentWindow,\n timeoutPromise,\n quietConsole,\n} from \"@adobe/uix-core\";\nimport { debugGuest } from \"./debug-guest.js\";\n\n/**\n * @public\n */\nexport type GuestEvent<\n Type extends string = string,\n Detail = Record<string, unknown>\n> = NamedEvent<\n Type,\n Detail &\n Record<string, unknown> & {\n guest: Guest;\n }\n>;\n\n/**\n * @public\n */\nexport type GuestEventContextChange = GuestEvent<\n \"contextchange\",\n { context: Record<string, unknown> }\n>;\n\n/** @public */\nexport type GuestEventBeforeConnect = GuestEvent<\"beforeconnect\">;\n/** @public */\nexport type GuestEventConnected = GuestEvent<\"connected\">;\n/** @public */\nexport type GuestEventError = GuestEvent<\"error\", { error: Error }>;\n\n/**\n * @public\n */\nexport type GuestEvents =\n | GuestEventContextChange\n | GuestEventBeforeConnect\n | GuestEventConnected\n | GuestEventError;\n\n/**\n * @public\n */\nexport interface GuestConfig {\n /**\n * String slug identifying extension. This may need to use IDs from an\n * external system in the future.\n */\n id: string;\n /**\n * Set debug flags on all libraries that have them, and add loggers to SDK\n * objects. Log a lot to the console.\n */\n debug?: boolean;\n /**\n * Time out and stop trying to reach the host after this many milliseconds\n */\n timeout?: number;\n}\n\n/**\n * A `Map` representing the {@link @adobe/uix-host#HostConfig.sharedContext}\n * object.\n *\n * @remarks While the Host object is a plain JavaScript object. the `sharedContext` in the Guest object implements the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map | Map} interface.\n *\n * @example\n * In the host app window, the Host object shares context:\n * ```javascript\n *host.shareContext({\n * someAuthToken: 'abc'\n *});\n * ```\n *\n * After the `contentchange` event has fired in the guest window:\n * ```javascript\n * guest.sharedContext.get('someAuthToken') === 'abc'\n * ```\n * @public\n */\nexport class SharedContext {\n private _map: Map<string, unknown>;\n constructor(values: Record<string, unknown>) {\n this.reset(values);\n }\n private reset(values: Record<string, unknown>) {\n this._map = new Map(Object.entries(values));\n }\n /**\n * @public\n * Retrieve a copy of a value from the {@link @adobe/uix-host#HostConfig.sharedContext} object. *Note that this is not a reference to any actual objects from the parent. If the parent updates an \"inner object\" inside the SharedContext, that change will not be reflected in the Guest!*\n */\n get(key: string) {\n return this._map.get(key);\n }\n}\n\n/**\n * Generic Guest object, with methods shared by all types of Guest.\n * @internal\n */\nexport class Guest<\n Incoming extends object = VirtualApi\n> extends Emitter<GuestEvents> {\n /**\n * Shared context has been set or updated.\n * @eventProperty\n */\n public contextchange: GuestEventContextChange;\n /**\n * About to attempt connection to the host.\n * @eventProperty\n */\n public beforeconnect: GuestEventBeforeConnect;\n /**\n * Host connection has been established.\n * @eventProperty\n */\n public connected: GuestEventConnected;\n /**\n * Host connection has failed.\n * @eventProperty\n */\n public error: GuestEventError;\n /**\n * {@inheritdoc SharedContext}\n */\n sharedContext: SharedContext;\n /**\n * A guest (extension) configuration\n */\n configuration?: Record<string, unknown>;\n logger: Console = quietConsole;\n\n /**\n * @param config - Initializer for guest object, including ID.\n */\n constructor(config: GuestConfig) {\n super(config.id);\n if (typeof config.timeout === \"number\") {\n this.timeout = config.timeout;\n }\n if (config.debug) {\n this.logger = debugGuest(this);\n }\n this.addEventListener(\"contextchange\", (event) => {\n this.sharedContext = new SharedContext(event.detail.context);\n });\n }\n /**\n * Proxy object for calling methods on the host.\n *\n * @remarks Any APIs exposed to the extension via {@link @adobe/uix-host#Port.provide}\n * can be called on this object. Because these methods are called with RPC,\n * they are all asynchronous, The return types of all Host methods will be\n * Promises which resolve to the value the Host method returns.\n * @public\n */\n host: RemoteHostApis<Incoming> = makeNamespaceProxy<Incoming>(\n async (address) => {\n await this.hostConnectionPromise;\n try {\n const result = await timeoutPromise(\n () => `Calling ${formatHostMethodAddress(address)}`,\n this.invokeAwaiter(\n this.hostConnection.getRemoteApi().invokeHostMethod,\n address\n ),\n 10000\n );\n return result;\n } catch (e) {\n const error =\n e instanceof Error ? e : new Error(e as unknown as string);\n this.logger.error(error);\n throw error;\n }\n }\n );\n\n /**\n * @internal\n */\n private async invokeChecker<T>(\n invoker: RemoteMethodInvoker<unknown>,\n address: HostMethodAddress<unknown[]>\n ): Promise<unknown> {\n try {\n const res = await invoker(address);\n return new Promise((resolve) => resolve(res));\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n return this.invokeChecker(invoker, address);\n }\n }\n\n /**\n * @internal\n */\n private async invokeAwaiter(\n invoker: RemoteMethodInvoker<unknown>,\n address: HostMethodAddress<unknown[]>\n ): Promise<any> {\n const final = setTimeout(() => {\n return new Promise((resolve, reject) =>\n reject(`${address} doesn't exist`)\n );\n }, 20000);\n const res = await this.invokeChecker(invoker, address);\n return new Promise((resolve) => {\n clearTimeout(final);\n return resolve(res);\n }).catch((e) => {\n clearTimeout(final);\n return e;\n });\n }\n private timeout = 20000;\n protected hostConnectionPromise: Promise<CrossRealmObject<HostConnection>>;\n protected hostConnection!: CrossRealmObject<HostConnection>;\n /** @internal */\n protected getLocalMethods() {\n return {\n emit: (...args: Parameters<typeof this.emit>) => {\n this.logger.log(`Event \"${args[0]}\" emitted from host`);\n this.emit(...args);\n },\n };\n }\n /**\n * Accept a connection from the Host.\n * @returns A Promise that resolves when the Host has established a connection.\n * @deprecated It is preferable to use {@link register} for primary frames,\n * and {@link attach} for UI frames and other secondary frames, than to\n * instantiate a Guest and then call `.connect()` on it. The latter style\n * returns an object that cannot be used until it is connected, and therefore\n * risks errors.\n * @public\n */\n async connect() {\n return this._connect();\n }\n\n /**\n * @internal\n */\n async _connect() {\n this.emit(\"beforeconnect\", { guest: this });\n try {\n const hostConnectionPromise = connectParentWindow<HostConnection>(\n {\n targetOrigin: \"*\",\n timeout: this.timeout,\n logger: this.logger,\n },\n this.getLocalMethods()\n );\n\n this.hostConnectionPromise = hostConnectionPromise;\n this.hostConnection = await this.hostConnectionPromise;\n this.emit(\"connected\", { guest: this });\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"Connection failed!\", e);\n throw e;\n }\n try {\n this.sharedContext = new SharedContext(\n await this.hostConnection.getRemoteApi().getSharedContext()\n );\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"getSharedContext failed!\", e);\n throw e;\n }\n try {\n this.configuration = await this.hostConnection\n .getRemoteApi()\n .getConfiguration();\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"getConfiguration failed!\", e);\n throw e;\n }\n }\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * Adapter to attach console logging listeners to a Guest running in a frame/\n * @internal @preapproved\n */\nimport { debugEmitter, Emits, EmitterDebugLogger } from \"@adobe/uix-core\";\nimport { GuestEvents } from \"./guest\";\n\nexport function debugGuest(guest: Emits<GuestEvents>): EmitterDebugLogger {\n return debugEmitter(guest, {\n theme: \"yellow medium\",\n type: \"Guest\",\n })\n .listen(\"beforeconnect\", (log, { detail: { guest } }) => {\n log.info(guest);\n })\n .listen(\"connecting\", (log, { detail: { connection } }) => {\n log.info(connection);\n })\n .listen(\"connected\", (log, { detail: { guest } }) => {\n log.info(guest);\n })\n .listen(\"error\", (log, { detail: { error, guest } }) => {\n log.error(\n \"❌ Failed to connect! %s\",\n (error as Error).message,\n guest,\n error\n );\n });\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type {\n CrossRealmObject,\n RemoteHostApis,\n UIHostConnection,\n VirtualApi,\n} from \"@adobe/uix-core\";\nimport {\n Guest,\n GuestConfig,\n GuestEventBeforeConnect,\n GuestEventConnected,\n GuestEventContextChange,\n GuestEventError,\n} from \"./guest\";\n\n/**\n * A Guest to be used in an extension-controlled frame, usually to display UI.\n *\n * @typeParam Incoming - Optional interface of host methods. If using\n * TypeScript, supply this type parameter and a promisified version of the\n * interface will be available at {@link Guest.host}\n *\n * @remarks\n * This is the object returned when calling {@link @adobe/uix-guest#attach}. It\n * represents an additional frame or runtime created by the host application, on\n * behalf of the extension's control frame which is running the {@link\n * GuestServer}. It is a \"secondary\" guest object, which a host won't use before\n * the control frame has connected. It exposes a subset of the functionality of\n * the {@link GuestServer}.\n *\n * Unlike the {@link GuestServer}, it cannot register methods or update the\n * {@link Guest.sharedContext}, but it remains in sync with the GuestServer and\n * can access the {@link Guest.sharedContext} of the control frame, as well as\n * any of the published methods on the host.\n *\n * Extensible host apps using the React bindings will likely render GuestUI\n * frames using the {@link @adobe/uix-host-react#GuestUIFrame} component.\n *\n * @example\n * When an extensible app renders this page, {@link @adobe/uix-guest#attach}\n * creates a GuestUI. Once it attaches to the host, it\n * ```javascript\n * import React, { useEffect, useState } from \"react\";\n * import { attach } from \"@adobe/uix-guest\";\n * import { Tooltip } from \"./tooltip\";\n *\n * export default function PopupOverlay(props) {\n * // how large am I?\n * const [dimensions, setDimensions] = useState(\n * document.body.getBoundingClientRect()\n * );\n * // if possible, use language preloaded in query parameters\n * const [language, setLanguage] = useState(props.params.lang)\n *\n * // attach only once, in a useEffect\n * useEffect(() => {\n * attach({\n * id: \"my-extension-id\",\n * debug: true,\n * })\n * .then(guestUI => {\n * // this event fires whenever the host, or the control frame, changes\n * // any sharedContext value\n * guestUI.addEventListener(\"contextchange\", ({ detail: { context }}) => {\n * setLanguage(context.lang)\n * });\n * // how large does the host want me to be?\n * return guestUI.host.tooltips.getDimensions()\n * .then(setDimensions)\n * })\n * .catch((e) => {\n * console.error(\"ui attach failed\", e);\n * });\n * }, []);\n * // render UI! Due to the setup and useState, this component will re-render\n * // once attach() is complete.\n * return (\n * <Tooltip {...props.params} lang={language} dimensions={dimensions} />\n * );\n * }\n * ```\n *\n * @public\n */\nexport class GuestUI<IHost extends VirtualApi> extends Guest<IHost> {\n /**\n * {@inheritDoc Guest.\"constructor\"}\n */\n constructor(config: GuestConfig) {\n super(config);\n this.addEventListener(\"connected\", () => {\n const resizeObserver = new ResizeObserver((entries) => {\n const doc = entries.find((entry) => entry.target === document.body);\n const borderBoxSize = doc.borderBoxSize.length\n ? doc.borderBoxSize[0]\n : (doc.borderBoxSize as unknown as ResizeObserverSize);\n this.hostConnection.getRemoteApi().onIframeResize({\n height:\n borderBoxSize.blockSize +\n this.calculateChildrenMargin(doc.target.querySelectorAll(\"*\")),\n width: borderBoxSize.inlineSize,\n });\n });\n resizeObserver.observe(document.body);\n });\n\n this.logger.log(\"Will add resize observer on connect\");\n }\n\n /**\n * @internal\n */\n private calculateChildrenMargin(elems: NodeListOf<any>): number {\n let margin = 0;\n\n for (let i = 0; i < elems.length; i++) {\n const style = elems[i].currentStyle || window.getComputedStyle(elems[i]);\n\n if (style.marginTop !== \"0px\") {\n margin = margin + parseInt(style.marginTop);\n }\n\n if (style.marginBottom !== \"0px\") {\n margin = margin + parseInt(style.marginBottom);\n }\n }\n\n return margin;\n }\n\n /**\n * {@inheritDoc Guest.contextchange}\n * @eventProperty\n */\n public contextchange: GuestEventContextChange;\n /**\n * {@inheritDoc Guest.beforeconnect}\n * @eventProperty\n */\n public beforeconnect: GuestEventBeforeConnect;\n /**\n * {@inheritDoc Guest.connected}\n * @eventProperty\n */\n public connected: GuestEventConnected;\n /**\n * {@inheritDoc Guest.error}\n * @eventProperty\n */\n public error: GuestEventError;\n /**\n * {@inheritDoc Guest.host}\n */\n host: RemoteHostApis<IHost>;\n protected hostConnection!: CrossRealmObject<UIHostConnection>;\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type { GuestApis, GuestMetadata } from \"@adobe/uix-core\";\nimport type { SharedContext } from \"./guest\";\nimport { Guest } from \"./guest\";\n\n/**\n * A Guest to be used in the \"main\" or primary frame of an extension, the frame\n * the Host loads first.\n *\n * @remarks This is the Guest object returned from {@link register}. It can\n * expose internal methods to the Host via the {@link GuestServer.register}\n * method.\n *\n *\n * @public\n */\nexport class GuestServer<Outgoing extends GuestApis> extends Guest<Outgoing> {\n private localMethods: Outgoing;\n metadata: GuestMetadata;\n protected getLocalMethods() {\n return {\n ...super.getLocalMethods(),\n apis: this.localMethods,\n metadata: this.metadata,\n };\n }\n /**\n * {@inheritDoc BaseGuest.sharedContext}\n */\n sharedContext: SharedContext;\n /**\n * {@inheritdoc BaseGuest.host}\n */\n host: Guest<Outgoing>[\"host\"];\n /**\n * Pass an interface of methods which Host may call as callbacks.\n *\n * @remarks It is preferable to use {@link register} to obtain a guest object\n * and register local methods in one step. The returned guest object will be\n * pre-registered and connected.\n * @public\n */\n async register(implementedMethods: Outgoing, metadata: GuestMetadata) {\n this.localMethods = implementedMethods;\n this.metadata = metadata;\n return this._connect();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBA,IAAAA,mBAOO;;;ACbP,sBAAwD;AAGjD,SAAS,WAAW,OAA+C;AACxE,aAAO,8BAAa,OAAO;AAAA,IACzB,OAAO;AAAA,IACP,MAAM;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AAK,eAAe;AACpB,SAAK,WAAW;AAChB,WAAO,KAAK,SAAS;AAAA,EACvB;AACF;;;AJsCO,SAAS,YAAY,QAAqB;AAC/C,QAAM,QAAQ,IAAI,YAAY,MAAM;AACpC,SAAO;AACT;AAYA,eAAsB,OAAO,QAAqB;AAChD,QAAM,QAAQ,IAAI,QAAQ,MAAM;AAChC,QAAM,MAAM,SAAS;AACrB,SAAO;AACT;AAWA,eAAsB,SACpB,QACA;AACA,QAAM,QAAQ,IAAI,YAAY,MAAM;AACpC,QAAM,SAAS,OAAO,SAAS,OAAO,QAAQ;AAC9C,SAAO;AACT;","names":["import_uix_core","guest","Guest","Guest","Guest"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/guest.ts","../src/debug-guest.ts","../src/guest-ui.ts","../src/guest-server.ts"],"sourcesContent":["/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * @packageDocumentation\n * Tools for UI Extensions meant to run inside extensible apps. Connects\n * Extensions running in their own window contexts with the host app, allowing\n * the host and guest to exchange method, events, and signals.\n *\n * @remarks The core object of this library, which extensions use for\n * communication, is the Guest object. There are two variants of the Guest\n * object {@link GuestServer} for the bootstrap frame which your extension keeps\n * running in the background, and {@link GuestUI} for frames meant to be\n * displayed in the host application. An extension must have one GuestServer\n * frame, and the host app may choose to use one or more GuestUI frames.\n *\n * @example Creating and connecting a GuestServer with {@link register}\n * ```typescript\n * import { register } from \"@adobe/uix-guest\";\n *\n * const server = await register({\n * // Must match extension ID from registry\n * id: \"My Custom View Extension\",\n * // enable logging in dev build\n * debug: process.env.NODE_ENV !== \"production\",\n * // Host can access these methods from its Port to this guest\n * methods: {\n * // Methods must be namespaced by one or more levels\n * myCustomView: {\n * async documentIsViewable(docId) {\n * const doc = await callMyRuntimeAction(docId);\n * return someValidation(doc);\n * },\n * renderView(docId, depth) {\n * // Use a host method\n * const tooltip = await server.host.editor.requestTooltip({\n * type: 'frame',\n * url: new URL(`/show/${docId}`, location).href\n * })\n * }\n * },\n * },\n * })\n * ```\n *\n * @example Connecting to an existing GuestServer with a GuestUI\n * ```typescript\n * import { attach } from \"@adobe/uix-guest\";\n *\n * const ui = await attach({\n * id: \"My Custom View Extension\",\n * })\n *\n * // when editing is done:\n * const saved = await ui.host.editor.saveChanges();\n * if (!saved) {\n * const editorState = ui.sharedContext.get('editorState');\n * if (editorState.tooltips[ui.id].invalid === true) {\n * putGuestUIInInvalidState();\n * }\n * } else {\n * ui.host.editor.dismissTooltip();\n * }\n * ```\n *\n */\nimport type { Guest, GuestConfig } from \"./guest.js\";\nimport { GuestUI } from \"./guest-ui.js\";\nimport { GuestServer } from \"./guest-server.js\";\nimport { GuestApis, GuestMetadata } from \"@adobe/uix-core\";\n\n/**\n * {@inheritdoc GuestConfig}\n * @public\n */\ntype GuestConfigWithMethods<Outgoing extends GuestApis> = GuestConfig & {\n methods: Outgoing;\n metadata?: GuestMetadata;\n};\n\n/**\n * Create and immediately return a {@link GuestServer}.\n *\n * @deprecated Use {@link attach} or {@link register}, which return Promises\n * that resolve once the guest is connected.\n * @public\n */\nexport function createGuest(config: GuestConfig) {\n const guest = new GuestServer(config);\n return guest;\n}\n\n/**\n * Connect to a running {@link GuestServer} to share its context and render UI.\n *\n * @remarks Creates a guest object that shares most of the GuestServer API,\n * except it cannot register its own methods. Use `attach()` in an app or\n * document that is meant to render a UI in the host application; it will have\n * access to the sharedContext object shared by the host and GuestServer.\n *\n * @public\n */\nexport async function attach(config: GuestConfig) {\n const guest = new GuestUI(config);\n await guest._connect();\n return guest;\n}\n\n/**\n * Initiate a connection to the host app and its extension points.\n *\n * @remarks Creates the \"main\" {@link GuestServer}, which runs in the background\n * without UI. Registers methods passed in the `methods` parameter, then\n * resolves the returned Promise with the connected GuestServer object.\n *\n * @public\n */\nexport async function register<Outgoing extends GuestApis>(\n config: GuestConfigWithMethods<Outgoing>\n) {\n const guest = new GuestServer(config);\n guest.register(config.methods, config.metadata);\n return guest;\n}\n\n// backwards compatibility\nexport {\n Guest,\n Guest as BaseGuest,\n GuestUI,\n GuestUI as UIGuest,\n GuestServer,\n GuestServer as PrimaryGuest,\n};\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/* eslint @typescript-eslint/no-explicit-any: \"off\" */\nimport type {\n RemoteHostApis,\n HostConnection,\n NamedEvent,\n CrossRealmObject,\n VirtualApi,\n RemoteMethodInvoker,\n HostMethodAddress,\n} from \"@adobe/uix-core\";\nimport {\n Emitter,\n formatHostMethodAddress,\n makeNamespaceProxy,\n connectParentWindow,\n timeoutPromise,\n quietConsole,\n} from \"@adobe/uix-core\";\nimport { debugGuest } from \"./debug-guest.js\";\n\n/**\n * @public\n */\nexport type GuestEvent<\n Type extends string = string,\n Detail = Record<string, unknown>\n> = NamedEvent<\n Type,\n Detail &\n Record<string, unknown> & {\n guest: Guest;\n }\n>;\n\n/**\n * @public\n */\nexport type GuestEventContextChange = GuestEvent<\n \"contextchange\",\n { context: Record<string, unknown> }\n>;\n\n/** @public */\nexport type GuestEventBeforeConnect = GuestEvent<\"beforeconnect\">;\n/** @public */\nexport type GuestEventConnected = GuestEvent<\"connected\">;\n/** @public */\nexport type GuestEventError = GuestEvent<\"error\", { error: Error }>;\n\n/**\n * @public\n */\nexport type GuestEvents =\n | GuestEventContextChange\n | GuestEventBeforeConnect\n | GuestEventConnected\n | GuestEventError;\n\n/**\n * @public\n */\nexport interface GuestConfig {\n /**\n * String slug identifying extension. This may need to use IDs from an\n * external system in the future.\n */\n id: string;\n /**\n * Set debug flags on all libraries that have them, and add loggers to SDK\n * objects. Log a lot to the console.\n */\n debug?: boolean;\n /**\n * Time out and stop trying to reach the host after this many milliseconds\n */\n timeout?: number;\n}\n\n/**\n * A `Map` representing the {@link @adobe/uix-host#HostConfig.sharedContext}\n * object.\n *\n * @remarks While the Host object is a plain JavaScript object. the `sharedContext` in the Guest object implements the {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map | Map} interface.\n *\n * @example\n * In the host app window, the Host object shares context:\n * ```javascript\n *host.shareContext({\n * someAuthToken: 'abc'\n *});\n * ```\n *\n * After the `contentchange` event has fired in the guest window:\n * ```javascript\n * guest.sharedContext.get('someAuthToken') === 'abc'\n * ```\n * @public\n */\nexport class SharedContext {\n private _map: Map<string, unknown>;\n constructor(values: Record<string, unknown>) {\n this.reset(values);\n }\n private reset(values: Record<string, unknown>) {\n this._map = new Map(Object.entries(values));\n }\n /**\n * @public\n * Retrieve a copy of a value from the {@link @adobe/uix-host#HostConfig.sharedContext} object. *Note that this is not a reference to any actual objects from the parent. If the parent updates an \"inner object\" inside the SharedContext, that change will not be reflected in the Guest!*\n */\n get(key: string) {\n return this._map.get(key);\n }\n}\n\n/**\n * Generic Guest object, with methods shared by all types of Guest.\n * @internal\n */\nexport class Guest<\n Incoming extends object = VirtualApi\n> extends Emitter<GuestEvents> {\n /**\n * Shared context has been set or updated.\n * @eventProperty\n */\n public contextchange: GuestEventContextChange;\n /**\n * About to attempt connection to the host.\n * @eventProperty\n */\n public beforeconnect: GuestEventBeforeConnect;\n /**\n * Host connection has been established.\n * @eventProperty\n */\n public connected: GuestEventConnected;\n /**\n * Host connection has failed.\n * @eventProperty\n */\n public error: GuestEventError;\n /**\n * {@inheritdoc SharedContext}\n */\n sharedContext: SharedContext;\n /**\n * A guest (extension) configuration\n */\n configuration?: Record<string, unknown>;\n logger: Console = quietConsole;\n\n /**\n * @param config - Initializer for guest object, including ID.\n */\n constructor(config: GuestConfig) {\n super(config.id);\n if (typeof config.timeout === \"number\") {\n this.timeout = config.timeout;\n }\n if (config.debug) {\n this.logger = debugGuest(this);\n }\n this.addEventListener(\"contextchange\", (event) => {\n this.sharedContext = new SharedContext(event.detail.context);\n });\n }\n /**\n * Proxy object for calling methods on the host.\n *\n * @remarks Any APIs exposed to the extension via {@link @adobe/uix-host#Port.provide}\n * can be called on this object. Because these methods are called with RPC,\n * they are all asynchronous, The return types of all Host methods will be\n * Promises which resolve to the value the Host method returns.\n * @public\n */\n host: RemoteHostApis<Incoming> = makeNamespaceProxy<Incoming>(\n async (address) => {\n await this.hostConnectionPromise;\n try {\n const result = await timeoutPromise(\n () => `Calling ${formatHostMethodAddress(address)}`,\n this.invokeAwaiter(\n this.hostConnection.getRemoteApi().invokeHostMethod,\n address\n ),\n 10000\n );\n return result;\n } catch (e) {\n const error =\n e instanceof Error ? e : new Error(e as unknown as string);\n this.logger.error(error);\n throw error;\n }\n }\n );\n\n /**\n * @internal\n */\n private async invokeChecker<T>(\n invoker: RemoteMethodInvoker<unknown>,\n address: HostMethodAddress<unknown[]>\n ): Promise<unknown> {\n try {\n const res = await invoker(address);\n return new Promise((resolve) => resolve(res));\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, 500));\n return this.invokeChecker(invoker, address);\n }\n }\n\n /**\n * @internal\n */\n private async invokeAwaiter(\n invoker: RemoteMethodInvoker<unknown>,\n address: HostMethodAddress<unknown[]>\n ): Promise<any> {\n const final = setTimeout(() => {\n return new Promise((resolve, reject) =>\n reject(`${address} doesn't exist`)\n );\n }, 20000);\n const res = await this.invokeChecker(invoker, address);\n return new Promise((resolve) => {\n clearTimeout(final);\n return resolve(res);\n }).catch((e) => {\n clearTimeout(final);\n return e;\n });\n }\n private timeout = 20000;\n protected hostConnectionPromise: Promise<CrossRealmObject<HostConnection>>;\n protected hostConnection!: CrossRealmObject<HostConnection>;\n /** @internal */\n protected getLocalMethods() {\n return {\n emit: (...args: Parameters<typeof this.emit>) => {\n this.logger.log(`Event \"${args[0]}\" emitted from host`);\n this.emit(...args);\n },\n };\n }\n /**\n * Accept a connection from the Host.\n * @returns A Promise that resolves when the Host has established a connection.\n * @deprecated It is preferable to use {@link register} for primary frames,\n * and {@link attach} for UI frames and other secondary frames, than to\n * instantiate a Guest and then call `.connect()` on it. The latter style\n * returns an object that cannot be used until it is connected, and therefore\n * risks errors.\n * @public\n */\n async connect() {\n return this._connect();\n }\n\n /**\n * @internal\n */\n async _connect() {\n this.emit(\"beforeconnect\", { guest: this });\n try {\n const hostConnectionPromise = connectParentWindow<HostConnection>(\n {\n targetOrigin: \"*\",\n timeout: this.timeout,\n logger: this.logger,\n },\n this.getLocalMethods()\n );\n\n this.hostConnectionPromise = hostConnectionPromise;\n this.hostConnection = await this.hostConnectionPromise;\n this.emit(\"connected\", { guest: this });\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"Connection failed!\", e);\n throw e;\n }\n try {\n this.sharedContext = new SharedContext(\n await this.hostConnection.getRemoteApi().getSharedContext()\n );\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"getSharedContext failed!\", e);\n throw e;\n }\n try {\n this.configuration = await this.hostConnection\n .getRemoteApi()\n .getConfiguration();\n } catch (e) {\n this.emit(\"error\", { guest: this, error: e });\n this.logger.error(\"getConfiguration failed!\", e);\n throw e;\n }\n }\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\n/**\n * Adapter to attach console logging listeners to a Guest running in a frame/\n * @internal @preapproved\n */\nimport { debugEmitter, Emits, EmitterDebugLogger } from \"@adobe/uix-core\";\nimport { GuestEvents } from \"./guest\";\n\nexport function debugGuest(guest: Emits<GuestEvents>): EmitterDebugLogger {\n return debugEmitter(guest, {\n theme: \"yellow medium\",\n type: \"Guest\",\n })\n .listen(\"beforeconnect\", (log, { detail: { guest } }) => {\n log.info(guest);\n })\n .listen(\"connecting\", (log, { detail: { connection } }) => {\n log.info(connection);\n })\n .listen(\"connected\", (log, { detail: { guest } }) => {\n log.info(guest);\n })\n .listen(\"error\", (log, { detail: { error, guest } }) => {\n log.error(\n \"❌ Failed to connect! %s\",\n (error as Error).message,\n guest,\n error\n );\n });\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type {\n CrossRealmObject,\n RemoteHostApis,\n UIHostConnection,\n VirtualApi,\n} from \"@adobe/uix-core\";\nimport {\n Guest,\n GuestConfig,\n GuestEventBeforeConnect,\n GuestEventConnected,\n GuestEventContextChange,\n GuestEventError,\n} from \"./guest\";\n\n/**\n * A Guest to be used in an extension-controlled frame, usually to display UI.\n *\n * @typeParam Incoming - Optional interface of host methods. If using\n * TypeScript, supply this type parameter and a promisified version of the\n * interface will be available at {@link Guest.host}\n *\n * @remarks\n * This is the object returned when calling {@link @adobe/uix-guest#attach}. It\n * represents an additional frame or runtime created by the host application, on\n * behalf of the extension's control frame which is running the {@link\n * GuestServer}. It is a \"secondary\" guest object, which a host won't use before\n * the control frame has connected. It exposes a subset of the functionality of\n * the {@link GuestServer}.\n *\n * Unlike the {@link GuestServer}, it cannot register methods or update the\n * {@link Guest.sharedContext}, but it remains in sync with the GuestServer and\n * can access the {@link Guest.sharedContext} of the control frame, as well as\n * any of the published methods on the host.\n *\n * Extensible host apps using the React bindings will likely render GuestUI\n * frames using the {@link @adobe/uix-host-react#GuestUIFrame} component.\n *\n * @example\n * When an extensible app renders this page, {@link @adobe/uix-guest#attach}\n * creates a GuestUI. Once it attaches to the host, it\n * ```javascript\n * import React, { useEffect, useState } from \"react\";\n * import { attach } from \"@adobe/uix-guest\";\n * import { Tooltip } from \"./tooltip\";\n *\n * export default function PopupOverlay(props) {\n * // how large am I?\n * const [dimensions, setDimensions] = useState(\n * document.body.getBoundingClientRect()\n * );\n * // if possible, use language preloaded in query parameters\n * const [language, setLanguage] = useState(props.params.lang)\n *\n * // attach only once, in a useEffect\n * useEffect(() => {\n * attach({\n * id: \"my-extension-id\",\n * debug: true,\n * })\n * .then(guestUI => {\n * // this event fires whenever the host, or the control frame, changes\n * // any sharedContext value\n * guestUI.addEventListener(\"contextchange\", ({ detail: { context }}) => {\n * setLanguage(context.lang)\n * });\n * // how large does the host want me to be?\n * return guestUI.host.tooltips.getDimensions()\n * .then(setDimensions)\n * })\n * .catch((e) => {\n * console.error(\"ui attach failed\", e);\n * });\n * }, []);\n * // render UI! Due to the setup and useState, this component will re-render\n * // once attach() is complete.\n * return (\n * <Tooltip {...props.params} lang={language} dimensions={dimensions} />\n * );\n * }\n * ```\n *\n * @public\n */\nexport class GuestUI<IHost extends VirtualApi> extends Guest<IHost> {\n /**\n * {@inheritDoc Guest.\"constructor\"}\n */\n constructor(config: GuestConfig) {\n super(config);\n this.addEventListener(\"connected\", () => {\n const resizeObserver = new ResizeObserver((entries) => {\n const doc = entries.find((entry) => entry.target === document.body);\n const borderBoxSize = doc.borderBoxSize.length\n ? doc.borderBoxSize[0]\n : (doc.borderBoxSize as unknown as ResizeObserverSize);\n this.hostConnection.getRemoteApi().onIframeResize({\n height:\n borderBoxSize.blockSize +\n this.calculateChildrenMargin(doc.target.querySelectorAll(\"*\")),\n width: borderBoxSize.inlineSize,\n });\n });\n resizeObserver.observe(document.body);\n });\n\n this.logger.log(\"Will add resize observer on connect\");\n }\n\n /**\n * @internal\n */\n private calculateChildrenMargin(elems: NodeListOf<any>): number {\n let margin = 0;\n\n for (let i = 0; i < elems.length; i++) {\n const style = elems[i].currentStyle || window.getComputedStyle(elems[i]);\n const marginTop = parseInt(style.marginTop);\n const marginBottom = parseInt(style.marginBottom);\n\n if (marginTop > 0) {\n margin = margin + marginTop;\n }\n\n if (marginBottom > 0) {\n margin = margin + marginBottom;\n }\n }\n\n return margin;\n }\n\n /**\n * {@inheritDoc Guest.contextchange}\n * @eventProperty\n */\n public contextchange: GuestEventContextChange;\n /**\n * {@inheritDoc Guest.beforeconnect}\n * @eventProperty\n */\n public beforeconnect: GuestEventBeforeConnect;\n /**\n * {@inheritDoc Guest.connected}\n * @eventProperty\n */\n public connected: GuestEventConnected;\n /**\n * {@inheritDoc Guest.error}\n * @eventProperty\n */\n public error: GuestEventError;\n /**\n * {@inheritDoc Guest.host}\n */\n host: RemoteHostApis<IHost>;\n protected hostConnection!: CrossRealmObject<UIHostConnection>;\n}\n","/*\nCopyright 2022 Adobe. All rights reserved.\nThis file is licensed to you under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License. You may obtain a copy\nof the License at http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software distributed under\nthe License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\nOF ANY KIND, either express or implied. See the License for the specific language\ngoverning permissions and limitations under the License.\n*/\n\nimport type { GuestApis, GuestMetadata } from \"@adobe/uix-core\";\nimport type { SharedContext } from \"./guest\";\nimport { Guest } from \"./guest\";\n\n/**\n * A Guest to be used in the \"main\" or primary frame of an extension, the frame\n * the Host loads first.\n *\n * @remarks This is the Guest object returned from {@link register}. It can\n * expose internal methods to the Host via the {@link GuestServer.register}\n * method.\n *\n *\n * @public\n */\nexport class GuestServer<Outgoing extends GuestApis> extends Guest<Outgoing> {\n private localMethods: Outgoing;\n metadata: GuestMetadata;\n protected getLocalMethods() {\n return {\n ...super.getLocalMethods(),\n apis: this.localMethods,\n metadata: this.metadata,\n };\n }\n /**\n * {@inheritDoc BaseGuest.sharedContext}\n */\n sharedContext: SharedContext;\n /**\n * {@inheritdoc BaseGuest.host}\n */\n host: Guest<Outgoing>[\"host\"];\n /**\n * Pass an interface of methods which Host may call as callbacks.\n *\n * @remarks It is preferable to use {@link register} to obtain a guest object\n * and register local methods in one step. The returned guest object will be\n * pre-registered and connected.\n * @public\n */\n async register(implementedMethods: Outgoing, metadata: GuestMetadata) {\n this.localMethods = implementedMethods;\n this.metadata = {\n ...metadata,\n extensionId: this.id,\n };\n return this._connect();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsBA,IAAAA,mBAOO;;;ACbP,sBAAwD;AAGjD,SAAS,WAAW,OAA+C;AACxE,aAAO,8BAAa,OAAO;AAAA,IACzB,OAAO;AAAA,IACP,MAAM;AAAA,EACR,CAAC,EACE,OAAO,iBAAiB,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAAC,OAAM,EAAE,MAAM;AACvD,QAAI,KAAKA,MAAK;AAAA,EAChB,CAAC,EACA,OAAO,cAAc,CAAC,KAAK,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM;AACzD,QAAI,KAAK,UAAU;AAAA,EACrB,CAAC,EACA,OAAO,aAAa,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAAA,OAAM,EAAE,MAAM;AACnD,QAAI,KAAKA,MAAK;AAAA,EAChB,CAAC,EACA,OAAO,SAAS,CAAC,KAAK,EAAE,QAAQ,EAAE,OAAO,OA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S,OAAO,QAAQ;AAC9C,SAAO;AACT;","names":["import_uix_core","guest","Guest","Guest","Guest"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adobe/uix-guest",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -18,7 +18,7 @@
18
18
  ],
19
19
  "bugs": "https://github.com/adobe/uix-sdk/issues",
20
20
  "dependencies": {
21
- "@adobe/uix-core": "^1.0.0",
21
+ "@adobe/uix-core": "^1.0.1",
22
22
  "ajv": "^8.12.0",
23
23
  "js-yaml": "^4.1.0"
24
24
  },
@@ -53,7 +53,10 @@ export class GuestServer<Outgoing extends GuestApis> extends Guest<Outgoing> {
53
53
  */
54
54
  async register(implementedMethods: Outgoing, metadata: GuestMetadata) {
55
55
  this.localMethods = implementedMethods;
56
- this.metadata = metadata;
56
+ this.metadata = {
57
+ ...metadata,
58
+ extensionId: this.id,
59
+ };
57
60
  return this._connect();
58
61
  }
59
62
  }
package/src/guest-ui.ts CHANGED
@@ -127,13 +127,15 @@ export class GuestUI<IHost extends VirtualApi> extends Guest<IHost> {
127
127
 
128
128
  for (let i = 0; i < elems.length; i++) {
129
129
  const style = elems[i].currentStyle || window.getComputedStyle(elems[i]);
130
+ const marginTop = parseInt(style.marginTop);
131
+ const marginBottom = parseInt(style.marginBottom);
130
132
 
131
- if (style.marginTop !== "0px") {
132
- margin = margin + parseInt(style.marginTop);
133
+ if (marginTop > 0) {
134
+ margin = margin + marginTop;
133
135
  }
134
136
 
135
- if (style.marginBottom !== "0px") {
136
- margin = margin + parseInt(style.marginBottom);
137
+ if (marginBottom > 0) {
138
+ margin = margin + marginBottom;
137
139
  }
138
140
  }
139
141