UNPKG

@prismatic-io/embedded

Version:

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

144 lines 14 kB
import{t as e}from"./rolldown-runtime-DK3Fl9T5.mjs";import t from"lodash.merge";import n from"url-join";const r={agent:void 0,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_AGENT_CONTEXT=`SET_AGENT_CONTEXT`,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(C),ee=()=>{d()?.classList.add(w)},f=()=>{let e=D(`${x} > iframe`);O(e)&&(e.contentWindow?.postMessage({event:`MARKETPLACE_CLOSED`},`*`),window.postMessage({event:`POPOVER_CLOSED`},`*`),d()?.classList.remove(w))},p=e=>Array.from(document.getElementsByTagName(`iframe`)).find(t=>t.contentWindow===e.source),m=e=>`iframe`in e,h=e=>{let t=m(e)?e.iframe:te(e.selector);O(t)&&t.contentWindow?.postMessage(e.event,`*`)},g=`pio__embedded`,_=`pio__iframe`,v=`pio__iframe-preload`,y=`pio__styles`,b=`pio__iframeContainer`,x=`#${g} .${b}`,S=`pio__overlay`,C=`#${g} > .${S}`,w=`${S}--is_visible`,T=`pio__popover`,E=`pio__closeBtn`,D=e=>document.querySelector(e),te=e=>document.querySelector(`${e||x} > iframe`),O=e=>!!(e&&e.tagName===`IFRAME`),k=(e,r,i)=>{!l(r)&&!r.selector&&console.error(`Could not find display selector.`);let c=D(l(r)?x:r.selector);if(!c)return;let u=s.getStateCopy();r&&Object.entries(r).forEach(([e,n])=>{if(a(e)){let r=u[e],i=r instanceof Object?t(r,n):n;o(u,e,i)}});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));let p=`${n(u.prismaticUrl,e)}?${d}`;c.innerHTML=` <iframe id="${_}" src="${p}" height="100%" width="100%" frameBorder="0" allow="clipboard-read; clipboard-write" ></iframe> `;let m=c.querySelector(`iframe`);if(m){let e=new AbortController;ne(e),window.addEventListener(`message`,e=>{if(e.data?.event===`PRISMATIC_INITIALIZED`){h({iframe:m,event:{event:`SET_TOKEN`,data:u.jwt}}),h({iframe:m,event:{event:`SET_VERSION`,data:`4.13.0`}}),h({iframe:m,event:{event:`SET_TRANSLATION`,data:u.translation}});let e=l(r)?{...u.screenConfiguration??{},isInPopover:!0}:u.screenConfiguration;h({iframe:m,event:{event:`SET_SCREEN_CONFIGURATION`,data:e}}),h({iframe:m,event:{event:`SET_FILTERS`,data:u.filters}}),h({iframe:m,event:{event:`SET_AGENT_CONTEXT`,data:u.agent?.context}})}else e.data?.event===`POPOVER_CLOSE_REQUESTED`&&f()},{signal:e.signal}),r?.autoFocusIframe!==!1&&m.addEventListener(`mouseenter`,()=>{m.focus()},{signal:e.signal})}l(r)&&ee()},ne=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})},A=({...e})=>{if(c(`configureInstance`),j(e)){let{instanceId:t,skipRedirectOnRemove:n,...r}=e;return k(`/find-integration-marketplace/`,r,{instanceId:t,...n?{skipRedirectOnRemove:`true`}:{}})}if(M(e)){let{integrationId:t,skipRedirectOnRemove:n,...r}=e;return k(`/find-integration-marketplace/`,r,{integrationId:t,...n?{skipRedirectOnRemove:`true`}:{}})}if(N(e)){let{integrationName:t,skipRedirectOnRemove:n,...r}=e;k(`/find-integration-marketplace/`,r,{integrationName:t,...n?{skipRedirectOnRemove:`true`}:{}})}},j=e=>!!(`instanceId`in e&&e.instanceId),M=e=>!!(`integrationId`in e&&e.integrationId),N=e=>!!(`integrationName`in e&&e.integrationName),P=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()},F=`The authenticate method expects an object containing a token and additional optional configuration.`,re=[`token`],I=async e=>{if(c(`authenticate`),!e)throw Error(F);let t=new Set(Object.keys(e));if(!re.every(e=>t.has(e)))throw Error(F);let{token:r}=e,i=document.getElementById(_),a=s.getStateCopy();a.jwt!==r&&i&&h({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 P({query:`{ authenticatedUser { customer { allowEmbeddedDesigner } } }`})).data.authenticatedUser.customer.allowEmbeddedDesigner,s.setState(a)};async function L(e,t){return c(`createWorkflow`),P({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 ie=`<style id="${y}"> .${S} { 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; } .${S}.${w} { opacity: 1; visibility: visible; } .${T} { background: #fff; border-radius: 4px; bottom: 0; height: 80vh; left: 0; margin: auto; overflow: hidden; position: absolute; right: 0; top: 0; width: 80vw; } .${E} { all: unset; cursor: pointer; position: absolute; right: 1.5em; top: 1.3em; } .${b} { height: 100% } </style>`;let R;const ae=()=>{R?.abort(),R=void 0},z={filters:{marketplace:{includeActiveIntegrations:!0},integrations:{},components:{}},screenConfiguration:{configurationWizard:{},instance:{},marketplace:{},initializing:{}},skipPreload:!1,theme:`LIGHT`,fontConfiguration:void 0,translation:{}},oe=e=>{let n=t({},z,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="${v}" src="${r.prismaticUrl}/embedded" style="visibility: hidden; display: none;" height="0" width="0" />`),document.head.insertAdjacentHTML(`beforeend`,ie);let i=document.createElement(`div`);i.id=g,i.innerHTML=` <div class="${S}"> <div class="${T}"> <button class="${E}" aria-label="close popover" data-close>✕</button> <div class="${b}"></div> </div> </div> `,document.body.appendChild(i);let c=document.querySelector(`#${g} .${E}`),l=document.querySelector(C);R=new AbortController;let{signal:u}=R;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(`.${w}`)&&f()},{signal:u})},B=()=>{document.getElementById(g)?.remove(),document.getElementById(v)?.remove(),document.getElementById(y)?.remove(),ae(),s.setState(s.getInitialState())},V=({instanceId:e,selector:t,theme:n,screenConfiguration:r,onCancel:i,onSuccess:a,onDelete:o})=>{if(c(`editInstanceConfiguration`),k(`/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()}},{signal:s.signal}),()=>s.abort()},H=async e=>(c(`queryWorkflows`),P({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})),U=({configVars:e,...t})=>{h({...t,event:{event:`SET_CONFIG_VAR`,data:e}})},W=({componentId:e,...t})=>{c(`showComponent`),k(`/components/${e}/`,t,{})},G=e=>{c(`showComponents`),k(`/components/`,e,{})},K=e=>{c(`showConnections`),k(`/customer-connections/`,e,{})},q=(e={usePopover:!0})=>{c(`showDashboard`),k(`/dashboard/`,e,{})},J=e=>{let{embeddedDesignerEnabled:t}=s.getStateCopy();if(!t)throw Error(`Embedded designer must be enabled for this customer in order to call ${e}`)},Y=({integrationId:e,...t})=>{c(`showDesigner`),J(`showDesigner`),k(`/integrations/${e}/`,t,{})},X=e=>{c(`showIntegrations`),J(`showIntegrations`),k(`/integrations/`,e,{})},Z=e=>{c(`showLogs`),k(`/logs/`,e,{})},Q=(e={usePopover:!0})=>{c(`showMarketplace`),k(`/integration-marketplace/`,e,{})},$=({workflowId:e,onDelete:t,...n})=>{if(c(`showWorkflowBuilder`),k(`/builder/${e}/`,n,{}),t){let e=new AbortController;return window.addEventListener(`message`,e=>{e.data?.event===`WORKFLOW_DELETED`&&t()},{signal:e.signal}),()=>e.abort()}},se=e=>{c(`showWorkflows`),k(`/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:()=>z,PrismaticMessageEvent:()=>u,TermOperator:()=>le,authenticate:()=>I,closePopover:()=>f,configureInstance:()=>A,createWorkflow:()=>L,dispose:()=>B,editInstanceConfiguration:()=>V,getMessageIframe:()=>p,graphqlRequest:()=>P,init:()=>oe,isConfigureInstanceWithInstanceId:()=>j,isConfigureInstanceWithIntegrationId:()=>M,isConfigureInstanceWithIntegrationName:()=>N,queryWorkflows:()=>H,setConfigVars:()=>U,showComponent:()=>W,showComponents:()=>G,showConnections:()=>K,showDashboard:()=>q,showDesigner:()=>Y,showIntegrations:()=>X,showLogs:()=>Z,showMarketplace:()=>Q,showWorkflow:()=>$,showWorkflows:()=>se});export{ce as BooleanOperator,z as EMBEDDED_DEFAULTS,u as PrismaticMessageEvent,le as TermOperator,I as authenticate,f as closePopover,A as configureInstance,L as createWorkflow,ue as default,B as dispose,V as editInstanceConfiguration,p as getMessageIframe,P as graphqlRequest,oe as init,j as isConfigureInstanceWithInstanceId,M as isConfigureInstanceWithIntegrationId,N as isConfigureInstanceWithIntegrationName,H as queryWorkflows,U as setConfigVars,W as showComponent,G as showComponents,K as showConnections,q as showDashboard,Y as showDesigner,X as showIntegrations,Z as showLogs,Q as showMarketplace,$ as showWorkflow,se as showWorkflows}; //# sourceMappingURL=index.mjs.map