@drip-apex/sdk 0.1.0 → 0.2.0
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.
- package/README.md +5 -0
- package/dist/bundle-report.json +584 -226
- package/dist/define.cjs +123 -0
- package/dist/define.cjs.map +7 -0
- package/dist/define.mjs +102 -0
- package/dist/define.mjs.map +7 -0
- package/dist/drip.cjs +19262 -0
- package/dist/drip.cjs.map +7 -0
- package/dist/drip.debug.js +1 -1
- package/dist/drip.debug.js.map +1 -1
- package/dist/drip.heatmap.js +1 -1
- package/dist/drip.heatmap.js.map +1 -1
- package/dist/drip.js +1 -1
- package/dist/drip.js.map +1 -1
- package/dist/drip.live.js +1 -1
- package/dist/drip.live.js.map +1 -1
- package/dist/drip.mjs +19246 -0
- package/dist/drip.mjs.map +7 -0
- package/dist/drip.replay-recorder.js +2 -0
- package/dist/drip.replay-recorder.js.map +1 -0
- package/dist/editor.js +147 -142
- package/dist/editor.js.map +4 -4
- package/dist/flags.cjs +1788 -0
- package/dist/flags.cjs.map +7 -0
- package/dist/flags.mjs +1765 -0
- package/dist/flags.mjs.map +7 -0
- package/dist/index.mjs +12 -0
- package/dist/index.mjs.map +2 -2
- package/dist/metafiles/define.cjs.meta.json +28 -0
- package/dist/metafiles/define.mjs.meta.json +32 -0
- package/dist/metafiles/drip.cjs.meta.json +3193 -0
- package/dist/metafiles/drip.debug.meta.json +2859 -574
- package/dist/metafiles/drip.heatmap.meta.json +2732 -460
- package/dist/metafiles/drip.live.meta.json +2732 -460
- package/dist/metafiles/drip.meta.json +2859 -574
- package/dist/metafiles/drip.mjs.meta.json +3235 -0
- package/dist/metafiles/drip.replay-recorder.meta.json +82 -0
- package/dist/metafiles/editor.meta.json +67 -27
- package/dist/metafiles/flags.cjs.meta.json +220 -0
- package/dist/metafiles/flags.mjs.meta.json +225 -0
- package/dist/metafiles/index.meta.json +2717 -491
- package/dist/metafiles/index.mjs.meta.json +14 -4
- package/dist/react/index.js +16621 -13539
- package/dist/react/index.js.map +4 -4
- package/dist/sri.json +20 -15
- package/dist/types/activation-runtime.d.ts +91 -0
- package/dist/types/analytics-runtime.d.ts +166 -0
- package/dist/types/antiflicker.d.ts +9 -3
- package/dist/types/assignment-cookie-sync.d.ts +31 -0
- package/dist/types/assignment-runtime.d.ts +257 -0
- package/dist/types/assignment-store.d.ts +4 -8
- package/dist/types/bucket.d.ts +1 -2
- package/dist/types/compact-store.d.ts +1 -0
- package/dist/types/config-runtime.d.ts +313 -0
- package/dist/types/consent-evaluation.d.ts +27 -0
- package/dist/types/css.d.ts +5 -3
- package/dist/types/debug-loader.d.ts +2 -0
- package/dist/types/decide-assignments.d.ts +31 -0
- package/dist/types/delivery-timing.d.ts +8 -0
- package/dist/types/early-interaction-capture.d.ts +79 -0
- package/dist/types/early-reassert.d.ts +32 -0
- package/dist/types/edge-runtime.d.ts +11 -0
- package/dist/types/editor/api.d.ts +3 -0
- package/dist/types/editor/controller.d.ts +3 -1
- package/dist/types/editor/publication-result.d.ts +11 -0
- package/dist/types/editor/types.d.ts +2 -1
- package/dist/types/editor/view-kit.d.ts +1 -1
- package/dist/types/endpoint.d.ts +8 -0
- package/dist/types/exclusion-groups.d.ts +4 -7
- package/dist/types/flags.d.ts +2 -0
- package/dist/types/goal-eligibility.d.ts +4 -0
- package/dist/types/goals.d.ts +10 -1
- package/dist/types/guards.d.ts +7 -7
- package/dist/types/handover.d.ts +12 -1
- package/dist/types/hash.d.ts +8 -4
- package/dist/types/hydration.d.ts +2 -1
- package/dist/types/index.d.ts +24 -128
- package/dist/types/init-test-helpers.d.ts +48 -0
- package/dist/types/inline-bootstrap.d.ts +26 -0
- package/dist/types/js.d.ts +3 -1
- package/dist/types/money.d.ts +12 -0
- package/dist/types/mutate.d.ts +45 -6
- package/dist/types/performance.d.ts +2 -0
- package/dist/types/persistence-decoders.d.ts +12 -0
- package/dist/types/public-api.d.ts +209 -0
- package/dist/types/qa-assistant-state.d.ts +34 -0
- package/dist/types/react/index.d.ts +28 -3
- package/dist/types/reassert-sentinel.d.ts +6 -0
- package/dist/types/redirect.d.ts +48 -0
- package/dist/types/replay-recorder-entry.d.ts +1 -0
- package/dist/types/replay-signal-state.d.ts +6 -0
- package/dist/types/replay-signals.d.ts +13 -0
- package/dist/types/replay.d.ts +110 -0
- package/dist/types/router.d.ts +12 -2
- package/dist/types/runtime-state.d.ts +166 -0
- package/dist/types/sanitize.d.ts +1 -0
- package/dist/types/shadow.d.ts +3 -0
- package/dist/types/shopify-cart.d.ts +25 -1
- package/dist/types/storefront-vitals.d.ts +24 -0
- package/dist/types/targeting-diagnostics.d.ts +1 -0
- package/dist/types/targeting.d.ts +16 -2
- package/dist/types/track.d.ts +15 -1
- package/dist/types/types.d.ts +115 -9
- package/dist/types/wait.d.ts +14 -1
- package/dist/types/weekday-schedule.d.ts +3 -0
- package/package.json +17 -8
- package/src/activation-runtime.ts +2737 -0
- package/src/analytics-runtime.ts +2175 -0
- package/src/antiflicker.test.ts +216 -44
- package/src/antiflicker.ts +103 -28
- package/src/artifact-concurrency.test.ts +1091 -0
- package/src/assignment-cookie-sync.test.ts +202 -0
- package/src/assignment-cookie-sync.ts +189 -0
- package/src/assignment-runtime.ts +3204 -0
- package/src/assignment-store.test.ts +56 -0
- package/src/assignment-store.ts +7 -38
- package/src/bucket.ts +3 -18
- package/src/commerce-analytics-lifecycle.test.ts +75 -15
- package/src/commerce-config-lifecycle.test.ts +81 -1
- package/src/commerce-price-preserve.test.ts +133 -0
- package/src/commerce-price.test.ts +97 -0
- package/src/commerce-price.ts +74 -20
- package/src/commerce-shipping.test.ts +53 -0
- package/src/commerce-shipping.ts +5 -11
- package/src/compact-store.ts +15 -0
- package/src/config-fetch.test.ts +480 -9
- package/src/config-runtime.ts +2070 -0
- package/src/consent-evaluation-cookiescript.test.ts +50 -0
- package/src/consent-evaluation.ts +138 -0
- package/src/css.test.ts +30 -0
- package/src/css.ts +120 -6
- package/src/cwv.test.ts +60 -77
- package/src/debug-loader.test.ts +214 -0
- package/src/debug-loader.ts +41 -0
- package/src/decide-assignments.test.ts +196 -0
- package/src/decide-assignments.ts +204 -0
- package/src/delivery-timing.test.ts +104 -0
- package/src/delivery-timing.ts +89 -0
- package/src/early-interaction-capture.test.ts +451 -0
- package/src/early-interaction-capture.ts +230 -0
- package/src/early-reassert.test.ts +207 -0
- package/src/early-reassert.ts +152 -0
- package/src/edge-adoption.test.ts +435 -0
- package/src/edge-runtime.ts +30 -0
- package/src/editor/api.test.ts +109 -0
- package/src/editor/api.ts +34 -3
- package/src/editor/controller.test.ts +297 -14
- package/src/editor/controller.ts +69 -5
- package/src/editor/index.test.ts +2 -0
- package/src/editor/index.ts +1 -0
- package/src/editor/publication-result.ts +58 -0
- package/src/editor/types.ts +10 -1
- package/src/editor/view-kit.ts +2 -1
- package/src/editor/view.test.ts +108 -0
- package/src/editor/view.ts +49 -7
- package/src/endpoint.test.ts +15 -0
- package/src/endpoint.ts +10 -0
- package/src/exclusion-groups.ts +8 -18
- package/src/flags.test.ts +88 -1
- package/src/flags.ts +29 -29
- package/src/global-runtime-reconciler.test.ts +271 -0
- package/src/goal-eligibility.test.ts +29 -0
- package/src/goal-eligibility.ts +17 -0
- package/src/goals.test.ts +144 -1
- package/src/goals.ts +97 -18
- package/src/guards.test.ts +99 -1
- package/src/guards.ts +34 -15
- package/src/handover-cache-order.test.ts +6 -3
- package/src/handover.test.ts +154 -8
- package/src/handover.ts +122 -12
- package/src/hash.ts +29 -54
- package/src/holdout.test.ts +26 -0
- package/src/hydration.test.ts +73 -2
- package/src/hydration.ts +18 -9
- package/src/index.ts +130 -7287
- package/src/init-analytics.test.ts +1694 -0
- package/src/init-anti-flicker.test.ts +1211 -0
- package/src/init-cart-attributes.test.ts +2003 -0
- package/src/init-config-resolution.test.ts +999 -0
- package/src/init-consent.test.ts +971 -0
- package/src/init-empty.test.ts +11 -5406
- package/src/init-integrations.test.ts +846 -0
- package/src/init-page-activation.test.ts +5064 -0
- package/src/init-qa-loading.test.ts +740 -0
- package/src/init-redirects.test.ts +2156 -0
- package/src/init-test-helpers.ts +287 -0
- package/src/inline-bootstrap.test.ts +184 -0
- package/src/inline-bootstrap.ts +73 -0
- package/src/js.test.ts +51 -1
- package/src/js.ts +86 -2
- package/src/money.test.ts +55 -1
- package/src/money.ts +104 -2
- package/src/money.web-parity.contract.test.ts +85 -0
- package/src/mutate.test.ts +474 -10
- package/src/mutate.ts +739 -230
- package/src/page-trigger.test.ts +218 -8
- package/src/performance.ts +10 -0
- package/src/persistence-decoders.ts +18 -0
- package/src/public-api.ts +1828 -0
- package/src/qa-assistant-state.test.ts +249 -3
- package/src/qa-assistant-state.ts +146 -6
- package/src/qa-assistant-view.test.ts +220 -2
- package/src/qa-assistant-view.ts +102 -5
- package/src/react/index.test.tsx +37 -0
- package/src/react/index.tsx +19 -3
- package/src/reassert-sentinel.test.ts +155 -1
- package/src/reassert-sentinel.ts +168 -8
- package/src/redirect.test.ts +541 -0
- package/src/redirect.ts +572 -0
- package/src/replay-recorder-entry.ts +115 -0
- package/src/replay-signal-state.ts +100 -0
- package/src/replay-signals.test.ts +249 -0
- package/src/replay-signals.ts +151 -0
- package/src/replay.test.ts +764 -0
- package/src/replay.ts +514 -0
- package/src/router.test.ts +61 -2
- package/src/router.ts +50 -12
- package/src/runtime-state.ts +507 -0
- package/src/runtime.test.ts +174 -7
- package/src/runtime.ts +88 -14
- package/src/sanitize.test.ts +34 -0
- package/src/sanitize.ts +23 -12
- package/src/shadow.test.ts +187 -0
- package/src/shadow.ts +99 -0
- package/src/shopify-cart.test.ts +733 -23
- package/src/shopify-cart.ts +402 -49
- package/src/storefront-vitals.test.ts +217 -0
- package/src/storefront-vitals.ts +206 -0
- package/src/surface-signals.ts +6 -0
- package/src/targeting-conformance.test.ts +9 -0
- package/src/targeting-diagnostics.ts +38 -8
- package/src/targeting-parity-corpus.json +559 -0
- package/src/targeting-parity-corpus.test.ts +18 -0
- package/src/targeting.detailed.test.ts +105 -0
- package/src/targeting.test.ts +211 -0
- package/src/targeting.ts +88 -207
- package/src/track.test.ts +147 -0
- package/src/track.ts +125 -26
- package/src/types.ts +120 -13
- package/src/wait.test.ts +23 -0
- package/src/wait.ts +129 -13
- package/src/weekday-delivery.test.ts +56 -0
- package/src/weekday-schedule-parity-corpus.json +92 -0
- package/src/weekday-schedule.test.ts +69 -0
- package/src/weekday-schedule.ts +20 -0
package/dist/editor.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var ApexEditor=(()=>{var qt=Object.defineProperty;var mr=Object.getOwnPropertyDescriptor;var gr=Object.getOwnPropertyNames;var vr=Object.prototype.hasOwnProperty;var br=(r,t)=>{for(var e in t)qt(r,e,{get:t[e],enumerable:!0})},xr=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of gr(t))!vr.call(r,n)&&n!==e&&qt(r,n,{get:()=>t[n],enumerable:!(i=mr(t,n))||i.enumerable});return r};var yr=r=>xr(qt({},"__esModule",{value:!0}),r);var gi={};br(gi,{__test:()=>mi,getActiveEditorSession:()=>hi,start:()=>fi});var H=class extends Error{constructor(e,i,n){super(e);this.status=i;this.payload=n}};function Z(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function ke(r){let t=Z(r)??{};return{mutations:Array.isArray(t.mutations)?t.mutations:[],customCss:typeof t.customCss=="string"?t.customCss:"",customJs:typeof t.customJs=="string"?t.customJs:""}}var wr=new Set(["navigate","reload","back","forward","click","type","wait_for","snapshot","screenshot","eval_readonly","console_logs","network_logs","network_probe","current_url","select_element","apply_artifacts"]),X=class{constructor(t,e,i=(...n)=>fetch(...n)){this.apiOrigin=t;this.session=e;this.fetchImpl=i}url(t,e){let i=new URL(t,this.apiOrigin);return e&&i.searchParams.set("variationId",e),i.toString()}async request(t,e){let i=await this.fetchImpl(t,{...e,credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",headers:{Authorization:`Bearer ${this.session.bearer}`,...e.body?{"Content-Type":"application/json"}:{},...e.headers??{}}}),n=Z(await i.json().catch(()=>null));if(!i.ok||n?.ok===!1)throw new H(typeof n?.error=="string"?n.error:`Editor API failed (${i.status})`,i.status,n);return n??{}}async loadArtifacts(t){let e=await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/artifacts`,t),{method:"GET"}),i=Z(e.variation)??{};if(typeof i.artifactHash!="string"||!i.artifactHash)throw new H("Editor load response did not include an artifact hash",500,e);return{variation:{id:typeof i.id=="string"?i.id:t,name:typeof i.name=="string"?i.name:"Variation",artifactHash:i.artifactHash,reviewStatus:typeof i.reviewStatus=="string"?i.reviewStatus:null},artifacts:ke(e.artifacts)}}async saveArtifacts(t,e,i){let n=await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/artifacts`,t),{method:"PATCH",body:JSON.stringify({...e,expectedPriorHash:i})});if(typeof n.artifactHash!="string")throw new H("Editor save response did not include an artifact hash",500,n);return{artifactHash:n.artifactHash,reviewStatus:typeof n.reviewStatus=="string"?n.reviewStatus:null,warningIssues:Array.isArray(n.warningIssues)?n.warningIssues:[],artifacts:ke(n.artifacts)}}async extendSession(){let t=await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/extend`),{method:"POST"}),e=Z(t.session);return typeof e?.expiresAt=="string"?e.expiresAt:null}async revoke(){await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}`),{method:"DELETE"})}async claimCommands(t=10){let e=this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/commands`),i=new URL(e);i.searchParams.set("limit",String(Math.max(1,Math.min(t,20))));let n=await this.request(i.toString(),{method:"GET"});if(!Array.isArray(n.commands))return[];let a=[];for(let c of n.commands){let l=Z(c),f=typeof l?.commandId=="string"?l.commandId:"",g=typeof l?.command=="string"?l.command:"";!f||!wr.has(g)||a.push({commandId:f,command:g,args:Z(l?.args)??{},expiresAt:typeof l?.expiresAt=="string"?l.expiresAt:null})}return a}async completeCommand(t,e){await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/commands`),{method:"PATCH",body:JSON.stringify({commandId:t,...e})})}};var Se=/(?:^|[-_])(react|vue|ember|svelte|uid|uuid|random|generated)[-_]?|\d{5,}/i,kr=/^(active|current|selected|hover|focus|open|closed|js-|is-|has-)|\d{4,}/i;function Ft(r){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(r):r.replace(/[^a-zA-Z0-9_-]/g,t=>`\\${t}`)}function Er(r,t){return`[${r}="${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"]`}function Y(r,t){try{return t.querySelectorAll(r).length===1}catch{return!1}}function Ae(r){let t=r.id.trim();return t&&t.length<=80&&!Se.test(t)?t:null}function Sr(r){let t=["data-testid","data-test","data-cy","data-drip-id","name","aria-label"];for(let e of t){let i=r.getAttribute(e)?.trim();if(i&&i.length<=120)return{name:e,value:i}}for(let e of Array.from(r.attributes))if(e.name.startsWith("data-")&&!e.name.startsWith("data-react")&&e.value&&e.value.length<=120&&!Se.test(e.value))return{name:e.name,value:e.value};return null}function Me(r){return Array.from(r.classList).filter(t=>t.length<=64&&!kr.test(t)).slice(0,2)}function Ee(r,t){let e=r.tagName.toLowerCase(),i=Ae(r);if(i){let f=`#${Ft(i)}`;if(Y(f,t))return f}let n=Sr(r);if(n){let f=`${e}${Er(n.name,n.value)}`;if(Y(f,t))return f}let a=Me(r);if(a.length){let f=`${e}.${a.map(Ft).join(".")}`;if(Y(f,t))return f}let c=r.parentElement;if(!c)return e;let l=Array.from(c.children).filter(f=>f.tagName===r.tagName);return l.length>1?`${e}:nth-of-type(${l.indexOf(r)+1})`:e}function lt(r,t=document){let e=r.ownerDocument??document,i=Ae(r);if(i){let l=`#${Ft(i)}`;if(Y(l,t))return l}let n=Ee(r,t);if(Y(n,t))return n;let a=[n],c=r.parentElement;for(;c&&c!==e.documentElement&&a.length<5;){let l=Ee(c,t);a.unshift(l);let f=a.join(" > ");if(Y(f,t))return f;if(l.startsWith("#"))break;c=c.parentElement}return a.join(" > ")}function ct(r){let t=r.tagName.toLowerCase(),e=Me(r)[0],i=r.getBoundingClientRect();return`${t}${e?`.${e}`:""} ${Math.round(i.width)}x${Math.round(i.height)}`}var Ar=900,Ce=80,z="[redacted]",Mr=/(?:account|address|auth(?:orization)?|bearer|card|cookie|credential|customer|cvv|email|name|pass(?:word|wd)?|payment|phone|postal|secret|session|ssn|token|user|value|zip)/i,Cr=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,$r=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,Tr=/\b(?:bearer|basic)\s+[A-Za-z0-9._~+\/-]+=*/gi,Lr=/\b(?:\+?\d[\d .()-]{6,}\d)\b/g,Or=new Set(["html","text","setText","attribute","style","setStyle","remove","insertBefore","insertAfter"]);function dt(r){return r&&typeof r=="object"&&!Array.isArray(r)?r:null}function N(r){return typeof r=="string"?r.trim():""}function Rr(r){try{let t=new URL(r).hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"||t==="::1"||t==="[::1]"}catch{return!1}}function L(r,t){try{let e=new URL(r,t);return e.protocol!=="http:"&&e.protocol!=="https:"?`${e.protocol}${z}`:(e.username="",e.password="",e.search="",e.hash="",e.toString())}catch{return z}}function kt(r){return r.replace(/https?:\/\/[^\s"'<>]+/gi,t=>L(t)).replace(Cr,z).replace($r,z).replace(Tr,z).replace(Lr,z).replace(/\b(?:api[-_]?key|authorization|cookie|password|secret|token)\s*[:=]\s*[^\s,;]+/gi,t=>{let e=t.includes(":")?":":"=";return`${t.split(e,1)[0]}${e}${z}`})}function pt(r,t=0,e=""){if(e&&Mr.test(e))return z;if(r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean")return typeof r=="string"?kt(r).slice(0,500):r;if(typeof r>"u")return null;if(t>4)return"[truncated]";if(r instanceof Element)return V(r);if(Array.isArray(r))return r.slice(0,120).map(i=>pt(i,t+1));if(typeof r=="object"){let i={};for(let[n,a]of Object.entries(r).slice(0,80))try{i[n]=pt(a,t+1,n)}catch{}return i}return`[${typeof r}]`}function Te(r){return!r||r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement||r instanceof HTMLFormElement||r instanceof HTMLElement&&r.isContentEditable?"":(r.textContent??"").trim().replace(/\s+/g," ")}function V(r){if(!r)return null;let t=null;try{let e=r.getBoundingClientRect();t={x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)}}catch{}return{selector:lt(r),tag:r.tagName.toLowerCase(),text:kt(Te(r)).slice(0,220)||null,role:r.getAttribute("role"),href:r instanceof HTMLAnchorElement?L(r.href):null,name:r.getAttribute("name"),type:r.getAttribute("type"),rect:t}}function $e(r){return{...pt(r),...typeof r.url=="string"?{url:L(r.url)}:{}}}function wt(r){let t=N(r.selector);if(t)try{let a=document.querySelector(t);return a?{ok:!0,element:a,mode:"selector"}:{ok:!1,error:"Selector target not found.",repairHint:"Call browser_snapshot or browser_select_element to find a selector that exists on the live page."}}catch{return{ok:!1,error:`Invalid selector: ${t}`,repairHint:"Pass visible text or a valid CSS selector."}}let e=N(r.text??r.selectorOrText??r.instruction??r.condition);if(!e)return{ok:!1,error:"Target not found"};try{let a=document.querySelector(e);if(a)return{ok:!0,element:a,mode:"selectorOrText"}}catch{}let i=e.toLowerCase(),n=Array.from(document.querySelectorAll("button,a,input,textarea,select,label,[role='button'],[onclick],[data-testid]")).slice(0,350).filter(a=>{let c=`${a.getAttribute("aria-label")??""} ${a.getAttribute("title")??""} ${a.getAttribute("value")??""}`.toLowerCase();return Te(a).toLowerCase().includes(i)||c.includes(i)});return n.length===1?{ok:!0,element:n[0],mode:"text"}:n.length>1?{ok:!1,error:"Browser target text is ambiguous.",repairHint:"Pass the exact selector from browser_snapshot/browser_select_element instead of loose text."}:{ok:!1,error:"Target not found"}}function Ir(r){let t=dt(r),e=N(t?.selector),i=t?.action;if(!e||typeof i!="string"||!Or.has(i))return null;let n={selector:e,action:i};typeof t?.html=="string"&&(n.html=t.html),typeof t?.text=="string"&&(n.text=t.text);let a=dt(t?.attribute);a&&typeof a.name=="string"&&(typeof a.value=="string"||a.value===null)&&(n.attribute={name:a.name,value:a.value});let c=dt(t?.attributes);c&&(n.attributes=Object.fromEntries(Object.entries(c).filter(([,f])=>typeof f=="string"||f===null)));let l=dt(t?.styles);return l&&(n.styles=Object.fromEntries(Object.entries(l).filter(([,f])=>typeof f=="string"))),n}function Hr(r){let t=dt(r);if(!t||!Array.isArray(t.mutations))return null;let e=t.mutations.map(Ir);return e.some(i=>i===null)?null:{mutations:e,customCss:typeof t.customCss=="string"?t.customCss:"",customJs:typeof t.customJs=="string"?t.customJs:""}}function _r(r){return{...r}}var Et=class{constructor(t,e={navigate:i=>location.assign(i),reload:()=>location.reload(),back:()=>history.back(),forward:()=>history.forward()}){this.controller=t;this.navigation=e;this.consoleLogs=[];this.networkLogs=[];this.restoreConsole=null;this.performanceObserver=null}start(){if(this.restoreConsole)return;let t=new Map;for(let e of["log","info","warn","error"]){let i=console[e];t.set(e,i),console[e]=(...n)=>{this.consoleLogs.push({level:e,args:pt(n),ts:Date.now()}),this.consoleLogs.splice(0,Math.max(0,this.consoleLogs.length-Ce)),i.apply(console,n)}}if(this.restoreConsole=()=>{for(let[e,i]of t)console[e]=i;this.restoreConsole=null},typeof PerformanceObserver<"u")try{this.performanceObserver=new PerformanceObserver(e=>{for(let i of e.getEntries())this.networkLogs.push({url:i.name,type:i.entryType,startTime:Math.round(i.startTime),duration:Math.round(i.duration)});this.networkLogs.splice(0,Math.max(0,this.networkLogs.length-Ce))}),this.performanceObserver.observe({type:"resource",buffered:!0})}catch{}}stop(){this.restoreConsole?.(),this.performanceObserver?.disconnect(),this.performanceObserver=null}async execute(t){let e=t.args;switch(t.command){case"current_url":return{result:{ok:!0,url:L(location.href),originalUrl:L(location.href)}};case"snapshot":return{result:{ok:!0,snapshot:this.snapshot()}};case"console_logs":return{result:{ok:!0,logs:this.consoleLogs.slice(-50).map(i=>pt(i))}};case"network_logs":{let i=N(e.filter).toLowerCase();return{result:{ok:!0,logs:this.networkLogs.slice(-80).map($e).filter(a=>!i||JSON.stringify(a).toLowerCase().includes(i))}}}case"screenshot":return{result:{ok:!1,error:"Live-page screenshot capture is unsupported in the merchant SDK runtime.",repairHint:"Use browser_snapshot for DOM evidence or capture the store tab through the connected browser runner.",screenshot:{captured:!1,reason:"unsupported_live_origin"}}};case"eval_readonly":return{result:this.evaluateReadonly(e)};case"click":return{result:this.click(e)};case"type":return{result:this.type(e)};case"select_element":return{result:this.selectElement(e)};case"wait_for":return{result:await this.waitFor(e)};case"network_probe":return{result:await this.networkProbe(e)};case"apply_artifacts":{let i=Hr(e.artifacts);return{result:i?_r(this.controller.applyCommandArtifacts(i)):{ok:!1,error:"apply_artifacts requires a valid full artifact snapshot."}}}case"navigate":{let i=N(e.url);try{let n=new URL(i,this.controller.session.targetOrigin);return n.origin!==this.controller.session.targetOrigin?{result:{ok:!1,error:"Navigation must stay on the editor session origin."}}:{result:{ok:!0,url:L(n.toString())},afterAcknowledge:()=>this.navigation.navigate(n.toString())}}catch{return{result:{ok:!1,error:"Invalid navigation URL"}}}}case"reload":return{result:{ok:!0},afterAcknowledge:()=>this.navigation.reload()};case"back":return{result:{ok:!0},afterAcknowledge:()=>this.navigation.back()};case"forward":return{result:{ok:!0},afterAcknowledge:()=>this.navigation.forward()}}}snapshot(){let t=(e,i)=>Array.from(document.querySelectorAll(e)).slice(0,i).map(V).filter(Boolean);return{title:document.title?kt(document.title).slice(0,220):null,url:L(location.href),originalUrl:L(location.href),bodyTextLength:(document.body.textContent??"").length,headings:t("h1,h2,h3",18),interactive:t("button,a,input,textarea,select,[role='button'],form",45),generated:t("[data-drip-preview-generated], [class*='apex-'], [class*='abt-'], [class*='drip-']",20),consoleCount:this.consoleLogs.length,networkCount:this.networkLogs.length}}click(t){let e=wt(t);if(!e.ok||!e.element)return e;try{e.element.scrollIntoView({block:"center",inline:"center"})}catch{}return e.element instanceof HTMLElement?e.element.click():e.element.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),{ok:!0,element:V(e.element),targetResolution:{mode:e.mode}}}type(t){let e=wt(t);if(!e.ok||!e.element)return e;let i=typeof t.value=="string"?t.value:String(t.value??"");if(e.element instanceof HTMLInputElement||e.element instanceof HTMLTextAreaElement||e.element instanceof HTMLSelectElement)e.element.focus(),e.element.value=i;else if(e.element instanceof HTMLElement&&e.element.isContentEditable)e.element.focus(),e.element.textContent=i;else return{ok:!1,error:"Target does not accept text input"};return e.element.dispatchEvent(new Event("input",{bubbles:!0})),e.element.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0,element:V(e.element),valueLength:i.length}}selectElement(t){let e=wt(t);return e.ok&&e.element?{ok:!0,element:V(e.element),targetResolution:{mode:e.mode}}:e}async waitFor(t){let e=Math.max(100,Math.min(Number(t.timeoutMs)||5e3,15e3)),i=Date.now();for(;Date.now()-i<e;){let n=wt(t);if(n.ok&&n.element)return{ok:!0,element:V(n.element),waitedMs:Date.now()-i};await new Promise(a=>setTimeout(a,100))}return{ok:!1,error:"Target not found before timeout",waitedMs:Date.now()-i}}async networkProbe(t){let e=this.networkLogs.length,i=Math.max(250,Math.min(Number(t.waitMs)||2e3,8e3)),n=this.click(t);await new Promise(c=>setTimeout(c,i));let a=this.networkLogs.slice(e).slice(-30).map($e);return{ok:n.ok,attemptedAction:n.ok,action:n,waitedMs:i,currentUrl:L(location.href),originalUrl:L(location.href),networkObserved:a.length>0,successfulRequestCount:a.length,entries:a,...a.length?{}:{repairHint:"No resource request was observed after the action. Inspect the handler and selector, then retry browser_network_probe."}}}evaluateReadonly(t){if(!Rr(this.controller.session.targetOrigin))return{ok:!1,error:"eval_readonly is unsupported on live merchant origins.",repairHint:"Use browser_snapshot, browser_select_element, or another allowlisted inspection command."};if(N(t.code))return{ok:!1,error:"JavaScript evaluation is disabled in the merchant SDK runtime.",repairHint:"Pass an allowlisted operation: document_title, current_url, viewport, element_exists, element_count, or element_summary."};let e=N(t.operation);if(e==="document_title")return{ok:!0,operation:e,result:kt(document.title).slice(0,220)};if(e==="current_url")return{ok:!0,operation:e,result:L(location.href)};if(e==="viewport")return{ok:!0,operation:e,result:{width:window.innerWidth,height:window.innerHeight}};if(["element_exists","element_count","element_summary"].includes(e)){let i=N(t.selector);if(!i)return{ok:!1,error:`${e} requires a selector.`};try{let n=Array.from(document.querySelectorAll(i));return e==="element_exists"?{ok:!0,operation:e,result:n.length>0}:e==="element_count"?{ok:!0,operation:e,result:n.length}:{ok:!0,operation:e,result:V(n[0]??null)}}catch{return{ok:!1,error:"The inspection selector is invalid."}}}return{ok:!1,error:"eval_readonly requires an allowlisted declarative operation.",repairHint:"Use document_title, current_url, viewport, element_exists, element_count, or element_summary."}}},St=class{constructor(t,e){this.api=t;this.executor=e;this.running=!1;this.timer=null;this.polling=!1}start(){this.running||(this.running=!0,this.executor.start(),this.poll())}stop(){this.running=!1,this.timer&&clearTimeout(this.timer),this.timer=null,this.executor.stop()}async poll(){if(!(!this.running||this.polling)){this.polling=!0;try{let t=await this.api.claimCommands();for(let e of t){if(!this.running)break;let i;try{i=await this.executor.execute(e)}catch(n){await this.api.completeCommand(e.commandId,{error:n instanceof Error?n.message:"Browser command execution failed"});continue}if(await this.api.completeCommand(e.commandId,{result:i.result}),i.afterAcknowledge){let n=i.afterAcknowledge;this.stop(),setTimeout(n,0);break}}}catch(t){t instanceof H&&[401,403,410].includes(t.status)&&this.stop()}finally{this.polling=!1,this.running&&(this.timer=setTimeout(()=>{this.poll()},Ar))}}}};function At(r){let t=new DOMParser().parseFromString(r,"text/html");for(let e of Array.from(t.querySelectorAll("script")))e.remove();for(let e of Array.from(t.body.querySelectorAll("*")))for(let i of Array.from(e.attributes)){if(i.name.toLowerCase().startsWith("on")){e.removeAttribute(i.name);continue}["href","src","action","formaction","xlink:href"].includes(i.name.toLowerCase())&&i.value.replace(/\s+/g,"").toLowerCase().startsWith("javascript:")&&e.removeAttribute(i.name)}return t.body.innerHTML}var Le=new Map,Mt=0;function Ct(r){if(Mt===0)for(let[t,e]of Le)try{let i=t.takeRecords();i.length&&e&&e(i,t)}catch{}Mt+=1;try{return r()}finally{if(Mt-=1,Mt===0)for(let t of Le.keys())try{t.takeRecords()}catch{}}}var Pr="hybrid";function $t(){return Pr==="strict"}var Gt="data-drip-inserted",Dr=[],zr=new Set(["href","src","action","formaction","xlink:href"]),Nr=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif"]);function Zt(r,t){let e=r.trim().toLowerCase();if(!e||e.startsWith("on")||e==="srcdoc")return!1;if(t===null||!zr.has(e))return!0;let i=t.replace(/[\u0000-\u0020]+/g,"").toLowerCase();if(i.startsWith("javascript:"))return!1;if(!i.startsWith("data:"))return!0;let n=i.slice(5).split(/[;,]/,1)[0];return Nr.has(n)}function Kt(r){let t=At(r);if(!$t())return t;let e=document.createElement("template");e.innerHTML=t;for(let i of Array.from(e.content.querySelectorAll("*")))for(let n of Array.from(i.attributes))Zt(n.name,n.value)||i.removeAttribute(n.name);return e.innerHTML}function Wt(r){if(!r||r.startsWith("--")||r.includes("-"))return r;let t=r.replace(/[A-Z]/g,e=>"-"+e.toLowerCase());return t.startsWith("ms-")&&(t="-"+t),t}function Ur(r,t){return r.action+":"+t+":"+(r.selector||"")+":"+(r.html||r.text||"")}function Ie(r){return r==="insertBefore"||r==="insertAfter"}function jr(r,t,e=Dr){switch(r.action){case"html":e.push({kind:"content",element:t,property:"innerHTML",value:t.innerHTML});break;case"text":case"setText":e.push({kind:"content",element:t,property:"textContent",value:t.textContent});break;case"attribute":{let i=new Set;r.attribute&&i.add(r.attribute.name),r.attributes&&Object.keys(r.attributes).forEach(n=>i.add(n)),e.push({kind:"attribute",element:t,values:Array.from(i).map(n=>({name:n,value:t.getAttribute(n)}))});break}case"style":case"setStyle":{let i=t.style,n=Object.keys(r.styles??{}).map(Wt);e.push({kind:"style",element:t,values:n.map(a=>({name:a,value:i.getPropertyValue(a),priority:i.getPropertyPriority(a)}))});break}case"remove":e.push({kind:"remove",element:t,parent:t.parentNode,nextSibling:t.nextSibling});break}}function Jr(r){switch(r.kind){case"content":r.property==="innerHTML"?r.element.innerHTML=r.value??"":r.element.textContent=r.value;break;case"attribute":for(let{name:t,value:e}of r.values)e===null?r.element.removeAttribute(t):r.element.setAttribute(t,e);break;case"style":for(let{name:t,value:e,priority:i}of r.values)e?r.element.style.setProperty(t,e,i):r.element.style.removeProperty(t);break;case"remove":if(!r.parent||r.element.parentNode)return;try{r.parent.insertBefore(r.element,r.nextSibling)}catch{r.parent.appendChild(r.element)}break;case"insert":for(let t of r.nodes)t.parentNode?.removeChild(t);break}}function Oe(r,t){switch(r.action){case"html":typeof r.html=="string"&&(t.innerHTML=Kt(r.html));break;case"text":case"setText":typeof r.text=="string"&&(t.textContent=r.text);break;case"attribute":if(r.attribute&&(!$t()||Zt(r.attribute.name,r.attribute.value))&&(r.attribute.value===null?t.removeAttribute(r.attribute.name):t.setAttribute(r.attribute.name,r.attribute.value)),r.attributes)for(let[e,i]of Object.entries(r.attributes))$t()&&!Zt(e,i)||(i===null?t.removeAttribute(e):t.setAttribute(e,i));break;case"style":case"setStyle":if(r.styles)for(let[e,i]of Object.entries(r.styles))t.style.setProperty(Wt(e),i);break;case"remove":t.remove();break;case"insertBefore":typeof r.html=="string"&&t.insertAdjacentHTML("beforebegin",Kt(r.html));break;case"insertAfter":typeof r.html=="string"&&t.insertAdjacentHTML("afterend",Kt(r.html));break}}function Br(r,t){let e=r.parentElement;return e?Array.from(e.querySelectorAll("["+Gt+"]")).some(i=>i.getAttribute(Gt)===t):!1}function Vr(r,t){r.setAttribute(Gt,t)}function Re(r,t,e,i){return Ct(()=>{if(Ie(r.action)){let n=t.parentNode;if(!n||typeof r.html!="string")return null;let a=t.previousSibling,c=t.nextSibling;Oe(r,t);let l=[],f=r.action==="insertBefore"?a?a.nextSibling:n.firstChild:t.nextSibling,g=r.action==="insertBefore"?t:c;for(;f&&f!==g;)l.push(f),f=f.nextSibling;let S=l.filter(E=>E instanceof Element);return i&&S.forEach(E=>Vr(E,i)),l.length&&e.push({kind:"insert",nodes:l}),S[0]??null}return jr(r,t,e),Oe(r,t),null})}function qr(r,t,e){let i=t.root||document;r.forEach((n,a)=>{let c;try{c=i.querySelectorAll(n.selector)}catch{t.onMiss?.(n,a);return}if(c.length===0){t.onMiss?.(n,a);return}c.forEach(l=>{let f=Ur(n,a);if(Ie(n.action)){if(Br(l,f))return;Re(n,l,e,f),t.onApplied?.(n,l,a);return}Re(n,l,e,f),t.onApplied?.(n,l,a)})})}function Tt(){let r=[];return{apply(t,e={}){qr(t,e,r)},rollback(){Ct(()=>{for(let t=r.length-1;t>=0;t-=1)Jr(r[t])}),r.length=0},get snapshotCount(){return r.length}}}var Xt={mutations:[],customCss:"",customJs:""};function w(r){return{mutations:r.mutations.map(t=>({...t,attribute:t.attribute?{...t.attribute}:void 0,attributes:t.attributes?{...t.attributes}:void 0,styles:t.styles?{...t.styles}:void 0})),customCss:r.customCss,customJs:r.customJs}}function Fr(r,t){if(r.selector!==t.selector)return!1;let e=new Set(["text","setText","html"]),i=new Set(["style","setStyle"]);return e.has(r.action)&&e.has(t.action)||i.has(r.action)&&i.has(t.action)?!0:r.action===t.action}function Ot(r,t){if(t.action==="remove")return{...r,mutations:[...r.mutations.filter(n=>n.selector!==t.selector),t]};let e=r.mutations.filter(n=>!(n.selector===t.selector&&n.action==="remove")).map(n=>({...n})),i=e.findIndex(n=>Fr(n,t));if(i<0)e.push(t);else if((t.action==="style"||t.action==="setStyle")&&e[i].styles)e[i]={...e[i],...t,styles:{...e[i].styles,...t.styles}};else if(t.action==="attribute"){let n=e[i],a={...n.attribute?{[n.attribute.name]:n.attribute.value}:{},...n.attributes??{}},c={...t.attribute?{[t.attribute.name]:t.attribute.value}:{},...t.attributes??{}};e[i]={...n,...t,attribute:void 0,attributes:{...a,...c}}}else e[i]=t;return{...r,mutations:e}}function He(r,t){return{...r,mutations:r.mutations.filter(e=>e.selector!==t)}}function _e(r,t){return{...r,mutations:r.mutations.filter((e,i)=>i!==t)}}var Lt=class{constructor(){this.undoStack=[];this.redoStack=[]}push(t){this.undoStack.push(w(t)),this.undoStack=this.undoStack.slice(-50),this.redoStack=[]}undo(t){let e=this.undoStack.pop();return e?(this.redoStack.push(w(t)),w(e)):null}redo(t){let e=this.redoStack.pop();return e?(this.undoStack.push(w(t)),w(e)):null}reset(){this.undoStack=[],this.redoStack=[]}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}};var ut="apex-editor-draft-css",Wr=700,Kr=1500,Rt=class{constructor(t,e,i=new X(e,t),n=()=>location.reload()){this.session=t;this.apiOrigin=e;this.api=i;this.reload=n;this.state={variation:null,artifacts:w(Xt),artifactsEnabled:!0,pickerActive:!1,selectedElement:null,selectedSelector:null,saveState:"idle",saveMessage:null,dock:"top",canUndo:!1,canRedo:!1,jsApplied:!1,reloadRequired:!1,deviceState:"closed"};this.listeners=new Set;this.history=new Lt;this.visualContext=null;this.devicePreview=null;this.saveTimer=null;this.saveQueue=Promise.resolve();this.revision=0;this.variationRequest=0;this.cleanups=new Set}getState(){return this.state}subscribe(t){return this.listeners.add(t),t(this.state),()=>this.listeners.delete(t)}async initialize(){await this.selectVariation(this.session.initialVariationId)}async selectVariation(t){let e=++this.variationRequest;this.cancelSave(),this.patch({saveState:"idle",saveMessage:"Loading draft..."});try{let i=await this.api.loadArtifacts(t);if(e!==this.variationRequest)return;this.history.reset(),this.revision+=1,this.state={...this.state,variation:i.variation,artifacts:w(i.artifacts),selectedElement:null,selectedSelector:null,saveState:"saved",saveMessage:"Saved",canUndo:!1,canRedo:!1,jsApplied:!1,reloadRequired:!1},this.applyVisualArtifacts(),this.emit()}catch(i){if(e!==this.variationRequest)return;this.patch({saveState:"error",saveMessage:i instanceof Error?i.message:"Draft could not be loaded"})}}setPickerActive(t){this.patch({pickerActive:t})}selectElement(t,e){this.patch({selectedElement:t,selectedSelector:e,pickerActive:!1})}clearSelection(){this.clearSelectedElement()}clearSelectedElement(){this.patch({selectedElement:null,selectedSelector:null,pickerActive:!1})}removeSelector(t){this.commit(He(this.state.artifacts,t))}removeMutation(t){!Number.isInteger(t)||t<0||t>=this.state.artifacts.mutations.length||this.commit(_e(this.state.artifacts,t))}restoreArtifacts(t){this.commit(w(t))}async extendSession(){let t=await this.api.extendSession();return t&&(this.session.expiresAt=t),t}async resolveConflict(t){let e=this.state.variation;if(!(!e||this.state.saveState!=="conflict")){if(t==="theirs"){await this.selectVariation(e.id);return}try{let i=await this.api.loadArtifacts(e.id);this.state={...this.state,variation:{...e,artifactHash:i.variation.artifactHash},saveState:"idle",saveMessage:"Unsaved changes"},this.emit(),await this.saveNow()}catch(i){this.patch({saveState:"error",saveMessage:i instanceof Error?i.message:"Draft could not be saved"})}}}toggleArtifacts(t){this.state={...this.state,artifactsEnabled:t},this.applyVisualArtifacts(),this.devicePreview?.update(this.state.artifacts,t),this.emit()}setDock(t){this.patch({dock:t})}setText(t){this.mutateSelected({action:"setText",text:t})}setImageSource(t){this.mutateSelected({action:"attribute",attributes:{src:t}})}setStyle(t,e){this.mutateSelected({action:"setStyle",styles:{[t]:e}})}hideSelected(){this.setStyle("display","none")}removeSelected(){this.mutateSelected({action:"remove"})}setCustomCss(t){this.commit({...this.state.artifacts,customCss:t})}setCustomJs(t){this.commit({...this.state.artifacts,customJs:t},!1),this.patch({jsApplied:!1})}applyCustomJs(){let t=this.state.artifacts.customJs.trim();if(t)try{new Function(`${t}
|
|
2
|
-
//# sourceURL=apex-editor-draft.js`)(),this.patch({jsApplied:!0,reloadRequired:!0,saveMessage:"JavaScript applied. Reload required to undo."})}catch(e){this.patch({saveState:"error",saveMessage:e instanceof Error?e.message:"JavaScript failed"})}}undo(){let t=this.history.undo(this.state.artifacts);t&&this.replaceFromHistory(t)}redo(){let t=this.history.redo(this.state.artifacts);t&&this.replaceFromHistory(t)}attachDevicePreview(t){this.devicePreview=t}setDeviceState(t){this.patch({deviceState:t})}openDevicePreview(){this.devicePreview?.open(this.state.artifactsEnabled?this.state.artifacts:w(Xt))}closeDevicePreview(){this.devicePreview?.close()}addCleanup(t){return this.cleanups.add(t),()=>this.cleanups.delete(t)}applyCommandArtifacts(t){this.visualContext?.rollback(),this.visualContext=null,document.getElementById(ut)?.remove();let e=t.mutations.map(g=>this.selectorCount(g.selector));this.state={...this.state,artifactsEnabled:!0},this.commit(w(t));let i=t.mutations.map((g,S)=>{let E=e[S],$=this.selectorCount(g.selector),Dt=this.verifyMutationEffect(g,E,$);return{index:S,selector:g.selector,action:g.action,beforeCount:E,afterCount:$,effectVerified:Dt,error:E<0?"Invalid selector":null}}),n=Array.from(new Set(t.mutations.filter(g=>g.action!=="remove").map(g=>g.selector))),a=n.map(g=>{let S=this.selectorElements(g),E=S.slice(0,8).map($=>({text:($.textContent??"").trim().replace(/\s+/g," ").slice(0,240),visible:this.isVisible($)}));return{selector:g,count:S.length,visibleCount:E.filter($=>$.visible).length,matches:E}}),c=i.filter(g=>!g.effectVerified),l=a.reduce((g,S)=>g+S.visibleCount,0),f=/\b(?:fetch|XMLHttpRequest|sendBeacon)\b/.test(t.customJs);return{ok:c.length===0,mutationAudit:i,generatedSelectors:n,generatedVisibility:a,visibleGeneratedCount:l,hiddenEffectVerifiedCount:i.filter(g=>g.action==="remove"&&g.effectVerified).length,networkRequired:f,customJsDeferred:t.customJs.trim().length>0,...c.length?{error:"One or more mutation selectors did not match the live page.",repairHint:"Inspect the current browser snapshot, choose a selector that exists, and reapply the draft."}:{}}}saveNow(){if(this.cancelSave(),!this.state.variation||this.state.saveState==="conflict")return Promise.resolve();let t=this.state.variation.id,e=this.variationRequest,i=this.saveQueue.then(()=>this.performSave(t,e));return this.saveQueue=i.catch(()=>{}),i}async performSave(t,e){if(e!==this.variationRequest||this.state.variation?.id!==t||this.state.saveState==="conflict")return;let i=this.state.variation.artifactHash,n=w(this.state.artifacts),a=this.revision;this.patch({saveState:"saving",saveMessage:"Saving..."});try{let c=await this.api.saveArtifacts(t,n,i);if(e!==this.variationRequest||this.state.variation?.id!==t)return;let l=a!==this.revision;this.state={...this.state,variation:{...this.state.variation,artifactHash:c.artifactHash,reviewStatus:c.reviewStatus},artifacts:l?this.state.artifacts:w(c.artifacts),saveState:l?"idle":"saved",saveMessage:l?"Saving latest changes...":c.warningIssues[0]?.message??"Saved"},this.emit()}catch(c){if(e!==this.variationRequest||this.state.variation?.id!==t)return;c instanceof H&&c.status===409?this.patch({saveState:"conflict",saveMessage:"Draft changed elsewhere. Reload this variation before saving."}):this.patch({saveState:"error",saveMessage:c instanceof Error?c.message:"Draft could not be saved"})}}async exit(){this.cancelSave(),this.runCleanups(),this.devicePreview?.close(!1),this.visualContext?.rollback(),document.getElementById(ut)?.remove();try{window.opener?.postMessage({type:"apex:editor-exited",sid:this.session.sid,experimentId:this.session.experimentId,variationId:this.state.variation?.id??this.session.initialVariationId},this.apiOrigin)}catch{}try{await this.withTimeout(this.api.revoke(),Kr)}catch{}this.reload()}destroy(){this.cancelSave(),this.runCleanups(),this.devicePreview?.close(!1),this.visualContext?.rollback(),document.getElementById(ut)?.remove(),this.listeners.clear()}mutateSelected(t){let e=this.state.selectedSelector;e&&this.commit(Ot(this.state.artifacts,{...t,selector:e}))}commit(t,e=!0){this.state.saveState!=="conflict"&&(this.history.push(this.state.artifacts),this.revision+=1,this.state={...this.state,artifacts:w(t),saveState:"idle",saveMessage:"Unsaved changes",canUndo:this.history.canUndo,canRedo:this.history.canRedo},e&&this.applyVisualArtifacts(),this.devicePreview?.update(this.state.artifacts,this.state.artifactsEnabled),this.emit(),this.scheduleSave())}replaceFromHistory(t){this.revision+=1,this.state={...this.state,artifacts:t,saveState:"idle",saveMessage:"Unsaved changes",canUndo:this.history.canUndo,canRedo:this.history.canRedo,jsApplied:!1},this.applyVisualArtifacts(),this.devicePreview?.update(t,this.state.artifactsEnabled),this.emit(),this.scheduleSave()}applyVisualArtifacts(){if(this.visualContext?.rollback(),this.visualContext=null,document.getElementById(ut)?.remove(),!!this.state.artifactsEnabled){if(this.state.artifacts.customCss.trim()){let t=document.createElement("style");t.id=ut,t.textContent=this.state.artifacts.customCss,(document.head||document.documentElement).appendChild(t)}this.visualContext=Tt(),this.visualContext.apply(this.state.artifacts.mutations)}}scheduleSave(){this.cancelSave(),this.saveTimer=setTimeout(()=>{this.saveNow()},Wr)}cancelSave(){this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=null}patch(t){this.state={...this.state,...t},this.emit()}emit(){for(let t of this.listeners)t(this.state)}selectorElements(t){try{return Array.from(document.querySelectorAll(t))}catch{return[]}}selectorCount(t){try{return document.querySelectorAll(t).length}catch{return-1}}isVisible(t){if(!(t instanceof HTMLElement))return!0;let e=getComputedStyle(t);if(e.display==="none"||e.visibility==="hidden"||Number(e.opacity)===0)return!1;let i=t.getBoundingClientRect();return i.width>0&&i.height>0||!!t.textContent?.trim()}verifyMutationEffect(t,e,i){if(e<=0)return!1;if(t.action==="remove")return i===0;let n=this.selectorElements(t.selector);if(!n.length)return!1;if((t.action==="text"||t.action==="setText")&&typeof t.text=="string")return n.every(a=>a.textContent===t.text);if(t.action==="html"&&typeof t.html=="string"){let a=At(t.html);return n.every(c=>{let l=c.cloneNode(!1);return l.innerHTML=a,c.innerHTML===l.innerHTML})}if(t.action==="attribute"){let a={...t.attribute?{[t.attribute.name]:t.attribute.value}:{},...t.attributes??{}};return n.every(c=>Object.entries(a).every(([l,f])=>f===null?!c.hasAttribute(l):c.getAttribute(l)===f))}return t.action==="style"||t.action==="setStyle"?n.every(a=>Object.entries(t.styles??{}).every(([c,l])=>a.style.getPropertyValue(c.includes("-")?c:c.replace(/[A-Z]/g,f=>`-${f.toLowerCase()}`))===l)):!0}runCleanups(){for(let t of this.cleanups)t();this.cleanups.clear()}async withTimeout(t,e){let i=null;try{return await Promise.race([t,new Promise(n=>{i=setTimeout(()=>n(void 0),e)})])}finally{i&&clearTimeout(i)}}};var Pe="apex-editor-device-preview";var Gr=5e3,De="apex-editor-device-css",It=class{constructor(t,e){this.frame=t;this.onState=e;this.context=null;this.hiddenChildren=[];this.timer=null;this.artifacts=null}open(t){this.close(!1),this.artifacts=t,this.hideStorePage(),this.onState("loading"),this.frame.hidden=!1,this.frame.onload=()=>this.handleLoad(),this.frame.onerror=()=>this.blocked();let e=new URL(location.href);e.hash="",this.frame.src=e.toString(),this.timer=setTimeout(()=>this.blocked(),Gr)}update(t,e=!0){this.artifacts=e?t:{mutations:[],customCss:"",customJs:""};let i=this.readDocument();i&&this.apply(i,this.artifacts)}close(t=!0){this.timer&&clearTimeout(this.timer),this.timer=null,this.context?.rollback(),this.context=null,this.frame.onload=null,this.frame.onerror=null,this.frame.hidden=!0,this.frame.removeAttribute("src");for(let e of this.hiddenChildren)e.element.style.visibility=e.visibility;this.hiddenChildren=[],t&&this.onState("closed")}handleLoad(){let t=this.readDocument();if(!t?.body||!this.artifacts){this.blocked();return}this.timer&&clearTimeout(this.timer),this.timer=null,this.apply(t,this.artifacts),this.onState("active")}readDocument(){try{let t=this.frame.contentDocument,e=this.frame.contentWindow?.location.href??"";return!t||!e||e==="about:blank"?null:t}catch{return null}}apply(t,e){if(this.context?.rollback(),this.context=Tt(),t.getElementById(De)?.remove(),e.customCss.trim()){let i=t.createElement("style");i.id=De,i.textContent=e.customCss,(t.head||t.documentElement).appendChild(i)}this.context.apply(e.mutations,{root:t})}hideStorePage(){let t=document.getElementById("apex-editor-host");this.hiddenChildren=Array.from(document.body?.children??[]).filter(e=>e instanceof HTMLElement&&e!==t).map(e=>{let i=e.style.visibility;return e.style.visibility="hidden",{element:e,visibility:i}})}blocked(){this.timer&&clearTimeout(this.timer),this.timer=null,this.frame.onload=null,this.frame.onerror=null,this.frame.hidden=!0,this.frame.removeAttribute("src"),this.restoreStorePage(),this.onState("blocked")}restoreStorePage(){for(let t of this.hiddenChildren)t.element.style.visibility=t.visibility;this.hiddenChildren=[]}};function Ht(r){return!!r?.closest("#apex-editor-host")}function ze(r){return r.composedPath().some(t=>t instanceof Element&&t.id==="apex-editor-host")}function Yt(r){return r.ownerDocument===document&&r.getRootNode()===document}var _t=class{constructor(t,e,i,n){this.overlay=t;this.onSelect=e;this.onActiveChange=i;this.onUnsupported=n;this.active=!1;this.hovered=null;this.selected=null;this.onPointerMove=t=>{if(!this.active||ze(t))return;let e=t.composedPath()[0],i=e instanceof Element?e:null;!i||!Yt(i)||Ht(i)||(this.hovered=i,this.renderOverlay(i))};this.onClick=t=>{if(!this.active||ze(t))return;let e=t.composedPath()[0],i=e instanceof Element?e:null;if(i){if(!Yt(i)||Ht(i)){Ht(i)||(t.preventDefault(),t.stopImmediatePropagation(),this.onUnsupported?.());return}t.preventDefault(),t.stopImmediatePropagation(),this.selected=i,this.hovered=null,this.active=!1,this.renderOverlay(i),this.onSelect(i,lt(i)),this.onActiveChange(!1)}};this.onKeyDown=t=>{if(t.key==="Escape"&&this.active){t.preventDefault(),this.setActive(!1);return}let e=t.target;if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement||e instanceof HTMLElement&&e.isContentEditable||!this.selected||!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t.key))return;let i=t.key==="ArrowUp"?this.selected.parentElement:t.key==="ArrowDown"?this.selected.firstElementChild:t.key==="ArrowLeft"?this.selected.previousElementSibling:this.selected.nextElementSibling;!i||!Yt(i)||Ht(i)||(t.preventDefault(),this.selected=i,this.renderOverlay(i),this.onSelect(i,lt(i)))};this.refresh=()=>{this.renderOverlay(this.active?this.hovered:this.selected)};document.addEventListener("pointermove",this.onPointerMove,!0),document.addEventListener("click",this.onClick,!0),document.addEventListener("keydown",this.onKeyDown,!0),window.addEventListener("scroll",this.refresh,!0),window.addEventListener("resize",this.refresh)}setActive(t){this.active=t,t||(this.hovered=null),this.renderOverlay(t?this.hovered:this.selected),this.onActiveChange(t)}setSelected(t){this.selected=t,this.renderOverlay(this.active?this.hovered:t)}destroy(){document.removeEventListener("pointermove",this.onPointerMove,!0),document.removeEventListener("click",this.onClick,!0),document.removeEventListener("keydown",this.onKeyDown,!0),window.removeEventListener("scroll",this.refresh,!0),window.removeEventListener("resize",this.refresh)}renderOverlay(t){if(!t?.isConnected){this.overlay.box.hidden=!0,this.overlay.label.hidden=!0;return}let e=t.getBoundingClientRect();if(e.width<=0||e.height<=0){this.overlay.box.hidden=!0,this.overlay.label.hidden=!0;return}this.overlay.box.hidden=!1,this.overlay.label.hidden=!1,this.overlay.box.dataset.state=this.active&&t!==this.selected?"hover":"selected",this.overlay.box.style.transform=`translate(${Math.round(e.left)}px,${Math.round(e.top)}px)`,this.overlay.box.style.width=`${Math.round(e.width)}px`,this.overlay.box.style.height=`${Math.round(e.height)}px`,this.overlay.label.textContent=ct(t);let i=e.top>=28?e.top-24:e.bottom+4;this.overlay.label.style.transform=`translate(${Math.max(4,Math.round(e.left))}px,${Math.round(i)}px)`}};var Ne=18e4,Zr=12,Xr=["main","header","footer","section","article","nav","form","h1","h2","h3","p","button","a[href]","input","select","textarea","img","[role]","[data-testid]"].join(",");function je(r){return r.replace(/\s+/g," ").trim()}function ft(r,t){try{let e=new URL(r,t);return e.protocol==="http:"||e.protocol==="https:"?(e.username="",e.password="",e.search="",e.hash="",e.toString()):`${e.protocol}[redacted]`}catch{return r.split(/[?#]/,1)[0].slice(0,500)}}function Yr(r){return Array.from(r.attributes).filter(({name:t})=>{let e=t.toLowerCase();return e==="id"||e==="class"||e==="href"||e==="src"||e==="alt"||e==="title"||e==="name"||e==="type"||e==="role"||e.startsWith("aria-")||e==="data-testid"||e==="data-section-id"||e==="data-product-id"}).map(({name:t,value:e})=>[t,t.toLowerCase()==="href"||t.toLowerCase()==="src"?ft(e,r.ownerDocument.baseURI):e.slice(0,500)])}function Qr(r){let t=r.tagName.toLowerCase(),e=Yr(r).map(([n,a])=>`${n}=${JSON.stringify(a)}`).join(" "),i=r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement?"":je(r.textContent??"").slice(0,600);return`<${t}${e?` ${e}`:""}>${i}</${t}>`}function ti(r=document){let t=[`url=${ft(r.location?.href??"")}`,`title=${je(r.title??"")}`],e=new Set;for(let i of Array.from(r.querySelectorAll(Xr)))if(!(e.has(i)||i.id==="apex-editor-host")&&(e.add(i),t.push(Qr(i)),t.join(`
|
|
3
|
-
`).length>=
|
|
4
|
-
`).slice(0,
|
|
1
|
+
"use strict";var ApexEditor=(()=>{var it=Object.defineProperty;var Gr=Object.getOwnPropertyDescriptor;var Yr=Object.getOwnPropertyNames;var Zr=Object.prototype.hasOwnProperty;var Xr=(t,e)=>{for(var r in e)it(t,r,{get:e[r],enumerable:!0})},Qr=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Yr(e))!Zr.call(t,i)&&i!==r&&it(t,i,{get:()=>e[i],enumerable:!(n=Gr(e,i))||n.enumerable});return t};var en=t=>Qr(it({},"__esModule",{value:!0}),t);var xi={};Xr(xi,{__test:()=>bi,getActiveEditorSession:()=>vi,start:()=>gi});function Vt(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ot(t){let e=Vt(t);if(!e||typeof e.saved!="boolean")return null;if(!e.saved)return e.publication===null?{saved:!1,artifactHash:null,publication:null}:null;if(typeof e.artifact_hash!="string"||!e.artifact_hash.trim())return null;let r=Vt(e.publication);return!r||r.status!=="ok"&&r.status!=="pending"&&r.status!=="warning"&&r.status!=="failed"||typeof r.code!="string"||!r.code||typeof r.message!="string"||!r.message?null:{saved:!0,artifactHash:e.artifact_hash,publication:{status:r.status,code:r.code,message:r.message}}}var D=class extends Error{constructor(r,n,i){super(r);this.status=n;this.payload=i;this.outcome=ot(i)}};function re(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Jt(t){let e=re(t)??{};return{mutations:Array.isArray(e.mutations)?e.mutations:[],customCss:typeof e.customCss=="string"?e.customCss:"",customJs:typeof e.customJs=="string"?e.customJs:""}}var tn=new Set(["navigate","reload","back","forward","click","type","wait_for","snapshot","screenshot","eval_readonly","console_logs","network_logs","network_probe","current_url","select_element","apply_artifacts"]),ne=class{constructor(e,r,n=(...i)=>fetch(...i)){this.apiOrigin=e;this.session=r;this.fetchImpl=n}url(e,r){let n=new URL(e,this.apiOrigin);return r&&n.searchParams.set("variationId",r),n.toString()}async request(e,r){let n=await this.fetchImpl(e,{...r,credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",headers:{Authorization:`Bearer ${this.session.bearer}`,...r.body?{"Content-Type":"application/json"}:{},...r.headers??{}}}),i=re(await n.json().catch(()=>null));if(!n.ok||i?.ok===!1)throw new D(typeof i?.error=="string"?i.error:`Editor API failed (${n.status})`,n.status,i);return i??{}}async loadArtifacts(e){let r=await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/artifacts`,e),{method:"GET"}),n=re(r.variation)??{};if(typeof n.artifactHash!="string"||!n.artifactHash)throw new D("Editor load response did not include an artifact hash",500,r);return{variation:{id:typeof n.id=="string"?n.id:e,name:typeof n.name=="string"?n.name:"Variation",artifactHash:n.artifactHash,reviewStatus:typeof n.reviewStatus=="string"?n.reviewStatus:null},artifacts:Jt(r.artifacts)}}async saveArtifacts(e,r,n){let i=await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/artifacts`,e),{method:"PATCH",body:JSON.stringify({...r,expectedPriorHash:n})}),o=ot(i),a=Object.prototype.hasOwnProperty.call(i,"saved")||Object.prototype.hasOwnProperty.call(i,"artifact_hash")||Object.prototype.hasOwnProperty.call(i,"publication"),l=typeof i.artifactHash=="string"&&i.artifactHash.trim()?i.artifactHash:null,d=o??(a?null:{saved:!0,artifactHash:l,publication:{status:"ok",code:"variation_saved",message:"Saved"}});if(!d?.saved||!d.artifactHash)throw new D("Editor save response did not include a complete publication outcome",500,i);return{artifactHash:d.artifactHash,reviewStatus:typeof i.reviewStatus=="string"?i.reviewStatus:null,outcome:d,warningIssues:Array.isArray(i.warningIssues)?i.warningIssues:[],artifacts:Jt(i.artifacts)}}async extendSession(){let e=await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/extend`),{method:"POST"}),r=re(e.session);return typeof r?.expiresAt=="string"?r.expiresAt:null}async revoke(){await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}`),{method:"DELETE"})}async claimCommands(e=10){let r=this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/commands`),n=new URL(r);n.searchParams.set("limit",String(Math.max(1,Math.min(e,20))));let i=await this.request(n.toString(),{method:"GET"});if(!Array.isArray(i.commands))return[];let o=[];for(let a of i.commands){let l=re(a),d=typeof l?.commandId=="string"?l.commandId:"",p=typeof l?.command=="string"?l.command:"";!d||!tn.has(p)||o.push({commandId:d,command:p,args:re(l?.args)??{},expiresAt:typeof l?.expiresAt=="string"?l.expiresAt:null})}return o}async completeCommand(e,r){await this.request(this.url(`/api/editor-sessions/${encodeURIComponent(this.session.sid)}/commands`),{method:"PATCH",body:JSON.stringify({commandId:e,...r})})}};var jt=/(?:^|[-_])(react|vue|ember|svelte|uid|uuid|random|generated)[-_]?|\d{5,}/i,rn=/^(active|current|selected|hover|focus|open|closed|js-|is-|has-)|\d{4,}/i;function at(t){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(t):t.replace(/[^a-zA-Z0-9_-]/g,e=>`\\${e}`)}function nn(t,e){return`[${t}="${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"]`}function ie(t,e){try{return e.querySelectorAll(t).length===1}catch{return!1}}function Ft(t){let e=t.id.trim();return e&&e.length<=80&&!jt.test(e)?e:null}function on(t){let e=["data-testid","data-test","data-cy","data-drip-id","name","aria-label"];for(let r of e){let n=t.getAttribute(r)?.trim();if(n&&n.length<=120)return{name:r,value:n}}for(let r of Array.from(t.attributes))if(r.name.startsWith("data-")&&!r.name.startsWith("data-react")&&r.value&&r.value.length<=120&&!jt.test(r.value))return{name:r.name,value:r.value};return null}function Kt(t){return Array.from(t.classList).filter(e=>e.length<=64&&!rn.test(e)).slice(0,2)}function qt(t,e){let r=t.tagName.toLowerCase(),n=Ft(t);if(n){let d=`#${at(n)}`;if(ie(d,e))return d}let i=on(t);if(i){let d=`${r}${nn(i.name,i.value)}`;if(ie(d,e))return d}let o=Kt(t);if(o.length){let d=`${r}.${o.map(at).join(".")}`;if(ie(d,e))return d}let a=t.parentElement;if(!a)return r;let l=Array.from(a.children).filter(d=>d.tagName===t.tagName);return l.length>1?`${r}:nth-of-type(${l.indexOf(t)+1})`:r}function ge(t,e=document){let r=t.ownerDocument??document,n=Ft(t);if(n){let l=`#${at(n)}`;if(ie(l,e))return l}let i=qt(t,e);if(ie(i,e))return i;let o=[i],a=t.parentElement;for(;a&&a!==r.documentElement&&o.length<5;){let l=qt(a,e);o.unshift(l);let d=o.join(" > ");if(ie(d,e))return d;if(l.startsWith("#"))break;a=a.parentElement}return o.join(" > ")}function ve(t){let e=t.tagName.toLowerCase(),r=Kt(t)[0],n=t.getBoundingClientRect();return`${e}${r?`.${r}`:""} ${Math.round(n.width)}x${Math.round(n.height)}`}var an=900,Wt=80,z="[redacted]",sn=/(?:account|address|auth(?:orization)?|bearer|card|cookie|credential|customer|cvv|email|name|pass(?:word|wd)?|payment|phone|postal|secret|session|ssn|token|user|value|zip)/i,ln=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,cn=/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,dn=/\b(?:bearer|basic)\s+[A-Za-z0-9._~+\/-]+=*/gi,pn=/\b(?:\+?\d[\d .()-]{6,}\d)\b/g,un=new Set(["html","text","setText","attribute","style","setStyle","remove","insertBefore","insertAfter"]);function be(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function B(t){return typeof t=="string"?t.trim():""}function fn(t){try{let e=new URL(t).hostname.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="127.0.0.1"||e==="::1"||e==="[::1]"}catch{return!1}}function O(t,e){try{let r=new URL(t,e);return r.protocol!=="http:"&&r.protocol!=="https:"?`${r.protocol}${z}`:(r.username="",r.password="",r.search="",r.hash="",r.toString())}catch{return z}}function Le(t){return t.replace(/https?:\/\/[^\s"'<>]+/gi,e=>O(e)).replace(ln,z).replace(cn,z).replace(dn,z).replace(pn,z).replace(/\b(?:api[-_]?key|authorization|cookie|password|secret|token)\s*[:=]\s*[^\s,;]+/gi,e=>{let r=e.includes(":")?":":"=";return`${e.split(r,1)[0]}${r}${z}`})}function xe(t,e=0,r=""){if(r&&sn.test(r))return z;if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return typeof t=="string"?Le(t).slice(0,500):t;if(typeof t>"u")return null;if(e>4)return"[truncated]";if(t instanceof Element)return K(t);if(Array.isArray(t))return t.slice(0,120).map(n=>xe(n,e+1));if(typeof t=="object"){let n={};for(let[i,o]of Object.entries(t).slice(0,80))try{n[i]=xe(o,e+1,i)}catch{}return n}return`[${typeof t}]`}function Yt(t){return!t||t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement||t instanceof HTMLFormElement||t instanceof HTMLElement&&t.isContentEditable?"":(t.textContent??"").trim().replace(/\s+/g," ")}function K(t){if(!t)return null;let e=null;try{let r=t.getBoundingClientRect();e={x:Math.round(r.x),y:Math.round(r.y),width:Math.round(r.width),height:Math.round(r.height)}}catch{}return{selector:ge(t),tag:t.tagName.toLowerCase(),text:Le(Yt(t)).slice(0,220)||null,role:t.getAttribute("role"),href:t instanceof HTMLAnchorElement?O(t.href):null,name:t.getAttribute("name"),type:t.getAttribute("type"),rect:e}}function Gt(t){return{...xe(t),...typeof t.url=="string"?{url:O(t.url)}:{}}}function Oe(t){let e=B(t.selector);if(e)try{let o=document.querySelector(e);return o?{ok:!0,element:o,mode:"selector"}:{ok:!1,error:"Selector target not found.",repairHint:"Call browser_snapshot or browser_select_element to find a selector that exists on the live page."}}catch{return{ok:!1,error:`Invalid selector: ${e}`,repairHint:"Pass visible text or a valid CSS selector."}}let r=B(t.text??t.selectorOrText??t.instruction??t.condition);if(!r)return{ok:!1,error:"Target not found"};try{let o=document.querySelector(r);if(o)return{ok:!0,element:o,mode:"selectorOrText"}}catch{}let n=r.toLowerCase(),i=Array.from(document.querySelectorAll("button,a,input,textarea,select,label,[role='button'],[onclick],[data-testid]")).slice(0,350).filter(o=>{let a=`${o.getAttribute("aria-label")??""} ${o.getAttribute("title")??""} ${o.getAttribute("value")??""}`.toLowerCase();return Yt(o).toLowerCase().includes(n)||a.includes(n)});return i.length===1?{ok:!0,element:i[0],mode:"text"}:i.length>1?{ok:!1,error:"Browser target text is ambiguous.",repairHint:"Pass the exact selector from browser_snapshot/browser_select_element instead of loose text."}:{ok:!1,error:"Target not found"}}function hn(t){let e=be(t),r=B(e?.selector),n=e?.action;if(!r||typeof n!="string"||!un.has(n))return null;let i={selector:r,action:n};typeof e?.html=="string"&&(i.html=e.html),typeof e?.text=="string"&&(i.text=e.text);let o=be(e?.attribute);o&&typeof o.name=="string"&&(typeof o.value=="string"||o.value===null)&&(i.attribute={name:o.name,value:o.value});let a=be(e?.attributes);a&&(i.attributes=Object.fromEntries(Object.entries(a).filter(([,d])=>typeof d=="string"||d===null)));let l=be(e?.styles);return l&&(i.styles=Object.fromEntries(Object.entries(l).filter(([,d])=>typeof d=="string"))),i}function mn(t){let e=be(t);if(!e||!Array.isArray(e.mutations))return null;let r=e.mutations.map(hn);return r.some(n=>n===null)?null:{mutations:r,customCss:typeof e.customCss=="string"?e.customCss:"",customJs:typeof e.customJs=="string"?e.customJs:""}}function gn(t){return{...t}}var Ie=class{constructor(e,r={navigate:n=>location.assign(n),reload:()=>location.reload(),back:()=>history.back(),forward:()=>history.forward()}){this.controller=e;this.navigation=r;this.consoleLogs=[];this.networkLogs=[];this.restoreConsole=null;this.performanceObserver=null}start(){if(this.restoreConsole)return;let e=new Map;for(let r of["log","info","warn","error"]){let n=console[r];e.set(r,n),console[r]=(...i)=>{this.consoleLogs.push({level:r,args:xe(i),ts:Date.now()}),this.consoleLogs.splice(0,Math.max(0,this.consoleLogs.length-Wt)),n.apply(console,i)}}if(this.restoreConsole=()=>{for(let[r,n]of e)console[r]=n;this.restoreConsole=null},typeof PerformanceObserver<"u")try{this.performanceObserver=new PerformanceObserver(r=>{for(let n of r.getEntries())this.networkLogs.push({url:n.name,type:n.entryType,startTime:Math.round(n.startTime),duration:Math.round(n.duration)});this.networkLogs.splice(0,Math.max(0,this.networkLogs.length-Wt))}),this.performanceObserver.observe({type:"resource",buffered:!0})}catch{}}stop(){this.restoreConsole?.(),this.performanceObserver?.disconnect(),this.performanceObserver=null}async execute(e){let r=e.args;switch(e.command){case"current_url":return{result:{ok:!0,url:O(location.href),originalUrl:O(location.href)}};case"snapshot":return{result:{ok:!0,snapshot:this.snapshot()}};case"console_logs":return{result:{ok:!0,logs:this.consoleLogs.slice(-50).map(n=>xe(n))}};case"network_logs":{let n=B(r.filter).toLowerCase();return{result:{ok:!0,logs:this.networkLogs.slice(-80).map(Gt).filter(o=>!n||JSON.stringify(o).toLowerCase().includes(n))}}}case"screenshot":return{result:{ok:!1,error:"Live-page screenshot capture is unsupported in the merchant SDK runtime.",repairHint:"Use browser_snapshot for DOM evidence or capture the store tab through the connected browser runner.",screenshot:{captured:!1,reason:"unsupported_live_origin"}}};case"eval_readonly":return{result:this.evaluateReadonly(r)};case"click":return{result:this.click(r)};case"type":return{result:this.type(r)};case"select_element":return{result:this.selectElement(r)};case"wait_for":return{result:await this.waitFor(r)};case"network_probe":return{result:await this.networkProbe(r)};case"apply_artifacts":{let n=mn(r.artifacts);return{result:n?gn(this.controller.applyCommandArtifacts(n)):{ok:!1,error:"apply_artifacts requires a valid full artifact snapshot."}}}case"navigate":{let n=B(r.url);try{let i=new URL(n,this.controller.session.targetOrigin);return i.origin!==this.controller.session.targetOrigin?{result:{ok:!1,error:"Navigation must stay on the editor session origin."}}:{result:{ok:!0,url:O(i.toString())},afterAcknowledge:()=>this.navigation.navigate(i.toString())}}catch{return{result:{ok:!1,error:"Invalid navigation URL"}}}}case"reload":return{result:{ok:!0},afterAcknowledge:()=>this.navigation.reload()};case"back":return{result:{ok:!0},afterAcknowledge:()=>this.navigation.back()};case"forward":return{result:{ok:!0},afterAcknowledge:()=>this.navigation.forward()}}}snapshot(){let e=(r,n)=>Array.from(document.querySelectorAll(r)).slice(0,n).map(K).filter(Boolean);return{title:document.title?Le(document.title).slice(0,220):null,url:O(location.href),originalUrl:O(location.href),bodyTextLength:(document.body.textContent??"").length,headings:e("h1,h2,h3",18),interactive:e("button,a,input,textarea,select,[role='button'],form",45),generated:e("[data-drip-preview-generated], [class*='apex-'], [class*='abt-'], [class*='drip-']",20),consoleCount:this.consoleLogs.length,networkCount:this.networkLogs.length}}click(e){let r=Oe(e);if(!r.ok||!r.element)return r;try{r.element.scrollIntoView({block:"center",inline:"center"})}catch{}return r.element instanceof HTMLElement?r.element.click():r.element.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0})),{ok:!0,element:K(r.element),targetResolution:{mode:r.mode}}}type(e){let r=Oe(e);if(!r.ok||!r.element)return r;let n=typeof e.value=="string"?e.value:String(e.value??"");if(r.element instanceof HTMLInputElement||r.element instanceof HTMLTextAreaElement||r.element instanceof HTMLSelectElement)r.element.focus(),r.element.value=n;else if(r.element instanceof HTMLElement&&r.element.isContentEditable)r.element.focus(),r.element.textContent=n;else return{ok:!1,error:"Target does not accept text input"};return r.element.dispatchEvent(new Event("input",{bubbles:!0})),r.element.dispatchEvent(new Event("change",{bubbles:!0})),{ok:!0,element:K(r.element),valueLength:n.length}}selectElement(e){let r=Oe(e);return r.ok&&r.element?{ok:!0,element:K(r.element),targetResolution:{mode:r.mode}}:r}async waitFor(e){let r=Math.max(100,Math.min(Number(e.timeoutMs)||5e3,15e3)),n=Date.now();for(;Date.now()-n<r;){let i=Oe(e);if(i.ok&&i.element)return{ok:!0,element:K(i.element),waitedMs:Date.now()-n};await new Promise(o=>setTimeout(o,100))}return{ok:!1,error:"Target not found before timeout",waitedMs:Date.now()-n}}async networkProbe(e){let r=this.networkLogs.length,n=Math.max(250,Math.min(Number(e.waitMs)||2e3,8e3)),i=this.click(e);await new Promise(a=>setTimeout(a,n));let o=this.networkLogs.slice(r).slice(-30).map(Gt);return{ok:i.ok,attemptedAction:i.ok,action:i,waitedMs:n,currentUrl:O(location.href),originalUrl:O(location.href),networkObserved:o.length>0,successfulRequestCount:o.length,entries:o,...o.length?{}:{repairHint:"No resource request was observed after the action. Inspect the handler and selector, then retry browser_network_probe."}}}evaluateReadonly(e){if(!fn(this.controller.session.targetOrigin))return{ok:!1,error:"eval_readonly is unsupported on live merchant origins.",repairHint:"Use browser_snapshot, browser_select_element, or another allowlisted inspection command."};if(B(e.code))return{ok:!1,error:"JavaScript evaluation is disabled in the merchant SDK runtime.",repairHint:"Pass an allowlisted operation: document_title, current_url, viewport, element_exists, element_count, or element_summary."};let r=B(e.operation);if(r==="document_title")return{ok:!0,operation:r,result:Le(document.title).slice(0,220)};if(r==="current_url")return{ok:!0,operation:r,result:O(location.href)};if(r==="viewport")return{ok:!0,operation:r,result:{width:window.innerWidth,height:window.innerHeight}};if(["element_exists","element_count","element_summary"].includes(r)){let n=B(e.selector);if(!n)return{ok:!1,error:`${r} requires a selector.`};try{let i=Array.from(document.querySelectorAll(n));return r==="element_exists"?{ok:!0,operation:r,result:i.length>0}:r==="element_count"?{ok:!0,operation:r,result:i.length}:{ok:!0,operation:r,result:K(i[0]??null)}}catch{return{ok:!1,error:"The inspection selector is invalid."}}}return{ok:!1,error:"eval_readonly requires an allowlisted declarative operation.",repairHint:"Use document_title, current_url, viewport, element_exists, element_count, or element_summary."}}},De=class{constructor(e,r){this.api=e;this.executor=r;this.running=!1;this.timer=null;this.polling=!1}start(){this.running||(this.running=!0,this.executor.start(),this.poll())}stop(){this.running=!1,this.timer&&clearTimeout(this.timer),this.timer=null,this.executor.stop()}async poll(){if(!(!this.running||this.polling)){this.polling=!0;try{let e=await this.api.claimCommands();for(let r of e){if(!this.running)break;let n;try{n=await this.executor.execute(r)}catch(i){await this.api.completeCommand(r.commandId,{error:i instanceof Error?i.message:"Browser command execution failed"});continue}if(await this.api.completeCommand(r.commandId,{result:n.result}),n.afterAcknowledge){let i=n.afterAcknowledge;this.stop(),setTimeout(i,0);break}}}catch(e){e instanceof D&&[401,403,410].includes(e.status)&&this.stop()}finally{this.polling=!1,this.running&&(this.timer=setTimeout(()=>{this.poll()},an))}}}};var vn=new Set(["href","src","action","formaction","xlink:href"]),bn=new Set(["image/png","image/jpeg","image/gif","image/webp","image/avif"]);function W(t,e){let r=t.trim().toLowerCase();if(!r)return!1;if(e===null)return!0;if(r.startsWith("on")||r==="srcdoc")return!1;if(!vn.has(r))return!0;let n=e.replace(/[\u0000-\u0020]+/g,"").toLowerCase();if(n.startsWith("javascript:"))return!1;if(!n.startsWith("data:"))return!0;let i=n.slice(5).split(/[;,]/,1)[0];return bn.has(i)}function _e(t){let e=new DOMParser().parseFromString(t,"text/html");for(let r of Array.from(e.querySelectorAll("script")))r.remove();for(let r of Array.from(e.body.querySelectorAll("*")))for(let n of Array.from(r.attributes))W(n.name,n.value)||r.removeAttribute(n.name);return e.body.innerHTML}var He=new Map,Pe=0;function Zt(t,e){He.set(t,e)}function st(t){He.delete(t)}function oe(t){if(Pe===0)for(let[e,r]of He)try{let n=e.takeRecords();n.length&&r&&r(n,e)}catch{}Pe+=1;try{return t()}finally{if(Pe-=1,Pe===0)for(let e of He.keys())try{e.takeRecords()}catch{}}}var ae=new Set,Ne=new Map,xn=new Set,Xt=!1;function ye(t){let e=[];typeof Element=="function"&&t instanceof Element&&e.push(t),t.querySelectorAll?.("*")?.forEach(r=>e.push(r));for(let r of e){if(!r.shadowRoot)continue;let n=r;ae.has(n)||(ae.add(n),yn(n.shadowRoot)),ye(n.shadowRoot)}}function yn(t){if(typeof MutationObserver>"u"||Ne.has(t))return;let e=new MutationObserver(r=>{for(let n of r)n.addedNodes.forEach(i=>{typeof Element=="function"&&i instanceof Element&&ye(i)});xn.forEach(n=>n(r,t))});e.observe(t,{attributes:!0,characterData:!0,childList:!0,subtree:!0}),Ne.set(t,e)}function Qt(){for(let t of ae)t.isConnected||(Ne.get(t.shadowRoot)?.disconnect(),Ne.delete(t.shadowRoot),ae.delete(t))}function wn(){if(Xt||typeof document>"u"||(Xt=!0,ye(document),typeof MutationObserver>"u"||!document.documentElement))return;new MutationObserver(e=>{Qt();for(let r of e)r.addedNodes.forEach(n=>{typeof Element=="function"&&n instanceof Element&&ye(n)})}).observe(document.documentElement,{childList:!0,subtree:!0})}function En(){return Array.from(ae).sort((t,e)=>{let r=t.compareDocumentPosition(e);return r&Node.DOCUMENT_POSITION_DISCONNECTED?0:r&Node.DOCUMENT_POSITION_FOLLOWING?-1:1})}function lt(t){let e=Array.from(document.querySelectorAll(t));if(e.length>0||(wn(),Qt(),ye(document),ae.size===0))return e;let r=[];for(let n of En())n.shadowRoot.querySelectorAll(t).forEach(i=>r.push(i));return r}var Sn=1e4;function Ue(t){if(t.mutation.action==="html")t.appliedNodes=Array.from(t.el.childNodes);else if(t.mutation.action==="style"||t.mutation.action==="setStyle"){let e=t.el.style;t.appliedStyles=Object.keys(t.mutation.styles??{}).map(r=>[r=Be(r),e.getPropertyValue(r)])}}function kn(t,e){return(t.appliedNodes??[]).some(n=>n.isConnected&&t.el.contains(n))?Date.now()-t.appliedAt>Sn||!e?!0:!rr(t.el,t.el.innerHTML):!1}var we=new Set,ze=new Set,G=new Map,ct=null;function er(){if(typeof window>"u")return null;let t=window;return t.__dripPerf=t.__dripPerf??{}}function An(t,e){if(!t.el.isConnected)return!1;let r=t.mutation.action;if(r==="style"||r==="setStyle"){if(e.type!=="attributes"||e.target!==t.el||e.attributeName!=="style")return!1;let n=t.el.style;return t.appliedStyles.some(([i,o])=>n.getPropertyValue(i)!==o)}if(r==="attribute"){if(e.type!=="attributes"||e.target!==t.el||!e.attributeName)return!1;let n=e.attributeName===t.mutation.attribute?.name?t.mutation.attribute.value:t.mutation.attributes?.[e.attributeName];return n!==void 0&&t.el.getAttribute(e.attributeName)!==n}return r==="html"?!0:e.type!=="attributes"&&t.el.textContent!==t.mutation.text}function Mn(t){we.add(t),t.mutation.action==="html"&&ze.add(t)}function Cn(){ct===null&&(ct=requestAnimationFrame(()=>{ct=null;let t=Date.now();for(let e of we){if(e.stopped||e.requiresOwner&&e.ownerKeys.size===0)continue;if(e.times=e.times.filter(n=>t-n<1e4),e.times.length===12){e.stopped=!0;let n=er();n&&(n.reassert_loop_detected=!0);continue}if(e.mutation.action==="html"&&kn(e,ze.has(e))){Ue(e);continue}e.times.push(t),oe(()=>e.apply(e.el,e.mutation)),Ue(e);let r=er();r&&(r.reapply_count=(Number(r.reapply_count)||0)+1),e.mutation.action==="html"&&document.dispatchEvent(new CustomEvent("drip:mutation-reapplied",{detail:{experimentId:e.experimentId,variationId:e.variationId,selector:e.mutation.selector,action:e.mutation.action}}))}we.clear(),ze.clear()}))}function Tn(t){return t.entries.some(e=>!e.stopped&&e.shadowRoot!==void 0&&e.shadowRoot.host.isConnected)}function $n(t){if(typeof MutationObserver>"u"||G.has(t))return;for(let[i,o]of G)i.isConnected||Tn(o)||(o.observer.disconnect(),st(o.observer),G.delete(i));let e=[],r=i=>{for(let o of i)for(let a of e)!a.stopped&&An(a,o)&&Mn(a);we.size&&Cn()},n=new MutationObserver(r);G.set(t,{entries:e,observer:n}),Zt(n,r),n.observe(t,{attributes:!0,characterData:!0,childList:!0,subtree:!0})}function Rn(t,e){let[r]=t.splice(e,1);we.delete(r),ze.delete(r)}function tr(t,e){for(let[r,n]of Array.from(G.entries())){let i=n.entries.findIndex(a=>a.journalSeq===t);if(i<0)continue;let o=n.entries[i];if(o.el===e){o.appliedAt=Date.now(),Ue(o);return}Rn(n.entries,i),n.entries.length===0&&(n.observer.disconnect(),st(n.observer),G.delete(r)),$n(e),o.el=e,o.appliedAt=Date.now(),o.times=[],o.stopped=!1,Ue(o),G.get(e)?.entries.push(o);return}}function dt(t){let e=[],r=String.raw`\d(?:[\d.,\u00a0 ]*\d)?`,n=String.raw`[$\u20ac\u00a3\u00a5\u20b9]`,i=new RegExp(String.raw`(?:(${n})\s*(${r})|(?:^|([^A-Z]))([A-Z]{3})\s*(${r})|(${r})\s*(${n}|[A-Z]{3}|kr)(?![A-Za-z]))`,"g"),o;for(;(o=i.exec(t))!==null;){let a=o[3]??"",l=o[0].slice(a.length),d=o[1]??o[4]??o[7],p=o[2]??o[5]??o[6];if(/^[A-Z]{3}$/.test(d)&&!On.has(d))continue;let y=Ln(p);y&&e.push({symbol:d,cents:y.cents,raw:l})}return e}var nr="AED AFN ALL AMD ANG AOA ARS AUD AWG AZN BAM BBD BDT BGN BHD BIF BMD BND BOB BOV BRL BSD BTN BWP BYN BZD CAD CDF CHE CHF CHW CLF CLP CNY COP COU CRC CUP CVE CZK DJF DKK DOP DZD EGP ERN ETB EUR FJD FKP GBP GEL GHS GIP GMD GNF GTQ GYD HKD HNL HRK HTG HUF IDR ILS INR IQD IRR ISK JMD JOD JPY KES KGS KHR KMF KPW KRW KWD KYD KZT LAK LBP LKR LRD LSL LYD MAD MDL MGA MKD MMK MNT MOP MRU MUR MVR MWK MXN MXV MYR MZN NAD NGN NIO NOK NPR NZD OMR PAB PEN PGK PHP PKR PLN PYG QAR RON RSD RUB RWF SAR SBD SCR SDG SEK SGD SHP SLE SOS SRD SSP STN SVC SYP SZL THB TJS TMT TND TOP TRY TTD TWD TZS UAH UGX USD USN UYI UYU UYW UZS VES VND VUV WST XAF XCD XCG XDR XOF XPF XSU YER ZAR ZMW ZWG".split(" "),On=new Set(nr),Ni=new Set([...nr,"CUC","SLL","ZWL"]);var Ui=new Set("BIF CLP DJF GNF ISK JPY KMF KRW PYG RWF UGX UYI VND VUV XAF XOF XPF".split(" ")),zi=new Set("BHD IQD JOD KWD LYD OMR TND".split(" "));function Ln(t,e=2){let r=/\d(?:[\d.,\u00a0 ]*\d)?/g,n=r.exec(t);if(!n||r.exec(t))return null;let i=n[0],o=i.replace(/[ \u00a0]/g,""),a=Math.max(o.lastIndexOf("."),o.lastIndexOf(",")),l=a<0?0:o.length-a-1,d=a<0?"":o[a],p=d!==""&&o.indexOf(d)!==a,y=d===","?o.includes("."):d==="."&&o.includes(",");if(e===3&&l===3&&d===","&&!p&&!y)return null;let k=l===3&&e!==2&&!y&&(d===","||p),w=l&&l<=e&&!k?l:0,T=w?o[a]:null,h=i.slice(0,T?i.lastIndexOf(T):i.length).match(/[.,\u00a0 ]/)?.[0]??"",L=T??(h==="."?",":"."),Z=(w?o.slice(0,a):o).replace(/[.,]/g,""),V=w?o.slice(a+1):"",J=10**e;return{cents:Number(Z)*J+Number((V+"0".repeat(e)).slice(0,e)||0),convention:{decimal:L,group:h,decimals:w,minorUnits:e},start:n.index,end:n.index+i.length}}var Ee="data-drip-inserted",In=0,Dn=0,se={entries:[],baselines:new WeakMap,fallbackArtifactId:"runtime"},_n=new WeakSet;function Ve(t){return _e(t)}function Be(t){if(!t||t.startsWith("--")||t.includes("-"))return t;let e=t.replace(/[A-Z]/g,r=>"-"+r.toLowerCase());return e.startsWith("ms-")&&(e="-"+e),e}function Pn(t,e){return t.action+":"+e+":"+(t.selector||"")+":"+(t.html||t.text||"")}function ir(t){return t==="insertBefore"||t==="insertAfter"}function or(t){let e=globalThis.WeakRef;return e?new e(t):{deref:()=>t}}function ft(t){let e=new Set;return t.attribute&&e.add(t.attribute.name),Object.keys(t.attributes??{}).forEach(r=>e.add(r)),Array.from(e)}function ht(t,e){let r=t.namespaceURI;return r===null||r==="http://www.w3.org/1999/xhtml"?e.trim().toLowerCase():e}function mt(t){return t.action==="html"||t.action==="text"||t.action==="setText"}function gt(t){return t.action!=="style"&&t.action!=="setStyle"?[]:Object.keys(t.styles??{}).map(Be)}function ar(t,e,r){let n=t.baselines.get(e);n||(n={attributeValues:new Map,contentTouched:!1,styleAttributeTouched:!1,styleAttributeValue:null,styleValues:new Map,parent:e.parentNode,nextSibling:e.nextSibling},t.baselines.set(e,n));let i=ft(r).map(l=>ht(e,l)),o=gt(r),a=!1;!n.styleAttributeTouched&&(o.length>0||i.includes("style"))&&(n.styleAttributeValue=e.getAttribute("style"),n.styleAttributeTouched=!0,a=!0);for(let l of i)n.attributeValues.has(l)||n.attributeValues.set(l,l==="style"&&n.styleAttributeTouched?n.styleAttributeValue:e.getAttribute(l));if(o.length>0){let l;if(a)l=e.style;else if(n.styleAttributeTouched){let d=document.createElement("div"),p=n.styleAttributeValue;p!=null&&d.setAttribute("style",p),l=d.style}else l=e.style;for(let d of o)n.styleValues.has(d)||n.styleValues.set(d,{value:l.getPropertyValue(d),priority:l.getPropertyPriority(d)})}return!n.contentTouched&&mt(r)&&(typeof e.innerHTML=="string"&&(n.innerHTML=e.innerHTML),n.textContent=e.textContent,n.contentTouched=!0),n}function Hn(t,e,r){r.kind==="mutation"&&(t.position=!0,mt(r.mutation)&&(t.content=!0),ft(r.mutation).forEach(n=>t.attributes.add(ht(e,n))),gt(r.mutation).forEach(n=>t.styles.add(n)))}function Nn(t,e,r){if(r.position&&e.parent&&!t.parentNode)try{e.parent.insertBefore(t,e.nextSibling)}catch{e.parent.appendChild(t)}r.content&&e.contentTouched&&(e.innerHTML!==void 0?t.innerHTML=e.innerHTML:e.textContent!==void 0&&(t.textContent=e.textContent));let n=t.style;for(let i of r.styles){let o=e.styleValues.get(i);if(!o)continue;let{value:a,priority:l}=o;a?n.setProperty(i,a,l):n.removeProperty(i)}for(let i of r.attributes){if(!e.attributeValues.has(i))continue;let o=e.attributeValues.get(i);o===null?t.removeAttribute(i):o!==void 0&&t.setAttribute(i,o)}}function Un(t,e,r){return r??e[0]??t.fallbackArtifactId}function pt(t,e,r,n,i,o,a,l,d,p){let y={seq:++In,artifactId:Un(t,i,o),owners:new Set(i),target:{selector:e.selector,index:n,el:or(r)},mutation:e,epoch:l,kind:a,insertKey:d,nodes:p,state:"applied"};return t.entries.push(y),y}function vt(t,e){switch(t.action){case"html":typeof t.html=="string"&&(e.innerHTML=Ve(t.html));break;case"text":case"setText":typeof t.text=="string"&&(e.textContent=t.text);break;case"attribute":if(t.attribute&&W(t.attribute.name,t.attribute.value)&&(t.attribute.value===null?e.removeAttribute(t.attribute.name):e.setAttribute(t.attribute.name,t.attribute.value)),t.attributes)for(let[r,n]of Object.entries(t.attributes))W(r,n)&&(n===null?e.removeAttribute(r):e.setAttribute(r,n));break;case"style":case"setStyle":if(t.styles)for(let[r,n]of Object.entries(t.styles))e.style.setProperty(Be(r),n);break;case"remove":e.remove();break;case"insertBefore":typeof t.html=="string"&&e.insertAdjacentHTML("beforebegin",Ve(t.html));break;case"insertAfter":typeof t.html=="string"&&e.insertAdjacentHTML("afterend",Ve(t.html));break}}function sr(t,e){let r=t.parentElement;return r?Array.from(r.querySelectorAll("["+Ee+"]")).some(n=>n.getAttribute(Ee)===e):!1}function lr(t,e){t.setAttribute(Ee,e)}function cr(t,e){let r=e.parentNode;if(!r||typeof t.html!="string")return[];let n=e.previousSibling,i=e.nextSibling;vt(t,e);let o=[],a=t.action==="insertBefore"?n?n.nextSibling:r.firstChild:e.nextSibling,l=t.action==="insertBefore"?e:i;for(;a&&a!==l;)o.push(a),a=a.nextSibling;return o}function dr(t){return t.filter(e=>e instanceof Element)}function pr(t,e,r){for(let i=t.entries.length-1;i>=0;i-=1){let o=t.entries[i];if(o.insertKey===r&&o.target.el.deref()===e&&o.nodes?.some(a=>a.parentNode))return o.nodes}let n=e.parentElement;return n?Array.from(n.querySelectorAll("["+Ee+"]")).filter(i=>i.getAttribute(Ee)===r):[]}function ut(t,e,r,n,i=[],o,a=0,l=0){return oe(()=>{if(ar(r,e,t),ir(t.action)){let p=cr(t,e),y=dr(p);if(n&&y.forEach(w=>lr(w,n)),!p.length)return{inserted:null};let k=pt(r,t,e,a,i,o,"insert",l,n,p);return{inserted:y[0]??null,entry:k}}let d=pt(r,t,e,a,i,o,"mutation",l);return vt(t,e),{inserted:null,entry:d}})}function zn(t,e,r){if(oe(()=>{e.innerHTML=r}),!t)return;_n.add(t.mutation),t.state="invalidated",se.entries=se.entries.filter(i=>i!==t);let n=new Set(se.entries.filter(i=>i.mutation===t.mutation));for(let i of n)i.state="invalidated";n.size>0&&fr(se,n)}function rr(t,e){if(se.baselines.get(t)?.innerHTML===e)return!0;for(let r of se.entries)if(!(r.target.el.deref()!==t||r.mutation.action!=="html")&&typeof r.mutation.html=="string"&&Ve(r.mutation.html)===e)return!0;return!1}function Bn(t,e,r,n,i,o,a){let l=dt(e.textContent??""),d=l.length>0?e.innerHTML:null,p=ut(t,e,r,n,i.ownerKeys,i.artifactId,a,i.epoch??0);if(d!==null){let y=dt(e.textContent??"");if(!l.every(w=>y.some(T=>T.symbol===w.symbol&&T.cents===w.cents))){zn(p.entry,e,d),i.onPricePreservationViolation?.({mutation:t,selector:t.selector,originalPriceTokens:l});return}}i.onApplied?.(t,e,o,p.entry?.seq)}function Vn(t,e,r){let n=e.root||document;t.forEach((i,o)=>{let a;try{a=n===document?lt(i.selector):Array.from(n.querySelectorAll(i.selector))}catch{e.onMiss?.(i,o);return}if(a.length===0){e.onMiss?.(i,o);return}a.forEach((l,d)=>{let p=Pn(i,o);if(ir(i.action)){if(sr(l,p)){let T=pt(r,i,l,d,e.ownerKeys??[],e.artifactId,"adopt-insert",e.epoch??0,p,pr(r,l,p));e.onApplied?.(i,l,o,T.seq);return}let w=ut(i,l,r,p,e.ownerKeys,e.artifactId,d,e.epoch??0);e.onApplied?.(i,l,o,w.entry?.seq);return}let y=i.action==="html"||i.action==="text"||i.action==="setText";if(e.preservePrices&&!e.priceTestExempt&&y){Bn(i,l,r,p,e,o,d);return}let k=ut(i,l,r,p,e.ownerKeys,e.artifactId,d,e.epoch??0);e.onApplied?.(i,l,o,k.entry?.seq)})})}function ur(t,e){let r=e.target.el.deref();if(r&&(e.mutation.action==="remove"||r.isConnected!==!1))return r;try{let n=lt(e.target.selector)[e.target.index];if(n)return ar(t,n,e.mutation),e.target.el=or(n),n}catch{}return r}function Jn(t,e,r){let n=e.insertKey;if(n&&sr(r,n)){e.nodes=pr(t,r,n),e.kind="adopt-insert",e.state="applied";return}let i=cr(e.mutation,r);n&&dr(i).forEach(o=>lr(o,n)),e.nodes=i,e.kind="insert",e.state="applied"}function qn(t,e,r){for(let[n,i]of r){let o=t.baselines.get(n);o&&Nn(n,o,i)}for(let n of t.entries){let i=ur(t,n);!i||!e.has(i)||(n.kind==="insert"||n.kind==="adopt-insert"?Jn(t,n,i):(vt(n.mutation,i),n.state="applied",tr(n.seq,i)))}}function jn(t,e,r){let n=t.get(e);n||(n={attributes:new Set,content:!1,position:!1,styles:new Set},t.set(e,n)),Hn(n,e,r)}function Fn(t,e){let r=t.baselines.get(e);if(!r)return;let n=t.entries.filter(l=>l.target.el.deref()===e);if(n.length===0){t.baselines.delete(e);return}n.some(l=>l.kind==="mutation"&&mt(l.mutation))||(r.contentTouched=!1,delete r.innerHTML,delete r.textContent);let o=new Set(n.flatMap(l=>l.kind==="mutation"?ft(l.mutation).map(d=>ht(e,d)):[]));for(let l of r.attributeValues.keys())o.has(l)||r.attributeValues.delete(l);let a=new Set(n.flatMap(l=>l.kind==="mutation"?gt(l.mutation):[]));for(let l of r.styleValues.keys())a.has(l)||r.styleValues.delete(l);!o.has("style")&&a.size===0&&(r.styleAttributeTouched=!1,r.styleAttributeValue=null)}function fr(t,e,r={}){if(e.size===0)return;let n=new Set,i=new Map;for(let o of e){let a=r.preserveReplacementTargets?o.target.el.deref():ur(t,o),l=!1;if(r.preserveReplacementTargets&&a?.isConnected===!1)try{let d=document.querySelectorAll(o.target.selector)[o.target.index];l=!!(d&&d!==a)}catch{}a&&!l&&(n.add(a),jn(i,a,o))}for(let o=t.entries.length-1;o>=0;o-=1)e.has(t.entries[o])&&t.entries.splice(o,1);oe(()=>{for(let o of e)for(let a of o.nodes??[])t.entries.some(d=>d.nodes?.includes(a))||a.parentNode?.removeChild(a);qn(t,n,i)}),n.forEach(o=>Fn(t,o))}function Kn(t){let e=new Set(t.entries);fr(t,e),t.baselines=new WeakMap}function Je(){let t={entries:[],baselines:new WeakMap,fallbackArtifactId:"context-"+ ++Dn};return{apply(e,r={}){Vn(e,r,t)},rollback(){Kn(t)},get snapshotCount(){return t.entries.length}}}var bt={mutations:[],customCss:"",customJs:""};function S(t){return{mutations:t.mutations.map(e=>({...e,attribute:e.attribute?{...e.attribute}:void 0,attributes:e.attributes?{...e.attributes}:void 0,styles:e.styles?{...e.styles}:void 0})),customCss:t.customCss,customJs:t.customJs}}function Wn(t,e){if(t.selector!==e.selector)return!1;let r=new Set(["text","setText","html"]),n=new Set(["style","setStyle"]);return r.has(t.action)&&r.has(e.action)||n.has(t.action)&&n.has(e.action)?!0:t.action===e.action}function je(t,e){if(e.action==="remove")return{...t,mutations:[...t.mutations.filter(i=>i.selector!==e.selector),e]};let r=t.mutations.filter(i=>!(i.selector===e.selector&&i.action==="remove")).map(i=>({...i})),n=r.findIndex(i=>Wn(i,e));if(n<0)r.push(e);else if((e.action==="style"||e.action==="setStyle")&&r[n].styles)r[n]={...r[n],...e,styles:{...r[n].styles,...e.styles}};else if(e.action==="attribute"){let i=r[n],o={...i.attribute?{[i.attribute.name]:i.attribute.value}:{},...i.attributes??{}},a={...e.attribute?{[e.attribute.name]:e.attribute.value}:{},...e.attributes??{}};r[n]={...i,...e,attribute:void 0,attributes:{...o,...a}}}else r[n]=e;return{...t,mutations:r}}function hr(t,e){return{...t,mutations:t.mutations.filter(r=>r.selector!==e)}}function mr(t,e){return{...t,mutations:t.mutations.filter((r,n)=>n!==e)}}var qe=class{constructor(){this.undoStack=[];this.redoStack=[]}push(e){this.undoStack.push(S(e)),this.undoStack=this.undoStack.slice(-50),this.redoStack=[]}undo(e){let r=this.undoStack.pop();return r?(this.redoStack.push(S(e)),S(r)):null}redo(e){let r=this.redoStack.pop();return r?(this.undoStack.push(S(e)),S(r)):null}reset(){this.undoStack=[],this.redoStack=[]}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}};var Se="apex-editor-draft-css",Gn=700,Yn=1500,Zn=new Set(["draft","awaiting_client_approval","changes_requested","client_approved","qa","ready_to_launch","paused","completed"]),Fe=class{constructor(e,r,n=new ne(r,e),i=()=>location.reload(),o=a=>window.confirm(a)){this.session=e;this.apiOrigin=r;this.api=n;this.reload=i;this.confirmLiveSave=o;this.state={variation:null,artifacts:S(bt),artifactsEnabled:!0,pickerActive:!1,selectedElement:null,selectedSelector:null,saveState:"idle",saveMessage:null,dock:"top",canUndo:!1,canRedo:!1,jsApplied:!1,reloadRequired:!1,deviceState:"closed"};this.listeners=new Set;this.history=new qe;this.visualContext=null;this.devicePreview=null;this.saveTimer=null;this.saveQueue=Promise.resolve();this.revision=0;this.variationRequest=0;this.liveSaveConfirmed=!1;this.cleanups=new Set}getState(){return this.state}subscribe(e){return this.listeners.add(e),e(this.state),()=>this.listeners.delete(e)}async initialize(){await this.selectVariation(this.session.initialVariationId)}async selectVariation(e){this.state.variation?.id!==e&&(this.liveSaveConfirmed=!1);let r=++this.variationRequest;this.cancelSave(),this.patch({saveState:"idle",saveMessage:"Loading draft..."});try{let n=await this.api.loadArtifacts(e);if(r!==this.variationRequest)return;this.history.reset(),this.revision+=1,this.state={...this.state,variation:n.variation,artifacts:S(n.artifacts),selectedElement:null,selectedSelector:null,saveState:"saved",saveMessage:"Saved",canUndo:!1,canRedo:!1,jsApplied:!1,reloadRequired:!1},this.applyVisualArtifacts(),this.emit()}catch(n){if(r!==this.variationRequest)return;this.patch({saveState:"error",saveMessage:n instanceof Error?n.message:"Draft could not be loaded"})}}setPickerActive(e){this.patch({pickerActive:e})}selectElement(e,r){this.patch({selectedElement:e,selectedSelector:r,pickerActive:!1})}clearSelection(){this.clearSelectedElement()}clearSelectedElement(){this.patch({selectedElement:null,selectedSelector:null,pickerActive:!1})}removeSelector(e){this.commit(hr(this.state.artifacts,e))}removeMutation(e){!Number.isInteger(e)||e<0||e>=this.state.artifacts.mutations.length||this.commit(mr(this.state.artifacts,e))}restoreArtifacts(e){this.commit(S(e))}async extendSession(){let e=await this.api.extendSession();return e&&(this.session.expiresAt=e),e}async resolveConflict(e){let r=this.state.variation;if(!(!r||this.state.saveState!=="conflict")){if(e==="theirs"){await this.selectVariation(r.id);return}try{let n=await this.api.loadArtifacts(r.id);this.state={...this.state,variation:{...r,artifactHash:n.variation.artifactHash},saveState:"idle",saveMessage:"Unsaved changes"},this.emit(),await this.saveNow()}catch(n){this.patch({saveState:"error",saveMessage:n instanceof Error?n.message:"Draft could not be saved"})}}}toggleArtifacts(e){this.state={...this.state,artifactsEnabled:e},this.applyVisualArtifacts(),this.devicePreview?.update(this.state.artifacts,e),this.emit()}setDock(e){this.patch({dock:e})}setText(e){this.mutateSelected({action:"setText",text:e})}setImageSource(e){this.mutateSelected({action:"attribute",attributes:{src:e}})}setStyle(e,r){this.mutateSelected({action:"setStyle",styles:{[e]:r}})}hideSelected(){this.setStyle("display","none")}removeSelected(){this.mutateSelected({action:"remove"})}setCustomCss(e){this.commit({...this.state.artifacts,customCss:e})}setCustomJs(e){this.commit({...this.state.artifacts,customJs:e},!1),this.patch({jsApplied:!1})}applyCustomJs(){let e=this.state.artifacts.customJs.trim();if(e)try{new Function(`${e}
|
|
2
|
+
//# sourceURL=apex-editor-draft.js`)(),this.patch({jsApplied:!0,reloadRequired:!0,saveMessage:"JavaScript applied. Reload required to undo."})}catch(r){this.patch({saveState:"error",saveMessage:r instanceof Error?r.message:"JavaScript failed"})}}undo(){let e=this.history.undo(this.state.artifacts);e&&this.replaceFromHistory(e)}redo(){let e=this.history.redo(this.state.artifacts);e&&this.replaceFromHistory(e)}attachDevicePreview(e){this.devicePreview=e}setDeviceState(e){this.patch({deviceState:e})}openDevicePreview(){this.devicePreview?.open(this.state.artifactsEnabled?this.state.artifacts:S(bt))}closeDevicePreview(){this.devicePreview?.close()}addCleanup(e){return this.cleanups.add(e),()=>this.cleanups.delete(e)}applyCommandArtifacts(e){this.visualContext?.rollback(),this.visualContext=null,document.getElementById(Se)?.remove();let r=e.mutations.map(p=>this.selectorCount(p.selector));this.state={...this.state,artifactsEnabled:!0},this.commit(S(e));let n=e.mutations.map((p,y)=>{let k=r[y],w=this.selectorCount(p.selector),T=this.verifyMutationEffect(p,k,w);return{index:y,selector:p.selector,action:p.action,beforeCount:k,afterCount:w,effectVerified:T,error:k<0?"Invalid selector":null}}),i=Array.from(new Set(e.mutations.filter(p=>p.action!=="remove").map(p=>p.selector))),o=i.map(p=>{let y=this.selectorElements(p),k=y.slice(0,8).map(w=>({text:(w.textContent??"").trim().replace(/\s+/g," ").slice(0,240),visible:this.isVisible(w)}));return{selector:p,count:y.length,visibleCount:k.filter(w=>w.visible).length,matches:k}}),a=n.filter(p=>!p.effectVerified),l=o.reduce((p,y)=>p+y.visibleCount,0),d=/\b(?:fetch|XMLHttpRequest|sendBeacon)\b/.test(e.customJs);return{ok:a.length===0,mutationAudit:n,generatedSelectors:i,generatedVisibility:o,visibleGeneratedCount:l,hiddenEffectVerifiedCount:n.filter(p=>p.action==="remove"&&p.effectVerified).length,networkRequired:d,customJsDeferred:e.customJs.trim().length>0,...a.length?{error:"One or more mutation selectors did not match the live page.",repairHint:"Inspect the current browser snapshot, choose a selector that exists, and reapply the draft."}:{}}}saveNow(){if(this.cancelSave(),!this.state.variation||this.state.saveState==="conflict")return Promise.resolve();let e=this.state.variation.id,r=this.variationRequest,n=this.saveQueue.then(()=>this.performSave(e,r));return this.saveQueue=n.catch(()=>{}),n}async performSave(e,r){if(r!==this.variationRequest||this.state.variation?.id!==e||this.state.saveState==="conflict")return;let n=this.state.variation.artifactHash,i=S(this.state.artifacts),o=this.revision;if(!Zn.has(this.session.experimentStatus??"")&&!this.liveSaveConfirmed){if(!this.confirmLiveSave("This test is live. Saving publishes this treatment to real visitors, and the result will span both treatment versions. Save now?")){this.patch({saveState:"idle",saveMessage:"Live save cancelled. Your changes are still unsaved."});return}this.liveSaveConfirmed=!0}this.patch({saveState:"saving",saveMessage:"Saving..."});try{let a=await this.api.saveArtifacts(e,i,n);if(r!==this.variationRequest||this.state.variation?.id!==e)return;let l=o!==this.revision;this.state={...this.state,variation:{...this.state.variation,artifactHash:a.artifactHash,reviewStatus:a.reviewStatus},artifacts:l?this.state.artifacts:S(a.artifacts),saveState:l?"idle":a.outcome.publication?.status==="pending"?"pending":a.outcome.publication?.status==="warning"?"warning":"saved",saveMessage:l?"Saving latest changes...":a.outcome.publication?.status==="pending"?a.warningIssues[0]?.message??"Saved. Storefront publication is pending and will retry automatically.":a.outcome.publication?.status==="warning"?a.outcome.publication.message:a.warningIssues[0]?.message??"Saved"},this.emit()}catch(a){if(r!==this.variationRequest||this.state.variation?.id!==e)return;a instanceof D&&a.outcome?.saved===!0&&a.outcome.artifactHash?(this.state={...this.state,variation:{...this.state.variation,artifactHash:a.outcome.artifactHash,reviewStatus:typeof a.payload?.reviewStatus=="string"?a.payload.reviewStatus:this.state.variation.reviewStatus},saveState:a.outcome.publication?.status==="pending"?"pending":a.outcome.publication?.status==="warning"?"warning":"publication_failed",saveMessage:a.outcome.publication?.message??a.message},this.emit()):a instanceof D&&a.status===409?this.patch({saveState:"conflict",saveMessage:"Draft changed elsewhere. Reload this variation before saving."}):this.patch({saveState:"error",saveMessage:a instanceof Error?a.message:"Draft could not be saved"})}}async exit(){this.cancelSave(),this.runCleanups(),this.devicePreview?.close(!1),this.visualContext?.rollback(),document.getElementById(Se)?.remove();try{window.opener?.postMessage({type:"apex:editor-exited",sid:this.session.sid,experimentId:this.session.experimentId,variationId:this.state.variation?.id??this.session.initialVariationId},this.apiOrigin)}catch{}try{await this.withTimeout(this.api.revoke(),Yn)}catch{}this.reload()}destroy(){this.cancelSave(),this.runCleanups(),this.devicePreview?.close(!1),this.visualContext?.rollback(),document.getElementById(Se)?.remove(),this.listeners.clear()}mutateSelected(e){let r=this.state.selectedSelector;r&&this.commit(je(this.state.artifacts,{...e,selector:r}))}commit(e,r=!0){this.state.saveState!=="conflict"&&(this.history.push(this.state.artifacts),this.revision+=1,this.state={...this.state,artifacts:S(e),saveState:"idle",saveMessage:"Unsaved changes",canUndo:this.history.canUndo,canRedo:this.history.canRedo},r&&this.applyVisualArtifacts(),this.devicePreview?.update(this.state.artifacts,this.state.artifactsEnabled),this.emit(),this.scheduleSave())}replaceFromHistory(e){this.revision+=1,this.state={...this.state,artifacts:e,saveState:"idle",saveMessage:"Unsaved changes",canUndo:this.history.canUndo,canRedo:this.history.canRedo,jsApplied:!1},this.applyVisualArtifacts(),this.devicePreview?.update(e,this.state.artifactsEnabled),this.emit(),this.scheduleSave()}applyVisualArtifacts(){if(this.visualContext?.rollback(),this.visualContext=null,document.getElementById(Se)?.remove(),!!this.state.artifactsEnabled){if(this.state.artifacts.customCss.trim()){let e=document.createElement("style");e.id=Se,e.textContent=this.state.artifacts.customCss,(document.head||document.documentElement).appendChild(e)}this.visualContext=Je(),this.visualContext.apply(this.state.artifacts.mutations)}}scheduleSave(){this.cancelSave(),this.saveTimer=setTimeout(()=>{this.saveNow()},Gn)}cancelSave(){this.saveTimer&&clearTimeout(this.saveTimer),this.saveTimer=null}patch(e){this.state={...this.state,...e},this.emit()}emit(){for(let e of this.listeners)e(this.state)}selectorElements(e){try{return Array.from(document.querySelectorAll(e))}catch{return[]}}selectorCount(e){try{return document.querySelectorAll(e).length}catch{return-1}}isVisible(e){if(!(e instanceof HTMLElement))return!0;let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden"||Number(r.opacity)===0)return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0||!!e.textContent?.trim()}verifyMutationEffect(e,r,n){if(r<=0)return!1;if(e.action==="remove")return n===0;let i=this.selectorElements(e.selector);if(!i.length)return!1;if((e.action==="text"||e.action==="setText")&&typeof e.text=="string")return i.every(o=>o.textContent===e.text);if(e.action==="html"&&typeof e.html=="string"){let o=_e(e.html);return i.every(a=>{let l=a.cloneNode(!1);return l.innerHTML=o,a.innerHTML===l.innerHTML})}if(e.action==="attribute"){let o={...e.attribute?{[e.attribute.name]:e.attribute.value}:{},...e.attributes??{}},a=Object.entries(o),l=a.filter(([d,p])=>W(d,p));return a.length>0&&l.length===0?!1:i.every(d=>l.every(([p,y])=>y===null?!d.hasAttribute(p):d.getAttribute(p)===y))}return e.action==="style"||e.action==="setStyle"?i.every(o=>Object.entries(e.styles??{}).every(([a,l])=>o.style.getPropertyValue(a.includes("-")?a:a.replace(/[A-Z]/g,d=>`-${d.toLowerCase()}`))===l)):!0}runCleanups(){for(let e of this.cleanups)e();this.cleanups.clear()}async withTimeout(e,r){let n=null;try{return await Promise.race([e,new Promise(i=>{n=setTimeout(()=>i(void 0),r)})])}finally{n&&clearTimeout(n)}}};var gr="apex-editor-device-preview";var Xn=5e3,vr="apex-editor-device-css",Ke=class{constructor(e,r){this.frame=e;this.onState=r;this.context=null;this.hiddenChildren=[];this.timer=null;this.artifacts=null}open(e){this.close(!1),this.artifacts=e,this.hideStorePage(),this.onState("loading"),this.frame.hidden=!1,this.frame.onload=()=>this.handleLoad(),this.frame.onerror=()=>this.blocked();let r=new URL(location.href);r.hash="",this.frame.src=r.toString(),this.timer=setTimeout(()=>this.blocked(),Xn)}update(e,r=!0){this.artifacts=r?e:{mutations:[],customCss:"",customJs:""};let n=this.readDocument();n&&this.apply(n,this.artifacts)}close(e=!0){this.timer&&clearTimeout(this.timer),this.timer=null,this.context?.rollback(),this.context=null,this.frame.onload=null,this.frame.onerror=null,this.frame.hidden=!0,this.frame.removeAttribute("src");for(let r of this.hiddenChildren)r.element.style.visibility=r.visibility;this.hiddenChildren=[],e&&this.onState("closed")}handleLoad(){let e=this.readDocument();if(!e?.body||!this.artifacts){this.blocked();return}this.timer&&clearTimeout(this.timer),this.timer=null,this.apply(e,this.artifacts),this.onState("active")}readDocument(){try{let e=this.frame.contentDocument,r=this.frame.contentWindow?.location.href??"";return!e||!r||r==="about:blank"?null:e}catch{return null}}apply(e,r){if(this.context?.rollback(),this.context=Je(),e.getElementById(vr)?.remove(),r.customCss.trim()){let n=e.createElement("style");n.id=vr,n.textContent=r.customCss,(e.head||e.documentElement).appendChild(n)}this.context.apply(r.mutations,{root:e})}hideStorePage(){let e=document.getElementById("apex-editor-host");this.hiddenChildren=Array.from(document.body?.children??[]).filter(r=>r instanceof HTMLElement&&r!==e).map(r=>{let n=r.style.visibility;return r.style.visibility="hidden",{element:r,visibility:n}})}blocked(){this.timer&&clearTimeout(this.timer),this.timer=null,this.frame.onload=null,this.frame.onerror=null,this.frame.hidden=!0,this.frame.removeAttribute("src"),this.restoreStorePage(),this.onState("blocked")}restoreStorePage(){for(let e of this.hiddenChildren)e.element.style.visibility=e.visibility;this.hiddenChildren=[]}};function We(t){return!!t?.closest("#apex-editor-host")}function br(t){return t.composedPath().some(e=>e instanceof Element&&e.id==="apex-editor-host")}function xt(t){return t.ownerDocument===document&&t.getRootNode()===document}var Ge=class{constructor(e,r,n,i){this.overlay=e;this.onSelect=r;this.onActiveChange=n;this.onUnsupported=i;this.active=!1;this.hovered=null;this.selected=null;this.onPointerMove=e=>{if(!this.active||br(e))return;let r=e.composedPath()[0],n=r instanceof Element?r:null;!n||!xt(n)||We(n)||(this.hovered=n,this.renderOverlay(n))};this.onClick=e=>{if(!this.active||br(e))return;let r=e.composedPath()[0],n=r instanceof Element?r:null;if(n){if(!xt(n)||We(n)){We(n)||(e.preventDefault(),e.stopImmediatePropagation(),this.onUnsupported?.());return}e.preventDefault(),e.stopImmediatePropagation(),this.selected=n,this.hovered=null,this.active=!1,this.renderOverlay(n),this.onSelect(n,ge(n)),this.onActiveChange(!1)}};this.onKeyDown=e=>{if(e.key==="Escape"&&this.active){e.preventDefault(),this.setActive(!1);return}let r=e.target;if(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement||r instanceof HTMLSelectElement||r instanceof HTMLElement&&r.isContentEditable||!this.selected||!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return;let n=e.key==="ArrowUp"?this.selected.parentElement:e.key==="ArrowDown"?this.selected.firstElementChild:e.key==="ArrowLeft"?this.selected.previousElementSibling:this.selected.nextElementSibling;!n||!xt(n)||We(n)||(e.preventDefault(),this.selected=n,this.renderOverlay(n),this.onSelect(n,ge(n)))};this.refresh=()=>{this.renderOverlay(this.active?this.hovered:this.selected)};document.addEventListener("pointermove",this.onPointerMove,!0),document.addEventListener("click",this.onClick,!0),document.addEventListener("keydown",this.onKeyDown,!0),window.addEventListener("scroll",this.refresh,!0),window.addEventListener("resize",this.refresh)}setActive(e){this.active=e,e||(this.hovered=null),this.renderOverlay(e?this.hovered:this.selected),this.onActiveChange(e)}setSelected(e){this.selected=e,this.renderOverlay(this.active?this.hovered:e)}destroy(){document.removeEventListener("pointermove",this.onPointerMove,!0),document.removeEventListener("click",this.onClick,!0),document.removeEventListener("keydown",this.onKeyDown,!0),window.removeEventListener("scroll",this.refresh,!0),window.removeEventListener("resize",this.refresh)}renderOverlay(e){if(!e?.isConnected){this.overlay.box.hidden=!0,this.overlay.label.hidden=!0;return}let r=e.getBoundingClientRect();if(r.width<=0||r.height<=0){this.overlay.box.hidden=!0,this.overlay.label.hidden=!0;return}this.overlay.box.hidden=!1,this.overlay.label.hidden=!1,this.overlay.box.dataset.state=this.active&&e!==this.selected?"hover":"selected",this.overlay.box.style.transform=`translate(${Math.round(r.left)}px,${Math.round(r.top)}px)`,this.overlay.box.style.width=`${Math.round(r.width)}px`,this.overlay.box.style.height=`${Math.round(r.height)}px`,this.overlay.label.textContent=ve(e);let n=r.top>=28?r.top-24:r.bottom+4;this.overlay.label.style.transform=`translate(${Math.max(4,Math.round(r.left))}px,${Math.round(n)}px)`}};var xr=18e4,Qn=12,ei=["main","header","footer","section","article","nav","form","h1","h2","h3","p","button","a[href]","input","select","textarea","img","[role]","[data-testid]"].join(",");function wr(t){return t.replace(/\s+/g," ").trim()}function ke(t,e){try{let r=new URL(t,e);return r.protocol==="http:"||r.protocol==="https:"?(r.username="",r.password="",r.search="",r.hash="",r.toString()):`${r.protocol}[redacted]`}catch{return t.split(/[?#]/,1)[0].slice(0,500)}}function ti(t){return Array.from(t.attributes).filter(({name:e})=>{let r=e.toLowerCase();return r==="id"||r==="class"||r==="href"||r==="src"||r==="alt"||r==="title"||r==="name"||r==="type"||r==="role"||r.startsWith("aria-")||r==="data-testid"||r==="data-section-id"||r==="data-product-id"}).map(({name:e,value:r})=>[e,e.toLowerCase()==="href"||e.toLowerCase()==="src"?ke(r,t.ownerDocument.baseURI):r.slice(0,500)])}function ri(t){let e=t.tagName.toLowerCase(),r=ti(t).map(([i,o])=>`${i}=${JSON.stringify(o)}`).join(" "),n=t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement?"":wr(t.textContent??"").slice(0,600);return`<${e}${r?` ${r}`:""}>${n}</${e}>`}function ni(t=document){let e=[`url=${ke(t.location?.href??"")}`,`title=${wr(t.title??"")}`],r=new Set;for(let n of Array.from(t.querySelectorAll(ei)))if(!(r.has(n)||n.id==="apex-editor-host")&&(r.add(n),e.push(ri(n)),e.join(`
|
|
3
|
+
`).length>=xr))break;return e.join(`
|
|
4
|
+
`).slice(0,xr)}function ii(t){if(!t||typeof t!="object"||Array.isArray(t))return null;let e=t;return typeof e.selector=="string"&&typeof e.action=="string"?e:null}function yr(t,e){return e.trim()?t.trim()?`${t.trimEnd()}
|
|
5
5
|
|
|
6
|
-
${
|
|
7
|
-
<defs><mask id="${
|
|
8
|
-
<path d="M60 14 C92 14 106 36 106 60 C106 84 92 106 60 106 C28 106 14 84 14 60 C14 36 28 14 60 14 Z M60 38 C46 38 38 48 38 60 C38 72 46 82 60 82 C74 82 82 72 82 60 C82 48 74 38 60 38 Z" fill="${
|
|
6
|
+
${e.trimStart()}`:e:t}function oi(t){let e=Array.isArray(t.generatedMutations)?t.generatedMutations.map(ii).filter(i=>!!i):[],r=typeof t.generatedCss=="string"?t.generatedCss:"",n=typeof t.generatedJs=="string"?t.generatedJs:"";return t.mergeStrategy==="replace"?{mutations:e,customCss:r,customJs:n}:{mutations:e.reduce((i,o)=>je(i,o),t.current).mutations,customCss:yr(t.current.customCss,r),customJs:yr(t.current.customJs,n)}}function ai(t,e){if(t&&typeof t=="object"){let r=t.error;if(typeof r=="string"&&r.trim())return r.trim()}return`Operator request failed (${e})`}async function Er(t){let r=await(t.fetchImpl??fetch)(new URL(`/api/editor-sessions/${encodeURIComponent(t.session.sid)}/operator`,t.apiOrigin),{method:"POST",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:t.signal,headers:{Authorization:`Bearer ${t.session.bearer}`,"Content-Type":"application/json"},body:JSON.stringify({prompt:t.prompt,variationId:t.variationId,domContext:ni(t.documentLike),pageContext:t.pageContext??`Live merchant page: ${ke(t.session.targetUrl)}`,existingMutations:t.artifacts.mutations,existingCustomCss:t.artifacts.customCss,existingCustomJs:t.artifacts.customJs,conversation:t.conversation.slice(-Qn),selectedElement:t.selectedElement??void 0})}),n=await r.json().catch(()=>null);if(!r.ok||!n)throw new Error(ai(n,r.status));let i=n.mergeStrategy==="replace"?"replace":"append",o=oi({current:t.artifacts,generatedMutations:n.mutations,generatedCss:n.customCss,generatedJs:n.customJs,mergeStrategy:i}),a=(Array.isArray(n.mutations)?n.mutations.length:0)+(typeof n.customCss=="string"&&n.customCss.trim()?1:0)+(typeof n.customJs=="string"&&n.customJs.trim()?1:0);return{artifacts:o,explanation:typeof n.explanation=="string"&&n.explanation.trim()?n.explanation.trim():a?"Draft treatment created. Review the result before QA.":"No draft changes were produced.",artifactCount:a,mergeStrategy:i}}var si={pointer:"M4 3l7.6 18 2.3-7.4L21 11.5zM13.9 13.9L19 19",undo:"M9 14L4 9l5-5M4 9h10.5a5.5 5.5 0 015.5 5.5v0a5.5 5.5 0 01-5.5 5.5H11",redo:"M15 14l5-5-5-5M20 9H9.5A5.5 5.5 0 004 14.5v0A5.5 5.5 0 009.5 20H13",monitor:"M3 4h18a1 1 0 011 1v11a1 1 0 01-1 1H3a1 1 0 01-1-1V5a1 1 0 011-1zM8 21h8M12 17v4",tablet:"M6 2h12a2 2 0 012 2v16a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2zM12 18h.01",phone:"M8 2h8a2 2 0 012 2v16a2 2 0 01-2 2H8a2 2 0 01-2-2V4a2 2 0 012-2zM11 18h2",wifiOff:"M2 2l20 20M8.5 16.5a5 5 0 015.6-1M5 12.5a10 10 0 015.2-2.7M2 8.8a15 15 0 014.2-2.5M16.6 6.6A15 15 0 0122 8.8M12 20h.01",braces:"M8 3H7a2 2 0 00-2 2v4a2 2 0 01-2 2 2 2 0 012 2v4a2 2 0 002 2h1M16 3h1a2 2 0 012 2v4a2 2 0 002 2 2 2 0 00-2 2v4a2 2 0 01-2 2h-1",collapse:"M9 3v18M3 5a2 2 0 012-2h14a2 2 0 012 2v14a2 2 0 01-2 2H5a2 2 0 01-2-2zM13 10l3 2-3 2",history:"M3 12a9 9 0 113 6.7M3 12H1.5M3 12l-1.8 2M12 7v5l3.5 2",send:"M22 2L11 13M22 2l-7 20-4-9-9-4z",stop:"M6 6h12v12H6z",cursorBox:"M3 3h8M3 3v8M21 13v8h-8M9 9l7 7M16 9v7h-7",check:"M5 13l4 4L19 7",x:"M18 6L6 18M6 6l12 12",chevD:"M6 9l6 6 6-6",chevR:"M9 6l6 6-6 6",refresh:"M3 12a9 9 0 0114.5-7L21 8M21 3v5h-5M21 12a9 9 0 01-14.5 7L3 16M3 21v-5h5",external:"M15 3h6v6M21 3l-9 9M10 5H5a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2v-5",code:"M16 18l6-6-6-6M8 6l-6 6 6 6",clock:"M12 22a10 10 0 100-20 10 10 0 000 20zM12 7v5l3 2",eye:"M2 12s4-7 10-7 10 7 10 7-4 7-10 7-10-7-10-7zM12 15a3 3 0 100-6 3 3 0 000 6z",alert:"M10.3 3.9L1.8 18a2 2 0 001.7 3h17a2 2 0 001.7-3L13.7 3.9a2 2 0 00-3.4 0zM12 9v4M12 17h.01",globe:"M12 2a10 10 0 100 20 10 10 0 000-20zM2 12h20M12 2a15 15 0 010 20M12 2a15 15 0 000 20",play:"M6 4l14 8-14 8z",dot:"M12 12h.01"};function u(t,e=14,r=""){return`<svg width="${e}" height="${e}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" ${r}><path d="${si[t]}"/></svg>`}var li=0;function _(t=16,e="#fff"){let r=`apex-op-mark-${++li}`;return`<svg width="${t}" height="${t}" viewBox="0 0 120 120" fill="none" aria-hidden="true" style="flex-shrink:0">
|
|
7
|
+
<defs><mask id="${r}"><rect width="120" height="120" fill="#fff"/><rect x="0" y="68" width="120" height="6" fill="#000"/></mask></defs>
|
|
8
|
+
<path d="M60 14 C92 14 106 36 106 60 C106 84 92 106 60 106 C28 106 14 84 14 60 C14 36 28 14 60 14 Z M60 38 C46 38 38 48 38 60 C38 72 46 82 60 82 C74 82 82 72 82 60 C82 48 74 38 60 38 Z" fill="${e}" fill-rule="evenodd" mask="url(#${r})"/>
|
|
9
9
|
<rect x="92" y="92" width="14" height="14" rx="2" fill="#5B29FF"/>
|
|
10
|
-
</svg>`}function v(
|
|
10
|
+
</svg>`}function v(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}var Sr=`
|
|
11
11
|
:host {
|
|
12
12
|
--bg0:#08080A;--bg1:#0A0A0C;--raised:#141419;--raised-hi:#1A1A21;--inset:#0B0B0E;
|
|
13
13
|
--border:rgba(255,255,255,0.06);--border-hi:rgba(255,255,255,0.10);--border-px:rgba(255,255,255,0.14);
|
|
@@ -59,7 +59,8 @@ button:disabled{cursor:not-allowed}
|
|
|
59
59
|
.save-chip.unsaved{color:var(--warning)}
|
|
60
60
|
.save-chip.saving{color:var(--purple200)}
|
|
61
61
|
.save-chip.saved{color:var(--positive)}
|
|
62
|
-
.save-chip.
|
|
62
|
+
.save-chip.pending,.save-chip.warning{color:var(--warning);background:rgba(245,166,35,0.10);border-color:rgba(245,166,35,0.25)}
|
|
63
|
+
.save-chip.failed,.save-chip.publication-failed,.save-chip.conflict{color:var(--negative-soft);background:rgba(235,82,82,0.10);border-color:rgba(235,82,82,0.25)}
|
|
63
64
|
.save-chip .retry{border:none;background:rgba(255,255,255,0.1);color:#fff;font-size:11.5px;font-weight:600;border-radius:5px;padding:2px 7px;margin-left:2px;pointer-events:auto}
|
|
64
65
|
|
|
65
66
|
/* Segmented control */
|
|
@@ -109,9 +110,9 @@ button:disabled{cursor:not-allowed}
|
|
|
109
110
|
.modal .m-body p{margin:0}
|
|
110
111
|
.modal .m-body p+p{margin-top:10px}
|
|
111
112
|
.modal .m-actions{display:flex;justify-content:flex-end;gap:8px;padding:14px 18px 18px}
|
|
112
|
-
`;var
|
|
113
|
-
.zone{position:fixed;left:0;top:0;bottom:0;right:${
|
|
114
|
-
.zone.rail{right:${
|
|
113
|
+
`;var yt=352,kr=52,Ye=300,ci=`
|
|
114
|
+
.zone{position:fixed;left:0;top:0;bottom:0;right:${yt}px;pointer-events:none}
|
|
115
|
+
.zone.rail{right:${kr}px}
|
|
115
116
|
.zone.narrow{right:0}
|
|
116
117
|
.page-border{position:absolute;inset:0;pointer-events:none;box-shadow:inset 0 0 0 3px rgba(91,41,255,0.75)}
|
|
117
118
|
.select-banner{position:absolute;top:12px;left:50%;transform:translateX(-50%);display:flex;align-items:center;gap:9px;padding:7px 12px;background:var(--purple500);color:#fff;border-radius:999px;border:1px solid rgba(255,255,255,0.25);box-shadow:0 12px 32px rgba(91,41,255,0.45);font-size:12.5px;font-weight:600;white-space:nowrap;pointer-events:auto}
|
|
@@ -123,8 +124,8 @@ button:disabled{cursor:not-allowed}
|
|
|
123
124
|
.orig-chip svg{color:var(--purple300)}
|
|
124
125
|
.orig-chip button{border:none;background:var(--purple-soft);color:var(--purple200);font-size:11.5px;font-weight:600;border-radius:999px;padding:3px 9px}
|
|
125
126
|
|
|
126
|
-
.dock{position:fixed;right:0;top:0;bottom:0;width:${
|
|
127
|
-
.rail-dock{position:fixed;right:0;top:0;bottom:0;width:${
|
|
127
|
+
.dock{position:fixed;right:0;top:0;bottom:0;width:${yt}px;background:var(--bg1);border-left:1px solid var(--border-px);display:flex;flex-direction:column;min-height:0;pointer-events:auto}
|
|
128
|
+
.rail-dock{position:fixed;right:0;top:0;bottom:0;width:${kr}px;background:var(--bg1);border-left:1px solid var(--border-px);display:flex;flex-direction:column;align-items:center;gap:10px;padding:12px 0;pointer-events:auto}
|
|
128
129
|
.rail-dock .sep{width:24px;height:1px;background:var(--border)}
|
|
129
130
|
.rail-dock .grow{flex:1}
|
|
130
131
|
|
|
@@ -261,7 +262,7 @@ button:disabled{cursor:not-allowed}
|
|
|
261
262
|
.picker-label{position:fixed;left:0;top:0;padding:3px 8px;border-radius:6px;background:var(--purple500);color:#fff;font-size:11px;font-weight:600;white-space:nowrap;pointer-events:none;z-index:201}
|
|
262
263
|
|
|
263
264
|
/* Device preview */
|
|
264
|
-
.device{position:fixed;left:0;top:0;bottom:0;right:${
|
|
265
|
+
.device{position:fixed;left:0;top:0;bottom:0;right:${yt}px;background:var(--bg0);display:flex;align-items:center;justify-content:center;padding:24px;pointer-events:auto;z-index:90}
|
|
265
266
|
.device.narrow{right:0}
|
|
266
267
|
.device[hidden]{display:none}
|
|
267
268
|
.device-shell{display:flex;flex-direction:column;gap:12px;align-items:center;max-width:100%;max-height:100%}
|
|
@@ -277,204 +278,208 @@ button:disabled{cursor:not-allowed}
|
|
|
277
278
|
.sheet .bar{display:flex;align-items:center;gap:8px;padding:2px 14px 10px;flex-wrap:wrap}
|
|
278
279
|
.sheet .bar .grow{flex:1}
|
|
279
280
|
.sheet .row2{display:flex;align-items:center;gap:8px;padding:0 14px 8px;flex-wrap:wrap}
|
|
280
|
-
`,
|
|
281
|
-
`).length} lines`,origin:"code",risky:!1}),
|
|
282
|
-
<div class="device-head"><span class="d-title">Device preview</span><button type="button" class="iconbtn" data-action="device-close" aria-label="Close device preview">${
|
|
283
|
-
<iframe class="device-frame" name="${
|
|
281
|
+
`,di=["Make the announcement bar mention free returns","Add a trust message below the buy button","Make this section more compact"];function Mr(t){let e=pi(t.selector);switch(t.action){case"text":case"setText":return`${e}: \u201C${(t.text??"").trim().slice(0,80)}\u201D`;case"html":return`${e}: content replaced`;case"attribute":{let r=[...t.attribute?[t.attribute.name]:[],...Object.keys(t.attributes??{})];return r.includes("src")?`${e}: image swapped`:`${e}: ${r.join(", ")||"attribute"} changed`}case"style":case"setStyle":return`${e}: style changed`;case"remove":return`${e}: removed`;case"insertBefore":case"insertAfter":return`${e}: content added`;default:return`${e}: updated`}}function pi(t){return(t.split(/[\s>+~]+/).filter(Boolean).pop()??t).slice(0,60)||"Element"}function ui(t){return t.saveState==="saving"?"saving":t.saveState==="saved"?"saved":t.saveState==="pending"?"pending":t.saveState==="warning"?"warning":t.saveState==="publication_failed"?"publication-failed":t.saveState==="conflict"?"conflict":t.saveState==="error"?"failed":t.variation?"unsaved":"loading"}function wt(t){let e=ui(t),r=e==="unsaved"?"Unsaved changes":e==="saving"?"Saving\u2026":e==="saved"?"Saved":e==="pending"?"Saved \u2014 publication pending":e==="warning"?"Saved \u2014 publication warning":e==="publication-failed"?"Saved \u2014 publication failed":e==="failed"?"Save failed":e==="conflict"?"Conflict":"Loading draft\u2026",n=e==="saving"||e==="loading"?u("refresh",12,'class="spin"'):e==="saved"?u("check",12):e==="pending"||e==="warning"?u("alert",12):e==="unsaved"?u("dot",12):u("alert",12);return`<span class="save-chip ${e==="loading"?"saving":e}" role="status" aria-live="polite">${n}${r}${e==="failed"||e==="publication-failed"?'<button type="button" class="retry" data-action="retry-save">Retry</button>':""}</span>`}function Ae(t){let e=t.artifacts.mutations.map((r,n)=>({kind:"mutation",selector:r.selector,mutationIndex:n,label:Mr(r),target:r.selector,origin:"operator",risky:!1}));return t.artifacts.customCss.trim()&&e.push({kind:"css",selector:null,mutationIndex:null,label:"Custom CSS",target:`${t.artifacts.customCss.trim().split(`
|
|
282
|
+
`).length} lines`,origin:"code",risky:!1}),t.artifacts.customJs.trim()&&e.push({kind:"js",selector:null,mutationIndex:null,label:"Custom JavaScript",target:"runs when the variation loads",origin:"code",risky:t.reloadRequired}),e}function Et(t,e){let r=new Set(t.mutations.map(i=>JSON.stringify(i))),n=e.mutations.filter(i=>!r.has(JSON.stringify(i))).map(i=>({label:Mr(i),target:i.selector}));return e.customCss.trim()!==t.customCss.trim()&&n.push({label:"Custom CSS updated",target:"variation stylesheet"}),e.customJs.trim()!==t.customJs.trim()&&n.push({label:"Custom JavaScript updated",target:"variation script"}),n}function Ar(t){let e=Math.floor(t/60),r=Math.max(0,Math.floor(t%60));return`${e}:${String(r).padStart(2,"0")}`}function Cr(t,e){let r=document.createElement("style");r.textContent=Sr+ci;let n=document.createElement("div"),i=document.createElement("div");i.className="zone";let o=document.createElement("div");o.className="picker-box",o.hidden=!0;let a=document.createElement("div");a.className="picker-label",a.hidden=!0;let l=document.createElement("div");l.className="device",l.hidden=!0;let d=document.createElement("div");d.className="boot",t.append(r,i,n,o,a,l,d);let p=e.session,y=(()=>{try{return new URL(p.targetUrl).host}catch{return p.targetOrigin.replace(/^https?:\/\//,"")}})(),k=(()=>{try{let s=new URL(p.targetUrl);return s.pathname+s.search}catch{return null}})(),w=p.experimentName?.trim()||"On-site editor",T=s=>`${e.apiOrigin}/tests/${encodeURIComponent(p.experimentId)}/variations/${encodeURIComponent(s)}`,ce=()=>Math.max(0,Math.floor((Date.parse(p.expiresAt)-Date.now())/1e3)),h=e.getState(),L="operator",Z="css",V=!1,J=!1,H=!1,q=!1,j="variation",X=h.selectedSelector,P=h.selectedElement?ve(h.selectedElement):h.selectedSelector,de="desktop",N=navigator.onLine===!1?"offline":"connected",$=null,pe=!1,U=null,Q=!1,ue="",fe=!1,Me=null,Ze=0,Xe=null,Qe=ce()<=Ye,F=!1,Mt=0,I=[],he=[],Ce=typeof window.matchMedia=="function"?window.matchMedia("(max-width: 759px)"):null;H=Ce?.matches??!1;let Ct=new Ke($r(),s=>{e.setDeviceState(s)});e.attachDevicePreview(Ct);function $r(){return l.innerHTML=`<div class="device-shell">
|
|
283
|
+
<div class="device-head"><span class="d-title">Device preview</span><button type="button" class="iconbtn" data-action="device-close" aria-label="Close device preview">${u("x",13)}</button></div>
|
|
284
|
+
<iframe class="device-frame" name="${gr}" title="Store device preview"></iframe>
|
|
284
285
|
<div class="device-fallback" hidden>The store blocks device framing. Open this draft on a mobile device or use your browser's device mode.<div class="row"><button type="button" class="btn ghost sm" data-action="device-copy">Copy current URL</button></div></div>
|
|
285
|
-
</div>`,l.querySelector("iframe")}let
|
|
286
|
+
</div>`,l.querySelector("iframe")}let et=l.querySelector("iframe"),Rr=l.querySelector(".device-fallback"),R=new Ge({box:o,label:a},(s,c)=>{e.selectElement(s,c),R.setSelected(s),X=c,P=ve(s),L="operator",H&&(J=!0),g()},s=>{e.setPickerActive(s),g()},()=>{$="unsupported",g()}),tt=s=>`<span class="draft-pill">${u("eye",11)}${s?"Draft":"Draft \u2014 not visible to shoppers"}</span>`,Or=()=>N==="offline"?'<span class="conn-chip offline" role="status"><span class="dot err"><i></i><b></b></span>Offline \u2014 reconnecting\u2026</span>':"",Tt=()=>{let s=ce();return s<=Ye?`<span class="session-chip" title="Editing session time remaining">${u("clock",12)}<span data-session-text>Session ends in ${Ar(s)}</span><button type="button" class="extend" data-action="extend-session">Extend</button></span>`:`<span class="session-note" title="Editing session time remaining" data-session-text>Session \xB7 ${Math.floor(s/60)} min left</span>`},$t=s=>{let c=h.variation,m=c?.name||"Variation",f=(m.trim()[0]||"V").toUpperCase(),A=q?`<div class="var-menu ee-in" role="listbox" aria-label="Eligible variations">
|
|
286
287
|
<div class="note">Switching keeps your saved draft \u2014 nothing is lost.</div>
|
|
287
|
-
${
|
|
288
|
-
<span class="vid" aria-hidden="true">${v(
|
|
289
|
-
<span class="meta"><span class="n">${v(x)}</span><span class="s">${b?`${
|
|
290
|
-
${b?
|
|
288
|
+
${p.variations.map(E=>{let b=E.id===c?.id,x=E.name||E.slug||"Variation",ee=(x.trim()[0]||"V").toUpperCase();return`<button type="button" class="var-item" role="option" aria-selected="${b}" data-action="variation-pick" data-variation="${v(E.id)}">
|
|
289
|
+
<span class="vid" aria-hidden="true">${v(ee)}</span>
|
|
290
|
+
<span class="meta"><span class="n">${v(x)}</span><span class="s">${b?`${Ae(h).length} change${Ae(h).length===1?"":"s"} in draft`:"Draft"}</span></span>
|
|
291
|
+
${b?u("check",13):""}
|
|
291
292
|
</button>`}).join("")}
|
|
292
293
|
</div>`:"";return`<div class="var-wrap">
|
|
293
|
-
<button type="button" class="var-btn" data-action="variation-open" aria-haspopup="listbox" aria-expanded="${
|
|
294
|
-
<span class="vid" aria-hidden="true">${v(
|
|
295
|
-
${
|
|
296
|
-
${
|
|
294
|
+
<button type="button" class="var-btn" data-action="variation-open" aria-haspopup="listbox" aria-expanded="${q}" aria-label="Variation: ${v(m)}. Switch variation">
|
|
295
|
+
<span class="vid" aria-hidden="true">${v(f)}</span>
|
|
296
|
+
${s?"":`<span class="vname">${v(m)}</span>`}
|
|
297
|
+
${u("chevD",12)}
|
|
297
298
|
</button>
|
|
298
|
-
${
|
|
299
|
-
</div>`},
|
|
300
|
-
<button type="button" role="radio" aria-checked="${
|
|
301
|
-
<button type="button" role="radio" aria-checked="${
|
|
302
|
-
</div>`},
|
|
303
|
-
<button type="button" class="sm" role="radio" aria-checked="${
|
|
304
|
-
<button type="button" class="sm" role="radio" aria-checked="${
|
|
305
|
-
<button type="button" class="sm" role="radio" aria-checked="${
|
|
306
|
-
</div>`,
|
|
307
|
-
<button type="button" class="iconbtn" data-action="undo" aria-label="Undo" title="Undo" ${
|
|
308
|
-
<button type="button" class="iconbtn" data-action="redo" aria-label="Redo" title="Redo" ${
|
|
309
|
-
</div>`,
|
|
310
|
-
${
|
|
311
|
-
${
|
|
312
|
-
${
|
|
313
|
-
</div>`},
|
|
314
|
-
<div class="mark" aria-hidden="true">${
|
|
299
|
+
${A}
|
|
300
|
+
</div>`},Rt=()=>{let s=h.variation?.name||"Variation";return`<div class="seg" role="radiogroup" aria-label="Compare original and variation">
|
|
301
|
+
<button type="button" role="radio" aria-checked="${j==="original"}" data-action="compare" data-view="original">Original</button>
|
|
302
|
+
<button type="button" role="radio" aria-checked="${j==="variation"}" data-action="compare" data-view="variation">${v(s)}</button>
|
|
303
|
+
</div>`},Lr=()=>`<div class="seg" role="radiogroup" aria-label="Preview viewport">
|
|
304
|
+
<button type="button" class="sm" role="radio" aria-checked="${de==="desktop"}" data-action="device" data-device="desktop" title="Desktop preview" aria-label="Desktop preview">${u("monitor",13)}</button>
|
|
305
|
+
<button type="button" class="sm" role="radio" aria-checked="${de==="tablet"}" data-action="device" data-device="tablet" title="Tablet preview \u2014 768px" aria-label="Tablet preview, 768 pixels">${u("tablet",13)}</button>
|
|
306
|
+
<button type="button" class="sm" role="radio" aria-checked="${de==="mobile"}" data-action="device" data-device="mobile" title="Mobile preview \u2014 390px" aria-label="Mobile preview, 390 pixels">${u("phone",13)}</button>
|
|
307
|
+
</div>`,Ot=()=>`<div class="undo-redo">
|
|
308
|
+
<button type="button" class="iconbtn" data-action="undo" aria-label="Undo" title="Undo" ${h.canUndo?"":"disabled"}>${u("undo",15)}</button>
|
|
309
|
+
<button type="button" class="iconbtn" data-action="redo" aria-label="Redo" title="Redo" ${h.canRedo?"":"disabled"}>${u("redo",15)}</button>
|
|
310
|
+
</div>`,Lt=()=>{let s=Ae(h).length,c=(m,f,A,E)=>`<button type="button" class="tab" role="tab" aria-selected="${L===m}" data-action="tab" data-tab="${m}">${A}${f}${E?`<span class="count">${E}</span>`:""}</button>`;return`<div class="tabs" role="tablist" aria-label="Editor panels">
|
|
311
|
+
${c("operator","Operator",_(12,L==="operator"?"#fff":"rgba(255,255,255,0.55)"))}
|
|
312
|
+
${c("code","Code",u("braces",13))}
|
|
313
|
+
${c("changes","Changes",u("history",13),s)}
|
|
314
|
+
</div>`},Ir=(s,c)=>`<span class="ctx-chip">${u("cursorBox",12)}<span class="name">${v(c)}</span>${s?"":`<button type="button" class="replace" data-action="ctx-replace" aria-label="Replace selected element">Replace</button><button type="button" class="clear" data-action="ctx-clear" aria-label="Clear selected element">${u("x",11)}</button>`}</span>`,Dr=()=>{let s=h.pickerActive,c=X&&P?`<span class="lbl">Talking about</span>${Ir(!1,P)}`:`<button type="button" class="btn sm ${s?"primary":"soft"}" data-action="inspect-toggle">${u("pointer",13)}${s?"Click something on the page\u2026":"Point at an element"}</button><span class="opt">optional \u2014 you can also just describe the change</span>`,m=I.length===0,f=`<div class="op-empty">
|
|
315
|
+
<div class="mark" aria-hidden="true">${_(20)}</div>
|
|
315
316
|
<div class="t">What should change on this page?</div>
|
|
316
317
|
<p>Point at an element or just describe it. Operator makes the change on the draft \u2014 you see it on the real page immediately.</p>
|
|
317
|
-
<div class="sugs">${
|
|
318
|
-
</div>`,
|
|
319
|
-
<div class="head">${
|
|
320
|
-
<div class="steps" role="status" aria-live="polite">${b.steps.map((
|
|
318
|
+
<div class="sugs">${di.map(b=>`<button type="button" class="sug" data-action="suggestion">${v(b)}</button>`).join("")}</div>
|
|
319
|
+
</div>`,A=I.map(b=>{if(b.role==="user")return`<div class="msg-user">${b.ctxLabel?`<span class="ref">${u("cursorBox",10)} ${v(b.ctxLabel)}</span>`:""}<div class="bubble">${v(b.text)}</div></div>`;if(b.phase==="working")return`<div class="op-card working ee-in">
|
|
320
|
+
<div class="head">${_(13)}<span>Operator</span>${b.abort?`<button type="button" class="btn sm bare" style="margin-left:auto;padding:2px 6px" data-action="op-stop" data-msg="${b.id}">${u("stop",12)}Stop</button>`:""}</div>
|
|
321
|
+
<div class="steps" role="status" aria-live="polite">${b.steps.map((te,me)=>{let M=me<b.step?"done":me===b.step?"cur":"todo",$e=M==="done"?u("check",12):M==="cur"?u("refresh",12,'class="spin"'):'<span class="idle">\xB7</span>';return`<div class="step ${M}">${$e}${v(te)}</div>`}).join("")}</div>
|
|
321
322
|
</div>`;if(b.phase==="failed")return`<div class="op-card failed ee-in" role="alert">
|
|
322
|
-
<div class="head">${
|
|
323
|
+
<div class="head">${u("alert",13)} Operator couldn't finish</div>
|
|
323
324
|
<p>${v(b.error??"Something went wrong.")} Nothing was changed on the draft.</p>
|
|
324
|
-
<div class="row"><button type="button" class="btn sm soft" data-action="op-retry" data-msg="${b.id}">${
|
|
325
|
+
<div class="row"><button type="button" class="btn sm soft" data-action="op-retry" data-msg="${b.id}">${u("refresh",12)}Try again</button></div>
|
|
325
326
|
</div>`;if(b.phase==="save-failed")return`<div class="op-card failed ee-in" role="alert">
|
|
326
|
-
<div class="head">${
|
|
327
|
+
<div class="head">${u("alert",13)} Change applied, but not saved</div>
|
|
327
328
|
<p>${v(b.error??"The draft could not be saved.")} The proposed change remains on this page so you can review it and retry saving.</p>
|
|
328
|
-
<div class="row"><button type="button" class="btn sm soft" data-action="retry-save" data-msg="${b.id}">${
|
|
329
|
-
</div>`;
|
|
330
|
-
|
|
331
|
-
|
|
329
|
+
<div class="row"><button type="button" class="btn sm soft" data-action="retry-save" data-msg="${b.id}">${u("refresh",12)}Retry save</button><button type="button" class="btn sm bare" data-action="op-all-changes">${u("history",12)}Review changes</button></div>
|
|
330
|
+
</div>`;if(b.phase==="publication-failed")return`<div class="op-card failed ee-in" role="alert">
|
|
331
|
+
<div class="head">${u("alert",13)} Change saved, but publication failed</div>
|
|
332
|
+
<p>${v(b.error??"Storefront publication failed.")} The change is saved in Apex. Keep the editor open and retry publication.</p>
|
|
333
|
+
<div class="row"><button type="button" class="btn sm soft" data-action="retry-save" data-msg="${b.id}">${u("refresh",12)}Retry publication</button><button type="button" class="btn sm bare" data-action="op-all-changes">${u("history",12)}Review changes</button></div>
|
|
334
|
+
</div>`;let x=b.results.length,ee=_t(b);return`<div class="op-card done ee-in">
|
|
335
|
+
<div class="head">${u("check",13)} ${x===1?"Made 1 change":`Made ${x} changes`} \u2014 it's on the page now</div>
|
|
336
|
+
<div class="items">${b.results.map(te=>`<div class="item">${_(11)}<span class="b">${v(te.label)}<span class="sel">${v(te.target)}</span></span></div>`).join("")}</div>
|
|
332
337
|
<div class="row">
|
|
333
|
-
<button type="button" class="btn sm ghost" data-action="op-undo-run" data-msg="${b.id}" ${
|
|
334
|
-
<button type="button" class="btn sm bare" data-action="op-all-changes">${
|
|
338
|
+
<button type="button" class="btn sm ghost" data-action="op-undo-run" data-msg="${b.id}" ${ee?"":"disabled"}>${u("undo",12)}${b.undone?"Undone":"Undo this"}</button>
|
|
339
|
+
<button type="button" class="btn sm bare" data-action="op-all-changes">${u("history",12)}All changes</button>
|
|
335
340
|
</div>
|
|
336
341
|
<div class="hint">Not right? Just tell Operator what to adjust.</div>
|
|
337
|
-
</div>`}).join(""),
|
|
338
|
-
<div class="op-ctx">${
|
|
339
|
-
<div class="op-thread" data-op-thread>${
|
|
342
|
+
</div>`}).join(""),E=P?`What should change about the ${P.toLowerCase()}?`:"Describe a change\u2026";return`<div class="panel" role="tabpanel" aria-label="Operator">
|
|
343
|
+
<div class="op-ctx">${c}</div>
|
|
344
|
+
<div class="op-thread" data-op-thread>${m?f:A}</div>
|
|
340
345
|
<form class="op-input" data-operator-form>
|
|
341
346
|
<div class="line">
|
|
342
|
-
<textarea class="field" data-field="operator-prompt" rows="2" maxlength="30000" placeholder="${v(
|
|
343
|
-
<button type="submit" class="send" aria-label="Send to Operator" title="Send to Operator" ${
|
|
347
|
+
<textarea class="field" data-field="operator-prompt" rows="2" maxlength="30000" placeholder="${v(E)}" aria-label="Describe the change for Operator" ${fe?"disabled":""}>${v(ue)}</textarea>
|
|
348
|
+
<button type="submit" class="send" aria-label="Send to Operator" title="Send to Operator" ${fe||!h.variation?"disabled":""}>${u("send",15)}</button>
|
|
344
349
|
</div>
|
|
345
350
|
<div class="note">Operator edits this draft only \u2014 shoppers never see it.</div>
|
|
346
351
|
</form>
|
|
347
|
-
</div>`},
|
|
352
|
+
</div>`},_r=()=>{let s=`<div class="code-body">
|
|
348
353
|
<label><span class="flabel">CSS on this variation</span>
|
|
349
|
-
<textarea class="field code" data-field="css" rows="9" spellcheck="false" aria-label="Custom CSS for this variation">${v(
|
|
354
|
+
<textarea class="field code" data-field="css" rows="9" spellcheck="false" aria-label="Custom CSS for this variation">${v(h.artifacts.customCss)}</textarea>
|
|
350
355
|
<span class="fhint">Scoped to the experiment page. Applies live as you type.</span>
|
|
351
356
|
</label>
|
|
352
|
-
<div class="code-ok">${
|
|
353
|
-
</div>`,
|
|
357
|
+
<div class="code-ok">${u("check",12)} CSS changes are fully undoable.</div>
|
|
358
|
+
</div>`,c=`<div class="code-body">
|
|
354
359
|
<label><span class="flabel">JavaScript on this variation</span>
|
|
355
|
-
<textarea class="field code" data-field="js" rows="9" spellcheck="false" aria-label="Custom JavaScript for this variation">${v(
|
|
360
|
+
<textarea class="field code" data-field="js" rows="9" spellcheck="false" aria-label="Custom JavaScript for this variation">${v(h.artifacts.customJs)}</textarea>
|
|
356
361
|
</label>
|
|
357
|
-
<div class="js-warn" role="note">${
|
|
362
|
+
<div class="js-warn" role="note">${u("alert",14)}<span>JavaScript changes the live page directly and <strong>can't be undone by the editor</strong>. Undo removes it from the draft; close and relaunch the editor to fully reset the page.</span></div>
|
|
358
363
|
<div style="display:flex;gap:8px">
|
|
359
|
-
<button type="button" class="btn soft" data-action="run-js">${
|
|
364
|
+
<button type="button" class="btn soft" data-action="run-js">${u("play",13)}Run on page</button>
|
|
360
365
|
</div>
|
|
361
|
-
${
|
|
366
|
+
${h.reloadRequired?`<div class="code-ok" style="color:var(--warning)">${u("alert",12,'style="color:var(--warning)"')} JavaScript ran on this page. Relaunch the editor to fully reset it.</div>`:""}
|
|
362
367
|
</div>`;return`<div class="code-panel" role="tabpanel" aria-label="Code">
|
|
363
368
|
<div class="code-head">
|
|
364
369
|
<div class="seg" role="radiogroup" aria-label="Code language">
|
|
365
|
-
<button type="button" role="radio" aria-checked="${
|
|
366
|
-
<button type="button" role="radio" aria-checked="${
|
|
370
|
+
<button type="button" role="radio" aria-checked="${Z==="css"}" data-action="code-lang" data-lang="css">${u("braces",13)}CSS</button>
|
|
371
|
+
<button type="button" role="radio" aria-checked="${Z==="js"}" data-action="code-lang" data-lang="js">${u("code",13)}JavaScript</button>
|
|
367
372
|
</div>
|
|
368
373
|
<span class="peer">works without Operator</span>
|
|
369
374
|
</div>
|
|
370
|
-
${
|
|
375
|
+
${Z==="css"?s:c}
|
|
371
376
|
<div class="code-foot">Code and Operator write to the same draft. Operator's changes appear as artifact operations you can inspect under <button type="button" data-action="view-artifact">Changes \u2192 View artifact</button>. Full code authoring also lives in the variation workspace in Apex.</div>
|
|
372
|
-
</div>`},
|
|
373
|
-
<span class="org" title="${
|
|
377
|
+
</div>`},Pr=()=>{let s=Ae(h),c=s.map((f,A)=>`<div class="chg-row">
|
|
378
|
+
<span class="org" title="${f.origin==="operator"?"Made by Operator":"Custom code"}">${f.origin==="operator"?_(13):u(f.kind==="css"?"braces":"code",13)}</span>
|
|
374
379
|
<div class="meta">
|
|
375
|
-
<div class="l">${v(
|
|
376
|
-
<div class="s">${v(
|
|
380
|
+
<div class="l">${v(f.label)}</div>
|
|
381
|
+
<div class="s">${v(f.target)} \xB7 ${f.origin==="operator"?"Operator":"code"}${f.risky?" \xB7 relaunch the editor to fully revert":""}</div>
|
|
377
382
|
</div>
|
|
378
|
-
<button type="button" class="iconbtn xs" data-action="chg-remove" data-kind="${
|
|
379
|
-
</div>`).join(""),
|
|
380
|
-
<div class="chg-head"><span class="t">${
|
|
381
|
-
${
|
|
383
|
+
<button type="button" class="iconbtn xs" data-action="chg-remove" data-kind="${f.kind}" data-index="${f.mutationIndex??A}" aria-label="Remove change: ${v(f.label)}">${u("x",11)}</button>
|
|
384
|
+
</div>`).join(""),m=JSON.stringify({variation:h.variation?.name??null,artifactHash:h.variation?.artifactHash??null,operations:h.artifacts.mutations,customCss:h.artifacts.customCss||null,customJs:h.artifacts.customJs||null},null,2);return`<div class="chg-panel" role="tabpanel" aria-label="Changes">
|
|
385
|
+
<div class="chg-head"><span class="t">${s.length} change${s.length===1?"":"s"} in this draft</span>${wt(h)}</div>
|
|
386
|
+
${s.length===0?'<p class="chg-empty">No changes yet. Ask Operator, or add CSS or JavaScript in Code.</p>':`<div class="chg-list">${c}</div>`}
|
|
382
387
|
<div class="chg-art">
|
|
383
|
-
<button type="button" class="toggle" data-action="artifact-toggle" aria-expanded="${
|
|
384
|
-
${
|
|
388
|
+
<button type="button" class="toggle" data-action="artifact-toggle" aria-expanded="${Q}">${u(Q?"chevD":"chevR",12)}View artifact (JSON)</button>
|
|
389
|
+
${Q?`<div class="json ee-in" aria-label="Variation artifact JSON">${v(m)}</div>`:""}
|
|
385
390
|
<div class="note">Drafts save automatically. Nothing is shown to shoppers until the experiment is launched from Apex.</div>
|
|
386
|
-
<div class="pill-row">${
|
|
391
|
+
<div class="pill-row">${tt(!1)}</div>
|
|
387
392
|
</div>
|
|
388
|
-
</div>`},
|
|
389
|
-
${
|
|
390
|
-
<button type="button" class="iconbtn" data-action="expand" aria-label="Expand editor panel">${
|
|
393
|
+
</div>`},It=()=>L==="operator"?Dr():L==="code"?_r():Pr(),Hr=()=>V?`<div class="rail-dock">
|
|
394
|
+
${_(16)}
|
|
395
|
+
<button type="button" class="iconbtn" data-action="expand" aria-label="Expand editor panel">${u("collapse",15)}</button>
|
|
391
396
|
<div class="sep"></div>
|
|
392
|
-
<button type="button" class="iconbtn ${
|
|
397
|
+
<button type="button" class="iconbtn ${h.pickerActive?"active":""}" data-action="rail-inspect" aria-label="Point at an element">${u("pointer",15)}</button>
|
|
393
398
|
<div class="grow"></div>
|
|
394
|
-
<span title="Connection: ${
|
|
399
|
+
<span title="Connection: ${N}"><span class="dot ${N==="connected"?"ok":"err"}"><i></i>${N==="connected"?"":"<b></b>"}</span></span>
|
|
395
400
|
</div>`:`<div class="dock">
|
|
396
401
|
<div class="id-head">
|
|
397
402
|
<div class="id-row">
|
|
398
|
-
${
|
|
403
|
+
${_(18)}
|
|
399
404
|
<div class="id-meta">
|
|
400
|
-
<div class="id-title" title="${v(
|
|
401
|
-
<div class="id-sub">On your store \xB7 ${v(
|
|
405
|
+
<div class="id-title" title="${v(w)}">${v(w)}</div>
|
|
406
|
+
<div class="id-sub">On your store \xB7 ${v(y)}</div>
|
|
402
407
|
</div>
|
|
403
|
-
<button type="button" class="iconbtn" data-action="collapse" aria-label="Collapse editor panel">${
|
|
408
|
+
<button type="button" class="iconbtn" data-action="collapse" aria-label="Collapse editor panel">${u("collapse",15)}</button>
|
|
404
409
|
</div>
|
|
405
410
|
<div class="id-chips">
|
|
406
|
-
${
|
|
407
|
-
${
|
|
411
|
+
${$t(!1)}
|
|
412
|
+
${tt(!0)}
|
|
408
413
|
<span class="grow"></span>
|
|
409
|
-
${
|
|
414
|
+
${wt(h)}
|
|
410
415
|
</div>
|
|
411
|
-
${
|
|
416
|
+
${N!=="connected"?`<div class="id-conn">${Or()}</div>`:""}
|
|
412
417
|
</div>
|
|
413
418
|
<div class="view-row">
|
|
414
|
-
${
|
|
415
|
-
${
|
|
419
|
+
${Ot()}
|
|
420
|
+
${Rt()}
|
|
416
421
|
<span class="grow"></span>
|
|
417
|
-
${
|
|
422
|
+
${Lr()}
|
|
418
423
|
</div>
|
|
419
|
-
${
|
|
420
|
-
${
|
|
424
|
+
${Lt()}
|
|
425
|
+
${It()}
|
|
421
426
|
<div class="foot">
|
|
422
|
-
${
|
|
427
|
+
${Tt()}
|
|
423
428
|
<span class="grow"></span>
|
|
424
|
-
<button type="button" class="btn primary" data-action="done">${
|
|
429
|
+
<button type="button" class="btn primary" data-action="done">${u("check",13)}Done</button>
|
|
425
430
|
</div>
|
|
426
|
-
</div>`,
|
|
427
|
-
${
|
|
428
|
-
${
|
|
429
|
-
${
|
|
431
|
+
</div>`,Nr=()=>{let s=`<div class="bar">
|
|
432
|
+
${_(14)}
|
|
433
|
+
${$t(!0)}
|
|
434
|
+
${tt(!0)}
|
|
430
435
|
<span class="grow"></span>
|
|
431
|
-
${
|
|
432
|
-
</div>`;return
|
|
436
|
+
${wt(h)}
|
|
437
|
+
</div>`;return J?`<div class="sheet">
|
|
433
438
|
<button type="button" class="handle" data-action="sheet-toggle" aria-label="Collapse editor" aria-expanded="true"><i></i></button>
|
|
434
|
-
${
|
|
439
|
+
${s}
|
|
435
440
|
<div class="row2">
|
|
436
|
-
${
|
|
437
|
-
${
|
|
438
|
-
${
|
|
441
|
+
${Ot()}
|
|
442
|
+
${Rt()}
|
|
443
|
+
${Tt()}
|
|
439
444
|
<span class="grow"></span>
|
|
440
|
-
<button type="button" class="btn primary sm" data-action="done">${
|
|
445
|
+
<button type="button" class="btn primary sm" data-action="done">${u("check",12)}Done</button>
|
|
441
446
|
</div>
|
|
442
|
-
${
|
|
443
|
-
${
|
|
447
|
+
${Lt()}
|
|
448
|
+
${It()}
|
|
444
449
|
</div>`:`<div class="sheet">
|
|
445
450
|
<button type="button" class="handle" data-action="sheet-toggle" aria-label="Expand editor" aria-expanded="false"><i></i></button>
|
|
446
|
-
${
|
|
447
|
-
</div>`},
|
|
448
|
-
${
|
|
449
|
-
${
|
|
450
|
-
<div class="m-head"><span class="m-icon warn">${
|
|
451
|
+
${s}
|
|
452
|
+
</div>`},Ur=()=>{let s=h.pickerActive,c=[];return $==="unsupported"&&c.push(`<div class="banner warn ee-in" role="status">${u("alert",14)}<span class="body">That element can't be edited here. Point at an element on the storefront page instead.</span><button type="button" class="btn sm ghost" data-action="banner-dismiss">OK</button></div>`),$==="spanav"&&c.push(`<div class="banner info ee-in" role="status">${u("globe",14)}<span class="body">You navigated to ${v(location.pathname+location.search)}. This variation targets ${v(k||"")}, so changes are paused until you return.</span><button type="button" class="btn sm soft" data-action="spa-back">Back to target page</button><button type="button" class="btn sm ghost" data-action="banner-dismiss">Stay</button></div>`),N==="offline"&&c.push(`<div class="banner error ee-in" role="status">${u("wifiOff",14)}<span class="body">Connection lost. Your edits are kept locally and will save when you're back online.</span></div>`),`${s?`<div class="page-border" aria-hidden="true"></div><div class="select-banner ee-in">${u("pointer",13)}Click an element to talk about it<button type="button" data-action="back-to-browsing">Back to browsing \xB7 Esc</button></div>`:""}
|
|
453
|
+
${c.length?`<div class="banners ${s?"lower":""}">${c.join("")}</div>`:""}
|
|
454
|
+
${j==="original"?`<div class="orig-chip ee-in">${u("eye",13)}Viewing the original \u2014 draft changes hidden<button type="button" data-action="show-variation">Show ${v(h.variation?.name||"variation")}</button></div>`:""}`},zr=()=>{if(h.saveState==="conflict")return`<div class="modal-backdrop"><div class="modal ee-in" role="dialog" aria-modal="true" aria-label="This draft changed somewhere else">
|
|
455
|
+
<div class="m-head"><span class="m-icon warn">${u("alert",15)}</span><div class="m-title">This draft changed somewhere else</div></div>
|
|
451
456
|
<div class="m-body">
|
|
452
|
-
<p>Someone saved a newer version of <strong style="color:var(--text1)">${v(
|
|
457
|
+
<p>Someone saved a newer version of <strong style="color:var(--text1)">${v(h.variation?.name||"this variation")}</strong> while you were editing \u2014 likely from the Apex dashboard.</p>
|
|
453
458
|
<p>Loading the newer version discards your unsaved edits here. Keeping yours overwrites theirs.</p>
|
|
454
459
|
</div>
|
|
455
460
|
<div class="m-actions"><button type="button" class="btn ghost" data-action="conflict-mine">Keep my version</button><button type="button" class="btn primary" data-action="conflict-theirs">Load newer version</button></div>
|
|
456
|
-
</div></div>`;if(
|
|
457
|
-
<div class="m-head"><span class="m-icon purple">${
|
|
461
|
+
</div></div>`;if(U==="expired"){let s=Xe?`${Math.max(1,Math.round((Date.now()-Xe)/1e3))} seconds ago`:null;return`<div class="modal-backdrop"><div class="modal ee-in" role="dialog" aria-modal="true" aria-label="Editing session ended" style="width:410px">
|
|
462
|
+
<div class="m-head"><span class="m-icon purple">${u("clock",15)}</span><div class="m-title">Editing session ended</div></div>
|
|
458
463
|
<div class="m-body">
|
|
459
|
-
<p>Sessions are time-limited for security. ${
|
|
464
|
+
<p>Sessions are time-limited for security. ${s?`Your draft was saved <strong style="color:var(--text1)">${s}</strong> \u2014 nothing was lost.`:"Your saved draft is safe in Apex."}</p>
|
|
460
465
|
<p>Start a new session from the variation in Apex.</p>
|
|
461
466
|
</div>
|
|
462
|
-
<div class="m-actions"><button type="button" class="btn ghost" data-action="expired-close">Close editor</button><button type="button" class="btn primary" data-action="expired-apex">${
|
|
463
|
-
</div></div>`}if(
|
|
464
|
-
<div class="m-head"><span class="m-icon ok">${
|
|
467
|
+
<div class="m-actions"><button type="button" class="btn ghost" data-action="expired-close">Close editor</button><button type="button" class="btn primary" data-action="expired-apex">${u("external",13)}Open variation in Apex</button></div>
|
|
468
|
+
</div></div>`}if(U==="stop"){let s=Ae(h);return`<div class="modal-backdrop"><div class="modal ee-in" role="dialog" aria-modal="true" aria-label="Done editing?">
|
|
469
|
+
<div class="m-head"><span class="m-icon ok">${u("check",15)}</span><div class="m-title">Done editing?</div></div>
|
|
465
470
|
<div class="m-body">
|
|
466
|
-
<p>${
|
|
467
|
-
${
|
|
471
|
+
<p>${s.length} change${s.length===1?"":"s"} saved to the ${v(h.variation?.name||"variation")} draft. The editor will be removed from the page and the session closed.</p>
|
|
472
|
+
${s.length?`<div style="margin-top:12px;display:grid;gap:5px">${s.slice(0,4).map(c=>`<div style="font-size:12px;color:var(--text3);display:flex;gap:7px;align-items:center">${u("check",11,'style="color:var(--positive)"')} ${v(c.label)}</div>`).join("")}</div>`:""}
|
|
468
473
|
<p style="font-size:12px;color:var(--text3)">Launching the experiment still happens from Apex \u2014 closing here never starts traffic.</p>
|
|
469
474
|
</div>
|
|
470
|
-
<div class="m-actions"><button type="button" class="btn ghost" data-action="modal-keep">Keep editing</button><button type="button" class="btn primary" data-action="modal-save-close">${
|
|
471
|
-
</div></div>`}return""},
|
|
472
|
-
<div class="kicker">${
|
|
473
|
-
<div class="sub">On-site editor \xB7 ${v(
|
|
474
|
-
<div class="steps" role="status" aria-live="polite">${
|
|
475
|
-
<div class="bar"><i style="width:${Math.min(100,
|
|
476
|
-
${
|
|
477
|
-
<div class="scope">Session is scoped to this experiment and store, and expires after ${
|
|
478
|
-
</div>`},
|
|
479
|
-
`),
|
|
475
|
+
<div class="m-actions"><button type="button" class="btn ghost" data-action="modal-keep">Keep editing</button><button type="button" class="btn primary" data-action="modal-save-close">${u("check",13)}Save and close</button></div>
|
|
476
|
+
</div></div>`}return""},Br=()=>{let s=h.variation?3:2,c=!h.variation&&h.saveState==="error",m=Math.max(1,Math.round((Date.parse(p.expiresAt)-Date.now())/6e4)),f=["Starting a secure editing session",`Connecting to ${y}`,`Loading the ${h.variation?.name||"variation"} draft`];return`<div class="box">
|
|
477
|
+
<div class="kicker">${_(22)} Apex</div>
|
|
478
|
+
<div class="sub">On-site editor \xB7 ${v(w)}</div>
|
|
479
|
+
<div class="steps" role="status" aria-live="polite">${f.map((A,E)=>{let b=E<s?"done":E===s?"cur":"todo",x=b==="done"?u("check",14,'style="color:var(--positive)"'):b==="cur"?u("refresh",14,'class="spin" style="color:var(--purple300)"'):'<span class="idle">\xB7</span>';return`<div class="step ${b}">${x}${v(A)}</div>`}).join("")}</div>
|
|
480
|
+
<div class="bar"><i style="width:${Math.min(100,s/3*100+12)}%"></i></div>
|
|
481
|
+
${c?`<div class="err">${v(h.saveMessage||"The draft could not be loaded.")}<div style="margin-top:10px"><button type="button" class="btn soft sm" data-action="boot-retry">Try again</button></div></div>`:""}
|
|
482
|
+
<div class="scope">Session is scoped to this experiment and store, and expires after ${m} minutes. Drafts only \u2014 shoppers never see your edits.</div>
|
|
483
|
+
</div>`},g=()=>{h=e.getState(),!F&&h.variation&&(F=!0),d.hidden=F,F||(d.innerHTML=Br());let s=t.activeElement,c=s?.dataset?.field,m=s&&"selectionStart"in s?[s.selectionStart,s.selectionEnd]:null;i.className=`zone${H?" narrow":V?" rail":""}`,i.innerHTML=F?Ur():"",l.className=`device${H?" narrow":""}`,n.innerHTML=F?`${H?Nr():Hr()}${zr()}`:"",t.host.dataset.apexEditorSheetState=H?J?"expanded":"collapsed":"desktop",l.hidden=h.deviceState==="closed",et.hidden=h.deviceState==="blocked",Rr.hidden=h.deviceState!=="blocked";let f=l.querySelector(".d-title");if(f&&(f.textContent=de==="tablet"?"Tablet preview \xB7 768 \xD7 1024":"Mobile preview \xB7 390 \xD7 844"),c){let A=n.querySelector(`[data-field="${c}"]`);A?.focus(),A&&m&&"setSelectionRange"in A&&A.setSelectionRange(m[0],m[1])}Vr()},Vr=()=>{let s=n.querySelector("[data-op-thread]");s&&(s.scrollTop=s.scrollHeight)},Jr=e.subscribe(()=>g()),Dt=(s,c)=>JSON.stringify(s)===JSON.stringify(c);function _t(s){return s.phase!=="done"||s.undone||!s.postArtifacts?!1:[...I].reverse().find(m=>m.role==="op"&&m.phase==="done"&&!m.undone)?.id===s.id&&Dt(e.getState().artifacts,s.postArtifacts)}let Pt=(s,c,m)=>{if(!h.variation||fe)return;let f=S(e.getState().artifacts),A=c?{selector:c,tag:h.selectedSelector===c?h.selectedElement?.tagName.toLowerCase():void 0,textPreview:h.selectedSelector===c&&(h.selectedElement?.textContent??"").replace(/\s+/g," ").trim().slice(0,200)||void 0}:null,E=new AbortController,b={id:++Mt,role:"user",text:s,ctxLabel:m},x={id:++Mt,role:"op",phase:"working",step:0,steps:[m?`Inspecting the ${m.toLowerCase()}`:"Reading the page","Asking Operator to draft the change","Applying the change to the draft"],prompt:s,ctxSelector:c,ctxLabel:m,preArtifacts:f,postArtifacts:null,results:[],error:null,undone:!1,abort:E};I.push(b,x),he.push({role:"user",content:s}),fe=!0,A&&(X=null,P=null,R.setSelected(null),e.clearSelectedElement()),g();let ee=setTimeout(()=>{x.phase==="working"&&(x.step=1,g())},600),te=[`Live merchant page: ${ke(p.targetUrl)}`,c?`The user selected this element as the request context: selector "${c}"${m?` (${m})`:""}. Ground the change on it.`:""].filter(Boolean).join(`
|
|
484
|
+
`),me=Er({apiOrigin:e.apiOrigin,session:p,variationId:h.variation.id,prompt:s,artifacts:f,conversation:he.slice(0,-1).slice(-12),pageContext:te,signal:E.signal,selectedElement:A}).then(async M=>{if(clearTimeout(ee),x.phase!=="working"||E.signal.aborted||(x.step=2,g(),E.signal.aborted))return;let $e=e.applyCommandArtifacts(M.artifacts);if(x.postArtifacts=S(e.getState().artifacts),E.signal.aborted){e.restoreArtifacts(f),await e.saveNow();return}he.push({role:"assistant",content:M.explanation}),x.abort=null,await e.saveNow();let Re=e.getState().saveState;if(Re==="error"||Re==="conflict"||Re==="publication_failed"){x.phase=Re==="publication_failed"?"publication-failed":"save-failed",x.abort=null,x.results=Et(f,e.getState().artifacts),x.error=e.getState().saveMessage;return}x.phase="done",x.abort=null,x.postArtifacts=S(e.getState().artifacts),x.results=Et(f,e.getState().artifacts),x.results.length||(x.results=[{label:M.explanation,target:"no page changes"}]),$e.ok||x.results.push({label:"One selector needs review \u2014 check the result on the page.",target:$e.repairHint??"selector audit"})}).catch(M=>{clearTimeout(ee),!E.signal.aborted&&(x.phase=x.postArtifacts?"save-failed":"failed",x.abort=null,x.error=M instanceof Error?M.message:"Operator could not build the draft.",x.postArtifacts&&(x.results=Et(f,e.getState().artifacts)))}).finally(()=>{if(E.signal.aborted){let M=I.indexOf(b);M>=0&&I.splice(M,2),he.pop()}Me===me&&(Me=null),fe=!1,g()});Me=me},qr=async s=>{let c=++Ze;for(let f of I)f.role==="op"&&f.phase==="working"&&f.abort?.abort();if(await Me,c!==Ze||(await e.saveNow(),c!==Ze))return;let m=e.getState().saveState;if(m==="error"||m==="conflict"){g();return}X=null,P=null,R.setSelected(null),e.clearSelection(),I.length=0,he.length=0,j="variation",e.toggleArtifacts(!0),await e.selectVariation(s),g()},jr=async s=>{let c=!!(s?.postArtifacts&&Dt(e.getState().artifacts,s.postArtifacts));await e.saveNow();let m=e.getState().saveState;(s?.phase==="save-failed"||s?.phase==="publication-failed")&&m!=="error"&&m!=="conflict"&&m!=="publication_failed"&&(s.phase="done",s.error=null,s.postArtifacts=c?S(e.getState().artifacts):null),g()},Te=s=>{let c=Number(s.dataset.msg),m=I.find(f=>f.id===c);return m&&m.role==="op"?m:null},rt=s=>{if(de=s,s==="desktop"){e.closeDevicePreview(),g();return}let c=s==="tablet"?{width:768,height:1024}:{width:390,height:844};et.style.width=`${c.width}px`,et.style.height=`${c.height}px`,e.openDevicePreview(),g()},nt=s=>{let c=s.target.closest("[data-action]");if(!c){q&&(q=!1,g());return}switch(c.dataset.action){case"collapse":V=!0,g();break;case"expand":V=!1,g();break;case"rail-inspect":V=!1,R.setActive(!0);break;case"sheet-toggle":J=!J,g();break;case"variation-open":q=!q,g();break;case"variation-pick":{q=!1;let f=c.dataset.variation;f&&f!==h.variation?.id&&qr(f),g();break}case"tab":L=c.dataset.tab??"operator",g();break;case"compare":{let f=c.dataset.view==="original"?"original":"variation";f!==j&&(j=f,e.toggleArtifacts(f==="variation")),g();break}case"show-variation":j="variation",e.toggleArtifacts(!0),g();break;case"device":rt(c.dataset.device??"desktop");break;case"undo":e.undo();break;case"redo":e.redo();break;case"inspect-toggle":R.setActive(!h.pickerActive);break;case"back-to-browsing":R.setActive(!1);break;case"ctx-replace":R.setActive(!0);break;case"ctx-clear":X=null,P=null,R.setSelected(null),e.clearSelection(),g();break;case"suggestion":ue=c.textContent?.trim()??"",g();break;case"op-stop":Te(c)?.abort?.abort();break;case"op-retry":{let f=Te(c);f&&Pt(f.prompt,f.ctxSelector,f.ctxLabel);break}case"op-undo-run":{let f=Te(c);f&&_t(f)&&(e.restoreArtifacts(f.preArtifacts),f.undone=!0,g());break}case"op-all-changes":L="changes",g();break;case"code-lang":Z=c.dataset.lang==="js"?"js":"css",g();break;case"run-js":e.applyCustomJs();break;case"view-artifact":L="changes",Q=!0,g();break;case"artifact-toggle":Q=!Q,g();break;case"chg-remove":{let f=c.dataset.kind;f==="mutation"?e.removeMutation(Number(c.dataset.index)):f==="css"?e.setCustomCss(""):f==="js"&&e.setCustomJs("");break}case"retry-save":jr(Te(c));break;case"extend-session":Fr();break;case"banner-dismiss":$==="spanav"&&(pe=!0),$=null,g();break;case"spa-back":$=null,pe=!1,location.assign(p.targetUrl);break;case"done":U="stop",g();break;case"modal-keep":U=null,g();break;case"modal-save-close":e.saveNow().then(()=>{let f=e.getState().saveState;if(f!=="error"&&f!=="conflict"&&f!=="publication_failed")return e.exit();g()}).catch(()=>g());break;case"conflict-mine":e.resolveConflict("mine");break;case"conflict-theirs":e.resolveConflict("theirs");break;case"expired-close":e.exit();break;case"expired-apex":window.open(T(h.variation?.id??p.initialVariationId),"_blank","noopener");break;case"boot-retry":e.selectVariation(p.initialVariationId);break;default:break}};n.addEventListener("click",nt),i.addEventListener("click",nt),d.addEventListener("click",nt),n.addEventListener("input",s=>{let c=s.target;c.dataset.field==="css"?e.setCustomCss(c.value):c.dataset.field==="js"?e.setCustomJs(c.value):c.dataset.field==="operator-prompt"&&(ue=c.value)}),n.addEventListener("submit",s=>{if(!s.target.closest("[data-operator-form]"))return;s.preventDefault();let m=ue.trim();m&&(ue="",Pt(m,X,P))}),l.addEventListener("click",s=>{let c=s.target.closest("[data-action]")?.dataset.action;c==="device-close"&&rt("desktop"),c==="device-copy"&&navigator.clipboard?.writeText(location.href)});let Ht=s=>{let c=s.composedPath()[0],m=c instanceof HTMLInputElement||c instanceof HTMLTextAreaElement||c instanceof HTMLSelectElement||c instanceof HTMLElement&&c.isContentEditable;if(s.key==="Escape"){if(U==="stop"){U=null,g();return}if(h.deviceState!=="closed"){s.preventDefault(),rt("desktop");return}return}if(!m){if(s.key==="s"||s.key==="S"){R.setActive(!h.pickerActive);return}(s.metaKey||s.ctrlKey)&&(s.key==="z"||s.key==="Z")&&(s.preventDefault(),s.shiftKey?e.redo():e.undo())}};window.addEventListener("keydown",Ht,!0);let Fr=async()=>{try{await e.extendSession()&&(Qe=ce()<=Ye,g())}catch{}},Nt={value:h.saveState},Kr=e.subscribe(s=>{s.saveState==="saved"&&Nt.value!=="saved"&&(Xe=Date.now()),Nt.value=s.saveState}),Wr=setInterval(()=>{let s=ce();if(s<=0&&U!=="expired"){U="expired",R.setActive(!1),g();return}let c=s<=Ye;if(c!==Qe){Qe=c,g();return}let m=n.querySelector("[data-session-text]");if(m&&(m.textContent=c?`Session ends in ${Ar(s)}`:`Session \xB7 ${Math.floor(s/60)} min left`),k&&F){let f=location.pathname+location.search!==k;f&&$!=="spanav"&&!pe&&$===null?($="spanav",g()):!f&&($==="spanav"||pe)&&($==="spanav"&&($=null),pe=!1,g())}},1e3),Ut=()=>{N="connected",g(),e.saveNow()},zt=()=>{N="offline",g()};window.addEventListener("online",Ut),window.addEventListener("offline",zt);let Bt=()=>{H=Ce?.matches??!1,g()};return Ce?.addEventListener?.("change",Bt),g(),{destroy(){for(let s of I)s.role==="op"&&s.phase==="working"&&s.abort?.abort();Jr(),Kr(),clearInterval(Wr),R.destroy(),Ct.close(!1),window.removeEventListener("keydown",Ht,!0),window.removeEventListener("online",Ut),window.removeEventListener("offline",zt),Ce?.removeEventListener?.("change",Bt),r.remove(),n.remove(),i.remove(),o.remove(),a.remove(),l.remove(),d.remove()}}}var St="apex-editor-host",fi=1e4,At=null,Y=null,kt=null,le=null;function Tr(){le?.stop(),kt?.destroy(),Y?.destroy(),kt=null,le=null,Y=null,At=null,document.getElementById(St)?.remove()}function C(t){return typeof t=="string"&&t.trim()?t.trim():null}function hi(t,e){if(!t||typeof t!="object")return null;let r=t,n={sid:C(r.sid),bearer:C(r.bearer),expiresAt:C(r.expiresAt),shopId:C(r.shopId),experimentId:C(r.experimentId),initialVariationId:C(r.initialVariationId),targetUrl:C(r.targetUrl),targetOrigin:C(r.targetOrigin)};if(n.sid!==e||!n.bearer||!n.expiresAt||!n.shopId||!n.experimentId||!n.initialVariationId||!n.targetUrl||!n.targetOrigin||!Number.isFinite(Date.parse(n.expiresAt))||Date.parse(n.expiresAt)<=Date.now())return null;let i=[];if(Array.isArray(r.variations))for(let o of r.variations){if(!o||typeof o!="object")continue;let a=o,l=C(a.id);l&&i.push({id:l,name:C(a.name),slug:C(a.slug)})}return{sid:e,bearer:n.bearer,expiresAt:n.expiresAt,shopId:n.shopId,experimentId:n.experimentId,experimentName:C(r.experimentName),experimentStatus:C(r.experimentStatus),initialVariationId:n.initialVariationId,targetUrl:n.targetUrl,targetOrigin:n.targetOrigin,variations:i}}function mi(t){document.getElementById(St)?.remove();let e=document.createElement("div");e.id=St,e.setAttribute("data-apex-editor-state","connected");let r=e.attachShadow({mode:"closed"});(document.body||document.documentElement).appendChild(e),kt=Cr(r,t)}async function gi(t){let e=new AbortController,r=setTimeout(()=>e.abort(),fi),n=!1;try{let i=new URL("/api/editor-sessions/exchange",t.apiOrigin);i.searchParams.set("sid",t.sid);let o=await fetch(i.toString(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t.token}),cache:"no-store",credentials:"omit",referrerPolicy:"no-referrer",signal:e.signal});if(!o.ok)return!1;let a=await o.json().catch(()=>null);if(a?.ok!==!0)return!1;let l=hi(a.session,t.sid);if(!l||typeof location<"u"&&l.targetOrigin!==location.origin)return!1;At=l,n=!0;let d=new ne(t.apiOrigin,l);Y=new Fe(l,t.apiOrigin,d),mi(Y),await Y.initialize(),le=new De(d,new Ie(Y)),Y.addCleanup(()=>{le?.stop(),le=null}),le.start();try{window.opener?.postMessage({type:"apex:editor-connected",sid:l.sid,experimentId:l.experimentId,variationId:l.initialVariationId},t.apiOrigin)}catch{}return!0}catch{return n&&Tr(),!1}finally{clearTimeout(r)}}function vi(){return At}var bi={reset:Tr};return en(xi);})();
|
|
480
485
|
//# sourceMappingURL=editor.js.map
|