UNPKG

@prismatic-io/embedded

Version:

Embed Prismatic's integration marketplace and workflow designer within your existing application.

144 lines 13.9 kB
import{t as e}from"./chunk-0Lt9GpW0.mjs";import t from"lodash.merge";import n from"url-join";const r={filters:{},initComplete:!1,jwt:``,embeddedDesignerEnabled:!1,prismaticUrl:`https://app.prismatic.io`,screenConfiguration:void 0,theme:void 0,fontConfiguration:void 0,translation:void 0},i=new Set(Object.keys(r)),a=e=>i.has(e),o=(e,t,n)=>{e[t]=n},s=new class{constructor(e){this.state=null,this.defaultState=e}getInitialState(){return JSON.parse(JSON.stringify(this.defaultState))}getStateCopy(){return this.state?JSON.parse(JSON.stringify(this.state)):this.getInitialState()}setState(e){this.state=e}}(r),c=e=>{if(!s.getStateCopy().initComplete)throw Error(`Expected init to be called before calling ${e}`);if(!s.getStateCopy().jwt&&e!==`authenticate`)throw Error(`Expected authenticate to be called before calling ${e}`)},l=e=>e.usePopover===!0;let u=function(e){return e.INSTANCE_CONFIGURATION_CANCELED=`INSTANCE_CONFIGURATION_CANCELED`,e.INSTANCE_CONFIGURATION_CLOSED=`INSTANCE_CONFIGURATION_CLOSED`,e.INSTANCE_CONFIGURATION_LOADED=`INSTANCE_CONFIGURATION_LOADED`,e.INSTANCE_CONFIGURATION_PAGE_LOADED=`INSTANCE_CONFIGURATION_PAGE_LOADED`,e.INSTANCE_CONFIGURATION_OPENED=`INSTANCE_CONFIGURATION_OPENED`,e.INSTANCE_CREATED=`INSTANCE_CREATED`,e.INSTANCE_DELETED=`INSTANCE_DELETED`,e.INSTANCE_DEPLOYED=`INSTANCE_DEPLOYED`,e.MARKETPLACE_CLOSED=`MARKETPLACE_CLOSED`,e.POPOVER_CLOSE_REQUESTED=`POPOVER_CLOSE_REQUESTED`,e.POPOVER_CLOSED=`POPOVER_CLOSED`,e.SET_CONFIG_VAR=`SET_CONFIG_VAR`,e.SET_FILTERS=`SET_FILTERS`,e.SET_SCREEN_CONFIGURATION=`SET_SCREEN_CONFIGURATION`,e.SET_TOKEN=`SET_TOKEN`,e.SET_TRANSLATION=`SET_TRANSLATION`,e.SET_VERSION=`SET_VERSION`,e.USER_CONFIGURATION_CLOSED=`USER_CONFIGURATION_CLOSED`,e.USER_CONFIGURATION_DELETED=`USER_CONFIGURATION_DELETED`,e.USER_CONFIGURATION_DEPLOYED=`USER_CONFIGURATION_DEPLOYED`,e.USER_CONFIGURATION_LOADED=`USER_CONFIGURATION_LOADED`,e.USER_CONFIGURATION_PAGE_LOADED=`USER_CONFIGURATION_PAGE_LOADED`,e.USER_CONFIGURATION_OPENED=`USER_CONFIGURATION_OPENED`,e.WORKFLOW_ENABLED=`WORKFLOW_ENABLED`,e.WORKFLOW_DELETED=`WORKFLOW_DELETED`,e.WORKFLOW_DISABLED=`WORKFLOW_DISABLED`,e}({});const d=()=>document.querySelector(x),ee=()=>{d()?.classList.add(S)},f=()=>{let e=T(`${y} > iframe`);E(e)&&(e.contentWindow?.postMessage({event:`MARKETPLACE_CLOSED`},`*`),window.postMessage({event:`POPOVER_CLOSED`},`*`),d()?.classList.remove(S))},p=e=>Array.from(document.getElementsByTagName(`iframe`)).find(t=>t.contentWindow===e.source),te=e=>`iframe`in e,m=e=>{let t=te(e)?e.iframe:re(e.selector);E(t)&&t.contentWindow?.postMessage(e.event,`*`)},h=`pio__embedded`,g=`pio__iframe`,_=`pio__iframe-preload`,ne=`pio__styles`,v=`pio__iframeContainer`,y=`#${h} .${v}`,b=`pio__overlay`,x=`#${h} > .${b}`,S=`${b}--is_visible`,C=`pio__popover`,w=`pio__closeBtn`,T=e=>document.querySelector(e),re=e=>document.querySelector(`${e||y} > iframe`),E=e=>!!(e&&e.tagName===`IFRAME`),D=(e,r,i)=>{!l(r)&&!r.selector&&console.error(`Could not find display selector.`);let c=T(l(r)?y:r.selector);if(!c)return;let u=s.getStateCopy();r&&Object.entries(r).forEach(([e,n])=>{if(a(e)){let r=u[e];o(u,e,r instanceof Object?t(r,n):n)}});let d=new URLSearchParams({...i,embed:`true`});u.theme&&d.set(`theme`,u.theme),u.screenConfiguration?.initializing&&d.set(`initializing`,JSON.stringify(u.screenConfiguration.initializing)),u.fontConfiguration&&d.set(`fontConfiguration`,JSON.stringify(u.fontConfiguration)),c.innerHTML=` <iframe id="${g}" src="${`${n(u.prismaticUrl,e)}?${d}`}" height="100%" width="100%" frameBorder="0" allow="clipboard-read; clipboard-write" ></iframe> `;let p=c.querySelector(`iframe`);if(p){let e=new AbortController;ie(e),window.addEventListener(`message`,e=>{e.data?.event===`PRISMATIC_INITIALIZED`?(m({iframe:p,event:{event:`SET_TOKEN`,data:u.jwt}}),m({iframe:p,event:{event:`SET_VERSION`,data:`4.12.1`}}),m({iframe:p,event:{event:`SET_TRANSLATION`,data:u.translation}}),m({iframe:p,event:{event:`SET_SCREEN_CONFIGURATION`,data:l(r)?{...u.screenConfiguration??{},isInPopover:!0}:u.screenConfiguration}}),m({iframe:p,event:{event:`SET_FILTERS`,data:u.filters}})):e.data?.event===`POPOVER_CLOSE_REQUESTED`&&f()},{signal:e.signal}),r?.autoFocusIframe!==!1&&p.addEventListener(`mouseenter`,()=>{p.focus()},{signal:e.signal})}l(r)&&ee()},ie=e=>{new MutationObserver((t,n)=>{for(let r of t)if(r.type===`childList`){let t=Array.from(r.removedNodes);for(let r of t)r.nodeType===Node.ELEMENT_NODE&&(r.tagName===`IFRAME`&&r.id===`pio__iframe`||r.querySelector(`iframe#pio__iframe`)!==null)&&(e.abort(),n.disconnect())}}).observe(document.body,{attributes:!1,childList:!0,subtree:!0})},O=({...e})=>{if(c(`configureInstance`),k(e)){let{instanceId:t,skipRedirectOnRemove:n,...r}=e;return D(`/find-integration-marketplace/`,r,{instanceId:t,...n?{skipRedirectOnRemove:`true`}:{}})}if(A(e)){let{integrationId:t,skipRedirectOnRemove:n,...r}=e;return D(`/find-integration-marketplace/`,r,{integrationId:t,...n?{skipRedirectOnRemove:`true`}:{}})}if(j(e)){let{integrationName:t,skipRedirectOnRemove:n,...r}=e;D(`/find-integration-marketplace/`,r,{integrationName:t,...n?{skipRedirectOnRemove:`true`}:{}})}},k=e=>!!(`instanceId`in e&&e.instanceId),A=e=>!!(`integrationId`in e&&e.integrationId),j=e=>!!(`integrationName`in e&&e.integrationName),M=async({query:e,variables:t})=>{c(`authenticate`);let{jwt:r,prismaticUrl:i}=s.getStateCopy();return await(await fetch(n(i,`api`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`,Authorization:`Bearer ${r}`},body:JSON.stringify({query:e,variables:t})})).json()},N=`The authenticate method expects an object containing a token and additional optional configuration.`,ae=[`token`],P=async e=>{if(c(`authenticate`),!e)throw Error(N);let t=new Set(Object.keys(e));if(!ae.every(e=>t.has(e)))throw Error(N);let{token:r}=e,i=document.getElementById(g),a=s.getStateCopy();a.jwt!==r&&i&&m({iframe:i,event:{event:`SET_TOKEN`,data:r}});let o=e.prismaticUrl??a.prismaticUrl,l=await fetch(n(o,`embedded`,`authenticate`),{headers:{Authorization:`Bearer ${r}`},method:`post`});if(!l.ok){let e=await l.text();throw Error(e?`Authentication failed. Server sent back: ${e}`:`Authentication failed. Please check that your customer and organization information are correct, and that the token you provided is not expired.`)}a.jwt=r,s.setState(a),a.embeddedDesignerEnabled=(await M({query:`{ authenticatedUser { customer { allowEmbeddedDesigner } } }`})).data.authenticatedUser.customer.allowEmbeddedDesigner,s.setState(a)};async function F(e,t){return c(`createWorkflow`),M({query:` mutation createWorkflow($name: String!, $contextStableKey: String, $contextData: String, $externalId: String) { importWorkflow(input: { name: $name contextStableKey: $contextStableKey contextData: $contextData externalId: $externalId }) { workflow { id } errors { field messages } } } `,variables:{name:t.name,contextStableKey:e,contextData:JSON.stringify(t.contextData),externalId:t.externalId}})}const oe=`<style id="${ne}"> .${b} { backdrop-filter: blur(10px); background: rgb(119 119 119 / 29%); bottom: 0; display: block; left: 0; opacity: 0; position: fixed; right: 0; top: 0; transition: all 0.3s ease-in; visibility: hidden; z-index: 9999; } .${b}.${S} { opacity: 1; visibility: visible; } .${C} { background: #fff; border-radius: 4px; bottom: 0; height: 80vh; left: 0; margin: auto; overflow: hidden; position: absolute; right: 0; top: 0; width: 80vw; } .${w} { all: unset; cursor: pointer; position: absolute; right: 1.5em; top: 1.3em; } .${v} { height: 100% } </style>`;let I;const se=()=>{I?.abort(),I=void 0},L={filters:{marketplace:{includeActiveIntegrations:!0},integrations:{},components:{}},screenConfiguration:{configurationWizard:{},instance:{},marketplace:{},initializing:{}},skipPreload:!1,theme:`LIGHT`,fontConfiguration:void 0,translation:{}},R=e=>{let n=t({},L,e),r=s.getInitialState();if(n&&Object.entries(n).forEach(([e,t])=>{a(e)&&o(r,e,t)}),r.initComplete=!0,s.setState(r),document.getElementById(`pio__embedded`))return;!document.getElementById(`pio__iframe-preload`)&&!n.skipPreload&&document.body.insertAdjacentHTML(`beforeend`,`<iframe id="${_}" src="${r.prismaticUrl}/embedded" style="visibility: hidden; display: none;" height="0" width="0" />`),document.head.insertAdjacentHTML(`beforeend`,oe);let i=document.createElement(`div`);i.id=h,i.innerHTML=` <div class="${b}"> <div class="${C}"> <button class="${w}" aria-label="close popover" data-close>✕</button> <div class="${v}"></div> </div> </div> `,document.body.appendChild(i);let c=document.querySelector(`#${h} .${w}`),l=document.querySelector(x);I=new AbortController;let{signal:u}=I;l?.addEventListener(`click`,e=>{e.target===e.currentTarget&&f()},{signal:u}),c?.addEventListener(`click`,()=>f(),{signal:u}),document.addEventListener(`keyup`,e=>{e.key===`Escape`&&document.querySelector(`.${S}`)&&f()},{signal:u})},z=()=>{document.getElementById(h)?.remove(),document.getElementById(_)?.remove(),document.getElementById(ne)?.remove(),se(),s.setState(s.getInitialState())},B=({instanceId:e,selector:t,theme:n,screenConfiguration:r,onCancel:i,onSuccess:a,onDelete:o})=>{if(c(`editInstanceConfiguration`),D(`/configure-instance/${e}/`,{selector:t,...n?{theme:n}:{},screenConfiguration:{...r,configurationWizard:{...r?.configurationWizard,isInModal:!0}}},{reconfigure:`true`}),!i&&!a&&!o)return;let s=new AbortController;return window.addEventListener(`message`,e=>{switch(e.data?.event){case`INSTANCE_DEPLOYED`:a?.(),s.abort();break;case`INSTANCE_DELETED`:o?.(),s.abort();break;case`INSTANCE_CONFIGURATION_CANCELED`:i?.(),s.abort();break}},{signal:s.signal}),()=>s.abort()},V=async e=>(c(`queryWorkflows`),M({query:` query queryWorkflows( $cursor: String $searchTerm: String $descriptionSearch: String $categorySearch: String $labelSearch: String $contextStableKey: String $externalId: String $first: Int $sortBy: [IntegrationVariantOrder] ) { workflows: integrationVariants( after: $cursor name_Icontains: $searchTerm description_Icontains: $descriptionSearch category: $categorySearch labels_Icontains: $labelSearch contextStableKey: $contextStableKey externalId: $externalId exclude: [INTEGRATION] first: $first sortBy: $sortBy ) { nodes { ... on Workflow { id name versionNumber description externalId updatedAt lastExecutedAt createdAt category labels customer { id name } instance { enabled } deployedVersion { id } } } pageInfo { hasNextPage endCursor } totalCount } } `,variables:e})),H=({configVars:e,...t})=>{m({...t,event:{event:`SET_CONFIG_VAR`,data:e}})},U=({componentId:e,...t})=>{c(`showComponent`),D(`/components/${e}/`,t,{})},W=e=>{c(`showComponents`),D(`/components/`,e,{})},G=e=>{c(`showConnections`),D(`/customer-connections/`,e,{})},K=(e={usePopover:!0})=>{c(`showDashboard`),D(`/dashboard/`,e,{})},q=e=>{let{embeddedDesignerEnabled:t}=s.getStateCopy();if(!t)throw Error(`Embedded designer must be enabled for this customer in order to call ${e}`)},J=({integrationId:e,...t})=>{c(`showDesigner`),q(`showDesigner`),D(`/integrations/${e}/`,t,{})},Y=e=>{c(`showIntegrations`),q(`showIntegrations`),D(`/integrations/`,e,{})},X=e=>{c(`showLogs`),D(`/logs/`,e,{})},Z=(e={usePopover:!0})=>{c(`showMarketplace`),D(`/integration-marketplace/`,e,{})},Q=({workflowId:e,onDelete:t,...n})=>{if(c(`showWorkflowBuilder`),D(`/builder/${e}/`,n,{}),t){let e=new AbortController;return window.addEventListener(`message`,e=>{e.data?.event===`WORKFLOW_DELETED`&&t()},{signal:e.signal}),()=>e.abort()}},$=e=>{c(`showWorkflows`),D(`/workflows/`,e,{})};let ce=function(e){return e.and=`and`,e.or=`or`,e}({}),le=function(e){return e.equal=`equal`,e.notEqual=`notEqual`,e.in=`in`,e.notIn=`notIn`,e.startsWith=`startsWith`,e.doesNotStartWith=`doesNotStartWith`,e.endsWith=`endsWith`,e.doesNotEndWith=`doesNotEndWith`,e}({});var ue=e({BooleanOperator:()=>ce,EMBEDDED_DEFAULTS:()=>L,PrismaticMessageEvent:()=>u,TermOperator:()=>le,authenticate:()=>P,closePopover:()=>f,configureInstance:()=>O,createWorkflow:()=>F,dispose:()=>z,editInstanceConfiguration:()=>B,getMessageIframe:()=>p,graphqlRequest:()=>M,init:()=>R,isConfigureInstanceWithInstanceId:()=>k,isConfigureInstanceWithIntegrationId:()=>A,isConfigureInstanceWithIntegrationName:()=>j,queryWorkflows:()=>V,setConfigVars:()=>H,showComponent:()=>U,showComponents:()=>W,showConnections:()=>G,showDashboard:()=>K,showDesigner:()=>J,showIntegrations:()=>Y,showLogs:()=>X,showMarketplace:()=>Z,showWorkflow:()=>Q,showWorkflows:()=>$});export{ce as BooleanOperator,L as EMBEDDED_DEFAULTS,u as PrismaticMessageEvent,le as TermOperator,P as authenticate,f as closePopover,O as configureInstance,F as createWorkflow,ue as default,z as dispose,B as editInstanceConfiguration,p as getMessageIframe,M as graphqlRequest,R as init,k as isConfigureInstanceWithInstanceId,A as isConfigureInstanceWithIntegrationId,j as isConfigureInstanceWithIntegrationName,V as queryWorkflows,H as setConfigVars,U as showComponent,W as showComponents,G as showConnections,K as showDashboard,J as showDesigner,Y as showIntegrations,X as showLogs,Z as showMarketplace,Q as showWorkflow,$ as showWorkflows}; //# sourceMappingURL=index.mjs.map