@widgetic/embed-sdk 2.1.7 → 2.1.8

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
- !function(t,e,o,i,s,n,r,d,a,l,u,c){"use strict";function h(t,e,o,i){return new(o||(o=Promise))((function(s,n){function r(t){try{a(i.next(t))}catch(t){n(t)}}function d(t){try{a(i.throw(t))}catch(t){n(t)}}function a(t){var e;t.done?s(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(r,d)}a((i=i.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const g=/^[A-Za-z0-9_-]{1,64}$/;function p(t){const e=new Map;for(const o of t.nodes)e.has(o.id)||e.set(o.id,o);const o=new Map,i=new Map;for(const e of t.edges)f(o,e.source,e),f(i,e.target,e);return{graph:t,nodesById:e,outgoingBySource:o,incomingByTarget:i}}function f(t,e,o){const i=t.get(e);i?i.push(o):t.set(e,[o])}function m(t,e){return t.outgoingBySource.get(e)??[]}function v(t){return"composition"===t?.type}function w(t){return"condition"===t?.type}function b(t,e){const o=[];for(const s of m(t,e)){const e=t.nodesById.get(s.target);i=e,"trigger"===i?.type&&o.push(e)}var i;return o}function y(t,e,o){return m(t,e).find((t=>t.sourcePort===o))}const I={text:["is","isNot","contains","doesNotContain","startsWith","endsWith","isEmpty","isNotEmpty"],number:["is","isNot","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"],boolean:["is","isNot"]},k=["is","isNot","contains","doesNotContain","startsWith","endsWith","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"];function T(t){return null==t||"string"==typeof t&&""===t.trim()}function E(t){return null==t?"":String(t).trim().toLowerCase()}function S(t){if("number"==typeof t)return Number.isFinite(t)?t:void 0;if("string"==typeof t){const e=t.trim();if(""===e)return;const o=Number(e);return Number.isFinite(o)?o:void 0}}const A=new Set(["true","yes","1","on"]),C=new Set(["false","no","0","off"]);function O(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(A.has(e))return!0;if(C.has(e))return!1}}function W(t,e){const{operator:o}=t;if("isEmpty"===o)return T(e);if("isNotEmpty"===o)return!T(e);if(!function(t,e){return I[e].includes(t)}(o,t.field.type))return!1;switch(t.field.type){case"number":return function(t,e,o){const i=S(e),s=S(o);if("isNot"===t)return void 0===i||void 0===s||i!==s;if(void 0===i||void 0===s)return!1;switch(t){case"is":return i===s;case"greaterThan":return i>s;case"atLeast":return i>=s;case"lessThan":return i<s;case"atMost":return i<=s;default:return!1}}(o,e,t.value);case"boolean":return function(t,e,o){const i=O(e),s=O(o),n=void 0!==i&&void 0!==s&&i===s;return"is"===t?n:"isNot"===t&&!n}(o,e,t.value);default:return function(t,e,o){const i=E(e),s=E(o),n=T(e);switch(t){case"is":return!n&&i===s;case"isNot":return n||i!==s;case"contains":return!n&&""!==s&&i.includes(s);case"doesNotContain":return n||""===s||!i.includes(s);case"startsWith":return!n&&""!==s&&i.startsWith(s);case"endsWith":return!n&&""!==s&&i.endsWith(s);default:return!1}}(o,e,t.value)}}function H(t,e){if(0===t.tests.length)return!1;const o=t=>W(t,e(t.field));return"any"===t.match?t.tests.some(o):t.tests.every(o)}const N={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5},_=["seconds","minutes","hours","days","weeks"],M=365*N.days;function L(t){return"string"==typeof t&&_.includes(t)}function P(t,e){if("after"===t.mode){const o=function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<1)return;if(!L(e))return;const o=t*N[e];return o<=M?o:void 0}(t.amount,t.unit);if(void 0===o||!Number.isFinite(e))return;return e+o}if("at"===t.mode){const e=Date.parse(t.at);return Number.isFinite(e)?e:void 0}}function $(t,e,o){const i=P(t,e);return void 0===i?void 0:Math.max(0,i-o)}function R(t,e){const o=t.trigger;switch(e.type){case"input":return"input"===o.kind&&o.table===e.table;case"action":return"action"===o.kind&&o.actionId===e.actionId;case"pageEvent":return"pageEvent"===o.kind&&o.name===e.name;case"scheduled":return"scheduled"===o.kind&&t.id===e.triggerId;default:return!1}}function F(t,e,o){const i=[e.id],s=[],n=function(t){const e="input"===t.type||"pageEvent"===t.type?t.values:void 0,o="input"===t.type?"input":"pageEvent"===t.type?"event":void 0;return t=>{if(e&&t.kind===o)return Object.prototype.hasOwnProperty.call(e,t.name)?e[t.name]:void 0}}(o);let r=y(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(v(e))return{destination:e,passedNodeIds:i,takenEdgeIds:s};if(!w(e))break;i.push(e.id);const o=e.cases.find((t=>H(t,n)));r=y(t,e.id,o?o.id:"default")}return{passedNodeIds:i,takenEdgeIds:s}}function B(t,e,o,i={}){const s=i.index??p(t),n=s.nodesById.get(e.nodeId);if(!v(n))return{outcome:"ignored",reason:"unknown_position"};const r=[];for(const t of b(s,n.id)){if(!R(t,o))continue;r.push(t.id);const e=F(s,t,o);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 x(t,e,o){t.some((t=>o(t,e)))||t.push(e)}function j(t,e,o,i){const s=[],n=y(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&&x(i,{table:o,column:e.field.name},((t,e)=>t.table===e.table&&t.column===e.column));for(const o of m(t,e))s.push(o.target)}}}function z(t,e,o={}){const i=o.index??p(t),s={inputTables:[],inputColumns:[],actionIds:[],pageEventNames:[],schedules:[]},n=(t,e)=>t===e;for(const t of b(i,e)){const e=t.trigger;switch(e.kind){case"input":if(""===e.table)break;x(s.inputTables,e.table,n),j(i,t.id,e.table,s.inputColumns);break;case"action":""!==e.actionId&&x(s.actionIds,e.actionId,n);break;case"pageEvent":""!==e.name&&x(s.pageEventNames,e.name,n);break;case"scheduled":s.schedules.push({triggerId:t.id,schedule:e.schedule})}}return s}class V{issues=[];report(t,e){this.issues.push({code:t,severity:"error",detail:e})}}function D(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function U(t){return"string"==typeof t&&g.test(t)?t:void 0}function q(t,e=200){return"string"==typeof t&&t.length<=e?t:void 0}function Z(t){return"text"===t||"number"===t||"boolean"===t?t:void 0}function G(t,e,o){if(!D(t))return void o.report("malformed",e);const i=function(t,e,o){if(!D(t))return void o.report("malformed",e);const i="input"===t.kind||"event"===t.kind?t.kind:void 0,s=q(t.name,64),n=Z(t.type);if(i&&void 0!==s&&n)return{kind:i,name:s,type:n};o.report("malformed",e)}(t.field,`${e}.field`,o),s=function(t){return"string"==typeof t&&k.includes(t)?t:void 0}(t.operator);let n;return s||o.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:q(t)}(t.value),void 0===n&&o.report("malformed",`${e}.value`)),i&&s?void 0===n?{field:i,operator:s}:{field:i,operator:s,value:n}:void 0}function Y(t,e,o){if(D(t))switch(t.kind){case"input":{const i=q(t.table);return void 0===i&&o.report("malformed",`${e}.table`),void 0===i?void 0:{kind:"input",table:i}}case"action":{const i=q(t.actionId);return void 0===i&&o.report("malformed",`${e}.actionId`),void 0===i?void 0:{kind:"action",actionId:i}}case"pageEvent":{const i=q(t.name,64);void 0===i&&o.report("malformed",`${e}.name`);const s=function(t,e,o){if(!Array.isArray(t)||t.length>100)return void o.report("malformed",e);const i=[];return t.forEach(((t,s)=>{const n=D(t)?q(t.name,64):void 0,r=D(t)?Z(t.type):void 0;void 0!==n&&r?i.push({name:n,type:r}):o.report("malformed",`${e}[${s}]`)})),i}(t.values,`${e}.values`,o);return void 0!==i&&s?{kind:"pageEvent",name:i,values:s}:void 0}case"scheduled":{const i=function(t,e,o){if(D(t)&&"after"===t.mode&&"number"==typeof t.amount&&L(t.unit)&&Number.isFinite(t.amount))return{mode:"after",amount:t.amount,unit:t.unit};if(D(t)&&"at"===t.mode){const e=q(t.at,64);if(void 0!==e)return{mode:"at",at:e}}o.report("malformed",e)}(t.schedule,`${e}.schedule`,o);return i?{kind:"scheduled",schedule:i}:void 0}default:return void o.report("unknown_trigger_kind",`${e}.kind`)}else o.report("malformed",e)}function J(t,e,o){if(!D(t))return void o.report("malformed",e);const i=U(t.id);i||o.report("bad_id",`${e}.id`);const s=function(t){if(void 0!==t)return D(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&&o.report("malformed",`${e}.position`);const n=i&&"invalid"!==s?s?{id:i,position:s}:{id:i}:void 0;switch(t.type){case"composition":{const i=q(t.compositionId,200);if(void 0===i&&o.report("malformed",`${e}.compositionId`),void 0!==t.startsHere&&"boolean"!=typeof t.startsHere)return void o.report("malformed",`${e}.startsHere`);if(!n||void 0===i)return;return!0===t.startsHere?{...n,type:"composition",compositionId:i,startsHere:!0}:{...n,type:"composition",compositionId:i}}case"trigger":{const i=Y(t.trigger,`${e}.trigger`,o);return n&&i?{...n,type:"trigger",trigger:i}:void 0}case"condition":{if(!Array.isArray(t.cases)||t.cases.length>100)return void o.report("malformed",`${e}.cases`);const i=[];return t.cases.forEach(((t,s)=>{const n=function(t,e,o){if(!D(t)||!Array.isArray(t.tests)||t.tests.length>100)return void o.report("malformed",e);const i=U(t.id),s="all"===t.match||"any"===t.match?t.match:void 0;let n;i||o.report("bad_id",`${e}.id`),s||o.report("malformed",`${e}.match`),void 0!==t.label&&(n=q(t.label),void 0===n&&o.report("malformed",`${e}.label`));const r=[];return t.tests.forEach(((t,i)=>{const s=G(t,`${e}.tests[${i}]`,o);s&&r.push(s)})),i&&s?void 0===n?{id:i,match:s,tests:r}:{id:i,label:n,match:s,tests:r}:void 0}(t,`${e}.cases[${s}]`,o);n&&i.push(n)})),n?{...n,type:"condition",cases:i}:void 0}default:return void o.report("unknown_node_type",`${e}.type`)}}function K(t){const e=new V;if(!D(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 o=[];t.nodes.forEach(((t,i)=>{const s=J(t,`nodes[${i}]`,e);s&&o.push(s)}));const i=[];return t.edges.forEach(((t,o)=>{const s=function(t,e,o){if(!D(t))return void o.report("malformed",e);const i=U(t.id),s=U(t.source),n=U(t.sourcePort),r=U(t.target);return i||o.report("bad_id",`${e}.id`),s&&n&&r||o.report("malformed",e),i&&s&&n&&r?{id:i,source:s,sourcePort:n,target:r}:void 0}(t,`edges[${o}]`,e);s&&i.push(s)})),e.issues.length>0?{issues:e.issues}:{graph:{schemaVersion:1,nodes:o,edges:i},issues:[]}}const Q=/^[A-Za-z0-9_.:-]{1,128}$/;function X(t){return`widgetic_workflow_${t}`}function tt(t){return"string"==typeof t&&Q.test(t)}function et(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0}function ot(t,e){try{a.writeStoredValue(X(t),JSON.stringify({v:1,versionId:e.versionId,nodeId:e.nodeId,compositionId:e.compositionId,startedAt:e.startedAt,reachedAt:e.reachedAt}))}catch(e){o.log.debug("[workflows] The visitor's position could not be kept",{workflowId:t,error:e})}}function it(t){a.removeStoredValue(X(t))}const st=/^[A-Za-z0-9_-]{1,64}$/,nt=new Set(["n","e","f"]);class rt{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,o=1){if(this.stopped||!this.options.token)return;if(!nt.has(t)||!st.test(e)||!Number.isInteger(o)||o<1)return;const i=`${t}:${e}`;let s=o;for(;s>0;){let o=this.lastEventOf.get(i);(!o||o.c>=50)&&(o={k:t,id:e,c:0},this.pending.push(o),this.lastEventOf.set(i,o));const n=Math.min(s,50-o.c);o.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 o.log.debug("[workflows] Counts handed to the browser to send",{eventCount:t.length})}catch(t){o.log.debug("[workflows] The browser would not take counts to send as the page closes",{error:t})}this.sendWithRequest(t)}sendWithRequest(t){return h(this,void 0,void 0,(function*(){try{const e=yield fetch(this.reportAddress(),{method:"POST",mode:"cors",credentials:"omit",keepalive:!0,headers:{"Content-Type":"text/plain"},body:this.reportBody(t)});if(401===e.status)return o.log.warn("[workflows] The gateway refused the token for counts, so this embed stops reporting",{workflowId:this.options.workflowId}),void this.dispose();o.log.debug("[workflows] Counts sent",{eventCount:t.length,status:e.status})}catch(e){o.log.debug("[workflows] Counts could not be sent and were dropped",{eventCount:t.length,error:e})}}))}}const dt=/^[a-z0-9]{1,8}(-[a-z0-9]{1,8}){0,4}$/,at=/^[A-Za-z0-9_.:-]{1,128}$/;function lt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function ut(t){if("string"!=typeof t||t.length>35)return null;const e=t.toLowerCase();return dt.test(e)?e:null}function ct(){var t,e;try{if("undefined"==typeof navigator)return[];const o=String(null!==(t=navigator.language)&&void 0!==t?t:"").toLowerCase(),i=((null===(e=navigator.languages)||void 0===e?void 0:e.map((t=>String(t).toLowerCase())))||[o]).flatMap((t=>{const e=[t];return t.includes("-")&&e.push(t.split("-")[0]),e}));return[...new Set(i)].filter((t=>""!==t))}catch(t){return o.log.debug("[workflows] The languages of the browser could not be read",{error:t}),[]}}function ht(t,e,o){if(!e||0===o.length||!Object.prototype.hasOwnProperty.call(e,t))return t;const i=e[t],{language:s}=function(t,e){const o=Object.keys(e.compositions);for(const e of t)if(o.includes(e))return{language:e,match:"exact"};for(const e of t){const t=e.split("-")[0],i=o.find((e=>e.startsWith(`${t}-`)||e===t));if(void 0!==i)return{language:i,match:"family"}}return{language:e.rootLanguage,match:"root"}}(o,i);return s===i.rootLanguage?t:i.compositions[s]||t}const gt=/^[A-Za-z0-9_-]{1,64}$/,pt=/^[A-Za-z0-9_.:-]{1,128}$/;function ft(t){return gt.test(t)}function mt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function vt(t,e){var i;if(!mt(t)||!0!==t.success||!mt(t.data))return{kind:"unreadable"};const s=t.data;if("paused"===s.status)return{kind:"paused"};if("live"!==s.status)return{kind:"unreadable"};if("string"!=typeof s.versionId||!pt.test(s.versionId))return{kind:"unreadable"};const n=K(s.graph);if(!n.graph||n.issues.length>0)return o.log.warn("[workflows] The published graph could not be read, so the embed stays a plain embed",{workflowId:e,issueCount:n.issues.length,firstIssue:null===(i=n.issues[0])||void 0===i?void 0:i.code}),{kind:"unreadable"};const r={workflowId:"string"==typeof s.workflowId?s.workflowId:e,versionId:s.versionId,timezone:"string"==typeof s.timezone&&""!==s.timezone.trim()&&s.timezone.length<=64?s.timezone:"UTC",graph:n.graph};"number"==typeof s.versionNumber&&Number.isInteger(s.versionNumber)&&(r.versionNumber=s.versionNumber),"string"==typeof s.publishedAt&&(r.publishedAt=s.publishedAt),"string"==typeof s.startCompositionId&&pt.test(s.startCompositionId)&&(r.startCompositionId=s.startCompositionId);const d=function(t){if(!lt(t))return;const e=Object.create(null);let o=0;for(const[i,s]of Object.entries(t)){if(o>=64)break;if(!at.test(i)||!lt(s))continue;const t=ut(s.rootLanguage);if(null===t||!lt(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 o=ut(t);null!==o&&"string"==typeof e&&at.test(e)&&(n[o]=e,r+=1)}0!==r&&(e[i]={rootLanguage:t,compositions:n},o+=1)}return 0===o?void 0:e}(s.translations);return d&&(r.translations=d),"string"==typeof s.eventToken&&""!==s.eventToken&&s.eventToken.length<=2048&&(r.eventToken=s.eventToken),{kind:"live",workflow:r}}function wt(t,e){return h(this,void 0,void 0,(function*(){const i=new AbortController,s=setTimeout((()=>i.abort()),1e4);try{const o=yield fetch(t,{method:"GET",mode:"cors",signal:i.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=vt(s,e);return"live"===n.kind?{kind:"live",workflow:n.workflow}:n}catch(t){return o.log.debug("[workflows] A host could not be reached",{workflowId:e,error:t}),{kind:"unreachable"}}finally{clearTimeout(s)}}))}const bt=new Map;function yt(t,e={}){var i,n;if(!ft(t)||void 0!==e.versionId&&!pt.test(e.versionId))return Promise.resolve({status:"unavailable",reason:"not_found"});const r=`${t}|${null!==(i=e.versionId)&&void 0!==i?i:""}|${(null!==(n=e.origins)&&void 0!==n?n:[]).join(",")}`,d=bt.get(r);if(d)return d;const a=function(t,e){return h(this,void 0,void 0,(function*(){var i;const n=null!==(i=e.origins)&&void 0!==i?i:s.publicEmbedApiOrigins(),r=e.versionId?`/embed/workflows/${encodeURIComponent(t)}/versions/${encodeURIComponent(e.versionId)}`:`/embed/workflows/${encodeURIComponent(t)}`;let d=!1,a=!1;for(const e of n){const o=yield wt(`${e}${r}`,t);if("live"===o.kind)return{status:"live",workflow:o.workflow,origin:e};if("paused"===o.kind)return{status:"paused"};"missing"===o.kind&&(d=!0),"unreadable"===o.kind&&(a=!0)}const l=d?"not_found":a?"unreadable":"unreachable";return o.log.debug("[workflows] The workflow is not available",{workflowId:t,reason:l}),{status:"unavailable",reason:l}}))}(t,e);return bt.set(r,a),a.finally((()=>{bt.get(r)===a&&bt.delete(r)})),a}const It={clicks:"click",submissions:"submit",plays:"play"},kt=new Set(["__proto__","constructor","prototype"]);function Tt(t){const e=t.detail;return"object"!=typeof e||null===e||Array.isArray(e)?{}:e}function Et(t,e){return("submissions"!==t.metric||"FORM"===e.tagName)&&(("plays"!==t.metric||"VIDEO"===e.tagName||"AUDIO"===e.tagName)&&(null!==t.selector?a.elementMatchesGoalTarget(e,t.selector):"clicks"!==t.metric||null!==e.closest('button, a, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-click-track]')))}function St({stage:t,watch:i,emit:s}){var n;let r=!1;const d=[];if(i.inputTables.length>0){const e=new Map;for(const{table:t,column:o}of i.inputColumns){const i=null!==(n=e.get(t))&&void 0!==n?n:new Set;i.add(o),e.set(t,i)}const a=new Set,l=t=>{var n;if(r)return;const d=Tt(t),l=d.table;if("string"!=typeof l||!i.inputTables.includes(l))return;if("string"==typeof d.entryId&&""!==d.entryId){const t=`${l}:${d.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 u=function(t,e){const o={};if("object"!=typeof t||null===t||Array.isArray(t))return o;for(const i of e){if(kt.has(i))continue;if(!Object.prototype.hasOwnProperty.call(t,i))continue;const e=t[i];"string"==typeof e?o[i]=e.length>200?e.slice(0,200):e:("number"==typeof e&&Number.isFinite(e)||"boolean"==typeof e)&&(o[i]=e)}return o}(d.values,null!==(n=e.get(l))&&void 0!==n?n:new Set);o.log.debug("[workflows] An entry was saved in a watched table",{table:l,valueCount:Object.keys(u).length}),s([{type:"input",table:l,values:u}])};t.addEventListener("widgetic:submitted",l),d.push((()=>t.removeEventListener("widgetic:submitted",l)))}if(i.actionIds.length>0){const n=t=>{if(r)return;const e=Tt(t);let n=null;"string"==typeof e.goalId?n=e.goalId:"string"==typeof e.metric&&""!==e.metric&&(n="string"==typeof e.goalTarget&&""!==e.goalTarget?`${e.metric}@${e.goalTarget}`:e.metric),null!==n&&i.actionIds.includes(n)&&(o.log.debug("[workflows] A widget reported a watched action",{actionId:n}),s([{type:"action",actionId:n}]))};t.addEventListener("widgetic:goal",n),d.push((()=>t.removeEventListener("widgetic:goal",n)));const l=[];for(const t of i.actionIds){const o=e.splitActionId(t);o&&(a=o.metric,Object.prototype.hasOwnProperty.call(It,a))&&l.push({actionId:t,metric:o.metric,selector:o.selector})}if(l.length>0){let e=null,i=()=>{};const n=t=>{const e=t.target instanceof Element?t.target:null;if(!e)return[];const o=[];for(const i of l)It[i.metric]===t.type&&Et(i,e)&&o.push({type:"action",actionId:i.actionId});return o},a=t=>{if(r)return;const e=n(t);0!==e.length&&(o.log.debug("[workflows] A watched action happened in the widget",{actionIds:e.map((t=>t.actionId))}),s(e))},u=()=>{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(l.map((t=>It[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",u),d.push((()=>t.removeEventListener("widgetic:ready",u))),d.push((()=>i())),u()}}var a;return{stop:()=>{if(!r){r=!0;for(const t of d)try{t()}catch(t){o.log.debug("[workflows] A listener could not be removed",{error:t})}}}}}const At=50,Ct=2e3,Ot=150,Wt=5,Ht=300,Nt=2e4;function _t(t,e,o,i){const s=t.getAttribute(e);if(null===s||!/^\d+$/.test(s.trim()))return o;const n=Number.parseInt(s.trim(),10);return Number.isFinite(n)?Math.min(n,i):o}function Mt(t,e,o){const i="number"==typeof o&&Number.isFinite(o)&&o>0?Math.min(e.maxHeight,Math.floor(o)):e.maxHeight,s=Math.min(e.minHeight,i);return Number.isNaN(t)?s:Math.max(s,Math.min(i,Math.ceil(t)))}function Lt(t,e,o){return null===t||e!==t&&Math.abs(e-t)>=o}const Pt=["width","height","resize","resize-mode","render-mode","use-iframe","theme","mode","colors","sandbox","autoload","adaptive","responsive"],$t=["values","context","media-resolver"],Rt=["design","content","content-items","contentitems","items"];function Ft(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 o.log.debug("[workflows] The browser could not watch heights",{error:t}),null}}function Bt(t){return t.getBoundingClientRect().height}function xt(){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 zt{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:xt,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 o=this.buildStage(t,!0,e);this.current=o;const i=this.waitUntilShown(o,null,(t=>{if("ready"===t.status&&!this.destroyed&&this.autoscaleOn&&this.current===o){const t=this.measure(o.element);jt(t)&&this.applyHeight(t,"immediate")}}));return this.viewportElement.appendChild(o.element),this.services.hydrate(o.element),{stage:o.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:Ft)((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(t){return h(this,arguments,void 0,(function*(t,e=t){var i,s,r;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming)return{status:"failed",reason:"busy"};this.enableAutoscale();const d=this.buildStage(t,!1,e);this.incoming=d,this.hideBeside(d.element);const a=this.waitUntilShown(d,null!==(i=this.services.readyTimeoutMilliseconds)&&void 0!==i?i:8e3);this.viewportElement.appendChild(d.element),this.services.hydrate(d.element);const l=yield a;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming=null,"failed"===l.status)return this.removeStage(d),"timeout"===l.reason&&n.dispatchPublishedHostError(this.host,t,"workflow_step_timeout"),o.log.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:t,reason:l.reason}),Object.assign({status:"failed",reason:"stopped"===l.reason?"stopped":l.reason},l.code?{code:l.code}:{});const u=this.current;this.revealInPlace(d.element),this.current=d,null===(s=this.heightObserver)||void 0===s||s.observe(d.element);const c=this.measure(d.element);return jt(c)&&this.applyHeight(c,"immediate"),u&&(null===(r=this.heightObserver)||void 0===r||r.unobserve(u.element),this.removeStage(u)),{status:"shown",stage:d.element}}))}destroy(){var t,e,o;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 i=[this.current,this.incoming];this.current=null,this.incoming=null;for(const t of i)t&&(null===(o=t.cancelWait)||void 0===o||o.call(t),this.removeStage(t));this.viewportElement.remove()}buildStage(t,e,i){var s,n,r;const d=document.createElement("widgetic");d.setAttribute("composition-id",t),d.setAttribute("data-widgetic-workflow-stage","1"),d.style.display="block";for(const t of Pt){const e=this.host.getAttribute(t);null!==e&&d.setAttribute(t,e)}this.widthOverride&&d.setAttribute("width",this.widthOverride);for(const t of $t){const e=this.host.getAttribute(t);null!==e&&d.setAttribute(t,e)}const a=i===(null!==(s=this.host.getAttribute("composition-id"))&&void 0!==s?s:"").trim();a&&this.copyWhatThePageWroteForTheTagComposition(d);const l={element:d,compositionId:t,standsFor:i,reportedHeight:!1,cancelWait:null,stopListening:()=>{}},u=t=>{var e;const o=null===(e=t.detail)||void 0===e?void 0:e.height;if("number"!=typeof o||!jt(o))return;const i=d.querySelector("iframe");i&&(i.style.height=`${Math.ceil(o)}px`,l.reportedHeight=!0)};d.addEventListener("widgetic:resize",u),l.stopListening=()=>d.removeEventListener("widgetic:resize",u);try{null===(r=(n=this.services).onStageCreated)||void 0===r||r.call(n,d,{compositionId:t,standsFor:i,isFirst:e,carriesPageContent:a})}catch(e){o.log.debug("[workflows] A listener for a new stage failed",{compositionId:t,error:e})}return l}copyWhatThePageWroteForTheTagComposition(t){for(const e of Array.from(this.host.attributes))u.isReservedHostAttribute(e.name)||t.setAttribute(e.name,e.value);for(const e of Rt){const o=this.host.getAttribute(e);null!==o&&t.setAttribute(e,o)}for(const e of u.declarativeChildrenOf(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&&$t.includes(null!==(e=t.attributeName)&&void 0!==e?e:"")}))&&this.mirrorAttributesToStages()})),this.attributeObserver.observe(this.host,{attributes:!0,attributeFilter:[...$t]})}catch(t){this.attributeObserver=null,o.log.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 $t){const o=this.host.getAttribute(e);null===o?t.element.removeAttribute(e):t.element.getAttribute(e)!==o&&t.element.setAttribute(e,o)}}waitUntilShown(t,e,i){return new Promise((s=>{const n=t.element;let r=null,d=!1;const a=e=>{if(!d){d=!0,null!==r&&clearTimeout(r),n.removeEventListener("widgetic:ready",l),n.removeEventListener("widgetic:error",u),n.removeEventListener("load",c,!0),t.cancelWait=null;try{null==i||i(e)}catch(e){o.log.debug("[workflows] A stage could not be settled",{compositionId:t.compositionId,error:e})}s(e)}},l=()=>a({status:"ready"}),u=t=>{var e;const o=null===(e=t.detail)||void 0===e?void 0:e.code;a(Object.assign({status:"failed",reason:"error"},"string"==typeof o?{code:o}:{}))},c=t=>{t.target instanceof HTMLIFrameElement&&a({status:"ready"})};n.addEventListener("widgetic:ready",l),n.addEventListener("widgetic:error",u),n.addEventListener("load",c,!0),t.cancelWait=()=>a({status:"failed",reason:"stopped"}),null!==e&&(r=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){o.log.debug("[workflows] A listener for a removed stage failed",{compositionId:t.compositionId,error:e})}}noteFrameWithoutHeight(t){this.warnedAboutFrameWithoutHeight||(this.warnedAboutFrameWithoutHeight=!0,o.log.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:Bt)(t)}catch(t){return o.log.debug("[workflows] The height of a stage could not be read",{error:t}),0}}holdRoomFor(t){const e=l.readStoredAutoscaleHeight(t);if(null===e)return;const o=this.settings();this.viewportElement.style.minHeight=`${Mt(e,o,this.overlayCap())}px`}settings(){return function(t,e={}){const o=_t(t,"autoscale-min-height",At,Nt),i=_t(t,"autoscale-max-height",Ct,Nt);return{minHeight:o,maxHeight:Math.max(i,o),debounceDelay:_t(t,"autoscale-debounce",Ot,5e3),threshold:_t(t,"autoscale-threshold",Wt,Nt),animate:"false"!==t.getAttribute("autoscale-animate")&&!0!==e.prefersReducedMotion,animationDuration:_t(t,"autoscale-animation-duration",Ht,5e3)}}(this.host,{prefersReducedMotion:this.prefersReducedMotion()})}overlayCap(){return this.host.hasAttribute(c.OVERLAY_HOST_ATTRIBUTE)?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 o=this.settings(),i=Mt(t,o,this.overlayCap());if("immediate"===e)return this.clearHeightTimer(),void this.setHeight(i,o);Lt(this.appliedHeight,i,o.threshold)?(this.pendingHeight=i,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();Lt(this.appliedHeight,t,e.threshold)&&this.setHeight(t,e)}),o.debounceDelay)):i===this.appliedHeight&&this.clearHeightTimer()}setHeight(t,e){var o;const i=this.viewportElement.style,s=null!==this.appliedHeight&&this.appliedHeight!==t;if(i.setProperty("transition",e.animate&&s?`height ${e.animationDuration}ms ease`:"none"),i.height=`${t}px`,i.removeProperty("min-height"),this.appliedHeight=t,this.current){const e=Number.parseInt(null!==(o=this.host.getAttribute("height"))&&void 0!==o?o:"",10);l.writeStoredAutoscaleHeight(this.current.compositionId,t,Number.isFinite(e)?e:t)}}clearHeightTimer(){null!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingHeight=null}}function Vt(t,s,r){var d;try{i.setDirectMountWorkflow(t,e.workflowWatchProperty(s,r)),null===(d=n.getPublishedHostBridge(t))||void 0===d||d.sendWorkflowWatch(r)}catch(t){o.log.debug("[workflows] A widget could not be told what to report",{compositionId:s,error:t})}}function Dt(t){try{s.resolvePublishedEmbed(t).then((t=>{var e;const o="found"===t.status?null===(e=t.payload.direct)||void 0===e?void 0:e.moduleUrl:void 0;o&&i.warmDirectModule(o)})).catch((()=>{}))}catch(e){o.log.debug("[workflows] A composition could not be got ready",{compositionId:t,error:e})}}function Ut(t){const e=window;if("function"==typeof e.requestIdleCallback){const o=e.requestIdleCallback((()=>t()),{timeout:5e3});return()=>{var t;return null===(t=e.cancelIdleCallback)||void 0===t?void 0:t.call(e,o)}}const o=setTimeout(t,1500);return()=>clearTimeout(o)}class qt{constructor(t,e,i,s,n){this.host=t,this.workflowId=e,this.tagCompositionId=i,this.options=s,this.services=n,this.mode="loading",this.stages=new Map,this.pageEvents=new d.PageEventQueue,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=d.readPageEvent(t.detail);e?"running"!==this.mode||this.stepping?this.pageEvents.add(e):this.hasEnded()||this.react([{type:"pageEvent",name:e.name,values:e.values}]):o.log.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 r=n.viewport;this.viewport=new zt(Object.assign(Object.assign(Object.assign({host:t},r.prefersReducedMotion?{prefersReducedMotion:r.prefersReducedMotion}:{}),s.width?{widthOverride:s.width}:{}),{services:Object.assign(Object.assign(Object.assign(Object.assign({hydrate:s.hydrate},r.createHeightObserver?{createHeightObserver:r.createHeightObserver}:{}),r.measureStageHeight?{measureStageHeight:r.measureStageHeight}:{}),void 0!==r.readyTimeoutMilliseconds?{readyTimeoutMilliseconds:r.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 o.log.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=X(t),s=a.readStoredValue(i);if(null===s)return null;try{const i=JSON.parse(s);if("object"!=typeof i||null===i||Array.isArray(i))return null;const n=i;return 1!==n.v?null:tt(n.versionId)&&tt(n.nodeId)&&tt(n.compositionId)&&et(n.startedAt)&&et(n.reachedAt)?n.startedAt>e+864e5?null:e-n.startedAt>2592e6?(it(t),o.log.debug("[workflows] The visitor's position is older than 30 days and was forgotten",{workflowId:t}),null):{versionId:n.versionId,nodeId:n.nodeId,compositionId:n.compositionId,startedAt:n.startedAt,reachedAt:Math.min(n.reachedAt,e)}:null}catch(e){return o.log.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(t,e){return h(this,void 0,void 0,(function*(){var i;try{const s=this.services.fetchWorkflow(this.workflowId);this.readiedCompositions.add(e),this.services.prefetchComposition(e);const n=yield this.waitForAnswer(s);if(this.hasEnded())return;const r=this.compositionToShow("live"===(null==n?void 0:n.status)?n.workflow:null,e),d=this.showFirstComposition(r,e),[a,l]=yield Promise.all([s,d]);if(this.hasEnded())return;let u=l;if("failed"===u.status&&"stopped"!==u.reason&&r!==e&&(u=yield this.fallBackToTheComposition(r,e),this.hasEnded()))return;let c=t,h=e;if("failed"===u.status){if("stopped"===u.reason)return;if(!t||t.compositionId===this.tagCompositionId)return void this.refuse(u.code);{o.log.debug("[workflows] The composition a returning visitor was on cannot be shown, so they start again",{compositionId:t.compositionId}),it(this.workflowId),c=null;const e=yield this.swapToComposition(this.tagCompositionId,"live"===a.status?a.workflow:null);if(this.hasEnded())return;if("shown"!==e.status)return void this.refuse(null!==(i=u.code)&&void 0!==i?i:"failed"===e.status?e.code:void 0);h=this.tagCompositionId}}if("live"!==a.status)return o.log.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 g=a.workflow,f=a.origin;if(c&&c.versionId!==g.versionId){const t=yield this.services.fetchWorkflow(this.workflowId,{versionId:c.versionId});if(this.hasEnded())return;"live"===t.status&&t.workflow.versionId===c.versionId?(g=t.workflow,f=t.origin):(o.log.debug("[workflows] The version a visitor started on cannot be read, so they continue as a new visitor",{versionId:c.versionId}),it(this.workflowId),c=null)}const m=p(g.graph);let v=c&&this.fitsTheGraph(c,g,m)?c:null;const w=null===v;if(null===v){c&&(o.log.debug("[workflows] The place a visitor was kept at is not in the workflow, so they continue as a new visitor"),it(this.workflowId));const t=function(t,e){for(const o of t.nodes)if("composition"===o.type&&o.compositionId===e)return o}(g.graph,this.tagCompositionId);if(!t)return o.log.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();v={versionId:g.versionId,nodeId:t.id,compositionId:this.tagCompositionId,startedAt:e,reachedAt:e}}const b=yield this.showThePlace(v.compositionId,g,h);if(this.hasEnded())return;if("plain"===b)return void(yield this.becomePlain());this.activate(g,f,m,v,w)}catch(t){o.log.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(((o,i)=>{let s=null;const n=t=>{null!==s&&clearTimeout(s),s=null,this.cancelWaitForAnswer=null,o(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,i(t)}))}))}showFirstComposition(t,e){t!==e&&o.log.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){o.log.debug("[workflows] The composition of the tag could not be shown",{error:t})}}compositionToShow(t,e){if(!t)return e;const o=ht(e,t.translations,this.visitorLanguages);return this.copiesThatCannotBeShown.has(o)?e:o}noteThatTheCopyCannotBeShown(t,e){this.copiesThatCannotBeShown.has(t)||(this.copiesThatCannotBeShown.add(t),o.log.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(t,e){return h(this,void 0,void 0,(function*(){this.noteThatTheCopyCannotBeShown(t,e);const o=yield this.viewport.swapTo(e);return"shown"===o.status?{status:"ready"}:Object.assign({status:"failed",reason:"busy"===o.reason?"error":o.reason},o.code?{code:o.code}:{})}))}swapToComposition(t,e){return h(this,void 0,void 0,(function*(){const i=this.compositionToShow(e,t);i!==t&&o.log.debug("[workflows] A composition is shown in the visitor's language",{compositionId:t,copyId:i});const s=yield this.viewport.swapTo(i,t);return"shown"===s.status||i===t||"stopped"===s.reason||"busy"===s.reason?s:this.hasEnded()?{status:"failed",reason:"stopped"}:(this.noteThatTheCopyCannotBeShown(i,t),this.viewport.swapTo(t))}))}showThePlace(t,e,o){return h(this,void 0,void 0,(function*(){const i=this.compositionToShow(e,t);if(o===t&&this.viewport.currentCompositionId()===i)return"shown";return"shown"===(yield this.swapToComposition(t,e)).status||o===t?"shown":"plain"}))}fitsTheGraph(t,e,o){if(t.versionId!==e.versionId)return!1;const i=o.nodesById.get(t.nodeId);return v(i)&&i.compositionId===t.compositionId}activate(t,e,i,s,n){var r;this.workflow=t,this.index=i,this.position=s,this.mode="running";const d=this.services.createCounts({workflowId:this.workflowId,versionId:t.versionId,token:null!==(r=t.eventToken)&&void 0!==r?r:null,apiOrigin:e,isActive:()=>"ended"!==this.mode&&this.host.isConnected});d.start(),this.counts=d,n&&(ot(this.workflowId,s),d.count("n",s.nodeId)),o.log.debug("[workflows] The workflow runs",{workflowId:this.workflowId,versionId:t.versionId,isNewVisitor:n}),this.viewport.enableAutoscale();const a=this.viewport.currentStage();a&&this.armStage(a,s.nodeId),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}becomePlain(){return h(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&&o.log.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(e){const i=this.viewport.currentStage(),s=(null==i?void 0:i.getAttribute(t.REFUSED_HOST_ATTRIBUTE))||e||"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(t.REFUSED_HOST_ATTRIBUTE,s),o.log.debug("[workflows] The composition of the tag cannot be shown",{workflowId:this.workflowId,reason:s})}listenToThePage(){this.host.addEventListener(d.WORKFLOW_EVENT_TYPE,this.onPageEvent),document.addEventListener("visibilitychange",this.onVisibilityChange),this.removeListeners.push((()=>this.host.removeEventListener(d.WORKFLOW_EVENT_TYPE,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 o of t.slice(e))this.pageEvents.add(o);return}const o=t[e];this.react([{type:"pageEvent",name:o.name,values:o.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,o;const i=this.stages.get(t);null===(e=null==i?void 0:i.signals)||void 0===e||e.stop(),null===(o=null==i?void 0:i.stopWatchingReady)||void 0===o||o.call(i),this.stages.delete(t)}armStage(t,o){var i,s,n;const r=this.workflow,d=this.index;if(!r||!d)return;const a=d.nodesById.get(o);if(!v(a))return;const l=null!==(i=this.stages.get(t))&&void 0!==i?i:{compositionId:a.compositionId,signals:null,stopWatchingReady:null};null===(s=l.signals)||void 0===s||s.stop(),null===(n=l.stopWatchingReady)||void 0===n||n.call(l),this.stages.set(t,l);const u=z(r.graph,o,{index:d});l.signals=St({stage:t,watch:u,emit:e=>this.onSignals(t,e)});const c=e.buildWorkflowWatch(u);if(0===c.tables.length&&0===c.fields.length&&0===c.goals.length)return;const h=()=>this.services.deliverWatch(t,l.compositionId,c);h(),t.addEventListener("widgetic:ready",h),l.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,s=this.position;if(e&&i&&s)for(const n of t){let t;try{t=B(e.graph,{nodeId:s.nodeId},n,{index:i})}catch(t){o.log.debug("[workflows] The engine could not decide on a signal",{signal:n.type,error:t});continue}if("moved"===t.outcome)return void this.moveOn(t,!1)}}moveOn(t,e){return h(this,void 0,void 0,(function*(){const i=this.index,s=this.position;if(!i||!s)return;const n=i.nodesById.get(t.position.nodeId);if(!v(n))return;let r;this.stepping=!0,this.cancelRetry(),this.cancelSchedules(),this.pendingStageNodeId=n.id;try{r=yield this.swapToComposition(n.compositionId,this.workflow)}catch(t){o.log.debug("[workflows] The next composition could not be built",{compositionId:n.compositionId,error:t}),r={status:"failed",reason:"error"}}this.pendingStageNodeId=null,this.stepping=!1,this.hasEnded()||("shown"===r.status?this.completeStep(t,n,s):this.failStep(t,n,s,e))}))}completeStep(t,e,i){const s=Object.assign(Object.assign({},i),{nodeId:e.id,compositionId:e.compositionId,reachedAt:Date.now()});this.position=s,ot(this.workflowId,s),this.countStep(i.nodeId,t,e.id),o.log.debug("[workflows] The visitor moved on",{from:i.compositionId,to:e.compositionId}),this.host.dispatchEvent(new CustomEvent(d.WORKFLOW_STEP_EVENT_TYPE,{detail:{workflowId:this.workflowId,from:i.compositionId,to:e.compositionId},bubbles:!0,composed:!0})),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}countStep(t,e,o){const i=this.counts,s=this.index;if(!i||!s)return;const n=m(s,t).find((t=>t.target===e.firedTriggerId));n&&i.count("e",n.id);for(const t of e.passedNodeIds)i.count("n",t);for(const t of e.takenEdgeIds)i.count("e",t);i.count("n",o)}failStep(t,e,i,s){var n;null===(n=this.counts)||void 0===n||n.count("f",e.id),o.log.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e.compositionId,isRetry:s}),this.armSchedules(),s||this.scheduleRetry(t,i.nodeId),this.drainPageEvents()}scheduleRetry(t,e){this.cancelRetry(),this.retryTimer=setTimeout((()=>{var o;this.retryTimer=null,"running"!==this.mode||this.stepping||this.hasEnded()||(null===(o=this.position)||void 0===o?void 0:o.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:s,schedule:n}of z(t.graph,i.nodeId,{index:e}).schedules){const t=$(n,i.reachedAt,Date.now());void 0!==t?this.waitFor(s,n,i.nodeId,t):o.log.debug("[workflows] A Scheduled trigger has no usable time and is ignored",{triggerId:s})}}waitFor(t,e,i,s){const n=setTimeout((()=>{this.scheduleTimers.delete(n);const s=this.position;if("running"!==this.mode||this.stepping||this.hasEnded()||!s||s.nodeId!==i)return;const r=$(e,s.reachedAt,Date.now());void 0!==r&&(r>0?this.waitFor(t,e,i,r):(o.log.debug("[workflows] A wait is over",{triggerId:t}),this.react([{type:"scheduled",triggerId:t}])))}),Math.min(s,432e5));this.scheduleTimers.add(n)}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 o=null===(e=this.position)||void 0===e?void 0:e.nodeId;o&&(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)!==o)return;let e=0;for(const t of this.compositionsReachableFrom(o)){const o=this.compositionToShow(this.workflow,t);if(!this.readiedCompositions.has(o)){if(e>=5)break;this.readiedCompositions.add(o),e+=1,this.services.prefetchComposition(o)}}})))}compositionsReachableFrom(t){const e=this.index;if(!e)return[];const o=[],i=new Set;for(const s of b(e,t)){const t=[s.id];for(;t.length>0;){const s=t.pop();if(!i.has(s)){i.add(s);for(const i of m(e,s)){const s=e.nodesById.get(i.target);v(s)?o.includes(s.compositionId)||o.push(s.compositionId):w(s)&&t.push(s.id)}}}}return o}hasEnded(){return"ended"===this.mode||!this.host.isConnected&&(o.log.debug("[workflows] The tag left the page, so its workflow ends",{workflowId:this.workflowId}),this.stop(),!0)}stop(){var t,e,i,s,n,r;if("ended"!==this.mode){try{null===(t=this.counts)||void 0===t||t.flushBeforeLeaving()}catch(t){o.log.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===(s=t.signals)||void 0===s||s.stop(),null===(n=t.stopWatchingReady)||void 0===n||n.call(t);this.stages.clear(),this.pageEvents.clear();try{null===(r=this.counts)||void 0===r||r.dispose()}catch(t){o.log.debug("[workflows] The counts could not be closed",{error:t})}this.viewport.destroy()}}}window.__widgeticEmbedWorkflows=Object.freeze({contractVersion:1,startWorkflowEmbed:function(t,e){var i,s,n;const d=(null!==(i=t.getAttribute("workflow-id"))&&void 0!==i?i:"").trim(),a=(null!==(s=t.getAttribute("composition-id"))&&void 0!==s?s:"").trim();if(!ft(d)||""===a)return o.log.debug("[workflows] The tag is not a workflow embed, so it is embedded as it is",{workflowId:d,tagCompositionId:a}),null;const l={fetchWorkflow:yt,createCounts:t=>new rt(t),deliverWatch:Vt,prefetchComposition:Dt,whenIdle:Ut,visitorLanguages:ct,firstCompositionWaitMilliseconds:2e3,viewport:{}},u=Object.assign(Object.assign(Object.assign({},l),e.services),{viewport:Object.assign(Object.assign({},l.viewport),null===(n=e.services)||void 0===n?void 0:n.viewport)}),c=new qt(t,d,a,e,u);try{c.start()}catch(t){return o.log.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{workflowId:d,error:t}),c.stop(),null}const h={stop:()=>c.stop()};return r.registerWorkflowEmbed(t,h),h}})}((window.__widgeticEmbedSharedServices||{}).hostBridgeMarkers,(window.__widgeticEmbedSharedServices||{}).hostWorkflowWatch,(window.__widgeticEmbedSharedServices||{}).logger,(window.__widgeticEmbedSharedServices||{}).mountDirectWidget,(window.__widgeticEmbedSharedServices||{}).publicEmbedLookup,(window.__widgeticEmbedSharedServices||{}).publishedHostBridge,(window.__widgeticEmbedSharedServices||{}).workflowEmbedRegistry,(window.__widgeticEmbedSharedServices||{}).workflowPageEvents,(window.__widgeticEmbedSharedServices||{}).abVisitor,(window.__widgeticEmbedSharedServices||{}).autoscaleManager,(window.__widgeticEmbedSharedServices||{}).declarativeEmbedParser,(window.__widgeticEmbedSharedServices||{}).publishedHostDisplay);
1
+ !function(t,e,i,o,s,n,r,a,d,l,h,u){"use strict";function c(t,e,i,o){return new(i||(i=Promise))((function(s,n){function r(t){try{d(o.next(t))}catch(t){n(t)}}function a(t){try{d(o.throw(t))}catch(t){n(t)}}function d(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(r,a)}d((o=o.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const g=/^[A-Za-z0-9_-]{1,64}$/;function f(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)p(i,e.source,e),p(o,e.target,e);return{graph:t,nodesById:e,outgoingBySource:i,incomingByTarget:o}}function p(t,e,i){const o=t.get(e);o?o.push(i):t.set(e,[i])}function m(t,e){return t.outgoingBySource.get(e)??[]}function v(t){return"composition"===t?.type}function w(t){return"condition"===t?.type}function b(t,e){const i=[];for(const s of m(t,e)){const e=t.nodesById.get(s.target);o=e,"trigger"===o?.type&&i.push(e)}var o;return i}function y(t,e,i){return m(t,e).find((t=>t.sourcePort===i))}const I={text:["is","isNot","contains","doesNotContain","startsWith","endsWith","isEmpty","isNotEmpty"],number:["is","isNot","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"],boolean:["is","isNot"]},k=["is","isNot","contains","doesNotContain","startsWith","endsWith","greaterThan","atLeast","lessThan","atMost","isEmpty","isNotEmpty"];function T(t){return null==t||"string"==typeof t&&""===t.trim()}function E(t){return null==t?"":String(t).trim().toLowerCase()}function S(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 A=new Set(["true","yes","1","on"]),C=new Set(["false","no","0","off"]);function O(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(A.has(e))return!0;if(C.has(e))return!1}}function H(t,e){const{operator:i}=t;if("isEmpty"===i)return T(e);if("isNotEmpty"===i)return!T(e);if(!function(t,e){return I[e].includes(t)}(i,t.field.type))return!1;switch(t.field.type){case"number":return function(t,e,i){const o=S(e),s=S(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=O(e),s=O(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=E(e),s=E(i),n=T(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 W(t,e){if(0===t.tests.length)return!1;const i=t=>H(t,e(t.field));return"any"===t.match?t.tests.some(i):t.tests.every(i)}const _={seconds:1e3,minutes:6e4,hours:36e5,days:864e5,weeks:6048e5},N=["seconds","minutes","hours","days","weeks"],M=365*_.days;function L(t){return"string"==typeof t&&N.includes(t)}function R(t,e){if("after"===t.mode){const i=function(t,e){if("number"!=typeof t||!Number.isInteger(t)||t<1)return;if(!L(e))return;const i=t*_[e];return i<=M?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 $(t,e,i){const o=R(t,e);return void 0===o?void 0:Math.max(0,o-i)}function F(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 P(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=y(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(v(e))return{destination:e,passedNodeIds:o,takenEdgeIds:s};if(!w(e))break;o.push(e.id);const i=e.cases.find((t=>W(t,n)));r=y(t,e.id,i?i.id:"default")}return{passedNodeIds:o,takenEdgeIds:s}}function B(t,e,i,o={}){const s=o.index??f(t),n=s.nodesById.get(e.nodeId);if(!v(n))return{outcome:"ignored",reason:"unknown_position"};const r=[];for(const t of b(s,n.id)){if(!F(t,i))continue;r.push(t.id);const e=P(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 x(t,e,i){t.some((t=>i(t,e)))||t.push(e)}function j(t,e,i,o){const s=[],n=y(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&&x(o,{table:i,column:e.field.name},((t,e)=>t.table===e.table&&t.column===e.column));for(const i of m(t,e))s.push(i.target)}}}function V(t,e,i={}){const o=i.index??f(t),s={inputTables:[],inputColumns:[],actionIds:[],pageEventNames:[],schedules:[]},n=(t,e)=>t===e;for(const t of b(o,e)){const e=t.trigger;switch(e.kind){case"input":if(""===e.table)break;x(s.inputTables,e.table,n),j(o,t.id,e.table,s.inputColumns);break;case"action":""!==e.actionId&&x(s.actionIds,e.actionId,n);break;case"pageEvent":""!==e.name&&x(s.pageEventNames,e.name,n);break;case"scheduled":s.schedules.push({triggerId:t.id,schedule:e.schedule})}}return s}class z{issues=[];report(t,e){this.issues.push({code:t,severity:"error",detail:e})}}function D(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function U(t){return"string"==typeof t&&g.test(t)?t:void 0}function q(t,e=200){return"string"==typeof t&&t.length<=e?t:void 0}function Z(t){return"text"===t||"number"===t||"boolean"===t?t:void 0}function Y(t,e,i){if(!D(t))return void i.report("malformed",e);const o=function(t,e,i){if(!D(t))return void i.report("malformed",e);const o="input"===t.kind||"event"===t.kind?t.kind:void 0,s=q(t.name,64),n=Z(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&&k.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:q(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 G(t,e,i){if(D(t))switch(t.kind){case"input":{const o=q(t.table);return void 0===o&&i.report("malformed",`${e}.table`),void 0===o?void 0:{kind:"input",table:o}}case"action":{const o=q(t.actionId);return void 0===o&&i.report("malformed",`${e}.actionId`),void 0===o?void 0:{kind:"action",actionId:o}}case"pageEvent":{const o=q(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=D(t)?q(t.name,64):void 0,r=D(t)?Z(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(D(t)&&"after"===t.mode&&"number"==typeof t.amount&&L(t.unit)&&Number.isFinite(t.amount))return{mode:"after",amount:t.amount,unit:t.unit};if(D(t)&&"at"===t.mode){const e=q(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 J(t,e,i){if(!D(t))return void i.report("malformed",e);const o=U(t.id);o||i.report("bad_id",`${e}.id`);const s=function(t){if(void 0!==t)return D(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=q(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=G(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(!D(t)||!Array.isArray(t.tests)||t.tests.length>100)return void i.report("malformed",e);const o=U(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=q(t.label),void 0===n&&i.report("malformed",`${e}.label`));const r=[];return t.tests.forEach(((t,o)=>{const s=Y(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 K(t){const e=new z;if(!D(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=J(t,`nodes[${o}]`,e);s&&i.push(s)}));const o=[];return t.edges.forEach(((t,i)=>{const s=function(t,e,i){if(!D(t))return void i.report("malformed",e);const o=U(t.id),s=U(t.source),n=U(t.sourcePort),r=U(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 Q=/^[A-Za-z0-9_.:-]{1,128}$/;function X(t){return`widgetic_workflow_${t}`}function tt(t){return"string"==typeof t&&Q.test(t)}function et(t){return"number"==typeof t&&Number.isFinite(t)&&t>=0}function it(t,e){try{d.writeStoredValue(X(t),JSON.stringify({v:1,versionId:e.versionId,nodeId:e.nodeId,compositionId:e.compositionId,startedAt:e.startedAt,reachedAt:e.reachedAt}))}catch(e){i.log.debug("[workflows] The visitor's position could not be kept",{workflowId:t,error:e})}}function ot(t){d.removeStoredValue(X(t))}const st=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,nt=/^[A-Za-z0-9_-]{1,64}$/,rt=new Set(["n","e","f"]),at=new Map([["timeout","t"],["widget_error","e"],["build","b"],["other","o"]]);function dt(t,e,i){return i?`${t}:${e}:${i}`:`${t}:${e}`}class lt{constructor(t){this.pending=[],this.lastEventOf=new Map,this.flushTimer=null,this.waitingHeights=new Map,this.settledHeights=[],this.reportedSteps=new Set,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,o){if(this.stopped||!this.options.token)return;if(!rt.has(t)||!nt.test(e)||!Number.isInteger(i)||i<1)return;const s="f"===t&&"string"==typeof o?at.get(o):void 0,n=dt(t,e,s);let r=i;for(;r>0;){let i=this.lastEventOf.get(n);(!i||i.c>=50)&&(i=Object.assign({k:t,id:e,c:0},s?{r:s}:{}),this.pending.push(i),this.lastEventOf.set(n,i));const o=Math.min(r,50-i.c);i.c+=o,r-=o}this.pending.length>=100?this.flush():null===this.flushTimer&&(this.flushTimer=setTimeout((()=>this.flush()),2e3))}noteHeight(t,e){if(this.stopped||!this.options.token)return;if(!st.test(t))return;if(!Number.isFinite(e))return;const i=Math.round(e);if(i<1||i>1e5)return;const o=t.toLowerCase();if(this.reportedSteps.has(o))return;const s=this.waitingHeights.get(o);(null==s?void 0:s.height)!==i&&(!s&&this.waitingHeights.size+this.reportedSteps.size>=10||(s&&clearTimeout(s.timer),this.waitingHeights.set(o,{height:i,timer:setTimeout((()=>this.settleHeight(o)),3e3)})))}flushBeforeLeaving(){if(!this.stopped&&this.options.token)for(this.settleWaitingHeights();this.pending.length>0||this.settledHeights.length>0;){const t=this.takeBatch(),e=this.takeSettledHeights();if(!this.options.isActive())return void this.forgetPending();this.sendWithBeacon(t,e)}}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=dt(e.k,e.id,e.r);this.lastEventOf.get(t)===e&&this.lastEventOf.delete(t)}return t}takeSettledHeights(){return this.settledHeights.splice(0,10)}settleHeight(t){const e=this.waitingHeights.get(t);e&&(this.waitingHeights.delete(t),this.handOver(t,e.height),this.flush())}settleWaitingHeights(){for(const[t,e]of this.waitingHeights)clearTimeout(e.timer),this.handOver(t,e.height);this.waitingHeights.clear()}handOver(t,e){this.reportedSteps.add(t),this.settledHeights.push({compositionId:t,height:e})}forgetPending(){null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.pending=[],this.lastEventOf.clear();for(const t of this.waitingHeights.values())clearTimeout(t.timer);this.waitingHeights.clear(),this.settledHeights=[]}flush(){if(null!==this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.stopped||0===this.pending.length&&0===this.settledHeights.length)return;if(!this.options.isActive())return void this.forgetPending();const t=this.takeBatch(),e=this.takeSettledHeights();this.sendWithRequest(t,e),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,e){return JSON.stringify(Object.assign({versionId:this.options.versionId,token:this.options.token,events:t.map((t=>Object.assign(Object.assign({k:t.k,id:t.id},t.c>1?{c:t.c}:{}),t.r?{r:t.r}:{})))},e.length>0?{heights:e}:{}))}sendWithBeacon(t,e){try{const o=this.reportBody(t,e),s="undefined"!=typeof navigator?navigator.sendBeacon:void 0;if("function"==typeof s&&s.call(navigator,this.reportAddress(),new Blob([o],{type:"text/plain"})))return void i.log.debug("[workflows] Counts handed to the browser to send",{eventCount:t.length,heightCount:e.length})}catch(t){i.log.debug("[workflows] The browser would not take counts to send as the page closes",{error:t})}this.sendWithRequest(t,e)}sendWithRequest(t,e){return c(this,void 0,void 0,(function*(){try{const o=yield fetch(this.reportAddress(),{method:"POST",mode:"cors",credentials:"omit",keepalive:!0,headers:{"Content-Type":"text/plain"},body:this.reportBody(t,e)});if(401===o.status)return i.log.warn("[workflows] The gateway refused the token for counts, so this embed stops reporting",{workflowId:this.options.workflowId}),void this.dispose();i.log.debug("[workflows] Counts sent",{eventCount:t.length,heightCount:e.length,status:o.status})}catch(o){i.log.debug("[workflows] Counts could not be sent and were dropped",{eventCount:t.length,heightCount:e.length,error:o})}}))}}const ht=/^[a-z0-9]{1,8}(-[a-z0-9]{1,8}){0,4}$/,ut=/^[A-Za-z0-9_.:-]{1,128}$/;function ct(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function gt(t){if("string"!=typeof t||t.length>35)return null;const e=t.toLowerCase();return ht.test(e)?e:null}function ft(){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 i.log.debug("[workflows] The languages of the browser could not be read",{error:t}),[]}}function pt(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 mt=/^[A-Za-z0-9_-]{1,64}$/,vt=/^[A-Za-z0-9_.:-]{1,128}$/;function wt(t){return mt.test(t)}function bt(t){return"object"==typeof t&&null!==t&&!Array.isArray(t)}function yt(t,e){var o;if(!bt(t)||!0!==t.success||!bt(t.data))return{kind:"unreadable"};const s=t.data;if("paused"===s.status)return{kind:"paused"};if("live"!==s.status)return{kind:"unreadable"};if("string"!=typeof s.versionId||!vt.test(s.versionId))return{kind:"unreadable"};const n=K(s.graph);if(!n.graph||n.issues.length>0)return i.log.warn("[workflows] The published graph could not be read, so the embed stays a plain embed",{workflowId:e,issueCount:n.issues.length,firstIssue:null===(o=n.issues[0])||void 0===o?void 0:o.code}),{kind:"unreadable"};const r={workflowId:"string"==typeof s.workflowId?s.workflowId:e,versionId:s.versionId,timezone:"string"==typeof s.timezone&&""!==s.timezone.trim()&&s.timezone.length<=64?s.timezone:"UTC",graph:n.graph};"number"==typeof s.versionNumber&&Number.isInteger(s.versionNumber)&&(r.versionNumber=s.versionNumber),"string"==typeof s.publishedAt&&(r.publishedAt=s.publishedAt),"string"==typeof s.startCompositionId&&vt.test(s.startCompositionId)&&(r.startCompositionId=s.startCompositionId);const a=function(t){if(!ct(t))return;const e=Object.create(null);let i=0;for(const[o,s]of Object.entries(t)){if(i>=64)break;if(!ut.test(o)||!ct(s))continue;const t=gt(s.rootLanguage);if(null===t||!ct(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=gt(t);null!==i&&"string"==typeof e&&ut.test(e)&&(n[i]=e,r+=1)}0!==r&&(e[o]={rootLanguage:t,compositions:n},i+=1)}return 0===i?void 0:e}(s.translations);return a&&(r.translations=a),"string"==typeof s.eventToken&&""!==s.eventToken&&s.eventToken.length<=2048&&(r.eventToken=s.eventToken),{kind:"live",workflow:r}}function It(t,e){return c(this,void 0,void 0,(function*(){const o=new AbortController,s=setTimeout((()=>o.abort()),1e4);try{const i=yield fetch(t,{method:"GET",mode:"cors",signal:o.signal});if(404===i.status)return{kind:"missing"};if(!i.ok)return{kind:"unreachable"};let s;try{s=yield i.json()}catch(t){return{kind:"unreadable"}}const n=yt(s,e);return"live"===n.kind?{kind:"live",workflow:n.workflow}:n}catch(t){return i.log.debug("[workflows] A host could not be reached",{workflowId:e,error:t}),{kind:"unreachable"}}finally{clearTimeout(s)}}))}const kt=new Map;function Tt(t,e={}){var o,n;if(!wt(t)||void 0!==e.versionId&&!vt.test(e.versionId))return Promise.resolve({status:"unavailable",reason:"not_found"});const r=`${t}|${null!==(o=e.versionId)&&void 0!==o?o:""}|${(null!==(n=e.origins)&&void 0!==n?n:[]).join(",")}`,a=kt.get(r);if(a)return a;const d=function(t,e){return c(this,void 0,void 0,(function*(){var o;const n=null!==(o=e.origins)&&void 0!==o?o:s.publicEmbedApiOrigins(),r=e.versionId?`/embed/workflows/${encodeURIComponent(t)}/versions/${encodeURIComponent(e.versionId)}`:`/embed/workflows/${encodeURIComponent(t)}`;let a=!1,d=!1;for(const e of n){const i=yield It(`${e}${r}`,t);if("live"===i.kind)return{status:"live",workflow:i.workflow,origin:e};if("paused"===i.kind)return{status:"paused"};"missing"===i.kind&&(a=!0),"unreadable"===i.kind&&(d=!0)}const l=a?"not_found":d?"unreadable":"unreachable";return i.log.debug("[workflows] The workflow is not available",{workflowId:t,reason:l}),{status:"unavailable",reason:l}}))}(t,e);return kt.set(r,d),d.finally((()=>{kt.get(r)===d&&kt.delete(r)})),d}const Et={clicks:"click",submissions:"submit",plays:"play"},St=new Set(["__proto__","constructor","prototype"]);function At(t){const e=t.detail;return"object"!=typeof e||null===e||Array.isArray(e)?{}:e}function Ct(t,e){return("submissions"!==t.metric||"FORM"===e.tagName)&&(("plays"!==t.metric||"VIDEO"===e.tagName||"AUDIO"===e.tagName)&&(null!==t.selector?d.elementMatchesGoalTarget(e,t.selector):"clicks"!==t.metric||null!==e.closest('button, a, input[type="button"], input[type="submit"], [role="button"], [onclick], [data-click-track]')))}function Ot({stage:t,watch:o,emit:s}){var n;let r=!1;const a=[];if(o.inputTables.length>0){const e=new Map;for(const{table:t,column:i}of o.inputColumns){const o=null!==(n=e.get(t))&&void 0!==n?n:new Set;o.add(i),e.set(t,o)}const d=new Set,l=t=>{var n;if(r)return;const a=At(t),l=a.table;if("string"!=typeof l||!o.inputTables.includes(l))return;if("string"==typeof a.entryId&&""!==a.entryId){const t=`${l}:${a.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 h=function(t,e){const i={};if("object"!=typeof t||null===t||Array.isArray(t))return i;for(const o of e){if(St.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}(a.values,null!==(n=e.get(l))&&void 0!==n?n:new Set);i.log.debug("[workflows] An entry was saved in a watched table",{table:l,valueCount:Object.keys(h).length}),s([{type:"input",table:l,values:h}])};t.addEventListener("widgetic:submitted",l),a.push((()=>t.removeEventListener("widgetic:submitted",l)))}if(o.actionIds.length>0){const n=t=>{if(r)return;const e=At(t);let n=null;"string"==typeof e.goalId?n=e.goalId:"string"==typeof e.metric&&""!==e.metric&&(n="string"==typeof e.goalTarget&&""!==e.goalTarget?`${e.metric}@${e.goalTarget}`:e.metric),null!==n&&o.actionIds.includes(n)&&(i.log.debug("[workflows] A widget reported a watched action",{actionId:n}),s([{type:"action",actionId:n}]))};t.addEventListener("widgetic:goal",n),a.push((()=>t.removeEventListener("widgetic:goal",n)));const l=[];for(const t of o.actionIds){const i=e.splitActionId(t);i&&(d=i.metric,Object.prototype.hasOwnProperty.call(Et,d))&&l.push({actionId:t,metric:i.metric,selector:i.selector})}if(l.length>0){let e=null,o=()=>{};const n=t=>{const e=t.target instanceof Element?t.target:null;if(!e)return[];const i=[];for(const o of l)Et[o.metric]===t.type&&Ct(o,e)&&i.push({type:"action",actionId:o.actionId});return i},d=t=>{if(r)return;const e=n(t);0!==e.length&&(i.log.debug("[workflows] A watched action happened in the widget",{actionIds:e.map((t=>t.actionId))}),s(e))},h=()=>{var i;const s=t.querySelector("[data-widgetic-direct]"),n=null!==(i=null==s?void 0:s.shadowRoot)&&void 0!==i?i:null;if(!n||n===e)return;o();const r=new Set(l.map((t=>Et[t.metric])));for(const t of r)n.addEventListener(t,d,!0);e=n,o=()=>{for(const t of r)n.removeEventListener(t,d,!0);e=null,o=()=>{}}};t.addEventListener("widgetic:ready",h),a.push((()=>t.removeEventListener("widgetic:ready",h))),a.push((()=>o())),h()}}var d;return{stop:()=>{if(!r){r=!0;for(const t of a)try{t()}catch(t){i.log.debug("[workflows] A listener could not be removed",{error:t})}}}}}const Ht=50,Wt=2e3,_t=150,Nt=5,Mt=300,Lt=2e4;function Rt(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 $t(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 Ft(t,e,i){return null===t||e!==t&&Math.abs(e-t)>=i}const Pt=["width","height","resize","resize-mode","render-mode","use-iframe","theme","mode","colors","sandbox","autoload","adaptive","responsive"],Bt=["values","context","media-resolver"],xt=["design","content","content-items","contentitems","items"];function jt(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 i.log.debug("[workflows] The browser could not watch heights",{error:t}),null}}function Vt(t){return t.getBoundingClientRect().height}function zt(){try{return"function"==typeof window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}catch(t){return!1}}function Dt(t){return"number"==typeof t&&Number.isFinite(t)&&t>0}class Ut{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.firstVisitStage=null,this.firstVisitStageIsReady=!1,this.host=t.host,this.services=t.services,this.prefersReducedMotion=null!==(e=t.prefersReducedMotion)&&void 0!==e?e:zt,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);const i=this.holdRoomFor(t),o=this.buildStage(t,!0,e);this.current=o,this.firstVisitStage=i||t!==e?null:o;const s=this.waitUntilShown(o,null,(t=>{if("ready"===t.status&&this.firstVisitStage===o&&(this.firstVisitStageIsReady=!0),"ready"===t.status&&!this.destroyed&&this.autoscaleOn&&this.current===o){const t=this.measure(o.element);Dt(t)&&this.applyHeight(t,"immediate")}}));return this.viewportElement.appendChild(o.element),this.services.hydrate(o.element),{stage:o.element,ready:s}}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:jt)((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);Dt(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(t){return c(this,arguments,void 0,(function*(t,e=t){var o,s,r;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming)return{status:"failed",reason:"busy"};this.enableAutoscale();const a=this.buildStage(t,!1,e);this.incoming=a,this.hideBeside(a.element);const d=this.waitUntilShown(a,null!==(o=this.services.readyTimeoutMilliseconds)&&void 0!==o?o:8e3);this.viewportElement.appendChild(a.element),this.services.hydrate(a.element);const l=yield d;if(this.destroyed)return{status:"failed",reason:"stopped"};if(this.incoming=null,"failed"===l.status)return this.removeStage(a),"timeout"===l.reason&&n.dispatchPublishedHostError(this.host,t,"workflow_step_timeout"),i.log.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:t,reason:l.reason}),Object.assign({status:"failed",reason:"stopped"===l.reason?"stopped":l.reason},l.code?{code:l.code}:{});const h=this.current;this.revealInPlace(a.element),this.current=a,null===(s=this.heightObserver)||void 0===s||s.observe(a.element);const u=this.measure(a.element);return Dt(u)&&this.applyHeight(u,"immediate"),h&&(null===(r=this.heightObserver)||void 0===r||r.unobserve(h.element),this.removeStage(h)),{status:"shown",stage:a.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,o){var s,n,r;const a=document.createElement("widgetic");a.setAttribute("composition-id",t),a.setAttribute("data-widgetic-workflow-stage","1"),a.style.display="block";for(const t of Pt){const e=this.host.getAttribute(t);null!==e&&a.setAttribute(t,e)}this.widthOverride&&a.setAttribute("width",this.widthOverride);for(const t of Bt){const e=this.host.getAttribute(t);null!==e&&a.setAttribute(t,e)}const d=o===(null!==(s=this.host.getAttribute("composition-id"))&&void 0!==s?s:"").trim();d&&this.copyWhatThePageWroteForTheTagComposition(a);const l={element:a,compositionId:t,standsFor:o,reportedHeight:!1,cancelWait:null,stopListening:()=>{}},h=t=>{var e;const i=null===(e=t.detail)||void 0===e?void 0:e.height;if("number"!=typeof i||!Dt(i))return;const o=a.querySelector("iframe");o&&(o.style.height=`${Math.ceil(i)}px`,l.reportedHeight=!0)};a.addEventListener("widgetic:resize",h),l.stopListening=()=>a.removeEventListener("widgetic:resize",h);try{null===(r=(n=this.services).onStageCreated)||void 0===r||r.call(n,a,{compositionId:t,standsFor:o,isFirst:e,carriesPageContent:d})}catch(e){i.log.debug("[workflows] A listener for a new stage failed",{compositionId:t,error:e})}return l}copyWhatThePageWroteForTheTagComposition(t){for(const e of Array.from(this.host.attributes))h.isReservedHostAttribute(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 h.declarativeChildrenOf(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&&Bt.includes(null!==(e=t.attributeName)&&void 0!==e?e:"")}))&&this.mirrorAttributesToStages()})),this.attributeObserver.observe(this.host,{attributes:!0,attributeFilter:[...Bt]})}catch(t){this.attributeObserver=null,i.log.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 Bt){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,o){return new Promise((s=>{const n=t.element;let r=null,a=!1;const d=e=>{if(!a){a=!0,null!==r&&clearTimeout(r),n.removeEventListener("widgetic:ready",l),n.removeEventListener("widgetic:error",h),n.removeEventListener("load",u,!0),t.cancelWait=null;try{null==o||o(e)}catch(e){i.log.debug("[workflows] A stage could not be settled",{compositionId:t.compositionId,error:e})}s(e)}},l=()=>d({status:"ready"}),h=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"})};n.addEventListener("widgetic:ready",l),n.addEventListener("widgetic:error",h),n.addEventListener("load",u,!0),t.cancelWait=()=>d({status:"failed",reason:"stopped"}),null!==e&&(r=setTimeout((()=>d({status:"failed",reason:"timeout"})),e))}))}removeStage(t){var e,o;t.stopListening(),t.element.querySelector("iframe")&&!t.reportedHeight&&this.noteFrameWithoutHeight(t.compositionId),t.element.remove();try{null===(o=(e=this.services).onStageRemoved)||void 0===o||o.call(e,t.element)}catch(e){i.log.debug("[workflows] A listener for a removed stage failed",{compositionId:t.compositionId,error:e})}}noteFrameWithoutHeight(t){this.warnedAboutFrameWithoutHeight||(this.warnedAboutFrameWithoutHeight=!0,i.log.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:Vt)(t)}catch(t){return i.log.debug("[workflows] The height of a stage could not be read",{error:t}),0}}holdRoomFor(t){const e=l.readStoredAutoscaleHeight(t);if(null===e)return!1;const i=this.settings();return this.viewportElement.style.minHeight=`${$t(e,i,this.overlayCap())}px`,!0}settings(){return function(t,e={}){const i=Rt(t,"autoscale-min-height",Ht,Lt),o=Rt(t,"autoscale-max-height",Wt,Lt);return{minHeight:i,maxHeight:Math.max(o,i),debounceDelay:Rt(t,"autoscale-debounce",_t,5e3),threshold:Rt(t,"autoscale-threshold",Nt,Lt),animate:"false"!==t.getAttribute("autoscale-animate")&&!0!==e.prefersReducedMotion,animationDuration:Rt(t,"autoscale-animation-duration",Mt,5e3)}}(this.host,{prefersReducedMotion:this.prefersReducedMotion()})}overlayCap(){return this.host.hasAttribute(u.OVERLAY_HOST_ATTRIBUTE)?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&&Dt(e.height)&&this.applyHeight(e.height,"observed")}applyHeight(t,e){this.tellFirstVisitHeight(t);const i=this.settings(),o=$t(t,i,this.overlayCap());if("immediate"===e)return this.clearHeightTimer(),void this.setHeight(o,i);Ft(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();Ft(this.appliedHeight,t,e.threshold)&&this.setHeight(t,e)}),i.debounceDelay)):o===this.appliedHeight&&this.clearHeightTimer()}tellFirstVisitHeight(t){var e,o;const s=this.current;if(s&&s===this.firstVisitStage&&this.firstVisitStageIsReady&&!this.host.hasAttribute(u.OVERLAY_HOST_ATTRIBUTE)&&(!s.element.querySelector("iframe")||s.reportedHeight))try{null===(o=(e=this.services).onFirstStageHeight)||void 0===o||o.call(e,s.standsFor,Math.ceil(t))}catch(t){i.log.debug("[workflows] A listener for the height of the first stage failed",{compositionId:s.compositionId,error:t})}}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);l.writeStoredAutoscaleHeight(this.current.compositionId,t,Number.isFinite(e)?e:t)}}clearHeightTimer(){null!==this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null),this.pendingHeight=null}}function qt(t,s,r){var a;try{o.setDirectMountWorkflow(t,e.workflowWatchProperty(s,r)),null===(a=n.getPublishedHostBridge(t))||void 0===a||a.sendWorkflowWatch(r)}catch(t){i.log.debug("[workflows] A widget could not be told what to report",{compositionId:s,error:t})}}function Zt(t){try{s.resolvePublishedEmbed(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&&o.warmDirectModule(i)})).catch((()=>{}))}catch(e){i.log.debug("[workflows] A composition could not be got ready",{compositionId:t,error:e})}}function Yt(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 Gt{constructor(t,e,o,s,n){this.host=t,this.workflowId=e,this.tagCompositionId=o,this.options=s,this.services=n,this.mode="loading",this.stages=new Map,this.pageEvents=new a.PageEventQueue,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.readPageEvent(t.detail);e?"running"!==this.mode||this.stepping?this.pageEvents.add(e):this.hasEnded()||this.react([{type:"pageEvent",name:e.name,values:e.values}]):i.log.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 r=n.viewport;this.viewport=new Ut(Object.assign(Object.assign(Object.assign({host:t},r.prefersReducedMotion?{prefersReducedMotion:r.prefersReducedMotion}:{}),s.width?{widthOverride:s.width}:{}),{services:Object.assign(Object.assign(Object.assign(Object.assign({hydrate:s.hydrate},r.createHeightObserver?{createHeightObserver:r.createHeightObserver}:{}),r.measureStageHeight?{measureStageHeight:r.measureStageHeight}:{}),void 0!==r.readyTimeoutMilliseconds?{readyTimeoutMilliseconds:r.readyTimeoutMilliseconds}:{}),{onStageCreated:(t,e)=>this.onStageCreated(t,e.compositionId),onStageRemoved:t=>this.onStageRemoved(t),onFirstStageHeight:(t,e)=>{var i;return null===(i=this.counts)||void 0===i?void 0:i.noteHeight(t,e)}})}))}readVisitorLanguages(){try{const t=this.services.visitorLanguages();return Array.isArray(t)?t.filter((t=>"string"==typeof t)):[]}catch(t){return i.log.debug("[workflows] The languages of the visitor could not be read",{error:t}),[]}}start(){var t;const e=function(t,e=Date.now()){const o=X(t),s=d.readStoredValue(o);if(null===s)return null;try{const o=JSON.parse(s);if("object"!=typeof o||null===o||Array.isArray(o))return null;const n=o;return 1!==n.v?null:tt(n.versionId)&&tt(n.nodeId)&&tt(n.compositionId)&&et(n.startedAt)&&et(n.reachedAt)?n.startedAt>e+864e5?null:e-n.startedAt>2592e6?(ot(t),i.log.debug("[workflows] The visitor's position is older than 30 days and was forgotten",{workflowId:t}),null):{versionId:n.versionId,nodeId:n.nodeId,compositionId:n.compositionId,startedAt:n.startedAt,reachedAt:Math.min(n.reachedAt,e)}:null}catch(e){return i.log.debug("[workflows] The kept position could not be read and is ignored",{workflowId:t,error:e}),null}}(this.workflowId),o=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,o)}run(t,e){return c(this,void 0,void 0,(function*(){var o;try{const s=this.services.fetchWorkflow(this.workflowId);this.readiedCompositions.add(e),this.services.prefetchComposition(e);const n=yield this.waitForAnswer(s);if(this.hasEnded())return;const r=this.compositionToShow("live"===(null==n?void 0:n.status)?n.workflow:null,e),a=this.showFirstComposition(r,e),[d,l]=yield Promise.all([s,a]);if(this.hasEnded())return;let h=l;if("failed"===h.status&&"stopped"!==h.reason&&r!==e&&(h=yield this.fallBackToTheComposition(r,e),this.hasEnded()))return;let u=t,c=e;if("failed"===h.status){if("stopped"===h.reason)return;if(!t||t.compositionId===this.tagCompositionId)return void this.refuse(h.code);{i.log.debug("[workflows] The composition a returning visitor was on cannot be shown, so they start again",{compositionId:t.compositionId}),ot(this.workflowId),u=null;const e=yield this.swapToComposition(this.tagCompositionId,"live"===d.status?d.workflow:null);if(this.hasEnded())return;if("shown"!==e.status)return void this.refuse(null!==(o=h.code)&&void 0!==o?o:"failed"===e.status?e.code:void 0);c=this.tagCompositionId}}if("live"!==d.status)return i.log.debug("[workflows] The workflow is not running, so the tag is a plain embed",{workflowId:this.workflowId,status:d.status}),void(yield this.becomePlain());let g=d.workflow,p=d.origin;if(u&&u.versionId!==g.versionId){const t=yield this.services.fetchWorkflow(this.workflowId,{versionId:u.versionId});if(this.hasEnded())return;"live"===t.status&&t.workflow.versionId===u.versionId?(g=t.workflow,p=t.origin):(i.log.debug("[workflows] The version a visitor started on cannot be read, so they continue as a new visitor",{versionId:u.versionId}),ot(this.workflowId),u=null)}const m=f(g.graph);let v=u&&this.fitsTheGraph(u,g,m)?u:null;const w=null===v;if(null===v){u&&(i.log.debug("[workflows] The place a visitor was kept at is not in the workflow, so they continue as a new visitor"),ot(this.workflowId));const t=function(t,e){for(const i of t.nodes)if("composition"===i.type&&i.compositionId===e)return i}(g.graph,this.tagCompositionId);if(!t)return i.log.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();v={versionId:g.versionId,nodeId:t.id,compositionId:this.tagCompositionId,startedAt:e,reachedAt:e}}const b=yield this.showThePlace(v.compositionId,g,c);if(this.hasEnded())return;if("plain"===b)return void(yield this.becomePlain());this.activate(g,p,m,v,w)}catch(t){i.log.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&&i.log.debug("[workflows] A composition is shown in the visitor's language",{compositionId:e,copyId:t});const{ready:o}=this.viewport.showFirstStage(t,e);return this.markHostMounted(),o}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){i.log.debug("[workflows] The composition of the tag could not be shown",{error:t})}}compositionToShow(t,e){if(!t)return e;const i=pt(e,t.translations,this.visitorLanguages);return this.copiesThatCannotBeShown.has(i)?e:i}noteThatTheCopyCannotBeShown(t,e){this.copiesThatCannotBeShown.has(t)||(this.copiesThatCannotBeShown.add(t),i.log.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(t,e){return c(this,void 0,void 0,(function*(){this.noteThatTheCopyCannotBeShown(t,e);const i=yield this.viewport.swapTo(e);return"shown"===i.status?{status:"ready"}:Object.assign({status:"failed",reason:"busy"===i.reason?"error":i.reason},i.code?{code:i.code}:{})}))}swapToComposition(t,e){return c(this,void 0,void 0,(function*(){const o=this.compositionToShow(e,t);o!==t&&i.log.debug("[workflows] A composition is shown in the visitor's language",{compositionId:t,copyId:o});const s=yield this.viewport.swapTo(o,t);return"shown"===s.status||o===t||"stopped"===s.reason||"busy"===s.reason?s:this.hasEnded()?{status:"failed",reason:"stopped"}:(this.noteThatTheCopyCannotBeShown(o,t),this.viewport.swapTo(t))}))}showThePlace(t,e,i){return c(this,void 0,void 0,(function*(){const o=this.compositionToShow(e,t);if(i===t&&this.viewport.currentCompositionId()===o)return"shown";return"shown"===(yield this.swapToComposition(t,e)).status||i===t?"shown":"plain"}))}fitsTheGraph(t,e,i){if(t.versionId!==e.versionId)return!1;const o=i.nodesById.get(t.nodeId);return v(o)&&o.compositionId===t.compositionId}activate(t,e,o,s,n){var r;this.workflow=t,this.index=o,this.position=s,this.mode="running";const a=this.services.createCounts({workflowId:this.workflowId,versionId:t.versionId,token:null!==(r=t.eventToken)&&void 0!==r?r:null,apiOrigin:e,isActive:()=>"ended"!==this.mode&&this.host.isConnected});a.start(),this.counts=a,n&&(it(this.workflowId,s),a.count("n",s.nodeId)),i.log.debug("[workflows] The workflow runs",{workflowId:this.workflowId,versionId:t.versionId,isNewVisitor:n}),this.viewport.enableAutoscale();const d=this.viewport.currentStage();d&&this.armStage(d,s.nodeId),this.armSchedules(),this.getNextCompositionsReady(),this.drainPageEvents()}becomePlain(){return c(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&&i.log.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(e){const o=this.viewport.currentStage(),s=(null==o?void 0:o.getAttribute(t.REFUSED_HOST_ATTRIBUTE))||e||"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(t.REFUSED_HOST_ATTRIBUTE,s),i.log.debug("[workflows] The composition of the tag cannot be shown",{workflowId:this.workflowId,reason:s})}listenToThePage(){this.host.addEventListener(a.WORKFLOW_EVENT_TYPE,this.onPageEvent),document.addEventListener("visibilitychange",this.onVisibilityChange),this.removeListeners.push((()=>this.host.removeEventListener(a.WORKFLOW_EVENT_TYPE,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,i){var o,s,n;const r=this.workflow,a=this.index;if(!r||!a)return;const d=a.nodesById.get(i);if(!v(d))return;const l=null!==(o=this.stages.get(t))&&void 0!==o?o:{compositionId:d.compositionId,signals:null,stopWatchingReady:null};null===(s=l.signals)||void 0===s||s.stop(),null===(n=l.stopWatchingReady)||void 0===n||n.call(l),this.stages.set(t,l);const h=V(r.graph,i,{index:a});l.signals=Ot({stage:t,watch:h,emit:e=>this.onSignals(t,e)});const u=e.buildWorkflowWatch(h);if(0===u.tables.length&&0===u.fields.length&&0===u.goals.length)return;const c=()=>this.services.deliverWatch(t,l.compositionId,u);c(),t.addEventListener("widgetic:ready",c),l.stopWatchingReady=()=>t.removeEventListener("widgetic:ready",c)}onSignals(t,e){"running"!==this.mode||this.stepping||this.hasEnded()||t===this.viewport.currentStage()&&this.react(e)}react(t){const e=this.workflow,o=this.index,s=this.position;if(e&&o&&s)for(const n of t){let t;try{t=B(e.graph,{nodeId:s.nodeId},n,{index:o})}catch(t){i.log.debug("[workflows] The engine could not decide on a signal",{signal:n.type,error:t});continue}if("moved"===t.outcome)return void this.moveOn(t,!1)}}moveOn(t,e){return c(this,void 0,void 0,(function*(){const o=this.index,s=this.position;if(!o||!s)return;const n=o.nodesById.get(t.position.nodeId);if(!v(n))return;let r;this.stepping=!0,this.cancelRetry(),this.cancelSchedules(),this.pendingStageNodeId=n.id;let a=!1;try{r=yield this.swapToComposition(n.compositionId,this.workflow)}catch(t){i.log.debug("[workflows] The next composition could not be built",{compositionId:n.compositionId,error:t}),a=!0,r={status:"failed",reason:"error"}}this.pendingStageNodeId=null,this.stepping=!1,this.hasEnded()||("shown"===r.status?this.completeStep(t,n,s):this.failStep(t,n,s,e,function(t,e){return e?"build":"timeout"===t.reason?"timeout":"error"===t.reason?"widget_error":"other"}(r,a)))}))}completeStep(t,e,o){const s=Object.assign(Object.assign({},o),{nodeId:e.id,compositionId:e.compositionId,reachedAt:Date.now()});this.position=s,it(this.workflowId,s),this.countStep(o.nodeId,t,e.id),i.log.debug("[workflows] The visitor moved on",{from:o.compositionId,to:e.compositionId}),this.host.dispatchEvent(new CustomEvent(a.WORKFLOW_STEP_EVENT_TYPE,{detail:{workflowId:this.workflowId,from:o.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=m(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,o,s,n){var r;null===(r=this.counts)||void 0===r||r.count("f",e.id,1,n),i.log.debug("[workflows] The next composition could not be shown, so the visitor stays where they are",{compositionId:e.compositionId,isRetry:s,reason:n}),this.armSchedules(),s||this.scheduleRetry(t,o.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,o=this.position;if("running"===this.mode&&!this.stepping&&t&&e&&o)for(const{triggerId:s,schedule:n}of V(t.graph,o.nodeId,{index:e}).schedules){const t=$(n,o.reachedAt,Date.now());void 0!==t?this.waitFor(s,n,o.nodeId,t):i.log.debug("[workflows] A Scheduled trigger has no usable time and is ignored",{triggerId:s})}}waitFor(t,e,o,s){const n=setTimeout((()=>{this.scheduleTimers.delete(n);const s=this.position;if("running"!==this.mode||this.stepping||this.hasEnded()||!s||s.nodeId!==o)return;const r=$(e,s.reachedAt,Date.now());void 0!==r&&(r>0?this.waitFor(t,e,o,r):(i.log.debug("[workflows] A wait is over",{triggerId:t}),this.react([{type:"scheduled",triggerId:t}])))}),Math.min(s,432e5));this.scheduleTimers.add(n)}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 b(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 m(e,s)){const s=e.nodesById.get(o.target);v(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&&(i.log.debug("[workflows] The tag left the page, so its workflow ends",{workflowId:this.workflowId}),this.stop(),!0)}stop(){var t,e,o,s,n,r;if("ended"!==this.mode){try{null===(t=this.counts)||void 0===t||t.flushBeforeLeaving()}catch(t){i.log.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===(o=this.cancelIdleWork)||void 0===o||o.call(this),this.cancelIdleWork=null;for(const t of this.removeListeners.splice(0))t();for(const t of this.stages.values())null===(s=t.signals)||void 0===s||s.stop(),null===(n=t.stopWatchingReady)||void 0===n||n.call(t);this.stages.clear(),this.pageEvents.clear();try{null===(r=this.counts)||void 0===r||r.dispose()}catch(t){i.log.debug("[workflows] The counts could not be closed",{error:t})}this.viewport.destroy()}}}window.__widgeticEmbedWorkflows=Object.freeze({contractVersion:1,startWorkflowEmbed:function(t,e){var o,s,n;const a=(null!==(o=t.getAttribute("workflow-id"))&&void 0!==o?o:"").trim(),d=(null!==(s=t.getAttribute("composition-id"))&&void 0!==s?s:"").trim();if(!wt(a)||""===d)return i.log.debug("[workflows] The tag is not a workflow embed, so it is embedded as it is",{workflowId:a,tagCompositionId:d}),null;const l={fetchWorkflow:Tt,createCounts:t=>new lt(t),deliverWatch:qt,prefetchComposition:Zt,whenIdle:Yt,visitorLanguages:ft,firstCompositionWaitMilliseconds:2e3,viewport:{}},h=Object.assign(Object.assign(Object.assign({},l),e.services),{viewport:Object.assign(Object.assign({},l.viewport),null===(n=e.services)||void 0===n?void 0:n.viewport)}),u=new Gt(t,a,d,e,h);try{u.start()}catch(t){return i.log.warn("[workflows] The workflow could not start, so the tag is embedded as it is",{workflowId:a,error:t}),u.stop(),null}const c={stop:()=>u.stop()};return r.registerWorkflowEmbed(t,c),c}})}((window.__widgeticEmbedSharedServices||{}).hostBridgeMarkers,(window.__widgeticEmbedSharedServices||{}).hostWorkflowWatch,(window.__widgeticEmbedSharedServices||{}).logger,(window.__widgeticEmbedSharedServices||{}).mountDirectWidget,(window.__widgeticEmbedSharedServices||{}).publicEmbedLookup,(window.__widgeticEmbedSharedServices||{}).publishedHostBridge,(window.__widgeticEmbedSharedServices||{}).workflowEmbedRegistry,(window.__widgeticEmbedSharedServices||{}).workflowPageEvents,(window.__widgeticEmbedSharedServices||{}).abVisitor,(window.__widgeticEmbedSharedServices||{}).autoscaleManager,(window.__widgeticEmbedSharedServices||{}).declarativeEmbedParser,(window.__widgeticEmbedSharedServices||{}).publishedHostDisplay);