@widgetic/embed-sdk 2.1.4 → 2.1.6

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.
@@ -1 +1 @@
1
- import{_ as t}from"./vendor.js";import{s as e,d as i,W as o,O as s,r as n,P as r,b as d,R as a,c as l,e as u,f as c,w as h,h as f,i as p,j as m}from"./api.js";import{r as g,l as v,q as w,w as b,t as y}from"./core.js";import{p as I,r as k,w as T,b as A}from"./renderers.js";import{q as E,r as S}from"./scanner.js";import"./media.js";import"./messaging.js";import"./advanced.js";import"./display.js";import"./performance.js";import"./security.js";const O=/^[A-Za-z0-9_-]{1,64}$/;function C(t){const e=new Map;for(const i of t.nodes)e.has(i.id)||e.set(i.id,i);const i=new Map,o=new Map;for(const e of t.edges)N(i,e.source,e),N(o,e.target,e);return{graph:t,nodesById:e,outgoingBySource:i,incomingByTarget:o}}function N(t,e,i){const o=t.get(e);o?o.push(i):t.set(e,[i])}function H(t,e){return t.outgoingBySource.get(e)??[]}function $(t){return"composition"===t?.type}function W(t){return"condition"===t?.type}function M(t,e){const i=[];for(const s of H(t,e)){const e=t.nodesById.get(s.target);o=e,"trigger"===o?.type&&i.push(e)}var o;return i}function R(t,e,i){return H(t,e).find((t=>t.sourcePort===i))}const L={text:["is","isNot","contains","doesNotContain","startsWith","endsWith","isEmpty","isNotEmpty"],number:["is","isNot","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"],boolean:["is","isNot"]},P=["is","isNot","contains","doesNotContain","startsWith","endsWith","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"];function x(t){return null==t||"string"==typeof t&&""===t.trim()}function j(t){return null==t?"":String(t).trim().toLowerCase()}function F(t){if("number"==typeof t)return Number.isFinite(t)?t:void 0;if("string"==typeof t){const e=t.trim();if(""===e)return;const i=Number(e);return Number.isFinite(i)?i:void 0}}const B=new Set(["true","yes","1","on"]),_=new Set(["false","no","0","off"]);function z(t){if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t||0!==t&&void 0;if("string"==typeof t){const e=t.trim().toLowerCase();if(B.has(e))return!0;if(_.has(e))return!1}}function D(t,e){const{operator:i}=t;if("isEmpty"===i)return x(e);if("isNotEmpty"===i)return!x(e);if(!function(t,e){return L[e].includes(t)}(i,t.field.type))return!1;switch(t.field.type){case"number":return function(t,e,i){const o=F(e),s=F(i);if("isNot"===t)return void 0===o||void 0===s||o!==s;if(void 0===o||void 0===s)return!1;switch(t){case"is":return o===s;case"greaterThan":return o>s;case"atLeast":return o>=s;case"lessThan":return o<s;case"atMost":return o<=s;default:return!1}}(i,e,t.value);case"boolean":return function(t,e,i){const o=z(e),s=z(i),n=void 0!==o&&void 0!==s&&o===s;return"is"===t?n:"isNot"===t&&!n}(i,e,t.value);default:return function(t,e,i){const o=j(e),s=j(i),n=x(e);switch(t){case"is":return!n&&o===s;case"isNot":return n||o!==s;case"contains":return!n&&""!==s&&o.includes(s);case"doesNotContain":return n||""===s||!o.includes(s);case"startsWith":return!n&&""!==s&&o.startsWith(s);case"endsWith":return!n&&""!==s&&o.endsWith(s);default:return!1}}(i,e,t.value)}}function U(t,e){if(0===t.tests.length)return!1;const i=t=>D(t,e(t.field));return"any"===t.match?t.tests.some(i):t.tests.every(i)}const V={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5},q=["seconds","minutes","hours","days","weeks"],Z=365*V.days;function G(t){return"string"==typeof t&&q.includes(t)}function J(t,e){if("after"===t.mode){const i=function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<1)return;if(!G(e))return;const i=t*V[e];return i<=Z?i:void 0}(t.amount,t.unit);if(void 0===i||!Number.isFinite(e))return;return e+i}if("at"===t.mode){const e=Date.parse(t.at);return Number.isFinite(e)?e:void 0}}function K(t,e,i){const o=J(t,e);return void 0===o?void 0:Math.max(0,o-i)}function Q(t,e){const i=t.trigger;switch(e.type){case"input":return"input"===i.kind&&i.table===e.table;case"action":return"action"===i.kind&&i.actionId===e.actionId;case"pageEvent":return"pageEvent"===i.kind&&i.name===e.name;case"scheduled":return"scheduled"===i.kind&&t.id===e.triggerId;default:return!1}}function X(t,e,i){const o=[e.id],s=[],n=function(t){const e="input"===t.type||"pageEvent"===t.type?t.values:void 0,i="input"===t.type?"input":"pageEvent"===t.type?"event":void 0;return t=>{if(e&&t.kind===i)return Object.prototype.hasOwnProperty.call(e,t.name)?e[t.name]:void 0}}(i);let r=R(t,e.id,"out");for(let e=0;e<=25&&r;e+=1){s.push(r.id);const e=t.nodesById.get(r.target);if($(e))return{destination:e,passedNodeIds:o,takenEdgeIds:s};if(!W(e))break;o.push(e.id);const i=e.cases.find((t=>U(t,n)));r=R(t,e.id,i?i.id:"default")}return{passedNodeIds:o,takenEdgeIds:s}}function Y(t,e,i,o={}){const s=o.index??C(t),n=s.nodesById.get(e.nodeId);if(!$(n))return{outcome:"ignored",reason:"unknown_position"};const r=[];for(const t of M(s,n.id)){if(!Q(t,i))continue;r.push(t.id);const e=X(s,t,i);if(e.destination&&e.destination.id!==n.id)return{outcome:"moved",position:{nodeId:e.destination.id},firedTriggerId:t.id,passedNodeIds:e.passedNodeIds,takenEdgeIds:e.takenEdgeIds}}return r.length>0?{outcome:"stayed",firedTriggerIds:r}:{outcome:"ignored",reason:"no_matching_trigger"}}function tt(t,e,i){t.some((t=>i(t,e)))||t.push(e)}function et(t,e,i,o){const s=[],n=R(t,e,"out");n&&s.push(n.target);const r=new Set;for(;s.length>0;){const e=s.pop();if(r.has(e))continue;r.add(e);const n=t.nodesById.get(e);if(W(n)){for(const t of n.cases)for(const e of t.tests)"input"===e.field.kind&&tt(o,{table:i,column:e.field.name},((t,e)=>t.table===e.table&&t.column===e.column));for(const i of H(t,e))s.push(i.target)}}}function it(t,e,i={}){const o=i.index??C(t),s={inputTables:[],inputColumns:[],actionIds:[],pageEventNames:[],schedules:[]},n=(t,e)=>t===e;for(const t of M(o,e)){const e=t.trigger;switch(e.kind){case"input":if(""===e.table)break;tt(s.inputTables,e.table,n),et(o,t.id,e.table,s.inputColumns);break;case"action":""!==e.actionId&&tt(s.actionIds,e.actionId,n);break;case"pageEvent":""!==e.name&&tt(s.pageEventNames,e.name,n);break;case"scheduled":s.schedules.push({triggerId:t.id,schedule:e.schedule})}}return s}class ot{issues=[];report(t,e){this.issues.push({code:t,severity:"error",detail:e})}}function st(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function nt(t){return"string"==typeof t&&O.test(t)?t:void 0}function rt(t,e=200){return"string"==typeof t&&t.length<=e?t:void 0}function dt(t){return"text"===t||"number"===t||"boolean"===t?t:void 0}function at(t,e,i){if(!st(t))return void i.report("malformed",e);const o=function(t,e,i){if(!st(t))return void i.report("malformed",e);const o="input"===t.kind||"event"===t.kind?t.kind:void 0,s=rt(t.name,64),n=dt(t.type);if(o&&void 0!==s&&n)return{kind:o,name:s,type:n};i.report("malformed",e)}(t.field,`${e}.field`,i),s=function(t){return"string"==typeof t&&P.includes(t)?t:void 0}(t.operator);let n;return s||i.report("malformed",`${e}.operator`),void 0!==t.value&&(n=function(t){return null===t||"boolean"==typeof t?t:"number"==typeof t?Number.isFinite(t)?t:void 0:rt(t)}(t.value),void 0===n&&i.report("malformed",`${e}.value`)),o&&s?void 0===n?{field:o,operator:s}:{field:o,operator:s,value:n}:void 0}function lt(t,e,i){if(st(t))switch(t.kind){case"input":{const o=rt(t.table);return void 0===o&&i.report("malformed",`${e}.table`),void 0===o?void 0:{kind:"input",table:o}}case"action":{const o=rt(t.actionId);return void 0===o&&i.report("malformed",`${e}.actionId`),void 0===o?void 0:{kind:"action",actionId:o}}case"pageEvent":{const o=rt(t.name,64);void 0===o&&i.report("malformed",`${e}.name`);const s=function(t,e,i){if(!Array.isArray(t)||t.length>100)return void i.report("malformed",e);const o=[];return t.forEach(((t,s)=>{const n=st(t)?rt(t.name,64):void 0,r=st(t)?dt(t.type):void 0;void 0!==n&&r?o.push({name:n,type:r}):i.report("malformed",`${e}[${s}]`)})),o}(t.values,`${e}.values`,i);return void 0!==o&&s?{kind:"pageEvent",name:o,values:s}:void 0}case"scheduled":{const o=function(t,e,i){if(st(t)&&"after"===t.mode&&"number"==typeof t.amount&&G(t.unit)&&Number.isFinite(t.amount))return{mode:"after",amount:t.amount,unit:t.unit};if(st(t)&&"at"===t.mode){const e=rt(t.at,64);if(void 0!==e)return{mode:"at",at:e}}i.report("malformed",e)}(t.schedule,`${e}.schedule`,i);return o?{kind:"scheduled",schedule:o}:void 0}default:return void i.report("unknown_trigger_kind",`${e}.kind`)}else i.report("malformed",e)}function ut(t,e,i){if(!st(t))return void i.report("malformed",e);const o=nt(t.id);o||i.report("bad_id",`${e}.id`);const s=function(t){if(void 0!==t)return st(t)&&"number"==typeof t.x&&"number"==typeof t.y&&Number.isFinite(t.x)&&Number.isFinite(t.y)?{x:t.x,y:t.y}:"invalid"}(t.position);"invalid"===s&&i.report("malformed",`${e}.position`);const n=o&&"invalid"!==s?s?{id:o,position:s}:{id:o}:void 0;switch(t.type){case"composition":{const o=rt(t.compositionId,200);if(void 0===o&&i.report("malformed",`${e}.compositionId`),void 0!==t.startsHere&&"boolean"!=typeof t.startsHere)return void i.report("malformed",`${e}.startsHere`);if(!n||void 0===o)return;return!0===t.startsHere?{...n,type:"composition",compositionId:o,startsHere:!0}:{...n,type:"composition",compositionId:o}}case"trigger":{const o=lt(t.trigger,`${e}.trigger`,i);return n&&o?{...n,type:"trigger",trigger:o}:void 0}case"condition":{if(!Array.isArray(t.cases)||t.cases.length>100)return void i.report("malformed",`${e}.cases`);const o=[];return t.cases.forEach(((t,s)=>{const n=function(t,e,i){if(!st(t)||!Array.isArray(t.tests)||t.tests.length>100)return void i.report("malformed",e);const o=nt(t.id),s="all"===t.match||"any"===t.match?t.match:void 0;let n;o||i.report("bad_id",`${e}.id`),s||i.report("malformed",`${e}.match`),void 0!==t.label&&(n=rt(t.label),void 0===n&&i.report("malformed",`${e}.label`));const r=[];return t.tests.forEach(((t,o)=>{const s=at(t,`${e}.tests[${o}]`,i);s&&r.push(s)})),o&&s?void 0===n?{id:o,match:s,tests:r}:{id:o,label:n,match:s,tests:r}:void 0}(t,`${e}.cases[${s}]`,i);n&&o.push(n)})),n?{...n,type:"condition",cases:o}:void 0}default:return void i.report("unknown_node_type",`${e}.type`)}}function ct(t){const e=new ot;if(!st(t))return e.report("malformed","graph"),{issues:e.issues};if(1!==t.schemaVersion)return e.report("schema_version","schemaVersion"),{issues:e.issues};if(!Array.isArray(t.nodes)||!Array.isArray(t.edges))return e.report("malformed","nodes/edges"),{issues:e.issues};if(t.nodes.length>100||t.edges.length>300)return e.report("graph_too_large","nodes/edges"),{issues:e.issues};const i=[];t.nodes.forEach(((t,o)=>{const s=ut(t,`nodes[${o}]`,e);s&&i.push(s)}));const o=[];return t.edges.forEach(((t,i)=>{const s=function(t,e,i){if(!st(t))return void i.report("malformed",e);const o=nt(t.id),s=nt(t.source),n=nt(t.sourcePort),r=nt(t.target);return o||i.report("bad_id",`${e}.id`),s&&n&&r||i.report("malformed",e),o&&s&&n&&r?{id:o,source:s,sourcePort:n,target:r}:void 0}(t,`edges[${i}]`,e);s&&o.push(s)})),e.issues.length>0?{issues:e.issues}:{graph:{schemaVersion:1,nodes:i,edges:o},issues:[]}}const ht=/^[A-Za-z0-9_.:-]{1,128}$/;function ft(t){return`widgetic_workflow_${t}`}function pt(t){return"string"==typeof t&&ht.test(t)}function mt(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0}function gt(t,e){try{b(ft(t),JSON.stringify({v:1,versionId:e.versionId,nodeId:e.nodeId,compositionId:e.compositionId,startedAt:e.startedAt,reachedAt:e.reachedAt}))}catch(e){v.debug("[workflows] The visitor's position could not be kept",{workflowId:t,error:e})}}function vt(t){w(ft(t))}const wt=/^[A-Za-z0-9_-]{1,64}$/,bt=new Set(["n","e","f"]);class yt{constructor(t){this.pending=[],this.lastEventOf=new Map,this.flushTimer=null,this.stopped=!1,this.listening=!1,this.onPageHide=()=>{this.flushBeforeLeaving()},this.onVisibilityChange=()=>{"hidden"===document.visibilityState&&this.flushBeforeLeaving()},this.options=t}isStopped(){return this.stopped}start(){this.listening||this.stopped||(this.listening=!0,window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange))}count(t,e,i=1){if(this.stopped||!this.options.token)return;if(!bt.has(t)||!wt.test(e)||!Number.isInteger(i)||i<1)return;const o=`${t}:${e}`;let s=i;for(;s>0;){let i=this.lastEventOf.get(o);(!i||i.c>=50)&&(i={k:t,id:e,c:0},this.pending.push(i),this.lastEventOf.set(o,i));const n=Math.min(s,50-i.c);i.c+=n,s-=n}this.pending.length>=100?this.flush():null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}flushBeforeLeaving(){if(!this.stopped&&this.options.token)for(;this.pending.length>0;){const t=this.takeBatch();if(!this.options.isActive())return void this.forgetPending();this.sendWithBeacon(t)}}dispose(){this.stopped=!0,this.forgetPending(),this.listening&&(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.listening=!1)}takeBatch(){const t=this.pending.splice(0,100);for(const e of t){const t=`${e.k}:${e.id}`;this.lastEventOf.get(t)===e&&this.lastEventOf.delete(t)}return t}forgetPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.pending=[],this.lastEventOf.clear()}flush(){if(null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.stopped||0===this.pending.length)return;if(!this.options.isActive())return void this.forgetPending();const t=this.takeBatch();this.sendWithRequest(t),this.pending.length>0&&null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}reportAddress(){return`${this.options.apiOrigin}/embed/workflows/${encodeURIComponent(this.options.workflowId)}/events`}reportBody(t){return JSON.stringify({versionId:this.options.versionId,token:this.options.token,events:t.map((t=>t.c>1?{k:t.k,id:t.id,c:t.c}:{k:t.k,id:t.id}))})}sendWithBeacon(t){try{const e=this.reportBody(t),i="undefined"!=typeof navigator?navigator.sendBeacon:void 0;if("function"==typeof i&&i.call(navigator,this.reportAddress(),new Blob([e],{type:"text/plain"})))return void v.debug("[workflows] Counts handed to the browser to send",{eventCount:t.length})}catch(t){v.debug("[workflows] The browser would not take counts to send as the page closes",{error:t})}this.sendWithRequest(t)}sendWithRequest(e){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(this.reportAddress(),{method:"POST",mode:"cors",credentials:"omit",keepalive:!0,headers:{"Content-Type":"text/plain"},body:this.reportBody(e)});if(401===t.status)return v.warn("[workflows] The gateway refused the token for counts, so this embed stops reporting",{workflowId:this.options.workflowId}),void this.dispose();v.debug("[workflows] Counts sent",{eventCount:e.length,status:t.status})}catch(t){v.debug("[workflows] Counts could not be sent and were dropped",{eventCount:e.length,error:t})}}))}}const It=/^[A-Za-z0-9_-]{1,64}$/,kt=/^[A-Za-z0-9_.:-]{1,128}$/;function Tt(t){return It.test(t)}function At(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function Et(e,i){return t(this,void 0,void 0,(function*(){const t=new AbortController,o=setTimeout((()=>t.abort()),1e4);try{const o=yield fetch(e,{method:"GET",mode:"cors",signal:t.signal});if(404===o.status)return{kind:"missing"};if(!o.ok)return{kind:"unreachable"};let s;try{s=yield o.json()}catch(t){return{kind:"unreadable"}}const n=function(t,e){var i;if(!At(t)||!0!==t.success||!At(t.data))return{kind:"unreadable"};const o=t.data;if("paused"===o.status)return{kind:"paused"};if("live"!==o.status)return{kind:"unreadable"};if("string"!=typeof o.versionId||!kt.test(o.versionId))return{kind:"unreadable"};const s=ct(o.graph);if(!s.graph||s.issues.length>0)return v.warn("[workflows] The published graph could not be read, so the embed stays a plain embed",{workflowId:e,issueCount:s.issues.length,firstIssue:null===(i=s.issues[0])||void 0===i?void 0:i.code}),{kind:"unreadable"};const n={workflowId:"string"==typeof o.workflowId?o.workflowId:e,versionId:o.versionId,timezone:"string"==typeof o.timezone&&""!==o.timezone.trim()&&o.timezone.length<=64?o.timezone:"UTC",graph:s.graph};return"number"==typeof o.versionNumber&&Number.isInteger(o.versionNumber)&&(n.versionNumber=o.versionNumber),"string"==typeof o.publishedAt&&(n.publishedAt=o.publishedAt),"string"==typeof o.startCompositionId&&kt.test(o.startCompositionId)&&(n.startCompositionId=o.startCompositionId),"string"==typeof o.eventToken&&""!==o.eventToken&&o.eventToken.length<=2048&&(n.eventToken=o.eventToken),{kind:"live",workflow:n}}(s,i);return"live"===n.kind?{kind:"live",workflow:n.workflow}:n}catch(t){return v.debug("[workflows] A host could not be reached",{workflowId:i,error:t}),{kind:"unreachable"}}finally{clearTimeout(o)}}))}const St=new Map;function Ot(e,i={}){var o,s;if(!Tt(e)||void 0!==i.versionId&&!kt.test(i.versionId))return Promise.resolve({status:"unavailable",reason:"not_found"});const n=`${e}|${null!==(o=i.versionId)&&void 0!==o?o:""}|${(null!==(s=i.origins)&&void 0!==s?s:[]).join(",")}`,r=St.get(n);if(r)return r;const d=function(e,i){return t(this,void 0,void 0,(function*(){var t;const o=null!==(t=i.origins)&&void 0!==t?t:I(),s=i.versionId?`/embed/workflows/${encodeURIComponent(e)}/versions/${encodeURIComponent(i.versionId)}`:`/embed/workflows/${encodeURIComponent(e)}`;let n=!1,r=!1;for(const t of o){const i=yield Et(`${t}${s}`,e);if("live"===i.kind)return{status:"live",workflow:i.workflow,origin:t};if("paused"===i.kind)return{status:"paused"};"missing"===i.kind&&(n=!0),"unreadable"===i.kind&&(r=!0)}const d=n?"not_found":r?"unreadable":"unreachable";return v.debug("[workflows] The workflow is not available",{workflowId:e,reason:d}),{status:"unavailable",reason:d}}))}(e,i);return St.set(n,d),d.finally((()=>{St.get(n)===d&&St.delete(n)})),d}const Ct={clicks:"click",submissions:"submit",plays:"play"},Nt=new Set(["__proto__","constructor","prototype"]);function Ht(t){const e=t.detail;return"object"!=typeof e||null===e||Array.isArray(e)?{}:e}function $t(t,e){return("submissions"!==t.metric||"FORM"===e.tagName)&&(("plays"!==t.metric||"VIDEO"===e.tagName||"AUDIO"===e.tagName)&&(null!==t.selector?y(e,t.selector):"clicks"!==t.metric||null!==e.closest('button, a, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-click-track]')))}function Wt({stage:t,watch:i,emit:o}){var s;let n=!1;const r=[];if(i.inputTables.length>0){const e=new Map;for(const{table:t,column:o}of i.inputColumns){const i=null!==(s=e.get(t))&&void 0!==s?s:new Set;i.add(o),e.set(t,i)}const d=new Set,a=t=>{var s;if(n)return;const r=Ht(t),a=r.table;if("string"!=typeof a||!i.inputTables.includes(a))return;if("string"==typeof r.entryId&&""!==r.entryId){const t=`${a}:${r.entryId}`;if(d.has(t))return;if(d.add(t),d.size>100){const t=d.values().next().value;void 0!==t&&d.delete(t)}}const l=function(t,e){const i={};if("object"!=typeof t||null===t||Array.isArray(t))return i;for(const o of e){if(Nt.has(o))continue;if(!Object.prototype.hasOwnProperty.call(t,o))continue;const e=t[o];"string"==typeof e?i[o]=e.length>200?e.slice(0,200):e:("number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e)&&(i[o]=e)}return i}(r.values,null!==(s=e.get(a))&&void 0!==s?s:new Set);v.debug("[workflows] An entry was saved in a watched table",{table:a,valueCount:Object.keys(l).length}),o([{type:"input",table:a,values:l}])};t.addEventListener("widgetic:submitted",a),r.push((()=>t.removeEventListener("widgetic:submitted",a)))}if(i.actionIds.length>0){const s=t=>{if(n)return;const e=Ht(t);let s=null;"string"==typeof e.goalId?s=e.goalId:"string"==typeof e.metric&&""!==e.metric&&(s="string"==typeof e.goalTarget&&""!==e.goalTarget?`${e.metric}@${e.goalTarget}`:e.metric),null!==s&&i.actionIds.includes(s)&&(v.debug("[workflows] A widget reported a watched action",{actionId:s}),o([{type:"action",actionId:s}]))};t.addEventListener("widgetic:goal",s),r.push((()=>t.removeEventListener("widgetic:goal",s)));const a=[];for(const t of i.actionIds){const i=e(t);i&&(d=i.metric,Object.prototype.hasOwnProperty.call(Ct,d))&&a.push({actionId:t,metric:i.metric,selector:i.selector})}if(a.length>0){let e=null,i=()=>{};const s=t=>{const e=t.target instanceof Element?t.target:null;if(!e)return[];const i=[];for(const o of a)Ct[o.metric]===t.type&&$t(o,e)&&i.push({type:"action",actionId:o.actionId});return i},d=t=>{if(n)return;const e=s(t);0!==e.length&&(v.debug("[workflows] A watched action happened in the widget",{actionIds:e.map((t=>t.actionId))}),o(e))},l=()=>{var o;const s=t.querySelector("[data-widgetic-direct]"),n=null!==(o=null==s?void 0:s.shadowRoot)&&void 0!==o?o:null;if(!n||n===e)return;i();const r=new Set(a.map((t=>Ct[t.metric])));for(const t of r)n.addEventListener(t,d,!0);e=n,i=()=>{for(const t of r)n.removeEventListener(t,d,!0);e=null,i=()=>{}}};t.addEventListener("widgetic:ready",l),r.push((()=>t.removeEventListener("widgetic:ready",l))),r.push((()=>i())),l()}}var d;return{stop:()=>{if(!n){n=!0;for(const t of r)try{t()}catch(t){v.debug("[workflows] A listener could not be removed",{error:t})}}}}}const Mt=50,Rt=2e3,Lt=150,Pt=5,xt=300,jt=2e4;function Ft(t,e,i,o){const s=t.getAttribute(e);if(null===s||!/^\d+$/.test(s.trim()))return i;const n=Number.parseInt(s.trim(),10);return Number.isFinite(n)?Math.min(n,o):i}function Bt(t,e,i){const o="number"==typeof i&&Number.isFinite(i)&&i>0?Math.min(e.maxHeight,Math.floor(i)):e.maxHeight,s=Math.min(e.minHeight,o);return Number.isNaN(t)?s:Math.max(s,Math.min(o,Math.ceil(t)))}function _t(t,e,i){return null===t||e!==t&&Math.abs(e-t)>=i}const zt=o,Dt=["width","height","resize","resize-mode","render-mode","use-iframe","theme","mode","colors","sandbox","autoload","adaptive","responsive"],Ut=["values","context","media-resolver"],Vt=["design","content","content-items","contentitems","items"];function qt(t){if("undefined"==typeof ResizeObserver)return null;try{return new ResizeObserver((e=>{t(e.map((t=>({target:t.target,height:t.contentRect.height}))))}))}catch(t){return v.debug("[workflows] The browser could not watch heights",{error:t}),null}}function Zt(t){return t.getBoundingClientRect().height}function Gt(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch(t){return!1}}function Jt(t){return"number"==typeof t&&Number.isFinite(t)&&t>0}class Kt{constructor(t){var e;this.current=null,this.incoming=null,this.heightObserver=null,this.attributeObserver=null,this.autoscaleOn=!1,this.appliedHeight=null,this.debounceTimer=null,this.pendingHeight=null,this.destroyed=!1,this.warnedAboutFrameWithoutHeight=!1,this.host=t.host,this.services=t.services,this.prefersReducedMotion=null!==(e=t.prefersReducedMotion)&&void 0!==e?e:Gt,this.widthOverride=t.widthOverride&&""!==t.widthOverride?t.widthOverride:null,this.viewportElement=document.createElement("div"),this.viewportElement.setAttribute("data-widgetic-workflow-viewport","1"),this.viewportElement.setAttribute("data-widgetic-internal","1"),this.viewportElement.style.display="block",this.observeMirroredAttributes()}currentStage(){var t,e;return null!==(e=null===(t=this.current)||void 0===t?void 0:t.element)&&void 0!==e?e:null}showFirstStage(t){if(this.current)return{stage:this.current.element,ready:Promise.resolve({status:"ready"})};this.viewportElement.isConnected||this.host.appendChild(this.viewportElement),this.holdRoomFor(t);const e=this.buildStage(t,!0);this.current=e;const i=this.waitUntilShown(e,null,(t=>{if("ready"===t.status&&!this.destroyed&&this.autoscaleOn&&this.current===e){const t=this.measure(e.element);Jt(t)&&this.applyHeight(t,"immediate")}}));return this.viewportElement.appendChild(e.element),this.services.hydrate(e.element),{stage:e.element,ready:i}}enableAutoscale(){var t,e;if(!this.destroyed&&!this.autoscaleOn&&(this.autoscaleOn=!0,this.viewportElement.style.position="relative",this.viewportElement.style.overflow="hidden",this.current&&this.positionAsLayer(this.current.element),this.heightObserver=(null!==(t=this.services.createHeightObserver)&&void 0!==t?t:qt)((t=>this.onHeightsReported(t))),this.current)){null===(e=this.heightObserver)||void 0===e||e.observe(this.current.element);const t=this.measure(this.current.element);Jt(t)&&this.applyHeight(t,"immediate")}}releaseAutoscale(){var t;if(this.destroyed)return;this.autoscaleOn=!1,this.clearHeightTimer(),null===(t=this.heightObserver)||void 0===t||t.disconnect(),this.heightObserver=null,this.appliedHeight=null;const e=this.viewportElement.style;for(const t of["position","overflow","height","min-height","transition"])e.removeProperty(t);this.current&&this.positionInFlow(this.current.element)}swapTo(e){return t(this,void 0,void 0,(function*(){var t,o,s;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming)return{status:"failed",reason:"busy"};this.enableAutoscale();const n=this.buildStage(e,!1);this.incoming=n,this.hideBeside(n.element);const r=this.waitUntilShown(n,null!==(t=this.services.readyTimeoutMilliseconds)&&void 0!==t?t:8e3);this.viewportElement.appendChild(n.element),this.services.hydrate(n.element);const d=yield r;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming=null,"failed"===d.status)return this.removeStage(n),"timeout"===d.reason&&i(this.host,e,"workflow_step_timeout"),v.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e,reason:d.reason}),Object.assign({status:"failed",reason:"stopped"===d.reason?"stopped":d.reason},d.code?{code:d.code}:{});const a=this.current;this.revealInPlace(n.element),this.current=n,null===(o=this.heightObserver)||void 0===o||o.observe(n.element);const l=this.measure(n.element);return Jt(l)&&this.applyHeight(l,"immediate"),a&&(null===(s=this.heightObserver)||void 0===s||s.unobserve(a.element),this.removeStage(a)),{status:"shown",stage:n.element}}))}destroy(){var t,e,i;if(this.destroyed)return;this.destroyed=!0,this.clearHeightTimer(),null===(t=this.heightObserver)||void 0===t||t.disconnect(),this.heightObserver=null,null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null;const o=[this.current,this.incoming];this.current=null,this.incoming=null;for(const t of o)t&&(null===(i=t.cancelWait)||void 0===i||i.call(t),this.removeStage(t));this.viewportElement.remove()}buildStage(t,e){var i,o,s;const n=document.createElement("widgetic");n.setAttribute("composition-id",t),n.setAttribute(zt,"1"),n.style.display="block";for(const t of Dt){const e=this.host.getAttribute(t);null!==e&&n.setAttribute(t,e)}this.widthOverride&&n.setAttribute("width",this.widthOverride);for(const t of Ut){const e=this.host.getAttribute(t);null!==e&&n.setAttribute(t,e)}const r=t===(null!==(i=this.host.getAttribute("composition-id"))&&void 0!==i?i:"").trim();r&&this.copyWhatThePageWroteForTheTagComposition(n);const d={element:n,compositionId:t,reportedHeight:!1,cancelWait:null,stopListening:()=>{}},a=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.height;if("number"!=typeof i||!Jt(i))return;const o=n.querySelector("iframe");o&&(o.style.height=`${Math.ceil(i)}px`,d.reportedHeight=!0)};n.addEventListener("widgetic:resize",a),d.stopListening=()=>n.removeEventListener("widgetic:resize",a);try{null===(s=(o=this.services).onStageCreated)||void 0===s||s.call(o,n,{compositionId:t,isFirst:e,carriesPageContent:r})}catch(e){v.debug("[workflows] A listener for a new stage failed",{compositionId:t,error:e})}return d}copyWhatThePageWroteForTheTagComposition(t){for(const e of Array.from(this.host.attributes))E(e.name)||t.setAttribute(e.name,e.value);for(const e of Vt){const i=this.host.getAttribute(e);null!==i&&t.setAttribute(e,i)}for(const e of S(this.host))t.appendChild(e.cloneNode(!0))}observeMirroredAttributes(){const t="undefined"!=typeof MutationObserver?MutationObserver:null;if(t)try{this.attributeObserver=new t((t=>{t.some((t=>{var e;return"attributes"===t.type&&Ut.includes(null!==(e=t.attributeName)&&void 0!==e?e:"")}))&&this.mirrorAttributesToStages()})),this.attributeObserver.observe(this.host,{attributes:!0,attributeFilter:[...Ut]})}catch(t){this.attributeObserver=null,v.debug("[workflows] The tag cannot be watched for changes",{error:t})}}mirrorAttributesToStages(){for(const t of[this.current,this.incoming])if(t)for(const e of Ut){const i=this.host.getAttribute(e);null===i?t.element.removeAttribute(e):t.element.getAttribute(e)!==i&&t.element.setAttribute(e,i)}}waitUntilShown(t,e,i){return new Promise((o=>{const s=t.element;let n=null,r=!1;const d=e=>{if(!r){r=!0,null!==n&&clearTimeout(n),s.removeEventListener("widgetic:ready",a),s.removeEventListener("widgetic:error",l),s.removeEventListener("load",u,!0),t.cancelWait=null;try{null==i||i(e)}catch(e){v.debug("[workflows] A stage could not be settled",{compositionId:t.compositionId,error:e})}o(e)}},a=()=>d({status:"ready"}),l=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.code;d(Object.assign({status:"failed",reason:"error"},"string"==typeof i?{code:i}:{}))},u=t=>{t.target instanceof HTMLIFrameElement&&d({status:"ready"})};s.addEventListener("widgetic:ready",a),s.addEventListener("widgetic:error",l),s.addEventListener("load",u,!0),t.cancelWait=()=>d({status:"failed",reason:"stopped"}),null!==e&&(n=setTimeout((()=>d({status:"failed",reason:"timeout"})),e))}))}removeStage(t){var e,i;t.stopListening(),t.element.querySelector("iframe")&&!t.reportedHeight&&this.noteFrameWithoutHeight(t.compositionId),t.element.remove();try{null===(i=(e=this.services).onStageRemoved)||void 0===i||i.call(e,t.element)}catch(e){v.debug("[workflows] A listener for a removed stage failed",{compositionId:t.compositionId,error:e})}}noteFrameWithoutHeight(t){this.warnedAboutFrameWithoutHeight||(this.warnedAboutFrameWithoutHeight=!0,v.debug("[workflows] A widget in a frame does not report its height (widgetic:resize), so the embed keeps the height of its frame",{compositionId:t}))}hideBeside(t){this.positionAsLayer(t),t.style.visibility="hidden",t.style.pointerEvents="none",t.setAttribute("aria-hidden","true")}revealInPlace(t){t.style.removeProperty("visibility"),t.style.removeProperty("pointer-events"),t.removeAttribute("aria-hidden")}positionAsLayer(t){t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.width="100%"}positionInFlow(t){for(const e of["position","top","left","width"])t.style.removeProperty(e)}measure(t){var e;try{return(null!==(e=this.services.measureStageHeight)&&void 0!==e?e:Zt)(t)}catch(t){return v.debug("[workflows] The height of a stage could not be read",{error:t}),0}}holdRoomFor(t){const e=k(t);if(null===e)return;const i=this.settings();this.viewportElement.style.minHeight=`${Bt(e,i,this.overlayCap())}px`}settings(){return function(t,e={}){const i=Ft(t,"autoscale-min-height",Mt,jt),o=Ft(t,"autoscale-max-height",Rt,jt);return{minHeight:i,maxHeight:Math.max(o,i),debounceDelay:Ft(t,"autoscale-debounce",Lt,5e3),threshold:Ft(t,"autoscale-threshold",Pt,jt),animate:"false"!==t.getAttribute("autoscale-animate")&&!0!==e.prefersReducedMotion,animationDuration:Ft(t,"autoscale-animation-duration",xt,5e3)}}(this.host,{prefersReducedMotion:this.prefersReducedMotion()})}overlayCap(){return this.host.hasAttribute(s)?Math.floor(.9*window.innerHeight):null}onHeightsReported(t){if(!this.destroyed&&this.autoscaleOn&&this.current)for(const e of t)e.target===this.current.element&&Jt(e.height)&&this.applyHeight(e.height,"observed")}applyHeight(t,e){const i=this.settings(),o=Bt(t,i,this.overlayCap());if("immediate"===e)return this.clearHeightTimer(),void this.setHeight(o,i);_t(this.appliedHeight,o,i.threshold)?(this.pendingHeight=o,null!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=null;const t=this.pendingHeight;if(this.pendingHeight=null,null===t||this.destroyed||!this.autoscaleOn)return;const e=this.settings();_t(this.appliedHeight,t,e.threshold)&&this.setHeight(t,e)}),i.debounceDelay)):o===this.appliedHeight&&this.clearHeightTimer()}setHeight(t,e){var i;const o=this.viewportElement.style,s=null!==this.appliedHeight&&this.appliedHeight!==t;if(o.setProperty("transition",e.animate&&s?`height ${e.animationDuration}ms ease`:"none"),o.height=`${t}px`,o.removeProperty("min-height"),this.appliedHeight=t,this.current){const e=Number.parseInt(null!==(i=this.host.getAttribute("height"))&&void 0!==i?i:"",10);T(this.current.compositionId,t,Number.isFinite(e)?e:t)}}clearHeightTimer(){null!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingHeight=null}}const Qt=3e4;function Xt(t,e,i){var o;try{f(t,p(e,i)),null===(o=m(t))||void 0===o||o.sendWorkflowWatch(i)}catch(t){v.debug("[workflows] A widget could not be told what to report",{compositionId:e,error:t})}}function Yt(t){try{A(t).then((t=>{var e;const i="found"===t.status?null===(e=t.payload.direct)||void 0===e?void 0:e.moduleUrl:void 0;i&&h(i)})).catch((()=>{}))}catch(e){v.debug("[workflows] A composition could not be got ready",{compositionId:t,error:e})}}function te(t){const e=window;if("function"==typeof e.requestIdleCallback){const i=e.requestIdleCallback((()=>t()),{timeout:5e3});return()=>{var t;return null===(t=e.cancelIdleCallback)||void 0===t?void 0:t.call(e,i)}}const i=setTimeout(t,1500);return()=>clearTimeout(i)}class ee{constructor(t,e,i,o,s){this.host=t,this.workflowId=e,this.tagCompositionId=i,this.options=o,this.services=s,this.mode="loading",this.stages=new Map,this.pageEvents=new r,this.removeListeners=[],this.workflow=null,this.index=null,this.counts=null,this.position=null,this.stepping=!1,this.pendingStageNodeId=null,this.retryTimer=null,this.scheduleTimers=new Set,this.cancelIdleWork=null,this.readiedCompositions=new Set,this.displayBeforeMounting="",this.onPageEvent=t=>{if("ended"===this.mode||"plain"===this.mode)return;const e=d(t.detail);e?"running"!==this.mode||this.stepping?this.pageEvents.add(e):this.hasEnded()||this.react([{type:"pageEvent",name:e.name,values:e.values}]):v.debug("[workflows] An event of the page was ignored: it is not one a workflow can wait for")},this.onVisibilityChange=()=>{"running"!==this.mode||this.stepping||this.hasEnded()||this.armSchedules()};const n=s.viewport;this.viewport=new Kt(Object.assign(Object.assign(Object.assign({host:t},n.prefersReducedMotion?{prefersReducedMotion:n.prefersReducedMotion}:{}),o.width?{widthOverride:o.width}:{}),{services:Object.assign(Object.assign(Object.assign(Object.assign({hydrate:o.hydrate},n.createHeightObserver?{createHeightObserver:n.createHeightObserver}:{}),n.measureStageHeight?{measureStageHeight:n.measureStageHeight}:{}),void 0!==n.readyTimeoutMilliseconds?{readyTimeoutMilliseconds:n.readyTimeoutMilliseconds}:{}),{onStageCreated:t=>this.onStageCreated(t),onStageRemoved:t=>this.onStageRemoved(t)})}))}start(){var t;const e=function(t,e=Date.now()){const i=ft(t),o=g(i);if(null===o)return null;try{const i=JSON.parse(o);if("object"!=typeof i||null===i||Array.isArray(i))return null;const s=i;return 1!==s.v?null:pt(s.versionId)&&pt(s.nodeId)&&pt(s.compositionId)&&mt(s.startedAt)&&mt(s.reachedAt)?s.startedAt>e+864e5?null:e-s.startedAt>2592e6?(vt(t),v.debug("[workflows] The visitor's position is older than 30 days and was forgotten",{workflowId:t}),null):{versionId:s.versionId,nodeId:s.nodeId,compositionId:s.compositionId,startedAt:s.startedAt,reachedAt:Math.min(s.reachedAt,e)}:null}catch(e){return v.debug("[workflows] The kept position could not be read and is ignored",{workflowId:t,error:e}),null}}(this.workflowId),i=null!==(t=null==e?void 0:e.compositionId)&&void 0!==t?t:this.tagCompositionId;this.listenToThePage();const{ready:o}=this.viewport.showFirstStage(i);this.displayBeforeMounting=this.host.style.display,this.options.markMounted(this.host),this.run(e,i,o)}run(e,i,o){return t(this,void 0,void 0,(function*(){var t;try{const[s,n]=yield Promise.all([this.services.fetchWorkflow(this.workflowId),o]);if(this.hasEnded())return;let r=e,d=i;if("failed"===n.status){if("stopped"===n.reason)return;if(!e||e.compositionId===this.tagCompositionId)return void this.refuse(n.code);{v.debug("[workflows] The composition a returning visitor was on cannot be shown, so they start again",{compositionId:e.compositionId}),vt(this.workflowId),r=null;const i=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;if("shown"!==i.status)return void this.refuse(null!==(t=n.code)&&void 0!==t?t:"failed"===i.status?i.code:void 0);d=this.tagCompositionId}}if("live"!==s.status)return v.debug("[workflows] The workflow is not running, so the tag is a plain embed",{workflowId:this.workflowId,status:s.status}),void(yield this.becomePlain(d));let a=s.workflow,l=s.origin;if(r&&r.versionId!==a.versionId){const t=yield this.services.fetchWorkflow(this.workflowId,{versionId:r.versionId});if(this.hasEnded())return;"live"===t.status&&t.workflow.versionId===r.versionId?(a=t.workflow,l=t.origin):(v.debug("[workflows] The version a visitor started on cannot be read, so they continue as a new visitor",{versionId:r.versionId}),vt(this.workflowId),r=null)}const u=C(a.graph);let c=r&&this.fitsTheGraph(r,a,u)?r:null;const h=null===c;if(null===c){r&&(v.debug("[workflows] The place a visitor was kept at is not in the workflow, so they continue as a new visitor"),vt(this.workflowId));const t=function(t,e){for(const i of t.nodes)if("composition"===i.type&&i.compositionId===e)return i}(a.graph,this.tagCompositionId);if(!t)return v.debug("[workflows] The composition of the tag is not a block of the workflow, so the tag is a plain embed",{compositionId:this.tagCompositionId}),void(yield this.becomePlain(d));if(d!==this.tagCompositionId){const t=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;if("shown"!==t.status)return void(yield this.becomePlain(d))}const e=Date.now();c={versionId:a.versionId,nodeId:t.id,compositionId:this.tagCompositionId,startedAt:e,reachedAt:e}}this.activate(a,l,u,c,h)}catch(t){v.warn("[workflows] The workflow stopped working, so the tag stays as it is",{workflowId:this.workflowId,error:t}),this.becomePlainWithoutWaiting()}}))}fitsTheGraph(t,e,i){if(t.versionId!==e.versionId)return!1;const o=i.nodesById.get(t.nodeId);return $(o)&&o.compositionId===t.compositionId}activate(t,e,i,o,s){var n;this.workflow=t,this.index=i,this.position=o,this.mode="running";const r=this.services.createCounts({workflowId:this.workflowId,versionId:t.versionId,token:null!==(n=t.eventToken)&&void 0!==n?n:null,apiOrigin:e,isActive:()=>"ended"!==this.mode&&this.host.isConnected});r.start(),this.counts=r,s&&(gt(this.workflowId,o),r.count("n",o.nodeId)),v.debug("[workflows] The workflow runs",{workflowId:this.workflowId,versionId:t.versionId,isNewVisitor:s}),this.viewport.enableAutoscale();const d=this.viewport.currentStage();d&&this.armStage(d,o.nodeId),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}becomePlain(e){return t(this,void 0,void 0,(function*(){if(this.mode="plain",this.pageEvents.clear(),e!==this.tagCompositionId){const t=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;"shown"!==t.status&&v.debug("[workflows] The composition of the tag could not be shown")}this.viewport.releaseAutoscale()}))}becomePlainWithoutWaiting(){"ended"!==this.mode&&(this.mode="plain",this.pageEvents.clear(),this.cancelRetry(),this.cancelSchedules(),this.viewport.releaseAutoscale())}refuse(t){const e=this.viewport.currentStage(),i=(null==e?void 0:e.getAttribute(a))||t||"NOT_FOUND";this.stop(),this.host.removeAttribute("data-widgetic-mounting"),this.host.removeAttribute("data-widgetic-mounted"),this.host.style.display=this.displayBeforeMounting,this.host.setAttribute(a,i),v.debug("[workflows] The composition of the tag cannot be shown",{workflowId:this.workflowId,reason:i})}listenToThePage(){this.host.addEventListener(l,this.onPageEvent),document.addEventListener("visibilitychange",this.onVisibilityChange),this.removeListeners.push((()=>this.host.removeEventListener(l,this.onPageEvent)),(()=>document.removeEventListener("visibilitychange",this.onVisibilityChange)))}drainPageEvents(){const t=this.pageEvents.take();for(let e=0;e<t.length;e+=1){if("running"!==this.mode)return;if(this.stepping){for(const i of t.slice(e))this.pageEvents.add(i);return}const i=t[e];this.react([{type:"pageEvent",name:i.name,values:i.values}])}}onStageCreated(t){if(this.stages.set(t,{signals:null,stopWatchingReady:null}),null!==this.pendingStageNodeId){const e=this.pendingStageNodeId;this.pendingStageNodeId=null,this.armStage(t,e)}}onStageRemoved(t){var e,i;const o=this.stages.get(t);null===(e=null==o?void 0:o.signals)||void 0===e||e.stop(),null===(i=null==o?void 0:o.stopWatchingReady)||void 0===i||i.call(o),this.stages.delete(t)}armStage(t,e){var i,o,s;const n=this.workflow,r=this.index;if(!n||!r)return;const d=r.nodesById.get(e);if(!$(d))return;const a=null!==(i=this.stages.get(t))&&void 0!==i?i:{signals:null,stopWatchingReady:null};null===(o=a.signals)||void 0===o||o.stop(),null===(s=a.stopWatchingReady)||void 0===s||s.call(a),this.stages.set(t,a);const l=it(n.graph,e,{index:r});a.signals=Wt({stage:t,watch:l,emit:e=>this.onSignals(t,e)});const c=u(l);if(0===c.tables.length&&0===c.fields.length&&0===c.goals.length)return;const h=()=>this.services.deliverWatch(t,d.compositionId,c);h(),t.addEventListener("widgetic:ready",h),a.stopWatchingReady=()=>t.removeEventListener("widgetic:ready",h)}onSignals(t,e){"running"!==this.mode||this.stepping||this.hasEnded()||t===this.viewport.currentStage()&&this.react(e)}react(t){const e=this.workflow,i=this.index,o=this.position;if(e&&i&&o)for(const s of t){let t;try{t=Y(e.graph,{nodeId:o.nodeId},s,{index:i})}catch(t){v.debug("[workflows] The engine could not decide on a signal",{signal:s.type,error:t});continue}if("moved"===t.outcome)return void this.moveOn(t,!1)}}moveOn(e,i){return t(this,void 0,void 0,(function*(){const t=this.index,o=this.position;if(!t||!o)return;const s=t.nodesById.get(e.position.nodeId);if(!$(s))return;let n;this.stepping=!0,this.cancelRetry(),this.cancelSchedules(),this.pendingStageNodeId=s.id;try{n=yield this.viewport.swapTo(s.compositionId)}catch(t){v.debug("[workflows] The next composition could not be built",{compositionId:s.compositionId,error:t}),n={status:"failed",reason:"error"}}this.pendingStageNodeId=null,this.stepping=!1,this.hasEnded()||("shown"===n.status?this.completeStep(e,s,o):this.failStep(e,s,o,i))}))}completeStep(t,e,i){const o=Object.assign(Object.assign({},i),{nodeId:e.id,compositionId:e.compositionId,reachedAt:Date.now()});this.position=o,gt(this.workflowId,o),this.countStep(i.nodeId,t,e.id),v.debug("[workflows] The visitor moved on",{from:i.compositionId,to:e.compositionId}),this.host.dispatchEvent(new CustomEvent(c,{detail:{workflowId:this.workflowId,from:i.compositionId,to:e.compositionId},bubbles:!0,composed:!0})),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}countStep(t,e,i){const o=this.counts,s=this.index;if(!o||!s)return;const n=H(s,t).find((t=>t.target===e.firedTriggerId));n&&o.count("e",n.id);for(const t of e.passedNodeIds)o.count("n",t);for(const t of e.takenEdgeIds)o.count("e",t);o.count("n",i)}failStep(t,e,i,o){var s;null===(s=this.counts)||void 0===s||s.count("f",e.id),v.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e.compositionId,isRetry:o}),this.armSchedules(),o||this.scheduleRetry(t,i.nodeId),this.drainPageEvents()}scheduleRetry(t,e){this.cancelRetry(),this.retryTimer=setTimeout((()=>{var i;this.retryTimer=null,"running"!==this.mode||this.stepping||this.hasEnded()||(null===(i=this.position)||void 0===i?void 0:i.nodeId)===e&&this.moveOn(t,!0)}),3e4)}cancelRetry(){null!==this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=null}armSchedules(){this.cancelSchedules();const t=this.workflow,e=this.index,i=this.position;if("running"===this.mode&&!this.stepping&&t&&e&&i)for(const{triggerId:o,schedule:s}of it(t.graph,i.nodeId,{index:e}).schedules){const t=K(s,i.reachedAt,Date.now());void 0!==t?this.waitFor(o,s,i.nodeId,t):v.debug("[workflows] A Scheduled trigger has no usable time and is ignored",{triggerId:o})}}waitFor(t,e,i,o){const s=setTimeout((()=>{this.scheduleTimers.delete(s);const o=this.position;if("running"!==this.mode||this.stepping||this.hasEnded()||!o||o.nodeId!==i)return;const n=K(e,o.reachedAt,Date.now());void 0!==n&&(n>0?this.waitFor(t,e,i,n):(v.debug("[workflows] A wait is over",{triggerId:t}),this.react([{type:"scheduled",triggerId:t}])))}),Math.min(o,432e5));this.scheduleTimers.add(s)}cancelSchedules(){for(const t of this.scheduleTimers)clearTimeout(t);this.scheduleTimers.clear()}getNextCompositionsReady(){var t,e;null===(t=this.cancelIdleWork)||void 0===t||t.call(this),this.cancelIdleWork=null;const i=null===(e=this.position)||void 0===e?void 0:e.nodeId;i&&(this.cancelIdleWork=this.services.whenIdle((()=>{var t;if(this.cancelIdleWork=null,"running"!==this.mode||this.hasEnded()||(null===(t=this.position)||void 0===t?void 0:t.nodeId)!==i)return;let e=0;for(const t of this.compositionsReachableFrom(i))if(!this.readiedCompositions.has(t)){if(e>=5)break;this.readiedCompositions.add(t),e+=1,this.services.prefetchComposition(t)}})))}compositionsReachableFrom(t){const e=this.index;if(!e)return[];const i=[],o=new Set;for(const s of M(e,t)){const t=[s.id];for(;t.length>0;){const s=t.pop();if(!o.has(s)){o.add(s);for(const o of H(e,s)){const s=e.nodesById.get(o.target);$(s)?i.includes(s.compositionId)||i.push(s.compositionId):W(s)&&t.push(s.id)}}}}return i}hasEnded(){return"ended"===this.mode||!this.host.isConnected&&(v.debug("[workflows] The tag left the page, so its workflow ends",{workflowId:this.workflowId}),this.stop(),!0)}stop(){var t,e,i,o,s;if("ended"!==this.mode){try{null===(t=this.counts)||void 0===t||t.flushBeforeLeaving()}catch(t){v.debug("[workflows] The last counts could not be sent",{error:t})}this.mode="ended",this.cancelRetry(),this.cancelSchedules(),null===(e=this.cancelIdleWork)||void 0===e||e.call(this),this.cancelIdleWork=null;for(const t of this.removeListeners.splice(0))t();for(const t of this.stages.values())null===(i=t.signals)||void 0===i||i.stop(),null===(o=t.stopWatchingReady)||void 0===o||o.call(t);this.stages.clear(),this.pageEvents.clear();try{null===(s=this.counts)||void 0===s||s.dispose()}catch(t){v.debug("[workflows] The counts could not be closed",{error:t})}this.viewport.destroy()}}}function ie(t,e){var i,o,s;const r=(null!==(i=t.getAttribute("workflow-id"))&&void 0!==i?i:"").trim(),d=(null!==(o=t.getAttribute("composition-id"))&&void 0!==o?o:"").trim();if(!Tt(r)||""===d)return v.debug("[workflows] The tag is not a workflow embed, so it is embedded as it is",{workflowId:r,tagCompositionId:d}),null;const a={fetchWorkflow:Ot,createCounts:t=>new yt(t),deliverWatch:Xt,prefetchComposition:Yt,whenIdle:te,viewport:{}},l=Object.assign(Object.assign(Object.assign({},a),e.services),{viewport:Object.assign(Object.assign({},a.viewport),null===(s=e.services)||void 0===s?void 0:s.viewport)}),u=new ee(t,r,d,e,l);try{u.start()}catch(t){return v.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{workflowId:r,error:t}),u.stop(),null}const c={stop:()=>u.stop()};return n(t,c),c}export{Qt as RETRY_AFTER_FAILED_STEP_MILLISECONDS,ie as startWorkflowEmbed};
1
+ import{_ as t}from"./vendor.js";import{s as e,d as i,W as o,O as s,r as n,P as r,b as a,R as d,c as l,e as u,f as c,w as h,h as p,i as f,j as g}from"./api.js";import{r as m,l as v,q as w,w as b,t as y}from"./core.js";import{p as I,r as k,w as T,b as A}from"./renderers.js";import{q as E,r as C}from"./scanner.js";import"./media.js";import"./messaging.js";import"./advanced.js";import"./display.js";import"./performance.js";import"./security.js";const S=/^[A-Za-z0-9_-]{1,64}$/;function O(t){const e=new Map;for(const i of t.nodes)e.has(i.id)||e.set(i.id,i);const i=new Map,o=new Map;for(const e of t.edges)N(i,e.source,e),N(o,e.target,e);return{graph:t,nodesById:e,outgoingBySource:i,incomingByTarget:o}}function N(t,e,i){const o=t.get(e);o?o.push(i):t.set(e,[i])}function H(t,e){return t.outgoingBySource.get(e)??[]}function M(t){return"composition"===t?.type}function $(t){return"condition"===t?.type}function W(t,e){const i=[];for(const s of H(t,e)){const e=t.nodesById.get(s.target);o=e,"trigger"===o?.type&&i.push(e)}var o;return i}function L(t,e,i){return H(t,e).find((t=>t.sourcePort===i))}const F={text:["is","isNot","contains","doesNotContain","startsWith","endsWith","isEmpty","isNotEmpty"],number:["is","isNot","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"],boolean:["is","isNot"]},P=["is","isNot","contains","doesNotContain","startsWith","endsWith","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"];function R(t){return null==t||"string"==typeof t&&""===t.trim()}function j(t){return null==t?"":String(t).trim().toLowerCase()}function x(t){if("number"==typeof t)return Number.isFinite(t)?t:void 0;if("string"==typeof t){const e=t.trim();if(""===e)return;const i=Number(e);return Number.isFinite(i)?i:void 0}}const B=new Set(["true","yes","1","on"]),_=new Set(["false","no","0","off"]);function z(t){if("boolean"==typeof t)return t;if("number"==typeof t)return 1===t||0!==t&&void 0;if("string"==typeof t){const e=t.trim().toLowerCase();if(B.has(e))return!0;if(_.has(e))return!1}}function D(t,e){const{operator:i}=t;if("isEmpty"===i)return R(e);if("isNotEmpty"===i)return!R(e);if(!function(t,e){return F[e].includes(t)}(i,t.field.type))return!1;switch(t.field.type){case"number":return function(t,e,i){const o=x(e),s=x(i);if("isNot"===t)return void 0===o||void 0===s||o!==s;if(void 0===o||void 0===s)return!1;switch(t){case"is":return o===s;case"greaterThan":return o>s;case"atLeast":return o>=s;case"lessThan":return o<s;case"atMost":return o<=s;default:return!1}}(i,e,t.value);case"boolean":return function(t,e,i){const o=z(e),s=z(i),n=void 0!==o&&void 0!==s&&o===s;return"is"===t?n:"isNot"===t&&!n}(i,e,t.value);default:return function(t,e,i){const o=j(e),s=j(i),n=R(e);switch(t){case"is":return!n&&o===s;case"isNot":return n||o!==s;case"contains":return!n&&""!==s&&o.includes(s);case"doesNotContain":return n||""===s||!o.includes(s);case"startsWith":return!n&&""!==s&&o.startsWith(s);case"endsWith":return!n&&""!==s&&o.endsWith(s);default:return!1}}(i,e,t.value)}}function V(t,e){if(0===t.tests.length)return!1;const i=t=>D(t,e(t.field));return"any"===t.match?t.tests.some(i):t.tests.every(i)}const U={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5},q=["seconds","minutes","hours","days","weeks"],Z=365*U.days;function G(t){return"string"==typeof t&&q.includes(t)}function J(t,e){if("after"===t.mode){const i=function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<1)return;if(!G(e))return;const i=t*U[e];return i<=Z?i:void 0}(t.amount,t.unit);if(void 0===i||!Number.isFinite(e))return;return e+i}if("at"===t.mode){const e=Date.parse(t.at);return Number.isFinite(e)?e:void 0}}function K(t,e,i){const o=J(t,e);return void 0===o?void 0:Math.max(0,o-i)}function Q(t,e){const i=t.trigger;switch(e.type){case"input":return"input"===i.kind&&i.table===e.table;case"action":return"action"===i.kind&&i.actionId===e.actionId;case"pageEvent":return"pageEvent"===i.kind&&i.name===e.name;case"scheduled":return"scheduled"===i.kind&&t.id===e.triggerId;default:return!1}}function X(t,e,i){const o=[e.id],s=[],n=function(t){const e="input"===t.type||"pageEvent"===t.type?t.values:void 0,i="input"===t.type?"input":"pageEvent"===t.type?"event":void 0;return t=>{if(e&&t.kind===i)return Object.prototype.hasOwnProperty.call(e,t.name)?e[t.name]:void 0}}(i);let r=L(t,e.id,"out");for(let e=0;e<=25&&r;e+=1){s.push(r.id);const e=t.nodesById.get(r.target);if(M(e))return{destination:e,passedNodeIds:o,takenEdgeIds:s};if(!$(e))break;o.push(e.id);const i=e.cases.find((t=>V(t,n)));r=L(t,e.id,i?i.id:"default")}return{passedNodeIds:o,takenEdgeIds:s}}function Y(t,e,i,o={}){const s=o.index??O(t),n=s.nodesById.get(e.nodeId);if(!M(n))return{outcome:"ignored",reason:"unknown_position"};const r=[];for(const t of W(s,n.id)){if(!Q(t,i))continue;r.push(t.id);const e=X(s,t,i);if(e.destination&&e.destination.id!==n.id)return{outcome:"moved",position:{nodeId:e.destination.id},firedTriggerId:t.id,passedNodeIds:e.passedNodeIds,takenEdgeIds:e.takenEdgeIds}}return r.length>0?{outcome:"stayed",firedTriggerIds:r}:{outcome:"ignored",reason:"no_matching_trigger"}}function tt(t,e,i){t.some((t=>i(t,e)))||t.push(e)}function et(t,e,i,o){const s=[],n=L(t,e,"out");n&&s.push(n.target);const r=new Set;for(;s.length>0;){const e=s.pop();if(r.has(e))continue;r.add(e);const n=t.nodesById.get(e);if($(n)){for(const t of n.cases)for(const e of t.tests)"input"===e.field.kind&&tt(o,{table:i,column:e.field.name},((t,e)=>t.table===e.table&&t.column===e.column));for(const i of H(t,e))s.push(i.target)}}}function it(t,e,i={}){const o=i.index??O(t),s={inputTables:[],inputColumns:[],actionIds:[],pageEventNames:[],schedules:[]},n=(t,e)=>t===e;for(const t of W(o,e)){const e=t.trigger;switch(e.kind){case"input":if(""===e.table)break;tt(s.inputTables,e.table,n),et(o,t.id,e.table,s.inputColumns);break;case"action":""!==e.actionId&&tt(s.actionIds,e.actionId,n);break;case"pageEvent":""!==e.name&&tt(s.pageEventNames,e.name,n);break;case"scheduled":s.schedules.push({triggerId:t.id,schedule:e.schedule})}}return s}class ot{issues=[];report(t,e){this.issues.push({code:t,severity:"error",detail:e})}}function st(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function nt(t){return"string"==typeof t&&S.test(t)?t:void 0}function rt(t,e=200){return"string"==typeof t&&t.length<=e?t:void 0}function at(t){return"text"===t||"number"===t||"boolean"===t?t:void 0}function dt(t,e,i){if(!st(t))return void i.report("malformed",e);const o=function(t,e,i){if(!st(t))return void i.report("malformed",e);const o="input"===t.kind||"event"===t.kind?t.kind:void 0,s=rt(t.name,64),n=at(t.type);if(o&&void 0!==s&&n)return{kind:o,name:s,type:n};i.report("malformed",e)}(t.field,`${e}.field`,i),s=function(t){return"string"==typeof t&&P.includes(t)?t:void 0}(t.operator);let n;return s||i.report("malformed",`${e}.operator`),void 0!==t.value&&(n=function(t){return null===t||"boolean"==typeof t?t:"number"==typeof t?Number.isFinite(t)?t:void 0:rt(t)}(t.value),void 0===n&&i.report("malformed",`${e}.value`)),o&&s?void 0===n?{field:o,operator:s}:{field:o,operator:s,value:n}:void 0}function lt(t,e,i){if(st(t))switch(t.kind){case"input":{const o=rt(t.table);return void 0===o&&i.report("malformed",`${e}.table`),void 0===o?void 0:{kind:"input",table:o}}case"action":{const o=rt(t.actionId);return void 0===o&&i.report("malformed",`${e}.actionId`),void 0===o?void 0:{kind:"action",actionId:o}}case"pageEvent":{const o=rt(t.name,64);void 0===o&&i.report("malformed",`${e}.name`);const s=function(t,e,i){if(!Array.isArray(t)||t.length>100)return void i.report("malformed",e);const o=[];return t.forEach(((t,s)=>{const n=st(t)?rt(t.name,64):void 0,r=st(t)?at(t.type):void 0;void 0!==n&&r?o.push({name:n,type:r}):i.report("malformed",`${e}[${s}]`)})),o}(t.values,`${e}.values`,i);return void 0!==o&&s?{kind:"pageEvent",name:o,values:s}:void 0}case"scheduled":{const o=function(t,e,i){if(st(t)&&"after"===t.mode&&"number"==typeof t.amount&&G(t.unit)&&Number.isFinite(t.amount))return{mode:"after",amount:t.amount,unit:t.unit};if(st(t)&&"at"===t.mode){const e=rt(t.at,64);if(void 0!==e)return{mode:"at",at:e}}i.report("malformed",e)}(t.schedule,`${e}.schedule`,i);return o?{kind:"scheduled",schedule:o}:void 0}default:return void i.report("unknown_trigger_kind",`${e}.kind`)}else i.report("malformed",e)}function ut(t,e,i){if(!st(t))return void i.report("malformed",e);const o=nt(t.id);o||i.report("bad_id",`${e}.id`);const s=function(t){if(void 0!==t)return st(t)&&"number"==typeof t.x&&"number"==typeof t.y&&Number.isFinite(t.x)&&Number.isFinite(t.y)?{x:t.x,y:t.y}:"invalid"}(t.position);"invalid"===s&&i.report("malformed",`${e}.position`);const n=o&&"invalid"!==s?s?{id:o,position:s}:{id:o}:void 0;switch(t.type){case"composition":{const o=rt(t.compositionId,200);if(void 0===o&&i.report("malformed",`${e}.compositionId`),void 0!==t.startsHere&&"boolean"!=typeof t.startsHere)return void i.report("malformed",`${e}.startsHere`);if(!n||void 0===o)return;return!0===t.startsHere?{...n,type:"composition",compositionId:o,startsHere:!0}:{...n,type:"composition",compositionId:o}}case"trigger":{const o=lt(t.trigger,`${e}.trigger`,i);return n&&o?{...n,type:"trigger",trigger:o}:void 0}case"condition":{if(!Array.isArray(t.cases)||t.cases.length>100)return void i.report("malformed",`${e}.cases`);const o=[];return t.cases.forEach(((t,s)=>{const n=function(t,e,i){if(!st(t)||!Array.isArray(t.tests)||t.tests.length>100)return void i.report("malformed",e);const o=nt(t.id),s="all"===t.match||"any"===t.match?t.match:void 0;let n;o||i.report("bad_id",`${e}.id`),s||i.report("malformed",`${e}.match`),void 0!==t.label&&(n=rt(t.label),void 0===n&&i.report("malformed",`${e}.label`));const r=[];return t.tests.forEach(((t,o)=>{const s=dt(t,`${e}.tests[${o}]`,i);s&&r.push(s)})),o&&s?void 0===n?{id:o,match:s,tests:r}:{id:o,label:n,match:s,tests:r}:void 0}(t,`${e}.cases[${s}]`,i);n&&o.push(n)})),n?{...n,type:"condition",cases:o}:void 0}default:return void i.report("unknown_node_type",`${e}.type`)}}function ct(t){const e=new ot;if(!st(t))return e.report("malformed","graph"),{issues:e.issues};if(1!==t.schemaVersion)return e.report("schema_version","schemaVersion"),{issues:e.issues};if(!Array.isArray(t.nodes)||!Array.isArray(t.edges))return e.report("malformed","nodes/edges"),{issues:e.issues};if(t.nodes.length>100||t.edges.length>300)return e.report("graph_too_large","nodes/edges"),{issues:e.issues};const i=[];t.nodes.forEach(((t,o)=>{const s=ut(t,`nodes[${o}]`,e);s&&i.push(s)}));const o=[];return t.edges.forEach(((t,i)=>{const s=function(t,e,i){if(!st(t))return void i.report("malformed",e);const o=nt(t.id),s=nt(t.source),n=nt(t.sourcePort),r=nt(t.target);return o||i.report("bad_id",`${e}.id`),s&&n&&r||i.report("malformed",e),o&&s&&n&&r?{id:o,source:s,sourcePort:n,target:r}:void 0}(t,`edges[${i}]`,e);s&&o.push(s)})),e.issues.length>0?{issues:e.issues}:{graph:{schemaVersion:1,nodes:i,edges:o},issues:[]}}const ht=/^[A-Za-z0-9_.:-]{1,128}$/;function pt(t){return`widgetic_workflow_${t}`}function ft(t){return"string"==typeof t&&ht.test(t)}function gt(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0}function mt(t,e){try{b(pt(t),JSON.stringify({v:1,versionId:e.versionId,nodeId:e.nodeId,compositionId:e.compositionId,startedAt:e.startedAt,reachedAt:e.reachedAt}))}catch(e){v.debug("[workflows] The visitor's position could not be kept",{workflowId:t,error:e})}}function vt(t){w(pt(t))}const wt=/^[A-Za-z0-9_-]{1,64}$/,bt=new Set(["n","e","f"]);class yt{constructor(t){this.pending=[],this.lastEventOf=new Map,this.flushTimer=null,this.stopped=!1,this.listening=!1,this.onPageHide=()=>{this.flushBeforeLeaving()},this.onVisibilityChange=()=>{"hidden"===document.visibilityState&&this.flushBeforeLeaving()},this.options=t}isStopped(){return this.stopped}start(){this.listening||this.stopped||(this.listening=!0,window.addEventListener("pagehide",this.onPageHide),document.addEventListener("visibilitychange",this.onVisibilityChange))}count(t,e,i=1){if(this.stopped||!this.options.token)return;if(!bt.has(t)||!wt.test(e)||!Number.isInteger(i)||i<1)return;const o=`${t}:${e}`;let s=i;for(;s>0;){let i=this.lastEventOf.get(o);(!i||i.c>=50)&&(i={k:t,id:e,c:0},this.pending.push(i),this.lastEventOf.set(o,i));const n=Math.min(s,50-i.c);i.c+=n,s-=n}this.pending.length>=100?this.flush():null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}flushBeforeLeaving(){if(!this.stopped&&this.options.token)for(;this.pending.length>0;){const t=this.takeBatch();if(!this.options.isActive())return void this.forgetPending();this.sendWithBeacon(t)}}dispose(){this.stopped=!0,this.forgetPending(),this.listening&&(window.removeEventListener("pagehide",this.onPageHide),document.removeEventListener("visibilitychange",this.onVisibilityChange),this.listening=!1)}takeBatch(){const t=this.pending.splice(0,100);for(const e of t){const t=`${e.k}:${e.id}`;this.lastEventOf.get(t)===e&&this.lastEventOf.delete(t)}return t}forgetPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.pending=[],this.lastEventOf.clear()}flush(){if(null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.stopped||0===this.pending.length)return;if(!this.options.isActive())return void this.forgetPending();const t=this.takeBatch();this.sendWithRequest(t),this.pending.length>0&&null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}reportAddress(){return`${this.options.apiOrigin}/embed/workflows/${encodeURIComponent(this.options.workflowId)}/events`}reportBody(t){return JSON.stringify({versionId:this.options.versionId,token:this.options.token,events:t.map((t=>t.c>1?{k:t.k,id:t.id,c:t.c}:{k:t.k,id:t.id}))})}sendWithBeacon(t){try{const e=this.reportBody(t),i="undefined"!=typeof navigator?navigator.sendBeacon:void 0;if("function"==typeof i&&i.call(navigator,this.reportAddress(),new Blob([e],{type:"text/plain"})))return void v.debug("[workflows] Counts handed to the browser to send",{eventCount:t.length})}catch(t){v.debug("[workflows] The browser would not take counts to send as the page closes",{error:t})}this.sendWithRequest(t)}sendWithRequest(e){return t(this,void 0,void 0,(function*(){try{const t=yield fetch(this.reportAddress(),{method:"POST",mode:"cors",credentials:"omit",keepalive:!0,headers:{"Content-Type":"text/plain"},body:this.reportBody(e)});if(401===t.status)return v.warn("[workflows] The gateway refused the token for counts, so this embed stops reporting",{workflowId:this.options.workflowId}),void this.dispose();v.debug("[workflows] Counts sent",{eventCount:e.length,status:t.status})}catch(t){v.debug("[workflows] Counts could not be sent and were dropped",{eventCount:e.length,error:t})}}))}}const It=/^[a-z0-9]{1,8}(-[a-z0-9]{1,8}){0,4}$/,kt=/^[A-Za-z0-9_.:-]{1,128}$/;function Tt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function At(t){if("string"!=typeof t||t.length>35)return null;const e=t.toLowerCase();return It.test(e)?e:null}function Et(){var t,e;try{if("undefined"==typeof navigator)return[];const i=String(null!==(t=navigator.language)&&void 0!==t?t:"").toLowerCase(),o=((null===(e=navigator.languages)||void 0===e?void 0:e.map((t=>String(t).toLowerCase())))||[i]).flatMap((t=>{const e=[t];return t.includes("-")&&e.push(t.split("-")[0]),e}));return[...new Set(o)].filter((t=>""!==t))}catch(t){return v.debug("[workflows] The languages of the browser could not be read",{error:t}),[]}}function Ct(t,e,i){if(!e||0===i.length||!Object.prototype.hasOwnProperty.call(e,t))return t;const o=e[t],{language:s}=function(t,e){const i=Object.keys(e.compositions);for(const e of t)if(i.includes(e))return{language:e,match:"exact"};for(const e of t){const t=e.split("-")[0],o=i.find((e=>e.startsWith(`${t}-`)||e===t));if(void 0!==o)return{language:o,match:"family"}}return{language:e.rootLanguage,match:"root"}}(i,o);return s===o.rootLanguage?t:o.compositions[s]||t}const St=/^[A-Za-z0-9_-]{1,64}$/,Ot=/^[A-Za-z0-9_.:-]{1,128}$/;function Nt(t){return St.test(t)}function Ht(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function Mt(t,e){var i;if(!Ht(t)||!0!==t.success||!Ht(t.data))return{kind:"unreadable"};const o=t.data;if("paused"===o.status)return{kind:"paused"};if("live"!==o.status)return{kind:"unreadable"};if("string"!=typeof o.versionId||!Ot.test(o.versionId))return{kind:"unreadable"};const s=ct(o.graph);if(!s.graph||s.issues.length>0)return v.warn("[workflows] The published graph could not be read, so the embed stays a plain embed",{workflowId:e,issueCount:s.issues.length,firstIssue:null===(i=s.issues[0])||void 0===i?void 0:i.code}),{kind:"unreadable"};const n={workflowId:"string"==typeof o.workflowId?o.workflowId:e,versionId:o.versionId,timezone:"string"==typeof o.timezone&&""!==o.timezone.trim()&&o.timezone.length<=64?o.timezone:"UTC",graph:s.graph};"number"==typeof o.versionNumber&&Number.isInteger(o.versionNumber)&&(n.versionNumber=o.versionNumber),"string"==typeof o.publishedAt&&(n.publishedAt=o.publishedAt),"string"==typeof o.startCompositionId&&Ot.test(o.startCompositionId)&&(n.startCompositionId=o.startCompositionId);const r=function(t){if(!Tt(t))return;const e=Object.create(null);let i=0;for(const[o,s]of Object.entries(t)){if(i>=64)break;if(!kt.test(o)||!Tt(s))continue;const t=At(s.rootLanguage);if(null===t||!Tt(s.compositions))continue;const n=Object.create(null);let r=0;for(const[t,e]of Object.entries(s.compositions)){if(r>=128)break;const i=At(t);null!==i&&"string"==typeof e&&kt.test(e)&&(n[i]=e,r+=1)}0!==r&&(e[o]={rootLanguage:t,compositions:n},i+=1)}return 0===i?void 0:e}(o.translations);return r&&(n.translations=r),"string"==typeof o.eventToken&&""!==o.eventToken&&o.eventToken.length<=2048&&(n.eventToken=o.eventToken),{kind:"live",workflow:n}}function $t(e,i){return t(this,void 0,void 0,(function*(){const t=new AbortController,o=setTimeout((()=>t.abort()),1e4);try{const o=yield fetch(e,{method:"GET",mode:"cors",signal:t.signal});if(404===o.status)return{kind:"missing"};if(!o.ok)return{kind:"unreachable"};let s;try{s=yield o.json()}catch(t){return{kind:"unreadable"}}const n=Mt(s,i);return"live"===n.kind?{kind:"live",workflow:n.workflow}:n}catch(t){return v.debug("[workflows] A host could not be reached",{workflowId:i,error:t}),{kind:"unreachable"}}finally{clearTimeout(o)}}))}const Wt=new Map;function Lt(e,i={}){var o,s;if(!Nt(e)||void 0!==i.versionId&&!Ot.test(i.versionId))return Promise.resolve({status:"unavailable",reason:"not_found"});const n=`${e}|${null!==(o=i.versionId)&&void 0!==o?o:""}|${(null!==(s=i.origins)&&void 0!==s?s:[]).join(",")}`,r=Wt.get(n);if(r)return r;const a=function(e,i){return t(this,void 0,void 0,(function*(){var t;const o=null!==(t=i.origins)&&void 0!==t?t:I(),s=i.versionId?`/embed/workflows/${encodeURIComponent(e)}/versions/${encodeURIComponent(i.versionId)}`:`/embed/workflows/${encodeURIComponent(e)}`;let n=!1,r=!1;for(const t of o){const i=yield $t(`${t}${s}`,e);if("live"===i.kind)return{status:"live",workflow:i.workflow,origin:t};if("paused"===i.kind)return{status:"paused"};"missing"===i.kind&&(n=!0),"unreadable"===i.kind&&(r=!0)}const a=n?"not_found":r?"unreadable":"unreachable";return v.debug("[workflows] The workflow is not available",{workflowId:e,reason:a}),{status:"unavailable",reason:a}}))}(e,i);return Wt.set(n,a),a.finally((()=>{Wt.get(n)===a&&Wt.delete(n)})),a}const Ft={clicks:"click",submissions:"submit",plays:"play"},Pt=new Set(["__proto__","constructor","prototype"]);function Rt(t){const e=t.detail;return"object"!=typeof e||null===e||Array.isArray(e)?{}:e}function jt(t,e){return("submissions"!==t.metric||"FORM"===e.tagName)&&(("plays"!==t.metric||"VIDEO"===e.tagName||"AUDIO"===e.tagName)&&(null!==t.selector?y(e,t.selector):"clicks"!==t.metric||null!==e.closest('button, a, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-click-track]')))}function xt({stage:t,watch:i,emit:o}){var s;let n=!1;const r=[];if(i.inputTables.length>0){const e=new Map;for(const{table:t,column:o}of i.inputColumns){const i=null!==(s=e.get(t))&&void 0!==s?s:new Set;i.add(o),e.set(t,i)}const a=new Set,d=t=>{var s;if(n)return;const r=Rt(t),d=r.table;if("string"!=typeof d||!i.inputTables.includes(d))return;if("string"==typeof r.entryId&&""!==r.entryId){const t=`${d}:${r.entryId}`;if(a.has(t))return;if(a.add(t),a.size>100){const t=a.values().next().value;void 0!==t&&a.delete(t)}}const l=function(t,e){const i={};if("object"!=typeof t||null===t||Array.isArray(t))return i;for(const o of e){if(Pt.has(o))continue;if(!Object.prototype.hasOwnProperty.call(t,o))continue;const e=t[o];"string"==typeof e?i[o]=e.length>200?e.slice(0,200):e:("number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e)&&(i[o]=e)}return i}(r.values,null!==(s=e.get(d))&&void 0!==s?s:new Set);v.debug("[workflows] An entry was saved in a watched table",{table:d,valueCount:Object.keys(l).length}),o([{type:"input",table:d,values:l}])};t.addEventListener("widgetic:submitted",d),r.push((()=>t.removeEventListener("widgetic:submitted",d)))}if(i.actionIds.length>0){const s=t=>{if(n)return;const e=Rt(t);let s=null;"string"==typeof e.goalId?s=e.goalId:"string"==typeof e.metric&&""!==e.metric&&(s="string"==typeof e.goalTarget&&""!==e.goalTarget?`${e.metric}@${e.goalTarget}`:e.metric),null!==s&&i.actionIds.includes(s)&&(v.debug("[workflows] A widget reported a watched action",{actionId:s}),o([{type:"action",actionId:s}]))};t.addEventListener("widgetic:goal",s),r.push((()=>t.removeEventListener("widgetic:goal",s)));const d=[];for(const t of i.actionIds){const i=e(t);i&&(a=i.metric,Object.prototype.hasOwnProperty.call(Ft,a))&&d.push({actionId:t,metric:i.metric,selector:i.selector})}if(d.length>0){let e=null,i=()=>{};const s=t=>{const e=t.target instanceof Element?t.target:null;if(!e)return[];const i=[];for(const o of d)Ft[o.metric]===t.type&&jt(o,e)&&i.push({type:"action",actionId:o.actionId});return i},a=t=>{if(n)return;const e=s(t);0!==e.length&&(v.debug("[workflows] A watched action happened in the widget",{actionIds:e.map((t=>t.actionId))}),o(e))},l=()=>{var o;const s=t.querySelector("[data-widgetic-direct]"),n=null!==(o=null==s?void 0:s.shadowRoot)&&void 0!==o?o:null;if(!n||n===e)return;i();const r=new Set(d.map((t=>Ft[t.metric])));for(const t of r)n.addEventListener(t,a,!0);e=n,i=()=>{for(const t of r)n.removeEventListener(t,a,!0);e=null,i=()=>{}}};t.addEventListener("widgetic:ready",l),r.push((()=>t.removeEventListener("widgetic:ready",l))),r.push((()=>i())),l()}}var a;return{stop:()=>{if(!n){n=!0;for(const t of r)try{t()}catch(t){v.debug("[workflows] A listener could not be removed",{error:t})}}}}}const Bt=50,_t=2e3,zt=150,Dt=5,Vt=300,Ut=2e4;function qt(t,e,i,o){const s=t.getAttribute(e);if(null===s||!/^\d+$/.test(s.trim()))return i;const n=Number.parseInt(s.trim(),10);return Number.isFinite(n)?Math.min(n,o):i}function Zt(t,e,i){const o="number"==typeof i&&Number.isFinite(i)&&i>0?Math.min(e.maxHeight,Math.floor(i)):e.maxHeight,s=Math.min(e.minHeight,o);return Number.isNaN(t)?s:Math.max(s,Math.min(o,Math.ceil(t)))}function Gt(t,e,i){return null===t||e!==t&&Math.abs(e-t)>=i}const Jt=o,Kt=["width","height","resize","resize-mode","render-mode","use-iframe","theme","mode","colors","sandbox","autoload","adaptive","responsive"],Qt=["values","context","media-resolver"],Xt=["design","content","content-items","contentitems","items"];function Yt(t){if("undefined"==typeof ResizeObserver)return null;try{return new ResizeObserver((e=>{t(e.map((t=>({target:t.target,height:t.contentRect.height}))))}))}catch(t){return v.debug("[workflows] The browser could not watch heights",{error:t}),null}}function te(t){return t.getBoundingClientRect().height}function ee(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch(t){return!1}}function ie(t){return"number"==typeof t&&Number.isFinite(t)&&t>0}class oe{constructor(t){var e;this.current=null,this.incoming=null,this.heightObserver=null,this.attributeObserver=null,this.autoscaleOn=!1,this.appliedHeight=null,this.debounceTimer=null,this.pendingHeight=null,this.destroyed=!1,this.warnedAboutFrameWithoutHeight=!1,this.host=t.host,this.services=t.services,this.prefersReducedMotion=null!==(e=t.prefersReducedMotion)&&void 0!==e?e:ee,this.widthOverride=t.widthOverride&&""!==t.widthOverride?t.widthOverride:null,this.viewportElement=document.createElement("div"),this.viewportElement.setAttribute("data-widgetic-workflow-viewport","1"),this.viewportElement.setAttribute("data-widgetic-internal","1"),this.viewportElement.style.display="block",this.observeMirroredAttributes()}currentStage(){var t,e;return null!==(e=null===(t=this.current)||void 0===t?void 0:t.element)&&void 0!==e?e:null}currentCompositionId(){var t,e;return null!==(e=null===(t=this.current)||void 0===t?void 0:t.compositionId)&&void 0!==e?e:null}showFirstStage(t,e=t){if(this.current)return{stage:this.current.element,ready:Promise.resolve({status:"ready"})};this.viewportElement.isConnected||this.host.appendChild(this.viewportElement),this.holdRoomFor(t);const i=this.buildStage(t,!0,e);this.current=i;const o=this.waitUntilShown(i,null,(t=>{if("ready"===t.status&&!this.destroyed&&this.autoscaleOn&&this.current===i){const t=this.measure(i.element);ie(t)&&this.applyHeight(t,"immediate")}}));return this.viewportElement.appendChild(i.element),this.services.hydrate(i.element),{stage:i.element,ready:o}}enableAutoscale(){var t,e;if(!this.destroyed&&!this.autoscaleOn&&(this.autoscaleOn=!0,this.viewportElement.style.position="relative",this.viewportElement.style.overflow="hidden",this.current&&this.positionAsLayer(this.current.element),this.heightObserver=(null!==(t=this.services.createHeightObserver)&&void 0!==t?t:Yt)((t=>this.onHeightsReported(t))),this.current)){null===(e=this.heightObserver)||void 0===e||e.observe(this.current.element);const t=this.measure(this.current.element);ie(t)&&this.applyHeight(t,"immediate")}}releaseAutoscale(){var t;if(this.destroyed)return;this.autoscaleOn=!1,this.clearHeightTimer(),null===(t=this.heightObserver)||void 0===t||t.disconnect(),this.heightObserver=null,this.appliedHeight=null;const e=this.viewportElement.style;for(const t of["position","overflow","height","min-height","transition"])e.removeProperty(t);this.current&&this.positionInFlow(this.current.element)}swapTo(e){return t(this,arguments,void 0,(function*(t,e=t){var o,s,n;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming)return{status:"failed",reason:"busy"};this.enableAutoscale();const r=this.buildStage(t,!1,e);this.incoming=r,this.hideBeside(r.element);const a=this.waitUntilShown(r,null!==(o=this.services.readyTimeoutMilliseconds)&&void 0!==o?o:8e3);this.viewportElement.appendChild(r.element),this.services.hydrate(r.element);const d=yield a;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming=null,"failed"===d.status)return this.removeStage(r),"timeout"===d.reason&&i(this.host,t,"workflow_step_timeout"),v.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:t,reason:d.reason}),Object.assign({status:"failed",reason:"stopped"===d.reason?"stopped":d.reason},d.code?{code:d.code}:{});const l=this.current;this.revealInPlace(r.element),this.current=r,null===(s=this.heightObserver)||void 0===s||s.observe(r.element);const u=this.measure(r.element);return ie(u)&&this.applyHeight(u,"immediate"),l&&(null===(n=this.heightObserver)||void 0===n||n.unobserve(l.element),this.removeStage(l)),{status:"shown",stage:r.element}}))}destroy(){var t,e,i;if(this.destroyed)return;this.destroyed=!0,this.clearHeightTimer(),null===(t=this.heightObserver)||void 0===t||t.disconnect(),this.heightObserver=null,null===(e=this.attributeObserver)||void 0===e||e.disconnect(),this.attributeObserver=null;const o=[this.current,this.incoming];this.current=null,this.incoming=null;for(const t of o)t&&(null===(i=t.cancelWait)||void 0===i||i.call(t),this.removeStage(t));this.viewportElement.remove()}buildStage(t,e,i){var o,s,n;const r=document.createElement("widgetic");r.setAttribute("composition-id",t),r.setAttribute(Jt,"1"),r.style.display="block";for(const t of Kt){const e=this.host.getAttribute(t);null!==e&&r.setAttribute(t,e)}this.widthOverride&&r.setAttribute("width",this.widthOverride);for(const t of Qt){const e=this.host.getAttribute(t);null!==e&&r.setAttribute(t,e)}const a=i===(null!==(o=this.host.getAttribute("composition-id"))&&void 0!==o?o:"").trim();a&&this.copyWhatThePageWroteForTheTagComposition(r);const d={element:r,compositionId:t,standsFor:i,reportedHeight:!1,cancelWait:null,stopListening:()=>{}},l=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.height;if("number"!=typeof i||!ie(i))return;const o=r.querySelector("iframe");o&&(o.style.height=`${Math.ceil(i)}px`,d.reportedHeight=!0)};r.addEventListener("widgetic:resize",l),d.stopListening=()=>r.removeEventListener("widgetic:resize",l);try{null===(n=(s=this.services).onStageCreated)||void 0===n||n.call(s,r,{compositionId:t,standsFor:i,isFirst:e,carriesPageContent:a})}catch(e){v.debug("[workflows] A listener for a new stage failed",{compositionId:t,error:e})}return d}copyWhatThePageWroteForTheTagComposition(t){for(const e of Array.from(this.host.attributes))E(e.name)||t.setAttribute(e.name,e.value);for(const e of Xt){const i=this.host.getAttribute(e);null!==i&&t.setAttribute(e,i)}for(const e of C(this.host))t.appendChild(e.cloneNode(!0))}observeMirroredAttributes(){const t="undefined"!=typeof MutationObserver?MutationObserver:null;if(t)try{this.attributeObserver=new t((t=>{t.some((t=>{var e;return"attributes"===t.type&&Qt.includes(null!==(e=t.attributeName)&&void 0!==e?e:"")}))&&this.mirrorAttributesToStages()})),this.attributeObserver.observe(this.host,{attributes:!0,attributeFilter:[...Qt]})}catch(t){this.attributeObserver=null,v.debug("[workflows] The tag cannot be watched for changes",{error:t})}}mirrorAttributesToStages(){for(const t of[this.current,this.incoming])if(t)for(const e of Qt){const i=this.host.getAttribute(e);null===i?t.element.removeAttribute(e):t.element.getAttribute(e)!==i&&t.element.setAttribute(e,i)}}waitUntilShown(t,e,i){return new Promise((o=>{const s=t.element;let n=null,r=!1;const a=e=>{if(!r){r=!0,null!==n&&clearTimeout(n),s.removeEventListener("widgetic:ready",d),s.removeEventListener("widgetic:error",l),s.removeEventListener("load",u,!0),t.cancelWait=null;try{null==i||i(e)}catch(e){v.debug("[workflows] A stage could not be settled",{compositionId:t.compositionId,error:e})}o(e)}},d=()=>a({status:"ready"}),l=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.code;a(Object.assign({status:"failed",reason:"error"},"string"==typeof i?{code:i}:{}))},u=t=>{t.target instanceof HTMLIFrameElement&&a({status:"ready"})};s.addEventListener("widgetic:ready",d),s.addEventListener("widgetic:error",l),s.addEventListener("load",u,!0),t.cancelWait=()=>a({status:"failed",reason:"stopped"}),null!==e&&(n=setTimeout((()=>a({status:"failed",reason:"timeout"})),e))}))}removeStage(t){var e,i;t.stopListening(),t.element.querySelector("iframe")&&!t.reportedHeight&&this.noteFrameWithoutHeight(t.compositionId),t.element.remove();try{null===(i=(e=this.services).onStageRemoved)||void 0===i||i.call(e,t.element)}catch(e){v.debug("[workflows] A listener for a removed stage failed",{compositionId:t.compositionId,error:e})}}noteFrameWithoutHeight(t){this.warnedAboutFrameWithoutHeight||(this.warnedAboutFrameWithoutHeight=!0,v.debug("[workflows] A widget in a frame does not report its height (widgetic:resize), so the embed keeps the height of its frame",{compositionId:t}))}hideBeside(t){this.positionAsLayer(t),t.style.visibility="hidden",t.style.pointerEvents="none",t.setAttribute("aria-hidden","true")}revealInPlace(t){t.style.removeProperty("visibility"),t.style.removeProperty("pointer-events"),t.removeAttribute("aria-hidden")}positionAsLayer(t){t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.width="100%"}positionInFlow(t){for(const e of["position","top","left","width"])t.style.removeProperty(e)}measure(t){var e;try{return(null!==(e=this.services.measureStageHeight)&&void 0!==e?e:te)(t)}catch(t){return v.debug("[workflows] The height of a stage could not be read",{error:t}),0}}holdRoomFor(t){const e=k(t);if(null===e)return;const i=this.settings();this.viewportElement.style.minHeight=`${Zt(e,i,this.overlayCap())}px`}settings(){return function(t,e={}){const i=qt(t,"autoscale-min-height",Bt,Ut),o=qt(t,"autoscale-max-height",_t,Ut);return{minHeight:i,maxHeight:Math.max(o,i),debounceDelay:qt(t,"autoscale-debounce",zt,5e3),threshold:qt(t,"autoscale-threshold",Dt,Ut),animate:"false"!==t.getAttribute("autoscale-animate")&&!0!==e.prefersReducedMotion,animationDuration:qt(t,"autoscale-animation-duration",Vt,5e3)}}(this.host,{prefersReducedMotion:this.prefersReducedMotion()})}overlayCap(){return this.host.hasAttribute(s)?Math.floor(.9*window.innerHeight):null}onHeightsReported(t){if(!this.destroyed&&this.autoscaleOn&&this.current)for(const e of t)e.target===this.current.element&&ie(e.height)&&this.applyHeight(e.height,"observed")}applyHeight(t,e){const i=this.settings(),o=Zt(t,i,this.overlayCap());if("immediate"===e)return this.clearHeightTimer(),void this.setHeight(o,i);Gt(this.appliedHeight,o,i.threshold)?(this.pendingHeight=o,null!==this.debounceTimer&&clearTimeout(this.debounceTimer),this.debounceTimer=setTimeout((()=>{this.debounceTimer=null;const t=this.pendingHeight;if(this.pendingHeight=null,null===t||this.destroyed||!this.autoscaleOn)return;const e=this.settings();Gt(this.appliedHeight,t,e.threshold)&&this.setHeight(t,e)}),i.debounceDelay)):o===this.appliedHeight&&this.clearHeightTimer()}setHeight(t,e){var i;const o=this.viewportElement.style,s=null!==this.appliedHeight&&this.appliedHeight!==t;if(o.setProperty("transition",e.animate&&s?`height ${e.animationDuration}ms ease`:"none"),o.height=`${t}px`,o.removeProperty("min-height"),this.appliedHeight=t,this.current){const e=Number.parseInt(null!==(i=this.host.getAttribute("height"))&&void 0!==i?i:"",10);T(this.current.compositionId,t,Number.isFinite(e)?e:t)}}clearHeightTimer(){null!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingHeight=null}}const se=3e4,ne=2e3;function re(t,e,i){var o;try{p(t,f(e,i)),null===(o=g(t))||void 0===o||o.sendWorkflowWatch(i)}catch(t){v.debug("[workflows] A widget could not be told what to report",{compositionId:e,error:t})}}function ae(t){try{A(t).then((t=>{var e;const i="found"===t.status?null===(e=t.payload.direct)||void 0===e?void 0:e.moduleUrl:void 0;i&&h(i)})).catch((()=>{}))}catch(e){v.debug("[workflows] A composition could not be got ready",{compositionId:t,error:e})}}function de(t){const e=window;if("function"==typeof e.requestIdleCallback){const i=e.requestIdleCallback((()=>t()),{timeout:5e3});return()=>{var t;return null===(t=e.cancelIdleCallback)||void 0===t?void 0:t.call(e,i)}}const i=setTimeout(t,1500);return()=>clearTimeout(i)}class le{constructor(t,e,i,o,s){this.host=t,this.workflowId=e,this.tagCompositionId=i,this.options=o,this.services=s,this.mode="loading",this.stages=new Map,this.pageEvents=new r,this.removeListeners=[],this.workflow=null,this.index=null,this.counts=null,this.position=null,this.stepping=!1,this.pendingStageNodeId=null,this.retryTimer=null,this.scheduleTimers=new Set,this.cancelIdleWork=null,this.readiedCompositions=new Set,this.displayBeforeMounting="",this.hostIsMarkedMounted=!1,this.copiesThatCannotBeShown=new Set,this.cancelWaitForAnswer=null,this.onPageEvent=t=>{if("ended"===this.mode||"plain"===this.mode)return;const e=a(t.detail);e?"running"!==this.mode||this.stepping?this.pageEvents.add(e):this.hasEnded()||this.react([{type:"pageEvent",name:e.name,values:e.values}]):v.debug("[workflows] An event of the page was ignored: it is not one a workflow can wait for")},this.onVisibilityChange=()=>{"running"!==this.mode||this.stepping||this.hasEnded()||this.armSchedules()},this.visitorLanguages=this.readVisitorLanguages();const n=s.viewport;this.viewport=new oe(Object.assign(Object.assign(Object.assign({host:t},n.prefersReducedMotion?{prefersReducedMotion:n.prefersReducedMotion}:{}),o.width?{widthOverride:o.width}:{}),{services:Object.assign(Object.assign(Object.assign(Object.assign({hydrate:o.hydrate},n.createHeightObserver?{createHeightObserver:n.createHeightObserver}:{}),n.measureStageHeight?{measureStageHeight:n.measureStageHeight}:{}),void 0!==n.readyTimeoutMilliseconds?{readyTimeoutMilliseconds:n.readyTimeoutMilliseconds}:{}),{onStageCreated:(t,e)=>this.onStageCreated(t,e.compositionId),onStageRemoved:t=>this.onStageRemoved(t)})}))}readVisitorLanguages(){try{const t=this.services.visitorLanguages();return Array.isArray(t)?t.filter((t=>"string"==typeof t)):[]}catch(t){return v.debug("[workflows] The languages of the visitor could not be read",{error:t}),[]}}start(){var t;const e=function(t,e=Date.now()){const i=pt(t),o=m(i);if(null===o)return null;try{const i=JSON.parse(o);if("object"!=typeof i||null===i||Array.isArray(i))return null;const s=i;return 1!==s.v?null:ft(s.versionId)&&ft(s.nodeId)&&ft(s.compositionId)&&gt(s.startedAt)&&gt(s.reachedAt)?s.startedAt>e+864e5?null:e-s.startedAt>2592e6?(vt(t),v.debug("[workflows] The visitor's position is older than 30 days and was forgotten",{workflowId:t}),null):{versionId:s.versionId,nodeId:s.nodeId,compositionId:s.compositionId,startedAt:s.startedAt,reachedAt:Math.min(s.reachedAt,e)}:null}catch(e){return v.debug("[workflows] The kept position could not be read and is ignored",{workflowId:t,error:e}),null}}(this.workflowId),i=null!==(t=null==e?void 0:e.compositionId)&&void 0!==t?t:this.tagCompositionId;this.listenToThePage(),this.displayBeforeMounting=this.host.style.display,this.run(e,i)}run(e,i){return t(this,void 0,void 0,(function*(){var t;try{const o=this.services.fetchWorkflow(this.workflowId);this.readiedCompositions.add(i),this.services.prefetchComposition(i);const s=yield this.waitForAnswer(o);if(this.hasEnded())return;const n=this.compositionToShow("live"===(null==s?void 0:s.status)?s.workflow:null,i),r=this.showFirstComposition(n,i),[a,d]=yield Promise.all([o,r]);if(this.hasEnded())return;let l=d;if("failed"===l.status&&"stopped"!==l.reason&&n!==i&&(l=yield this.fallBackToTheComposition(n,i),this.hasEnded()))return;let u=e,c=i;if("failed"===l.status){if("stopped"===l.reason)return;if(!e||e.compositionId===this.tagCompositionId)return void this.refuse(l.code);{v.debug("[workflows] The composition a returning visitor was on cannot be shown, so they start again",{compositionId:e.compositionId}),vt(this.workflowId),u=null;const i=yield this.swapToComposition(this.tagCompositionId,"live"===a.status?a.workflow:null);if(this.hasEnded())return;if("shown"!==i.status)return void this.refuse(null!==(t=l.code)&&void 0!==t?t:"failed"===i.status?i.code:void 0);c=this.tagCompositionId}}if("live"!==a.status)return v.debug("[workflows] The workflow is not running, so the tag is a plain embed",{workflowId:this.workflowId,status:a.status}),void(yield this.becomePlain());let h=a.workflow,p=a.origin;if(u&&u.versionId!==h.versionId){const t=yield this.services.fetchWorkflow(this.workflowId,{versionId:u.versionId});if(this.hasEnded())return;"live"===t.status&&t.workflow.versionId===u.versionId?(h=t.workflow,p=t.origin):(v.debug("[workflows] The version a visitor started on cannot be read, so they continue as a new visitor",{versionId:u.versionId}),vt(this.workflowId),u=null)}const f=O(h.graph);let g=u&&this.fitsTheGraph(u,h,f)?u:null;const m=null===g;if(null===g){u&&(v.debug("[workflows] The place a visitor was kept at is not in the workflow, so they continue as a new visitor"),vt(this.workflowId));const t=function(t,e){for(const i of t.nodes)if("composition"===i.type&&i.compositionId===e)return i}(h.graph,this.tagCompositionId);if(!t)return v.debug("[workflows] The composition of the tag is not a block of the workflow, so the tag is a plain embed",{compositionId:this.tagCompositionId}),void(yield this.becomePlain());const e=Date.now();g={versionId:h.versionId,nodeId:t.id,compositionId:this.tagCompositionId,startedAt:e,reachedAt:e}}const w=yield this.showThePlace(g.compositionId,h,c);if(this.hasEnded())return;if("plain"===w)return void(yield this.becomePlain());this.activate(h,p,f,g,m)}catch(t){v.warn("[workflows] The workflow stopped working, so the tag stays as it is",{workflowId:this.workflowId,error:t}),this.becomePlainWithoutWaiting(),this.makeSureTheTagCompositionIsShown()}}))}waitForAnswer(t){const e=this.services.firstCompositionWaitMilliseconds;return new Promise(((i,o)=>{let s=null;const n=t=>{null!==s&&clearTimeout(s),s=null,this.cancelWaitForAnswer=null,i(t)};this.cancelWaitForAnswer=()=>n(null),s=setTimeout((()=>n(null)),Number.isFinite(e)?Math.max(0,e):0),t.then(n,(t=>{null!==s&&clearTimeout(s),s=null,this.cancelWaitForAnswer=null,o(t)}))}))}showFirstComposition(t,e){t!==e&&v.debug("[workflows] A composition is shown in the visitor's language",{compositionId:e,copyId:t});const{ready:i}=this.viewport.showFirstStage(t,e);return this.markHostMounted(),i}markHostMounted(){this.hostIsMarkedMounted||(this.hostIsMarkedMounted=!0,this.options.markMounted(this.host))}makeSureTheTagCompositionIsShown(){if("ended"!==this.mode&&null===this.viewport.currentStage())try{this.viewport.showFirstStage(this.tagCompositionId),this.markHostMounted()}catch(t){v.debug("[workflows] The composition of the tag could not be shown",{error:t})}}compositionToShow(t,e){if(!t)return e;const i=Ct(e,t.translations,this.visitorLanguages);return this.copiesThatCannotBeShown.has(i)?e:i}noteThatTheCopyCannotBeShown(t,e){this.copiesThatCannotBeShown.has(t)||(this.copiesThatCannotBeShown.add(t),v.debug("[workflows] The copy of a composition in the visitor's language cannot be shown, so the composition itself is",{compositionId:e,copyId:t}))}fallBackToTheComposition(e,i){return t(this,void 0,void 0,(function*(){this.noteThatTheCopyCannotBeShown(e,i);const t=yield this.viewport.swapTo(i);return"shown"===t.status?{status:"ready"}:Object.assign({status:"failed",reason:"busy"===t.reason?"error":t.reason},t.code?{code:t.code}:{})}))}swapToComposition(e,i){return t(this,void 0,void 0,(function*(){const t=this.compositionToShow(i,e);t!==e&&v.debug("[workflows] A composition is shown in the visitor's language",{compositionId:e,copyId:t});const o=yield this.viewport.swapTo(t,e);return"shown"===o.status||t===e||"stopped"===o.reason||"busy"===o.reason?o:this.hasEnded()?{status:"failed",reason:"stopped"}:(this.noteThatTheCopyCannotBeShown(t,e),this.viewport.swapTo(e))}))}showThePlace(e,i,o){return t(this,void 0,void 0,(function*(){const t=this.compositionToShow(i,e);if(o===e&&this.viewport.currentCompositionId()===t)return"shown";return"shown"===(yield this.swapToComposition(e,i)).status||o===e?"shown":"plain"}))}fitsTheGraph(t,e,i){if(t.versionId!==e.versionId)return!1;const o=i.nodesById.get(t.nodeId);return M(o)&&o.compositionId===t.compositionId}activate(t,e,i,o,s){var n;this.workflow=t,this.index=i,this.position=o,this.mode="running";const r=this.services.createCounts({workflowId:this.workflowId,versionId:t.versionId,token:null!==(n=t.eventToken)&&void 0!==n?n:null,apiOrigin:e,isActive:()=>"ended"!==this.mode&&this.host.isConnected});r.start(),this.counts=r,s&&(mt(this.workflowId,o),r.count("n",o.nodeId)),v.debug("[workflows] The workflow runs",{workflowId:this.workflowId,versionId:t.versionId,isNewVisitor:s}),this.viewport.enableAutoscale();const a=this.viewport.currentStage();a&&this.armStage(a,o.nodeId),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}becomePlain(){return t(this,void 0,void 0,(function*(){if(this.mode="plain",this.pageEvents.clear(),this.viewport.currentCompositionId()!==this.tagCompositionId){const t=yield this.viewport.swapTo(this.tagCompositionId);if(this.hasEnded())return;"shown"!==t.status&&v.debug("[workflows] The composition of the tag could not be shown")}this.viewport.releaseAutoscale()}))}becomePlainWithoutWaiting(){"ended"!==this.mode&&(this.mode="plain",this.pageEvents.clear(),this.cancelRetry(),this.cancelSchedules(),this.viewport.releaseAutoscale())}refuse(t){const e=this.viewport.currentStage(),i=(null==e?void 0:e.getAttribute(d))||t||"NOT_FOUND";this.stop(),this.host.removeAttribute("data-widgetic-mounting"),this.host.removeAttribute("data-widgetic-mounted"),this.host.style.display=this.displayBeforeMounting,this.host.setAttribute(d,i),v.debug("[workflows] The composition of the tag cannot be shown",{workflowId:this.workflowId,reason:i})}listenToThePage(){this.host.addEventListener(l,this.onPageEvent),document.addEventListener("visibilitychange",this.onVisibilityChange),this.removeListeners.push((()=>this.host.removeEventListener(l,this.onPageEvent)),(()=>document.removeEventListener("visibilitychange",this.onVisibilityChange)))}drainPageEvents(){const t=this.pageEvents.take();for(let e=0;e<t.length;e+=1){if("running"!==this.mode)return;if(this.stepping){for(const i of t.slice(e))this.pageEvents.add(i);return}const i=t[e];this.react([{type:"pageEvent",name:i.name,values:i.values}])}}onStageCreated(t,e){this.stages.set(t,{compositionId:e,signals:null,stopWatchingReady:null}),null!==this.pendingStageNodeId&&this.armStage(t,this.pendingStageNodeId)}onStageRemoved(t){var e,i;const o=this.stages.get(t);null===(e=null==o?void 0:o.signals)||void 0===e||e.stop(),null===(i=null==o?void 0:o.stopWatchingReady)||void 0===i||i.call(o),this.stages.delete(t)}armStage(t,e){var i,o,s;const n=this.workflow,r=this.index;if(!n||!r)return;const a=r.nodesById.get(e);if(!M(a))return;const d=null!==(i=this.stages.get(t))&&void 0!==i?i:{compositionId:a.compositionId,signals:null,stopWatchingReady:null};null===(o=d.signals)||void 0===o||o.stop(),null===(s=d.stopWatchingReady)||void 0===s||s.call(d),this.stages.set(t,d);const l=it(n.graph,e,{index:r});d.signals=xt({stage:t,watch:l,emit:e=>this.onSignals(t,e)});const c=u(l);if(0===c.tables.length&&0===c.fields.length&&0===c.goals.length)return;const h=()=>this.services.deliverWatch(t,d.compositionId,c);h(),t.addEventListener("widgetic:ready",h),d.stopWatchingReady=()=>t.removeEventListener("widgetic:ready",h)}onSignals(t,e){"running"!==this.mode||this.stepping||this.hasEnded()||t===this.viewport.currentStage()&&this.react(e)}react(t){const e=this.workflow,i=this.index,o=this.position;if(e&&i&&o)for(const s of t){let t;try{t=Y(e.graph,{nodeId:o.nodeId},s,{index:i})}catch(t){v.debug("[workflows] The engine could not decide on a signal",{signal:s.type,error:t});continue}if("moved"===t.outcome)return void this.moveOn(t,!1)}}moveOn(e,i){return t(this,void 0,void 0,(function*(){const t=this.index,o=this.position;if(!t||!o)return;const s=t.nodesById.get(e.position.nodeId);if(!M(s))return;let n;this.stepping=!0,this.cancelRetry(),this.cancelSchedules(),this.pendingStageNodeId=s.id;try{n=yield this.swapToComposition(s.compositionId,this.workflow)}catch(t){v.debug("[workflows] The next composition could not be built",{compositionId:s.compositionId,error:t}),n={status:"failed",reason:"error"}}this.pendingStageNodeId=null,this.stepping=!1,this.hasEnded()||("shown"===n.status?this.completeStep(e,s,o):this.failStep(e,s,o,i))}))}completeStep(t,e,i){const o=Object.assign(Object.assign({},i),{nodeId:e.id,compositionId:e.compositionId,reachedAt:Date.now()});this.position=o,mt(this.workflowId,o),this.countStep(i.nodeId,t,e.id),v.debug("[workflows] The visitor moved on",{from:i.compositionId,to:e.compositionId}),this.host.dispatchEvent(new CustomEvent(c,{detail:{workflowId:this.workflowId,from:i.compositionId,to:e.compositionId},bubbles:!0,composed:!0})),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}countStep(t,e,i){const o=this.counts,s=this.index;if(!o||!s)return;const n=H(s,t).find((t=>t.target===e.firedTriggerId));n&&o.count("e",n.id);for(const t of e.passedNodeIds)o.count("n",t);for(const t of e.takenEdgeIds)o.count("e",t);o.count("n",i)}failStep(t,e,i,o){var s;null===(s=this.counts)||void 0===s||s.count("f",e.id),v.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e.compositionId,isRetry:o}),this.armSchedules(),o||this.scheduleRetry(t,i.nodeId),this.drainPageEvents()}scheduleRetry(t,e){this.cancelRetry(),this.retryTimer=setTimeout((()=>{var i;this.retryTimer=null,"running"!==this.mode||this.stepping||this.hasEnded()||(null===(i=this.position)||void 0===i?void 0:i.nodeId)===e&&this.moveOn(t,!0)}),3e4)}cancelRetry(){null!==this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=null}armSchedules(){this.cancelSchedules();const t=this.workflow,e=this.index,i=this.position;if("running"===this.mode&&!this.stepping&&t&&e&&i)for(const{triggerId:o,schedule:s}of it(t.graph,i.nodeId,{index:e}).schedules){const t=K(s,i.reachedAt,Date.now());void 0!==t?this.waitFor(o,s,i.nodeId,t):v.debug("[workflows] A Scheduled trigger has no usable time and is ignored",{triggerId:o})}}waitFor(t,e,i,o){const s=setTimeout((()=>{this.scheduleTimers.delete(s);const o=this.position;if("running"!==this.mode||this.stepping||this.hasEnded()||!o||o.nodeId!==i)return;const n=K(e,o.reachedAt,Date.now());void 0!==n&&(n>0?this.waitFor(t,e,i,n):(v.debug("[workflows] A wait is over",{triggerId:t}),this.react([{type:"scheduled",triggerId:t}])))}),Math.min(o,432e5));this.scheduleTimers.add(s)}cancelSchedules(){for(const t of this.scheduleTimers)clearTimeout(t);this.scheduleTimers.clear()}getNextCompositionsReady(){var t,e;null===(t=this.cancelIdleWork)||void 0===t||t.call(this),this.cancelIdleWork=null;const i=null===(e=this.position)||void 0===e?void 0:e.nodeId;i&&(this.cancelIdleWork=this.services.whenIdle((()=>{var t;if(this.cancelIdleWork=null,"running"!==this.mode||this.hasEnded()||(null===(t=this.position)||void 0===t?void 0:t.nodeId)!==i)return;let e=0;for(const t of this.compositionsReachableFrom(i)){const i=this.compositionToShow(this.workflow,t);if(!this.readiedCompositions.has(i)){if(e>=5)break;this.readiedCompositions.add(i),e+=1,this.services.prefetchComposition(i)}}})))}compositionsReachableFrom(t){const e=this.index;if(!e)return[];const i=[],o=new Set;for(const s of W(e,t)){const t=[s.id];for(;t.length>0;){const s=t.pop();if(!o.has(s)){o.add(s);for(const o of H(e,s)){const s=e.nodesById.get(o.target);M(s)?i.includes(s.compositionId)||i.push(s.compositionId):$(s)&&t.push(s.id)}}}}return i}hasEnded(){return"ended"===this.mode||!this.host.isConnected&&(v.debug("[workflows] The tag left the page, so its workflow ends",{workflowId:this.workflowId}),this.stop(),!0)}stop(){var t,e,i,o,s,n;if("ended"!==this.mode){try{null===(t=this.counts)||void 0===t||t.flushBeforeLeaving()}catch(t){v.debug("[workflows] The last counts could not be sent",{error:t})}this.mode="ended",null===(e=this.cancelWaitForAnswer)||void 0===e||e.call(this),this.cancelRetry(),this.cancelSchedules(),null===(i=this.cancelIdleWork)||void 0===i||i.call(this),this.cancelIdleWork=null;for(const t of this.removeListeners.splice(0))t();for(const t of this.stages.values())null===(o=t.signals)||void 0===o||o.stop(),null===(s=t.stopWatchingReady)||void 0===s||s.call(t);this.stages.clear(),this.pageEvents.clear();try{null===(n=this.counts)||void 0===n||n.dispose()}catch(t){v.debug("[workflows] The counts could not be closed",{error:t})}this.viewport.destroy()}}}function ue(t,e){var i,o,s;const r=(null!==(i=t.getAttribute("workflow-id"))&&void 0!==i?i:"").trim(),a=(null!==(o=t.getAttribute("composition-id"))&&void 0!==o?o:"").trim();if(!Nt(r)||""===a)return v.debug("[workflows] The tag is not a workflow embed, so it is embedded as it is",{workflowId:r,tagCompositionId:a}),null;const d={fetchWorkflow:Lt,createCounts:t=>new yt(t),deliverWatch:re,prefetchComposition:ae,whenIdle:de,visitorLanguages:Et,firstCompositionWaitMilliseconds:2e3,viewport:{}},l=Object.assign(Object.assign(Object.assign({},d),e.services),{viewport:Object.assign(Object.assign({},d.viewport),null===(s=e.services)||void 0===s?void 0:s.viewport)}),u=new le(t,r,a,e,l);try{u.start()}catch(t){return v.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{workflowId:r,error:t}),u.stop(),null}const c={stop:()=>u.stop()};return n(t,c),c}export{ne as FIRST_COMPOSITION_WAIT_MILLISECONDS,se as RETRY_AFTER_FAILED_STEP_MILLISECONDS,ue as startWorkflowEmbed};
@@ -43,7 +43,7 @@ export declare const SDK_DEFAULTS: {
43
43
  LOG_LEVEL: "info";
44
44
  VERSION: string;
45
45
  };
46
- export declare const SDK_VERSION = "2.1.4";
46
+ export declare const SDK_VERSION = "2.1.6";
47
47
  export declare function getDefaultVersionedApiUrl(): string;
48
48
  export declare const API_DEFAULTS: {
49
49
  DEV_API_URL: string;
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.1.4";
1
+ export declare const PACKAGE_VERSION = "2.1.6";
@@ -4,9 +4,12 @@
4
4
  *
5
5
  * Copy iframe = raw `<iframe src>` without SDK.
6
6
  * Copy web component = SDK + `<widgetic composition-id>`. When the published
7
- * version has a direct module, the SDK mounts it in a shadow root. A version
8
- * with only widget.html asks for a republish and does not insert an iframe
9
- * (`render-mode="iframe"` on the tag asks for the iframe).
7
+ * version has a direct module, the SDK mounts it in a shadow root. Anything
8
+ * that keeps a widget from being mounted in the page is shown in its frame
9
+ * instead of leaving the tag empty: a version with only widget.html (a widget
10
+ * that talks to its parent frame is built that way), a module that does not
11
+ * load or does not speak the SDK's contract, and a module that throws while it
12
+ * mounts. `render-mode="iframe"` on the tag asks for the frame from the start.
10
13
  *
11
14
  * The box of either is as big as the tag says. A tag that also says `autoscale`
12
15
  * gets a box that follows the height of the widget (embed-autoscale.ts): the
@@ -4,16 +4,23 @@
4
4
  *
5
5
  * How it goes, in the order it happens:
6
6
  *
7
- * 1. The composition the tag names is shown at once (the visitor's own, if they are coming back), so a workflow never
8
- * makes a page wait. While that is loading, the workflow is read from the gateway (the live version, or the one a
9
- * returning visitor started on).
7
+ * 1. The workflow is read from the gateway (the live version, or the one a returning visitor started on), and the
8
+ * composition the tag names (the visitor's own, if they are coming back) is shown as soon as the answer is in: the
9
+ * answer says which copy of each composition the visitor's language has (workflow-languages.ts), and the first
10
+ * composition is shown in that language, as `<widgetic-translations>` would show it. A page never waits long for
11
+ * that: when the answer is slow, after `firstCompositionWaitMilliseconds` the composition is shown as it is (its
12
+ * lookup and module are got ready meanwhile), and it is swapped for its copy once the answer is in.
10
13
  * 2. When both are in, the workflow starts. A workflow that is paused, gone or does not contain the tag's composition
11
14
  * leaves a plain embed of the tag's composition. A running one follows heights from now on, starts listening for what
12
15
  * its triggers wait for, tells the widget what to report and starts the clocks of its Scheduled triggers.
13
16
  * 3. Each thing that happens (a saved entry, an action in the widget, an event of the page, a wait that is over) goes to
14
- * the engine, which says whether the visitor moves. If so, the next composition is built beside the one on screen
15
- * and takes its place when it is ready. If it cannot be shown, the visitor stays where they are, the page and the
16
- * counts are told, and one more try is made half a minute later.
17
+ * the engine, which says whether the visitor moves. If so, the next composition, in the visitor's language, is built
18
+ * beside the one on screen and takes its place when it is ready. If it cannot be shown (the composition itself is
19
+ * tried when it was a copy), the visitor stays where they are, the page and the counts are told, and one more try
20
+ * is made half a minute later.
21
+ *
22
+ * What the visitor is shown and what the workflow is made of are told apart: the graph, the counts, the place kept in the
23
+ * visitor's browser and the events for the page all name the composition of the graph, whatever language it is shown in.
17
24
  *
18
25
  * The engine decides, the viewport shows (workflow-stage.ts), and this file connects them to the visitor's browser: where
19
26
  * the visitor is kept, what is counted, what the widgets are told, when the clocks go off. Everything it needs from outside
@@ -28,6 +35,12 @@ import { type WorkflowLookup, type WorkflowLookupOptions } from "./workflow-look
28
35
  import { type ViewportServices } from "./workflow-stage";
29
36
  /** How long after a failed step the visitor is moved on again, if they are still where they were. Once. */
30
37
  export declare const RETRY_AFTER_FAILED_STEP_MILLISECONDS = 30000;
38
+ /**
39
+ * The longest the first composition waits for the workflow to say which language to show it in. A slower answer does not
40
+ * hold the page up: the composition is shown as it is, and swapped for its copy in the visitor's language when the
41
+ * answer is in.
42
+ */
43
+ export declare const FIRST_COMPOSITION_WAIT_MILLISECONDS = 2000;
31
44
  /** What the runtime needs of the counts. */
32
45
  type CountsPort = Pick<WorkflowCounts, "start" | "count" | "flushBeforeLeaving" | "dispose">;
33
46
  /** What a test may steer about the viewport. */
@@ -47,6 +60,10 @@ export interface WorkflowHostServices {
47
60
  prefetchComposition: (compositionId: string) => void;
48
61
  /** Runs `task` when the page has nothing better to do. Returns what takes it back. */
49
62
  whenIdle: (task: () => void) => () => void;
63
+ /** The languages the visitor's browser asks for, most wanted first: the list `<widgetic-translations>` reads. */
64
+ visitorLanguages: () => string[];
65
+ /** The longest the first composition waits for the workflow to say which language to show it in. */
66
+ firstCompositionWaitMilliseconds: number;
50
67
  viewport: ViewportTuning;
51
68
  }
52
69
  export interface StartWorkflowEmbedOptions {
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The language of a workflow: which copy of a composition a visitor is shown at each step.
3
+ *
4
+ * A composition can have translations (the translation tool makes a copy of it in each language, and a translation that
5
+ * is active is what `<widgetic-translations>` shows). On a page with a plain `<widgetic-translations>` tag the visitor's
6
+ * browser language chooses the copy. A workflow works the same way, for every composition it shows and not only for the
7
+ * first: the gateway hands the browser, with the graph, the copies each composition of the graph has
8
+ * (`PublicWorkflow.translations`), and every time the workflow shows a composition this file says which copy that is.
9
+ *
10
+ * The rules are the tag's, step for step, so a composition appears in the same language in a workflow as it does on its
11
+ * own (`translations/TranslationElement.ts`: `detectBrowserLanguages`, `findBestLanguageMatch`,
12
+ * `getCompositionForLanguage`):
13
+ *
14
+ * 1. the visitor's languages are the browser's, in the browser's order, each followed by its base (`fr-ca`, `fr`);
15
+ * 2. the first of them that a composition has a copy in wins (`fr-ca` before `fr`);
16
+ * 3. then the first language of the same family (`fr` is shown to a visitor who asked for `fr-ca`, `fr-ch` to one who
17
+ * asked for `fr`);
18
+ * 4. otherwise the language the composition was written in, which is the composition itself.
19
+ *
20
+ * The workflow code is a bundle of its own and may not import the tag (see scripts-sdk/workflow-shared-modules.js: a new
21
+ * shared module would change the contract between the SDK's files), so the rules are written out here again.
22
+ * tests/unit/workflows/workflow-languages.test.ts runs both over the same visitors and compositions and says if they
23
+ * ever part.
24
+ *
25
+ * Nothing here can fail a workflow: what cannot be read is left out, a composition with no copy is shown as it is, and a
26
+ * browser that does not tell its languages has none.
27
+ */
28
+ /** What the gateway says about one composition of the graph. */
29
+ export interface WorkflowTranslation {
30
+ /** The language the composition was written in: what a visitor is shown when there is nothing for their language. */
31
+ rootLanguage: string;
32
+ /** Language code (lowercase) to the composition that shows it. The root language is listed too, and is the composition itself. */
33
+ compositions: Record<string, string>;
34
+ }
35
+ /** The copies of the compositions of a graph, by the composition id the graph names. */
36
+ export type WorkflowTranslations = Record<string, WorkflowTranslation>;
37
+ /** How a language was chosen for a composition. */
38
+ export type LanguageMatch = "exact" | "family" | "root";
39
+ export interface ChosenLanguage {
40
+ language: string;
41
+ match: LanguageMatch;
42
+ }
43
+ /**
44
+ * Turns the `translations` of an answer into what the rest of the SDK can trust. What is not well formed is left out (a
45
+ * composition whose entry cannot be read is shown as it is); `undefined` when nothing usable is left.
46
+ */
47
+ export declare function readTranslations(value: unknown): WorkflowTranslations | undefined;
48
+ /**
49
+ * The languages the visitor's browser asks for, lowercase, most wanted first, each language followed by its base. The
50
+ * very list `<widgetic-translations>` makes (`detectBrowserLanguages`). Empty when the browser says nothing.
51
+ */
52
+ export declare function detectVisitorLanguages(): string[];
53
+ /**
54
+ * Which language a composition is shown in for a visitor who asks for `visitorLanguages`: the first of theirs it has a
55
+ * copy in, else the first of the same family, else the language it was written in.
56
+ */
57
+ export declare function chooseLanguage(visitorLanguages: readonly string[], translation: WorkflowTranslation): ChosenLanguage;
58
+ /**
59
+ * The composition to show where the graph names `compositionId`: its copy in the visitor's language, or the composition
60
+ * itself (when it has no copies, when the visitor's language is the one it was written in, when nothing matches).
61
+ */
62
+ export declare function compositionInLanguage(compositionId: string, translations: WorkflowTranslations | undefined, visitorLanguages: readonly string[]): string;
@@ -12,6 +12,7 @@
12
12
  * embed of its `composition-id`. A workflow can never be a reason for a page to show nothing.
13
13
  */
14
14
  import { type WorkflowGraph } from "@widgetic/workflows-engine";
15
+ import { type WorkflowTranslations } from "./workflow-languages";
15
16
  /** What a visitor's browser reads of a live workflow. */
16
17
  export interface PublicWorkflow {
17
18
  workflowId: string;
@@ -25,6 +26,12 @@ export interface PublicWorkflow {
25
26
  timezone: string;
26
27
  /** In the runtime form: no positions, no editor notes. Checked by the engine's parser. */
27
28
  graph: WorkflowGraph;
29
+ /**
30
+ * The copies in other languages that the compositions of the graph have, by the composition the graph names (see
31
+ * workflow-languages.ts). Read by the gateway when it answers, so a language added later is here without a new version.
32
+ * Absent when no composition has one.
33
+ */
34
+ translations?: WorkflowTranslations;
28
35
  /** What lets the page report counts for this version (absent: the page reports nothing). */
29
36
  eventToken?: string;
30
37
  }
@@ -15,6 +15,10 @@
15
15
  *
16
16
  * What to show next, and when, is decided elsewhere (workflow-host.ts). This file only builds and swaps stages and
17
17
  * keeps the height right. The decisions about heights are in workflow-autoscale.ts.
18
+ *
19
+ * A stage shows the composition it is told to, which for a visitor whose language a composition has a copy in is that copy
20
+ * (workflow-languages.ts). It still stands for the composition of the graph: what the page wrote in the tag for the tag's
21
+ * composition goes to the copy of it as well, and heights are remembered for what is shown.
18
22
  */
19
23
  /** Marks the viewport the SDK puts on a tag. */
20
24
  export declare const VIEWPORT_ATTRIBUTE = "data-widgetic-workflow-viewport";
@@ -32,10 +36,13 @@ export interface HeightObserver {
32
36
  disconnect(): void;
33
37
  }
34
38
  export interface StageDescription {
39
+ /** The composition the stage shows: a copy of `standsFor` in the visitor's language, or `standsFor` itself. */
35
40
  compositionId: string;
41
+ /** The composition of the workflow the stage stands for (the one a block of the graph names). */
42
+ standsFor: string;
36
43
  /** The first stage the viewport built. */
37
44
  isFirst: boolean;
38
- /** Whether it shows the composition the tag names, and so gets what the page wrote in the tag for it. */
45
+ /** Whether it stands for the composition the tag names, and so gets what the page wrote in the tag for it. */
39
46
  carriesPageContent: boolean;
40
47
  }
41
48
  export interface ViewportServices {
@@ -95,11 +102,14 @@ export declare class WorkflowViewport {
95
102
  constructor(options: WorkflowViewportOptions);
96
103
  /** The stage on screen, if any. */
97
104
  currentStage(): HTMLElement | null;
105
+ /** The composition the stage on screen shows (a copy in the visitor's language, or the composition itself), if any. */
106
+ currentCompositionId(): string | null;
98
107
  /**
99
108
  * Builds the first composition's stage and starts loading it. `ready` settles when it is shown or has failed (it is
100
- * never given up on for being slow: a plain embed is not either).
109
+ * never given up on for being slow: a plain embed is not either). `standsFor` is the composition of the workflow the
110
+ * stage is for when it shows a copy of it.
101
111
  */
102
- showFirstStage(compositionId: string): {
112
+ showFirstStage(compositionId: string, standsFor?: string): {
103
113
  stage: HTMLElement;
104
114
  ready: Promise<StageReadiness>;
105
115
  };
@@ -112,9 +122,10 @@ export declare class WorkflowViewport {
112
122
  releaseAutoscale(): void;
113
123
  /**
114
124
  * Builds the next composition beside the one on screen and, once it is ready, takes the place of it. If it fails or
115
- * does not appear in time, the one on screen stays exactly as it was.
125
+ * does not appear in time, the one on screen stays exactly as it was. `standsFor` is the composition of the workflow
126
+ * the stage is for when it shows a copy of it.
116
127
  */
117
- swapTo(compositionId: string): Promise<SwapOutcome>;
128
+ swapTo(compositionId: string, standsFor?: string): Promise<SwapOutcome>;
118
129
  /** Takes everything this viewport put on the page away. Safe to call more than once. */
119
130
  destroy(): void;
120
131
  private buildStage;