@interopio/iframes-api 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1244,7 +1244,7 @@ class IoC {
1244
1244
  }
1245
1245
  }
1246
1246
 
1247
- var version = "1.0.0";
1247
+ var version = "1.1.0";
1248
1248
 
1249
1249
  const factoryFunction = async (io) => {
1250
1250
  const ioc = new IoC(io);
@@ -1250,7 +1250,7 @@
1250
1250
  }
1251
1251
  }
1252
1252
 
1253
- var version = "1.0.0";
1253
+ var version = "1.1.0";
1254
1254
 
1255
1255
  const factoryFunction = async (io) => {
1256
1256
  const ioc = new IoC(io);
@@ -1,2 +1,2 @@
1
- !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):((e="undefined"!=typeof globalThis?globalThis:e||self).iframes=e.iframes||{},e.iframes.min=r())}(this,function(){"use strict";var e=function(e){return{ok:!0,result:e}},r=function(e){return{ok:!1,error:e}},n=function(r,n,t){return!1===n.ok?n:!1===t.ok?t:e(r(n.result,t.result))},t=function(e,n){return!0===n.ok?n:r(e(n.error))},o=function(){return o=Object.assign||function(e){for(var r,n=1,t=arguments.length;n<t;n++)for(var o in r=arguments[n])Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o]);return e},o.apply(this,arguments)};function i(e,r){if(e===r)return!0;if(null===e&&null===r)return!0;if(typeof e!=typeof r)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(r))return!1;if(e.length!==r.length)return!1;for(var n=0;n<e.length;n++)if(!i(e[n],r[n]))return!1;return!0}var t=Object.keys(e);if(t.length!==Object.keys(r).length)return!1;for(n=0;n<t.length;n++){if(!r.hasOwnProperty(t[n]))return!1;if(!i(e[t[n]],r[t[n]]))return!1}return!0}}var a=function(e){return Array.isArray(e)},s=function(e){return"object"==typeof e&&null!==e&&!a(e)},u=function(e,r){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(r)},c=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},l=function(e,r){var n=r.at,t=function(e,r){var n={};for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&r.indexOf(t)<0&&(n[t]=e[t]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(t=Object.getOwnPropertySymbols(e);o<t.length;o++)r.indexOf(t[o])<0&&Object.prototype.propertyIsEnumerable.call(e,t[o])&&(n[t[o]]=e[t[o]])}return n}(r,["at"]);return o({at:e+(n||"")},t)},d=function(){function o(r){var n=this;this.decode=r,this.run=function(e){return t(function(r){return{kind:"DecoderError",input:e,at:"input"+(r.at||""),message:r.message||""}},n.decode(e))},this.runPromise=function(e){return!0===(r=n.run(e)).ok?Promise.resolve(r.result):Promise.reject(r.error);var r},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(r){return new o(function(t){return function(r,n){return!0===n.ok?e(r(n.result)):n}(r,n.decode(t))})},this.andThen=function(e){return new o(function(r){return function(e,r){return!0===r.ok?e(r.result):r}(function(n){return e(n).decode(r)},n.decode(r))})},this.where=function(e,r){return n.andThen(function(n){return e(n)?o.succeed(n):o.fail(r)})}}return o.string=function(){return new o(function(n){return"string"==typeof n?e(n):r({message:u("a string",n)})})},o.number=function(){return new o(function(n){return"number"==typeof n?e(n):r({message:u("a number",n)})})},o.boolean=function(){return new o(function(n){return"boolean"==typeof n?e(n):r({message:u("a boolean",n)})})},o.constant=function(n){return new o(function(t){return i(t,n)?e(n):r({message:"expected "+JSON.stringify(n)+", got "+JSON.stringify(t)})})},o.object=function(n){return new o(function(t){if(s(t)&&n){var o={};for(var i in n)if(n.hasOwnProperty(i)){var a=n[i].decode(t[i]);if(!0!==a.ok)return void 0===t[i]?r({message:"the key '"+i+"' is required but was not present"}):r(l("."+i,a.error));void 0!==a.result&&(o[i]=a.result)}return e(o)}return s(t)?e(t):r({message:u("an object",t)})})},o.array=function(i){return new o(function(o){if(a(o)&&i){return o.reduce(function(e,r,o){return n(function(e,r){return e.concat([r])},e,function(e,r){return t(function(e){return l("["+r+"]",e)},i.decode(e))}(r,o))},e([]))}return a(o)?e(o):r({message:u("an array",o)})})},o.tuple=function(n){return new o(function(t){if(a(t)){if(t.length!==n.length)return r({message:"expected a tuple of length "+n.length+", got one of length "+t.length});for(var o=[],i=0;i<n.length;i++){var s=n[i].decode(t[i]);if(!s.ok)return r(l("["+i+"]",s.error));o[i]=s.result}return e(o)}return r({message:u("a tuple of length "+n.length,t)})})},o.union=function(e,r){for(var n=[],t=2;t<arguments.length;t++)n[t-2]=arguments[t];return o.oneOf.apply(o,[e,r].concat(n))},o.intersection=function(r,t){for(var i=[],a=2;a<arguments.length;a++)i[a-2]=arguments[a];return new o(function(o){return[r,t].concat(i).reduce(function(e,r){return n(Object.assign,e,r.decode(o))},e({}))})},o.anyJson=function(){return new o(function(r){return e(r)})},o.unknownJson=function(){return new o(function(r){return e(r)})},o.dict=function(n){return new o(function(t){if(s(t)){var o={};for(var i in t)if(t.hasOwnProperty(i)){var a=n.decode(t[i]);if(!0!==a.ok)return r(l("."+i,a.error));o[i]=a.result}return e(o)}return r({message:u("an object",t)})})},o.optional=function(r){return new o(function(n){return null==n?e(void 0):r.decode(n)})},o.oneOf=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return new o(function(n){for(var t=[],o=0;o<e.length;o++){var i=e[o].decode(n);if(!0===i.ok)return i;t[o]=i.error}var a=t.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return r({message:'expected a value matching one of the decoders, got the errors ["'+a+'"]'})})},o.withDefault=function(r,n){return new o(function(t){return e(function(e,r){return!0===r.ok?r.result:e}(r,n.decode(t)))})},o.valueAt=function(e,n){return new o(function(o){for(var i=o,d=0;d<e.length;d++){if(void 0===i)return r({at:c(e.slice(0,d+1)),message:"path does not exist"});if("string"==typeof e[d]&&!s(i))return r({at:c(e.slice(0,d+1)),message:u("an object",i)});if("number"==typeof e[d]&&!a(i))return r({at:c(e.slice(0,d+1)),message:u("an array",i)});i=i[e[d]]}return t(function(r){return void 0===i?{at:c(e),message:"path does not exist"}:l(c(e),r)},n.decode(i))})},o.succeed=function(r){return new o(function(n){return e(r)})},o.fail=function(e){return new o(function(n){return r({message:e})})},o.lazy=function(e){return new o(function(r){return e().decode(r)})},o}(),f=d.string;d.number;var p=d.boolean,m=d.anyJson;d.unknownJson;var h=d.constant,g=d.object;d.array,d.tuple;var y=d.dict,w=d.optional,b=d.oneOf;d.union,d.intersection,d.withDefault,d.valueAt,d.succeed,d.fail,d.lazy;const v=f().where(e=>e.length>0,"Expected a non-empty string"),C=g({operation:v}),I=g({isSupported:p()}),O=g({windowId:v}),x=b(h("operationCheck"),h("reserveStandaloneIFrameApp"),h("registerStandaloneIFrameApp"),h("unregisterStandaloneIFrameApp"),h("closeRequested")),A=g({appName:v,channelId:w(v),container:w(m()),context:w(m()),iframeConfig:w(g({className:w(f()),styles:w(y(f()))}))}),k=g({appName:v}),S=g({flags:f()}),E=g({flags:f()}),P=g({iframePermissionsPolicy:w(S),iframeSandbox:w(E),instanceId:v,url:v}),j=g({channelId:w(v),context:w(m()),instanceId:v,parentId:v}),F=g({wasClosed:p()});class ${io;operations={operationCheck:{name:"operationCheck",dataDecoder:C,resultDecoder:I}};constructor(e){this.io=e}getMyInstanceId(){return this.io.interop.instance.instance}async initiate(e){await this.io.interop.registerAsync("T42.IFrames.Control",(r,n,t,o)=>{e(r).then(t).catch(o)})}async send(e,r,n,t,o){if(r.dataDecoder)try{r.dataDecoder.runWithException(n)}catch(e){throw new Error(`Unexpected IFrames API->Platform outgoing validation error: ${e.message}, for operation: ${r.name} and input: ${JSON.stringify(e.input)}`)}if(!(!o?.includeOperationCheck||(await this.checkOperationSupported(e,r)).isSupported))throw new Error(`Cannot complete operation: ${r.name} for domain: ${e} because this client is connected to a platform which does not support it`);const i=await this.transmitMessage(e,r,n,t);if(r.resultDecoder)try{r.resultDecoder.runWithException(i)}catch(e){throw new Error(`Unexpected IFrames API<-Platform incoming validation error: ${e.message}, for operation: ${r.name} and input: ${JSON.stringify(e.input)}`)}return i}async checkOperationSupported(e,r){try{return await this.send(e,this.operations.operationCheck,{operation:r.name})}catch{return{isSupported:!1}}}async transmitMessage(e,r,n,t){const o=(window.glue42core||window.iobrowser).communicationId,i={domain:e,data:n,operation:r.name};let a;const s=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(r.name)} with data: ${JSON.stringify(n)}. `;try{if(a=await this.io.interop.invoke("T42.Web.Platform.Control",i,o?{instance:o}:void 0,t),!a)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(a.all_return_values)||0===a.all_return_values.length)throw new Error("Received unsupported result from the platform - empty values collection")}catch(e){if(e?.all_errors?.length){const r=e.all_errors[0].message;throw new Error(`${s} -> Inner message: ${r}`)}throw new Error(`${s} -> Inner message: ${e.message}`)}return a.all_return_values[0].returned}}function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function N(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var r=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function t(n,t){var o=n instanceof Error?n:new Error(n);if(r)r(o);else{var i='[ERROR] callback-registry: User callback for key "'+t+'" failed: '+o.stack;if(e)switch(e.errorHandling){case"log":return console.error(i);case"silent":return;case"throw":throw new Error(i)}console.error(i)}}return{add:function(e,r,o){var i=n[e];return i||(i=[],n[e]=i),i.push(r),o&&setTimeout(function(){o.forEach(function(o){var i;if(null===(i=n[e])||void 0===i?void 0:i.includes(r))try{Array.isArray(o)?r.apply(void 0,o):r.apply(void 0,[o])}catch(r){t(r,e)}})},0),function(){var t=n[e];t&&(0===(t=t.reduce(function(e,n,t){return n===r&&e.length===t||e.push(n),e},[])).length?delete n[e]:n[e]=t)}},execute:function(e){for(var r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];var i=n[e];if(!i||0===i.length)return[];var a=[];return i.forEach(function(n){try{var o=n.apply(void 0,r);a.push(o)}catch(r){a.push(void 0),t(r,e)}}),a},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}N.default=N;var _=D(N);const R={operationCheck:{name:"operationCheck",dataDecoder:C,resultDecoder:I},reserveStandaloneIFrameApp:{name:"reserveStandaloneIFrameApp",dataDecoder:k,resultDecoder:P},registerStandaloneIFrameApp:{name:"registerStandaloneIFrameApp",dataDecoder:j},unregisterStandaloneIFrameApp:{name:"unregisterStandaloneIFrameApp",dataDecoder:O},closeRequested:{name:"closeRequested",dataDecoder:O,resultDecoder:F}};class T{logger;bridge;registry=_();frames=new Map;confirmFrameClosedTimeoutMs=15e3;supportedOperationsNames=[];constructor(e,r){this.logger=e,this.bridge=r,this.addOperationsExecutors()}exposeApi(e){const r={openApp:this.openApp.bind(this),onCloseRequested:this.onCloseRequested.bind(this),version:e};return Object.freeze(r)}async handleControlMessage(e){const r=x.runWithException(e.operation),n=R[r];if(!n.execute)return void this.logger.debug(`Operation '${r}' has no executor defined`);let t=e.data;return n.dataDecoder&&(t=n.dataDecoder.runWithException(e.data)),n.execute(t)}addOperationsExecutors(){R.closeRequested.execute=this.handleCloseRequested.bind(this),R.operationCheck.execute=async e=>{return r=this.supportedOperationsNames,n=e.operation,{isSupported:r.some(e=>e.toLowerCase()===n.toLowerCase())};var r,n},this.supportedOperationsNames=(e=>Object.keys(e).filter(r=>e[r].execute))(R)}async openApp(e){const{appName:r,channelId:n,container:t=document.body,context:o,iframeConfig:i}=A.runWithException(e);if(!(t instanceof HTMLElement))throw new TypeError("'container' must be an instance of HTMLElement");this.assertContainerConnected(t);const{iframePermissionsPolicy:a,iframeSandbox:s,instanceId:u,url:c}=await this.reserveStandaloneIFrameApp({appName:r}),l=this.bridge.getMyInstanceId(),d=this.generateIframeElement({className:i?.className,iframePermissionsPolicy:a,iframeSandbox:s,instanceId:u,styles:i?.styles,url:c});this.assertContainerConnected(t),t.appendChild(d);try{await this.registerStandaloneIFrameApp({channelId:n,context:o,instanceId:u,parentId:l})}catch(e){throw d.remove(),e}const f=Object.freeze({appName:r,id:u,iframe:d,parentId:l});return this.frames.set(u,{instance:f,isClosing:!1}),f}assertContainerConnected(e){if(!e.isConnected)throw new Error("'container' must be connected to the DOM")}generateIframeElement(e){const{className:r,iframePermissionsPolicy:n,iframeSandbox:t,instanceId:o,styles:i,url:a}=e,s=document.createElement("iframe");return s.name=`${o}#ifr`,s.id=o,s.src=a,r&&(s.className=r),i&&Object.assign(s.style,i),n&&s.setAttribute("allow",n.flags),t&&s.setAttribute("sandbox",t.flags),s}async reserveStandaloneIFrameApp(e){return this.bridge.send("iframes",R.reserveStandaloneIFrameApp,e)}async registerStandaloneIFrameApp(e){await this.bridge.send("iframes",R.registerStandaloneIFrameApp,e)}async handleCloseRequested({windowId:e}){const r=this.frames.get(e);if(!r)return this.logger.warn(`Cannot handle close request for iframe ${e}, because no local instance was found`),{wasClosed:!1};if(r.isClosing)return this.logger.warn(`Close request for iframe ${e} is already in progress`),{wasClosed:!1};const{promise:n,resolve:t}=(()=>{let e,r;return{promise:new Promise((n,t)=>{e=n,r=t}),resolve:e,reject:r}})();r.isClosing=!0;let o=!1;this.registry.execute("close-requested",r.instance,async()=>{o?this.logger.debug(`Close for iframe ${e} already handled, ignoring duplicate confirmClose call`):(o=!0,this.frames.delete(e),r.instance.iframe.remove(),await this.bridge.send("iframes",R.unregisterStandaloneIFrameApp,{windowId:e}),t())});try{return await(i=()=>n,a=this.confirmFrameClosedTimeoutMs,new Promise((e,r)=>{let n=!0;const t=setTimeout(()=>{n&&(n=!1,r(`Promise timeout hit: ${a}`))},a);i().then(r=>{n&&(n=!1,clearTimeout(t),e(r))}).catch(e=>{n&&(n=!1,clearTimeout(t),r(e))})})),{wasClosed:!0}}catch{return o=!0,r.isClosing=!1,this.logger.warn(`Close for iframe ${e} timed out waiting for client to be closed`),{wasClosed:!1}}var i,a}onCloseRequested(e){return this.registry.add("close-requested",e)}}class q{io;_bridge;_iframesController;constructor(e){this.io=e}get bridge(){return this._bridge||(this._bridge=new $(this.io)),this._bridge}get iframesController(){return this._iframesController||(this._iframesController=new T(this.io.logger.subLogger("iframes.iframes.controller"),this.bridge)),this._iframesController}}const M=async e=>{const r=new q(e);await r.bridge.initiate(r.iframesController.handleControlMessage.bind(r.iframesController)),e.iframes=r.iframesController.exposeApi("1.0.0")};return"undefined"!=typeof window&&(window.IOIFrames=M),M});
1
+ !function(e,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):((e="undefined"!=typeof globalThis?globalThis:e||self).iframes=e.iframes||{},e.iframes.min=r())}(this,function(){"use strict";var e=function(e){return{ok:!0,result:e}},r=function(e){return{ok:!1,error:e}},n=function(r,n,t){return!1===n.ok?n:!1===t.ok?t:e(r(n.result,t.result))},t=function(e,n){return!0===n.ok?n:r(e(n.error))},o=function(){return o=Object.assign||function(e){for(var r,n=1,t=arguments.length;n<t;n++)for(var o in r=arguments[n])Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o]);return e},o.apply(this,arguments)};function i(e,r){if(e===r)return!0;if(null===e&&null===r)return!0;if(typeof e!=typeof r)return!1;if("object"==typeof e){if(Array.isArray(e)){if(!Array.isArray(r))return!1;if(e.length!==r.length)return!1;for(var n=0;n<e.length;n++)if(!i(e[n],r[n]))return!1;return!0}var t=Object.keys(e);if(t.length!==Object.keys(r).length)return!1;for(n=0;n<t.length;n++){if(!r.hasOwnProperty(t[n]))return!1;if(!i(e[t[n]],r[t[n]]))return!1}return!0}}var a=function(e){return Array.isArray(e)},s=function(e){return"object"==typeof e&&null!==e&&!a(e)},u=function(e,r){return"expected "+e+", got "+function(e){switch(typeof e){case"string":return"a string";case"number":return"a number";case"boolean":return"a boolean";case"undefined":return"undefined";case"object":return e instanceof Array?"an array":null===e?"null":"an object";default:return JSON.stringify(e)}}(r)},c=function(e){return e.map(function(e){return"string"==typeof e?"."+e:"["+e+"]"}).join("")},l=function(e,r){var n=r.at,t=function(e,r){var n={};for(var t in e)Object.prototype.hasOwnProperty.call(e,t)&&r.indexOf(t)<0&&(n[t]=e[t]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(t=Object.getOwnPropertySymbols(e);o<t.length;o++)r.indexOf(t[o])<0&&Object.prototype.propertyIsEnumerable.call(e,t[o])&&(n[t[o]]=e[t[o]])}return n}(r,["at"]);return o({at:e+(n||"")},t)},d=function(){function o(r){var n=this;this.decode=r,this.run=function(e){return t(function(r){return{kind:"DecoderError",input:e,at:"input"+(r.at||""),message:r.message||""}},n.decode(e))},this.runPromise=function(e){return!0===(r=n.run(e)).ok?Promise.resolve(r.result):Promise.reject(r.error);var r},this.runWithException=function(e){return function(e){if(!0===e.ok)return e.result;throw e.error}(n.run(e))},this.map=function(r){return new o(function(t){return function(r,n){return!0===n.ok?e(r(n.result)):n}(r,n.decode(t))})},this.andThen=function(e){return new o(function(r){return function(e,r){return!0===r.ok?e(r.result):r}(function(n){return e(n).decode(r)},n.decode(r))})},this.where=function(e,r){return n.andThen(function(n){return e(n)?o.succeed(n):o.fail(r)})}}return o.string=function(){return new o(function(n){return"string"==typeof n?e(n):r({message:u("a string",n)})})},o.number=function(){return new o(function(n){return"number"==typeof n?e(n):r({message:u("a number",n)})})},o.boolean=function(){return new o(function(n){return"boolean"==typeof n?e(n):r({message:u("a boolean",n)})})},o.constant=function(n){return new o(function(t){return i(t,n)?e(n):r({message:"expected "+JSON.stringify(n)+", got "+JSON.stringify(t)})})},o.object=function(n){return new o(function(t){if(s(t)&&n){var o={};for(var i in n)if(n.hasOwnProperty(i)){var a=n[i].decode(t[i]);if(!0!==a.ok)return void 0===t[i]?r({message:"the key '"+i+"' is required but was not present"}):r(l("."+i,a.error));void 0!==a.result&&(o[i]=a.result)}return e(o)}return s(t)?e(t):r({message:u("an object",t)})})},o.array=function(i){return new o(function(o){if(a(o)&&i){return o.reduce(function(e,r,o){return n(function(e,r){return e.concat([r])},e,function(e,r){return t(function(e){return l("["+r+"]",e)},i.decode(e))}(r,o))},e([]))}return a(o)?e(o):r({message:u("an array",o)})})},o.tuple=function(n){return new o(function(t){if(a(t)){if(t.length!==n.length)return r({message:"expected a tuple of length "+n.length+", got one of length "+t.length});for(var o=[],i=0;i<n.length;i++){var s=n[i].decode(t[i]);if(!s.ok)return r(l("["+i+"]",s.error));o[i]=s.result}return e(o)}return r({message:u("a tuple of length "+n.length,t)})})},o.union=function(e,r){for(var n=[],t=2;t<arguments.length;t++)n[t-2]=arguments[t];return o.oneOf.apply(o,[e,r].concat(n))},o.intersection=function(r,t){for(var i=[],a=2;a<arguments.length;a++)i[a-2]=arguments[a];return new o(function(o){return[r,t].concat(i).reduce(function(e,r){return n(Object.assign,e,r.decode(o))},e({}))})},o.anyJson=function(){return new o(function(r){return e(r)})},o.unknownJson=function(){return new o(function(r){return e(r)})},o.dict=function(n){return new o(function(t){if(s(t)){var o={};for(var i in t)if(t.hasOwnProperty(i)){var a=n.decode(t[i]);if(!0!==a.ok)return r(l("."+i,a.error));o[i]=a.result}return e(o)}return r({message:u("an object",t)})})},o.optional=function(r){return new o(function(n){return null==n?e(void 0):r.decode(n)})},o.oneOf=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return new o(function(n){for(var t=[],o=0;o<e.length;o++){var i=e[o].decode(n);if(!0===i.ok)return i;t[o]=i.error}var a=t.map(function(e){return"at error"+(e.at||"")+": "+e.message}).join('", "');return r({message:'expected a value matching one of the decoders, got the errors ["'+a+'"]'})})},o.withDefault=function(r,n){return new o(function(t){return e(function(e,r){return!0===r.ok?r.result:e}(r,n.decode(t)))})},o.valueAt=function(e,n){return new o(function(o){for(var i=o,d=0;d<e.length;d++){if(void 0===i)return r({at:c(e.slice(0,d+1)),message:"path does not exist"});if("string"==typeof e[d]&&!s(i))return r({at:c(e.slice(0,d+1)),message:u("an object",i)});if("number"==typeof e[d]&&!a(i))return r({at:c(e.slice(0,d+1)),message:u("an array",i)});i=i[e[d]]}return t(function(r){return void 0===i?{at:c(e),message:"path does not exist"}:l(c(e),r)},n.decode(i))})},o.succeed=function(r){return new o(function(n){return e(r)})},o.fail=function(e){return new o(function(n){return r({message:e})})},o.lazy=function(e){return new o(function(r){return e().decode(r)})},o}(),f=d.string;d.number;var p=d.boolean,m=d.anyJson;d.unknownJson;var h=d.constant,g=d.object;d.array,d.tuple;var y=d.dict,w=d.optional,b=d.oneOf;d.union,d.intersection,d.withDefault,d.valueAt,d.succeed,d.fail,d.lazy;const v=f().where(e=>e.length>0,"Expected a non-empty string"),C=g({operation:v}),I=g({isSupported:p()}),O=g({windowId:v}),x=b(h("operationCheck"),h("reserveStandaloneIFrameApp"),h("registerStandaloneIFrameApp"),h("unregisterStandaloneIFrameApp"),h("closeRequested")),A=g({appName:v,channelId:w(v),container:w(m()),context:w(m()),iframeConfig:w(g({className:w(f()),styles:w(y(f()))}))}),k=g({appName:v}),S=g({flags:f()}),E=g({flags:f()}),P=g({iframePermissionsPolicy:w(S),iframeSandbox:w(E),instanceId:v,url:v}),j=g({channelId:w(v),context:w(m()),instanceId:v,parentId:v}),F=g({wasClosed:p()});class ${io;operations={operationCheck:{name:"operationCheck",dataDecoder:C,resultDecoder:I}};constructor(e){this.io=e}getMyInstanceId(){return this.io.interop.instance.instance}async initiate(e){await this.io.interop.registerAsync("T42.IFrames.Control",(r,n,t,o)=>{e(r).then(t).catch(o)})}async send(e,r,n,t,o){if(r.dataDecoder)try{r.dataDecoder.runWithException(n)}catch(e){throw new Error(`Unexpected IFrames API->Platform outgoing validation error: ${e.message}, for operation: ${r.name} and input: ${JSON.stringify(e.input)}`)}if(!(!o?.includeOperationCheck||(await this.checkOperationSupported(e,r)).isSupported))throw new Error(`Cannot complete operation: ${r.name} for domain: ${e} because this client is connected to a platform which does not support it`);const i=await this.transmitMessage(e,r,n,t);if(r.resultDecoder)try{r.resultDecoder.runWithException(i)}catch(e){throw new Error(`Unexpected IFrames API<-Platform incoming validation error: ${e.message}, for operation: ${r.name} and input: ${JSON.stringify(e.input)}`)}return i}async checkOperationSupported(e,r){try{return await this.send(e,this.operations.operationCheck,{operation:r.name})}catch{return{isSupported:!1}}}async transmitMessage(e,r,n,t){const o=(window.glue42core||window.iobrowser).communicationId,i={domain:e,data:n,operation:r.name};let a;const s=`Internal Platform Communication Error. Attempted operation: ${JSON.stringify(r.name)} with data: ${JSON.stringify(n)}. `;try{if(a=await this.io.interop.invoke("T42.Web.Platform.Control",i,o?{instance:o}:void 0,t),!a)throw new Error("Received unsupported result from the platform - empty result");if(!Array.isArray(a.all_return_values)||0===a.all_return_values.length)throw new Error("Received unsupported result from the platform - empty values collection")}catch(e){if(e?.all_errors?.length){const r=e.all_errors[0].message;throw new Error(`${s} -> Inner message: ${r}`)}throw new Error(`${s} -> Inner message: ${e.message}`)}return a.all_return_values[0].returned}}function D(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function N(e){if(e&&e.errorHandling&&"function"!=typeof e.errorHandling&&"log"!==e.errorHandling&&"silent"!==e.errorHandling&&"throw"!==e.errorHandling)throw new Error('Invalid options passed to createRegistry. Prop errorHandling should be ["log" | "silent" | "throw" | (err) => void], but '+typeof e.errorHandling+" was passed");var r=e&&"function"==typeof e.errorHandling&&e.errorHandling,n={};function t(n,t){var o=n instanceof Error?n:new Error(n);if(r)r(o);else{var i='[ERROR] callback-registry: User callback for key "'+t+'" failed: '+o.stack;if(e)switch(e.errorHandling){case"log":return console.error(i);case"silent":return;case"throw":throw new Error(i)}console.error(i)}}return{add:function(e,r,o){var i=n[e];return i||(i=[],n[e]=i),i.push(r),o&&setTimeout(function(){o.forEach(function(o){var i;if(null===(i=n[e])||void 0===i?void 0:i.includes(r))try{Array.isArray(o)?r.apply(void 0,o):r.apply(void 0,[o])}catch(r){t(r,e)}})},0),function(){var t=n[e];t&&(0===(t=t.reduce(function(e,n,t){return n===r&&e.length===t||e.push(n),e},[])).length?delete n[e]:n[e]=t)}},execute:function(e){for(var r=[],o=1;o<arguments.length;o++)r[o-1]=arguments[o];var i=n[e];if(!i||0===i.length)return[];var a=[];return i.forEach(function(n){try{var o=n.apply(void 0,r);a.push(o)}catch(r){a.push(void 0),t(r,e)}}),a},clear:function(){n={}},clearKey:function(e){n[e]&&delete n[e]}}}N.default=N;var _=D(N);const R={operationCheck:{name:"operationCheck",dataDecoder:C,resultDecoder:I},reserveStandaloneIFrameApp:{name:"reserveStandaloneIFrameApp",dataDecoder:k,resultDecoder:P},registerStandaloneIFrameApp:{name:"registerStandaloneIFrameApp",dataDecoder:j},unregisterStandaloneIFrameApp:{name:"unregisterStandaloneIFrameApp",dataDecoder:O},closeRequested:{name:"closeRequested",dataDecoder:O,resultDecoder:F}};class T{logger;bridge;registry=_();frames=new Map;confirmFrameClosedTimeoutMs=15e3;supportedOperationsNames=[];constructor(e,r){this.logger=e,this.bridge=r,this.addOperationsExecutors()}exposeApi(e){const r={openApp:this.openApp.bind(this),onCloseRequested:this.onCloseRequested.bind(this),version:e};return Object.freeze(r)}async handleControlMessage(e){const r=x.runWithException(e.operation),n=R[r];if(!n.execute)return void this.logger.debug(`Operation '${r}' has no executor defined`);let t=e.data;return n.dataDecoder&&(t=n.dataDecoder.runWithException(e.data)),n.execute(t)}addOperationsExecutors(){R.closeRequested.execute=this.handleCloseRequested.bind(this),R.operationCheck.execute=async e=>{return r=this.supportedOperationsNames,n=e.operation,{isSupported:r.some(e=>e.toLowerCase()===n.toLowerCase())};var r,n},this.supportedOperationsNames=(e=>Object.keys(e).filter(r=>e[r].execute))(R)}async openApp(e){const{appName:r,channelId:n,container:t=document.body,context:o,iframeConfig:i}=A.runWithException(e);if(!(t instanceof HTMLElement))throw new TypeError("'container' must be an instance of HTMLElement");this.assertContainerConnected(t);const{iframePermissionsPolicy:a,iframeSandbox:s,instanceId:u,url:c}=await this.reserveStandaloneIFrameApp({appName:r}),l=this.bridge.getMyInstanceId(),d=this.generateIframeElement({className:i?.className,iframePermissionsPolicy:a,iframeSandbox:s,instanceId:u,styles:i?.styles,url:c});this.assertContainerConnected(t),t.appendChild(d);try{await this.registerStandaloneIFrameApp({channelId:n,context:o,instanceId:u,parentId:l})}catch(e){throw d.remove(),e}const f=Object.freeze({appName:r,id:u,iframe:d,parentId:l});return this.frames.set(u,{instance:f,isClosing:!1}),f}assertContainerConnected(e){if(!e.isConnected)throw new Error("'container' must be connected to the DOM")}generateIframeElement(e){const{className:r,iframePermissionsPolicy:n,iframeSandbox:t,instanceId:o,styles:i,url:a}=e,s=document.createElement("iframe");return s.name=`${o}#ifr`,s.id=o,s.src=a,r&&(s.className=r),i&&Object.assign(s.style,i),n&&s.setAttribute("allow",n.flags),t&&s.setAttribute("sandbox",t.flags),s}async reserveStandaloneIFrameApp(e){return this.bridge.send("iframes",R.reserveStandaloneIFrameApp,e)}async registerStandaloneIFrameApp(e){await this.bridge.send("iframes",R.registerStandaloneIFrameApp,e)}async handleCloseRequested({windowId:e}){const r=this.frames.get(e);if(!r)return this.logger.warn(`Cannot handle close request for iframe ${e}, because no local instance was found`),{wasClosed:!1};if(r.isClosing)return this.logger.warn(`Close request for iframe ${e} is already in progress`),{wasClosed:!1};const{promise:n,resolve:t}=(()=>{let e,r;return{promise:new Promise((n,t)=>{e=n,r=t}),resolve:e,reject:r}})();r.isClosing=!0;let o=!1;this.registry.execute("close-requested",r.instance,async()=>{o?this.logger.debug(`Close for iframe ${e} already handled, ignoring duplicate confirmClose call`):(o=!0,this.frames.delete(e),r.instance.iframe.remove(),await this.bridge.send("iframes",R.unregisterStandaloneIFrameApp,{windowId:e}),t())});try{return await(i=()=>n,a=this.confirmFrameClosedTimeoutMs,new Promise((e,r)=>{let n=!0;const t=setTimeout(()=>{n&&(n=!1,r(`Promise timeout hit: ${a}`))},a);i().then(r=>{n&&(n=!1,clearTimeout(t),e(r))}).catch(e=>{n&&(n=!1,clearTimeout(t),r(e))})})),{wasClosed:!0}}catch{return o=!0,r.isClosing=!1,this.logger.warn(`Close for iframe ${e} timed out waiting for client to be closed`),{wasClosed:!1}}var i,a}onCloseRequested(e){return this.registry.add("close-requested",e)}}class q{io;_bridge;_iframesController;constructor(e){this.io=e}get bridge(){return this._bridge||(this._bridge=new $(this.io)),this._bridge}get iframesController(){return this._iframesController||(this._iframesController=new T(this.io.logger.subLogger("iframes.iframes.controller"),this.bridge)),this._iframesController}}const M=async e=>{const r=new q(e);await r.bridge.initiate(r.iframesController.handleControlMessage.bind(r.iframesController)),e.iframes=r.iframesController.exposeApi("1.1.0")};return"undefined"!=typeof window&&(window.IOIFrames=M),M});
2
2
  //# sourceMappingURL=iframes.umd.min.js.map
package/iframes.d.ts CHANGED
@@ -8,6 +8,10 @@ export default IFramesFactory;
8
8
  declare module "@interopio/core" {
9
9
  export namespace IOConnectCore {
10
10
  export interface API {
11
+ /**
12
+ * IFrames API.
13
+ * @since io.Connect Browser 4.5
14
+ */
11
15
  iframes: IOConnectIFrames.API;
12
16
  }
13
17
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interopio/iframes-api",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "description": "IOConnect IFrames API",
5
5
  "main": "dist/iframes.umd.js",
6
6
  "module": "dist/iframes.es.js",
@@ -37,5 +37,5 @@
37
37
  "peerDependencies": {
38
38
  "@interopio/core": ">=6.11.0"
39
39
  },
40
- "gitHead": "0b95d3cdbfc2816621d7995328b936bcf04f8888"
40
+ "gitHead": "4687d65cc52f52aa706e2540faf3b95b3033d3b2"
41
41
  }