UNPKG

@preset-sdk/embedded

Version:

Frontend SDK for embedding Preset data analytics into your own application

2 lines 5.37 kB
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.presetSdk=t():e.presetSdk=t()}(globalThis,(function(){return(()=>{"use strict";var e={d:(t,o)=>{for(var r in o)e.o(o,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:o[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{_initComms:()=>d,embedDashboard:()=>a});var o=function(e){return e.GET="get",e.REPLY="reply",e.EMIT="emit",e.ERROR="error",e}(o||{});class r{constructor(e){this.port=void 0,this.name="",this.methods={},this.incrementor=1,this.debugMode=void 0,this.isInitialised=void 0,e&&this.init(e)}init(e){if(this.isInitialised)return void this.logError("already initialized");const{port:t,name:r="switchboard",debug:i=!1}=e;this.port=t,this.name=r,this.debugMode=i,t.addEventListener("message",(async e=>{this.log("message received",e);const t=e.data;if(function(e){return e.switchboardAction===o.GET}(t))this.port.postMessage(await this.getMethodResult(t));else if(function(e){return e.switchboardAction===o.EMIT}(t)){const{method:e,args:o}=t,r=this.methods[e];r&&r(o)}})),this.isInitialised=!0}async getMethodResult({messageId:e,method:t,args:r}){const i=this.methods[t];if(null==i)return{switchboardAction:o.ERROR,messageId:e,error:`[${this.name}] Method "${t}" is not defined`};try{const t=await i(r);return{switchboardAction:o.REPLY,messageId:e,result:t}}catch(r){return this.logError(r),{switchboardAction:o.ERROR,messageId:e,error:`[${this.name}] Method "${t}" threw an error`}}}defineMethod(e,t){this.methods[e]=t}get(e,t){return new Promise(((r,i)=>{if(!this.isInitialised)return void i(new Error("Switchboard not initialised"));const s=this.getNewMessageId(),n=e=>{const t=e.data;if(t.messageId===s)if(this.port.removeEventListener("message",n),function(e){return e.switchboardAction===o.REPLY}(t))r(t.result);else{const e=function(e){return e.switchboardAction===o.ERROR}(t)?t.error:"Unexpected response message";i(new Error(e))}};this.port.addEventListener("message",n),this.port.start();const a={switchboardAction:o.GET,method:e,messageId:s,args:t};this.port.postMessage(a)}))}emit(e,t){if(!this.isInitialised)return void this.logError("Switchboard not initialised");const r={switchboardAction:o.EMIT,method:e,args:t};this.port.postMessage(r)}start(){this.isInitialised?this.port.start():this.logError("Switchboard not initialised")}log(...e){this.debugMode&&console.debug(`[${this.name}]`,...e)}logError(...e){console.error(`[${this.name}]`,...e)}getNewMessageId(){return`m_${this.name}_${this.incrementor++}`}}new r;const i="__embedded_comms__",s={visible:"show_filters",expanded:"expand_filters"};function n(e){const t=JSON.parse(atob(e.split(".")[1]).toString()),o=new Date(/[^0-9\.]/g.test(t.exp)?t.exp:1e3*parseFloat(t.exp));return("Invalid Date"!==o.toString()?Math.max(1e4,o.getTime()-Date.now()):3e5)-5e3}async function a(e){let{id:t,supersetDomain:o,mountPoint:r,fetchGuestToken:i,dashboardUiConfig:a,debug:c=!1,iframeTitle:l="Embedded Dashboard",iframeSandboxExtras:h=[],referrerPolicy:u}=e;function m(){if(c){for(var e=arguments.length,o=new Array(e),r=0;r<e;r++)o[r]=arguments[r];console.debug(`[preset-frontend-sdk][dashboard ${t}]`,...o)}}var g;function f(){let e=0;return a&&(a.hideTitle&&(e+=1),a.hideTab&&(e+=2),a.hideChartControls&&(e+=8)),e}m("embedding"),(g=Element.prototype).hasOwnProperty("replaceChildren")||Object.defineProperty(g,"replaceChildren",{configurable:!0,enumerable:!0,value:function(){for(;this.firstChild;)this.removeChild(this.firstChild);for(var e=arguments.length,t=new Array(e),o=0;o<e;o++)t[o]=arguments[o];t.forEach((e=>{this.appendChild("string"==typeof e?document.createTextNode(e):e)}))}}),o.endsWith("/")&&(o=o.slice(0,-1));const[p,b]=await Promise.all([i(),async function(){return new Promise((e=>{const i=document.createElement("iframe"),n=a?{uiConfig:`${f()}`}:void 0,g=a?.filters||{},p=Object.keys(g),b={...n,...Object.fromEntries(p.map((e=>[s[e],g[e]]))),...a?.urlParams},w=Object.keys(b).length?"?"+new URLSearchParams(b).toString():"";i.sandbox.add("allow-same-origin"),i.sandbox.add("allow-scripts"),i.sandbox.add("allow-presentation"),i.sandbox.add("allow-downloads"),i.sandbox.add("allow-top-navigation"),i.sandbox.add("allow-forms"),i.sandbox.add("allow-popups"),h.forEach((e=>{i.sandbox.add(e)})),u&&(i.referrerPolicy=u),i.addEventListener("load",(()=>{const t=d(i.contentWindow,o,c);m("sent message channel to the iframe"),e(t)})),i.src=`${o}/embedded/${t}${w}`,i.title=l,r?.replaceChildren(i),m("placed the iframe")}))}()]);let w;return b.emit("guestToken",{guestToken:p}),m("sent guest token"),w=setTimeout((async function e(){const t=await i();b.emit("guestToken",{guestToken:t}),w=setTimeout(e,n(t))}),n(p)),{getScrollSize:()=>b.get("getScrollSize"),unmount:function(){m("unmounting"),r?.replaceChildren(),clearTimeout(w)}}}function d(e,t){let o=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const s=new MessageChannel,n=s.port1,a=s.port2;return e.postMessage({type:i,handshake:"port transfer"},t,[a]),new r({port:n,name:"preset-frontend-sdk",debug:o})}return t})()})); //# sourceMappingURL=index.js.map