@vitraun/webar 0.2.1 → 0.2.4
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/dist/widget-runtime.min.js +4 -1
- package/dist/widget.min.js +4 -1
- package/package.json +1 -1
|
@@ -1 +1,4 @@
|
|
|
1
|
-
(function(){"use strict";var M="VITRAUN_CONFIG",m="vtrn-vto-session",L=18e5,E=1e4,g="en-US",f="Vitraun",c="vitraun",R="https://",G="app.",V="."+c+".com",k="/v1/public/virtual-tryon-embed-init",H="Content-Type",F="X-Origin",x="X-Tryon-Session-Id",W="X-Merchant-Id",B="X-Widget-Id",K="application/json",Y="00000000-0000-0000-0000-000000000000",q=["addToCart","removeFromCart","redirectToCart","analysisFinished"],T="vitraun-vto",Q="["+T+"]",O=c+"-loading",A=c+"-error",z=f+" VTO",X="Loading "+f+"...",J="Failed to load "+f+".",j="Timed out while initializing the "+f+" session.",i={MERCHANT_ID:"merchant-id",WIDGET_ID:"widget-id",ENV:"env",API_PORT:"api-port",APP_PORT:"app-port",LANG:"lang",ISOLATED_SKU:"isolated-sku",APPLY_SKUS:"apply-skus",FLOW:"flow",BASKET_OPENS_IN:"basket-opens-in",CHECKOUT_OPENS_IN:"checkout-opens-in",USE_SIMPLE_PAGE:"use-simple-page",SHOW_DETAILS:"show-details",SHOW_PRODUCT_PRICE:"show-product-price",PRICE_FROM:"price-from",PRICE_TO:"price-to",CURRENCY_SYMBOL:"currency-symbol",IS_SIMULATION_MODE:"is-simulation-mode",SIMULATION_INLINE_CONFIG:"simulation-inline-config",CONTAINER_MIN_HEIGHT:"container-min-height",APP_ID:"app-id",PLATFORM:"platform",BUNDLE_ID:"bundle-id",PACKAGE_NAME:"package-name",APP_VERSION:"app-version",ATTESTATION_TOKEN:"attestation-token",DEBUG:"debug",INIT_TIMEOUT_MS:"init-timeout-ms"},Z=[i.MERCHANT_ID,i.WIDGET_ID,i.ENV,i.API_PORT,i.APP_PORT,i.LANG,i.ISOLATED_SKU,i.APPLY_SKUS,i.FLOW,i.BASKET_OPENS_IN,i.CHECKOUT_OPENS_IN,i.USE_SIMPLE_PAGE,i.SHOW_DETAILS,i.SHOW_PRODUCT_PRICE,i.PRICE_FROM,i.PRICE_TO,i.CURRENCY_SYMBOL,i.IS_SIMULATION_MODE,i.SIMULATION_INLINE_CONFIG,i.CONTAINER_MIN_HEIGHT,i.APP_ID,i.PLATFORM,i.BUNDLE_ID,i.PACKAGE_NAME,i.APP_VERSION,i.ATTESTATION_TOKEN,i.DEBUG,i.INIT_TIMEOUT_MS],u={ENV_REQUIRED:"The env attribute is required.",ENV_INVALID:"The env attribute contains an invalid value.",MERCHANT_ID_REQUIRED:"The merchant-id attribute is required.",WIDGET_ID_REQUIRED:"The widget-id attribute is required.",INIT_INVALID_RESPONSE:"Invalid init response.",INIT_SESSION_TOKEN_MISSING:"The init API did not return sessionToken.",INIT_VTO_URL_MISSING:"The server did not return a virtual try-on URL (vtoUrl). Please contact the store.",INIT_VTO_URL_INVALID:"The virtual try-on URL returned by the server is invalid. Please contact the store."},$="The operation timed out.",tt={CONFIG_SKIPPED_NO_IFRAME_ORIGIN:"Config not sent: iframeOrigin is missing."},I={GENERIC_TRY_AGAIN_OR_STORE:"Could not start the virtual try-on. Please try again or contact the store.",GENERIC_TRY_AGAIN:"Could not start the virtual try-on. Please try again.",GENERIC_SERVER_OR_CLIENT_MISMATCH:"Could not start the virtual try-on. Please refresh the page or contact the store."},et="We couldn't connect to the virtual try-on service. If you are developing locally, make sure the API is running, then try again.",v={INVALID_PUBLIC_API_KEY:"We could not open the virtual try-on. If the problem persists, contact the store.",PUBLIC_API_KEY_REQUIRED:"The virtual try-on is not available right now. Please try again later.",TRYON_EMBED_SESSION_TOKEN_MISSING:"We could not verify this session. Please refresh the page or contact the store.",TRYON_EMBED_SESSION_TOKEN_INVALID:"This session is no longer valid. Please refresh the page or start again.",TRYON_EMBED_SESSION_JWT_SECRET_NOT_CONFIGURED:"The virtual try-on is temporarily unavailable. Please try again later.",INVALID_OR_MISSING_MERCHANT_ID:"This integration is missing valid store credentials. Please contact the store.",INVALID_OR_MISSING_WIDGET_ID:"This integration is missing valid widget credentials. Please contact the store.",EMBED_INIT_MERCHANT_MISMATCH:"The store information does not match this widget. Please contact the store.",WIDGET_KEY_OR_CHANNEL_NOT_FOUND:"This widget could not be found or is no longer active. Please contact the store.",EMBED_PARENT_ORIGIN_REQUIRED:"We could not verify where this page is embedded. Please contact the store.",EMBED_PARENT_ORIGIN_NOT_ALLOWED:"This page is not allowed to use the virtual try-on. Please contact the store.",UNIQUE_CONSTRAINT_VIOLATION:"This value conflicts with an existing record. Change it and try again.",FOREIGN_KEY_VIOLATION:"This action references data that does not exist or cannot be linked. Check related records.",VALUE_OUT_OF_RANGE:"One of the values is invalid or too large for the server. Adjust the data and try again.",RECORD_NOT_FOUND:"The record was not found. It may have been removed. Refresh the page and try again.",NULL_CONSTRAINT_VIOLATION:"A required field was empty. Fill in all required fields and try again.",MISSING_REQUIRED_VALUE:"Some required information is missing. Review the form and try again.",RELATION_CONSTRAINT_VIOLATION:"This change is not allowed because of how records are linked. Adjust relationships and try again.",TRANSACTION_CONFLICT:"The operation conflicted with another change. Please try again.",INVALID_DATABASE_INPUT:"The request could not be processed. Check the data format and try again.",UNEXPECTED_DATABASE_ERROR:"Something went wrong while saving. Try again or contact support if it continues."};function S(e){return":host { display:block; width:100%; min-height:"+e+"; box-sizing:border-box; }"}function rt(e,t){return S(e)+"."+t+" {min-height:"+e+";display:flex;align-items:center;justify-content:center;border:1px solid #ececec;background:#fafafa;color:#333;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}"}function it(e,t){return S(e)+"."+t+" {min-height:"+e+";display:flex;align-items:center;justify-content:center;border:1px solid #f1d5d5;background:#fff7f7;color:#7a1f1f;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}"}function a(e,t,r){var n=e.getAttribute(t);return n!=null&&n!==""?n:r}function h(e,t){if(e==null||e==="")return t;var r=String(e).toLowerCase();return r==="true"||r==="1"||r==="yes"}function y(e){if(e==null||e==="")return null;var t=parseFloat(String(e));return Number.isFinite(t)?t:null}function nt(e){return!e||typeof e!="string"?[]:e.split(",").map(function(t){return t.trim()}).filter(Boolean)}function st(e,t){var r=a(e,t,"");if(!r||typeof r!="string")return null;try{return JSON.parse(r)}catch{return null}}function P(e){try{return JSON.parse(e)}catch{return null}}function N(){return typeof window>"u"||!window.location||!window.location.origin?null:window.location.origin}function ot(){return typeof window>"u"||!window.location||!window.location.href?null:window.location.href}function at(e){if(!e||typeof e!="string")return null;try{return new URL(e).origin}catch{return null}}function lt(e){var t=String(e||"").trim().toLowerCase();if(!t)throw new Error(u.ENV_REQUIRED);if(!/^[a-z0-9-]+$/.test(t))throw new Error(u.ENV_INVALID);return t}function _t(e){return e?String(e).trim().toLowerCase():"web"}function C(e){if(e==null||e==="")return null;var t=parseInt(String(e),10);return!Number.isInteger(t)||t<=0||t>65535?null:t}function ut(e,t){if(e==null||e==="")return"";var r=parseInt(String(e),10);return!Number.isInteger(r)||r<=0||r>65535||t==="https://"&&r===443||t==="http://"&&r===80?"":":"+r}function w(e){return!e||typeof e!="object"?!1:!!Array.isArray(e.message)}function U(e){if(!e||typeof e!="string")return!1;var t=e.toLowerCase();return t.indexOf("should not exist")!==-1||t.indexOf("should not be empty")!==-1||t.indexOf("forbidnonwhitelisted")!==-1||t.indexOf("whitelist")!==-1&&t.indexOf("property")!==-1||t.indexOf("property")!==-1&&t.indexOf("should not")!==-1}function D(e){if(!e||typeof e!="string")return!1;var t=e.trim();if(t.charAt(0)!=="{"||t.indexOf('"message"')===-1||t.indexOf('"statusCode"')===-1)return!1;var r=P(t);return w(r)}function It(e,t){if(w(e))return I.GENERIC_SERVER_OR_CLIENT_MISMATCH;var r=e&&typeof e.errorCode=="string"?e.errorCode:null;if(r&&Object.prototype.hasOwnProperty.call(v,r))return v[r];var n=e&&typeof e.message=="string"?e.message.trim():"";if(n)return U(n)?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:n;if(r)return I.GENERIC_TRY_AGAIN_OR_STORE;if(t&&String(t).length>0&&String(t).length<600){var s=String(t).trim();return D(s)?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:s.charAt(0)==="{"&&s.indexOf("errorCode")!==-1?I.GENERIC_TRY_AGAIN:s.charAt(0)==="{"?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:s}return I.GENERIC_TRY_AGAIN}function dt(e){if(!e||typeof e.message!="string")return!1;var t=e.name,r=e.message.toLowerCase();return t==="TypeError"&&(r.indexOf("failed to fetch")!==-1||r.indexOf("load failed")!==-1)||r.indexOf("networkerror when attempting to fetch")!==-1||t==="NetworkError"||r.indexOf("network request failed")!==-1}function b(e){if(dt(e))return et;if(e&&typeof e.message=="string"&&e.message.trim()){var t=e.message.trim();return U(t)||D(t)||t.charAt(0)==="{"&&t.indexOf('"message"')!==-1&&t.indexOf('"statusCode"')!==-1?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:t}return I.GENERIC_TRY_AGAIN}function ht(e,t){return R+G+e+V+ut(t,R)+k}function ft(e){var t=e.merchantId!=null?String(e.merchantId):"",r=e.widgetId!=null?String(e.widgetId):"",n=e.tryonSessionId!=null?String(e.tryonSessionId):"",s=e.origin!==void 0&&e.origin!==null&&e.origin!==""?String(e.origin):N()||"",l={};return l[F]=s,l[x]=n,l[W]=t,l[B]=r,e.contentType&&(l[H]=e.contentType),l}function Et(e,t){return{merchantId:e.merchantId,widgetId:e.widgetId,tryonSessionId:t,env:e.env,lang:e.lang,isSimulationMode:e.isSimulationMode===!0,appPort:e.appPort,app:{appId:e.appId,platform:e.platform,bundleId:e.bundleId,packageName:e.packageName,appVersion:e.appVersion,attestationToken:e.attestationToken},context:{origin:N(),pageUrl:ot(),userAgent:typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:null,referrer:typeof document<"u"&&document.referrer?document.referrer:null,timezone:typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:null}}}function ct(e,t,r,n){return!t||t<=0?e:new Promise(function(s,l){var _=!1,o=setTimeout(function(){if(!_){_=!0;try{n&&typeof n.abort=="function"&&n.abort()}catch{}l(new Error(r||$))}},t);e.then(function(d){_||(_=!0,clearTimeout(o),s(d))}).catch(function(d){_||(_=!0,clearTimeout(o),l(d))})})}function p(){if(typeof window>"u"||!window.crypto||!window.crypto.randomUUID)return Y;try{var e=sessionStorage.getItem(m);if(e){var t=JSON.parse(e);if(t&&typeof t.id=="string"&&typeof t.exp=="number"&&Date.now()<t.exp)return t.id}}catch{}var r=window.crypto.randomUUID(),n=Date.now()+L;try{sessionStorage.setItem(m,JSON.stringify({id:r,exp:n}))}catch{}return r}function Tt(e,t){var r=t.merchantId!=null?String(t.merchantId).trim():"",n=t.widgetId!=null?String(t.widgetId).trim():"";if(!r||!n)return e;var s;try{s=new URL(e)}catch{return e}s.searchParams.set("merchantId",r),s.searchParams.set("widgetId",n),s.searchParams.set("embed","1");var l=t.tryonSessionId!=null?String(t.tryonSessionId).trim():"";return l||(l=p()),l&&s.searchParams.set("tryonSessionId",l),s.toString()}class St extends HTMLElement{static get observedAttributes(){return Z.slice()}constructor(){super(),this.attachShadow({mode:"open"}),this._state={merchantId:"",widgetId:"",env:"",apiPort:null,appPort:null,lang:g,isolatedSku:null,applySkus:[],iframeOrigin:null,flow:"checkout",basketOpensIn:"event",checkoutOpensIn:"event",useSimplePage:!0,showDetails:!0,showProductPrice:!1,priceFrom:null,priceTo:null,currencySymbol:null,isSimulationMode:!1,simulationInlineConfig:null,appId:null,platform:"web",bundleId:null,packageName:null,appVersion:null,attestationToken:null,debug:!1,sessionToken:null,tryonSessionId:null,resolvedInitUrl:null,resolvedIframeUrl:null,initTimeoutMs:E},this._boundHandleMessage=this._handleMessage.bind(this),this._initPromise=null,this._initStateKey=null,this._activeInitRequestId=0,this._renderVersion=0,this._abortController=null}connectedCallback(){this._readAttributes(),this._render(),typeof window<"u"&&window.addEventListener("message",this._boundHandleMessage)}disconnectedCallback(){if(typeof window<"u"&&window.removeEventListener("message",this._boundHandleMessage),this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}}attributeChangedCallback(t,r,n){r!==n&&(this._readAttributes(),this._render())}_log(){if(!(!this._state.debug||typeof console>"u"||!console.log)){var t=Array.prototype.slice.call(arguments);t.unshift(Q),console.log.apply(console,t)}}_readAttributes(){var t=st(this,i.SIMULATION_INLINE_CONFIG),r=!1;t&&t.features&&typeof t.features.showProductPrice=="boolean"&&(r=t.features.showProductPrice);var n=!0;t&&t.features&&typeof t.features.useSimplePage=="boolean"&&(n=t.features.useSimplePage);var s="checkout";t&&t.features&&(t.features.flow==="catalog"||t.features.flow==="checkout")&&(s=t.features.flow);var l=!0;t&&t.features&&typeof t.features.showDetails=="boolean"&&(l=t.features.showDetails);var _="";try{_=lt(a(this,i.ENV,""))}catch{_=""}var o=parseInt(a(this,i.INIT_TIMEOUT_MS,String(E)),10);(!Number.isFinite(o)||o<0)&&(o=E),this._state={merchantId:a(this,i.MERCHANT_ID,""),widgetId:a(this,i.WIDGET_ID,""),env:_,apiPort:C(a(this,i.API_PORT,null)),appPort:C(a(this,i.APP_PORT,null)),lang:a(this,i.LANG,g),isolatedSku:a(this,i.ISOLATED_SKU,null)||null,applySkus:nt(a(this,i.APPLY_SKUS,"")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:a(this,i.FLOW,s),basketOpensIn:a(this,i.BASKET_OPENS_IN,"event"),checkoutOpensIn:a(this,i.CHECKOUT_OPENS_IN,"event"),useSimplePage:h(a(this,i.USE_SIMPLE_PAGE,""),n),showDetails:h(a(this,i.SHOW_DETAILS,""),l),showProductPrice:h(a(this,i.SHOW_PRODUCT_PRICE,""),r),priceFrom:y(a(this,i.PRICE_FROM,null)),priceTo:y(a(this,i.PRICE_TO,null)),currencySymbol:a(this,i.CURRENCY_SYMBOL,null)||null,isSimulationMode:h(a(this,i.IS_SIMULATION_MODE,"false"),!1),simulationInlineConfig:t,appId:a(this,i.APP_ID,null)||null,platform:_t(a(this,i.PLATFORM,null)),bundleId:a(this,i.BUNDLE_ID,null)||null,packageName:a(this,i.PACKAGE_NAME,null)||null,appVersion:a(this,i.APP_VERSION,null)||null,attestationToken:a(this,i.ATTESTATION_TOKEN,null)||null,debug:h(a(this,i.DEBUG,"false"),!1),sessionToken:this._state&&this._state.sessionToken?this._state.sessionToken:null,tryonSessionId:this._state&&this._state.tryonSessionId?this._state.tryonSessionId:null,resolvedInitUrl:this._state&&this._state.resolvedInitUrl?this._state.resolvedInitUrl:null,resolvedIframeUrl:this._state&&this._state.resolvedIframeUrl?this._state.resolvedIframeUrl:null,initTimeoutMs:o}}_emit(t,r){this.dispatchEvent(new CustomEvent(t,{detail:r??null,bubbles:!0,composed:!0}))}_setStatus(t,r){this.setAttribute("data-status",t),this._emit("statusChange",{status:t,detail:r||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(t){var r=t.data;if(!(!r||typeof r!="object")){var n=this._getIframeElement();if(!(!n||!n.contentWindow)&&t.source===n.contentWindow&&!(!this._state.iframeOrigin||t.origin!==this._state.iframeOrigin)){var s=r.type,l=r.detail;if(s==="VTO_USAGE"){this._emit("vtoUsage",l);return}q.indexOf(s)!==-1&&this._emit(s,l)}}}_getInitStateKey(){return JSON.stringify({merchantId:this._state.merchantId,widgetId:this._state.widgetId,env:this._state.env,apiPort:this._state.apiPort,appPort:this._state.appPort,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,simulationInlineConfig:this._state.simulationInlineConfig,appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken})}_buildEmbedInitUrl(){if(!this._state.env)throw new Error(u.ENV_REQUIRED);return ht(this._state.env,this._state.apiPort)}_buildInitPayload(){var t=p();return{tryonSessionId:t,initRequestBody:Et(this._state,t)}}_normalizeInitResponse(t,r,n){if(!t||typeof t!="object")throw new Error(u.INIT_INVALID_RESPONSE);var s=typeof t.sessionToken=="string"&&t.sessionToken?t.sessionToken:null,l=typeof t.tryonSessionId=="string"&&t.tryonSessionId?t.tryonSessionId:n;if(!s)throw new Error(u.INIT_SESSION_TOKEN_MISSING);var _=typeof t.vtoUrl=="string"&&t.vtoUrl.trim()?t.vtoUrl.trim():null;if(!_&&typeof t.iframeUrl=="string"&&t.iframeUrl.trim()&&(_=t.iframeUrl.trim()),!_)throw new Error(u.INIT_VTO_URL_MISSING);var o=at(_);if(!o)throw new Error(u.INIT_VTO_URL_INVALID);return{sessionToken:s,tryonSessionId:l,initUrl:r,iframeUrl:_,iframeOrigin:o}}_initializeSessionIfNeeded(){var t=this;if(!this._state.merchantId)return Promise.reject(new Error(u.MERCHANT_ID_REQUIRED));if(!this._state.widgetId)return Promise.reject(new Error(u.WIDGET_ID_REQUIRED));if(!this._state.env)return Promise.reject(new Error(u.ENV_REQUIRED));var r=this._getInitStateKey();if(this._initPromise&&this._initStateKey===r)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}this._initStateKey=r,this._activeInitRequestId+=1;var n=this._activeInitRequestId;this._setStatus("loading");var s;try{s=this._buildEmbedInitUrl()}catch(o){return Promise.reject(o)}var l=this._buildInitPayload();this._state.tryonSessionId=l.tryonSessionId,this._abortController=typeof AbortController<"u"?new AbortController:null;var _=fetch(s,{method:"POST",headers:ft({merchantId:this._state.merchantId,widgetId:this._state.widgetId,tryonSessionId:l.tryonSessionId,contentType:K}),body:JSON.stringify(l.initRequestBody),signal:this._abortController?this._abortController.signal:void 0}).then(function(o){return o.ok?o.json():o.text().then(function(d){var Nt=P(d),pt=It(Nt,d);throw new Error(pt)})}).then(function(o){return t._normalizeInitResponse(o,s,l.tryonSessionId)});return this._initPromise=ct(_,this._state.initTimeoutMs,j,this._abortController).then(function(o){return n!==t._activeInitRequestId||(t._state.sessionToken=o.sessionToken,t._state.tryonSessionId=o.tryonSessionId,t._state.resolvedInitUrl=o.initUrl,t._state.resolvedIframeUrl=o.iframeUrl,t._state.iframeOrigin=o.iframeOrigin,t._setStatus("ready")),o}).catch(function(o){if(n!==t._activeInitRequestId)throw o;var d=b(o);throw t._state.sessionToken=null,t._state.resolvedInitUrl=null,t._state.resolvedIframeUrl=null,t._state.iframeOrigin=null,t._setStatus("error",{message:d}),new Error(d)}).finally(function(){n===t._activeInitRequestId&&(t._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var t=this._getIframeElement();if(!(!t||!t.contentWindow)){var r=this._state.iframeOrigin;if(!r){this._log(tt.CONFIG_SKIPPED_NO_IFRAME_ORIGIN);return}var n={merchantId:this._state.merchantId,widgetId:this._state.widgetId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||p(),lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},embedParentOrigin:N()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(n.inlineVirtualTryonConfig=this._state.simulationInlineConfig),t.contentWindow.postMessage({type:M,payload:n},r)}}_renderLoading(){if(this.shadowRoot){var t=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var r=document.createElement("style");r.textContent=rt(t,O);var n=document.createElement("div");n.className=O,n.textContent=X,this.shadowRoot.appendChild(r),this.shadowRoot.appendChild(n)}}_renderError(t){if(this.shadowRoot){var r=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=it(r,A);var s=document.createElement("div");s.className=A,s.textContent=t||J,this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(s)}}_renderIframe(t,r){if(this.shadowRoot&&!(!t||typeof t!="string"||!t.trim())){var n=this,s=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var l=document.createElement("style");l.textContent=S(s);var _=document.createElement("iframe");_.src=Tt(t.trim(),this._state),_.title=z,_.style.cssText="width:100%;height:100%;border:0;min-height:"+s,_.setAttribute("allow","camera"),_.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),_.onload=function(){r===n._renderVersion&&[0,50,150,400,1e3].forEach(function(o){setTimeout(function(){r===n._renderVersion&&n._sendConfigToIframe()},o)})},this.shadowRoot.appendChild(l),this.shadowRoot.appendChild(_)}}_render(){if(this.shadowRoot){this._renderVersion+=1;var t=this._renderVersion;if(!this._state.merchantId){this._setStatus("error",{message:u.MERCHANT_ID_REQUIRED}),this._renderError(u.MERCHANT_ID_REQUIRED);return}if(!this._state.widgetId){this._setStatus("error",{message:u.WIDGET_ID_REQUIRED}),this._renderError(u.WIDGET_ID_REQUIRED);return}if(!this._state.env){this._setStatus("error",{message:u.ENV_REQUIRED}),this._renderError(u.ENV_REQUIRED);return}this._renderLoading(),this._initializeSessionIfNeeded().then(function(r){t===this._renderVersion&&this._renderIframe(r.iframeUrl,t)}.bind(this)).catch(function(r){if(t===this._renderVersion){var n=b(r instanceof Error?r:new Error(String(r)));this._renderError(n)}}.bind(this))}}open(){return this.style.display="",Promise.resolve()}close(){return this.style.display="none",Promise.resolve()}}typeof customElements<"u"&&!customElements.get(T)&&customElements.define(T,St)})();
|
|
1
|
+
(function(){"use strict";var F="VITRAUN_CONFIG",A="vtrn-vto-session",B=18e5,T=1e4,C="en-US",p="Vitraun",m="vitraun",y="https://",W="app.",K="app",b="."+m+".com",Y="/v1/public/virtual-tryon-embed-init",q="Content-Type",z="X-Origin",X="X-Tryon-Session-Id",Q="X-Merchant-Id",J="X-Widget-Id",j="application/json",Z="00000000-0000-0000-0000-000000000000",w=["addToCart","removeFromCart","redirectToCart","analysisFinished"],$=w.concat(["statusChange","vtoUsage"]),ee=150,g="vitraun-vto",te="["+g+"]",P=m+"-loading",L=m+"-error",ne=p+" VTO",re="Loading "+p+"...",ie="Failed to load "+p+".",oe="Timed out while initializing the "+p+" session.",i={MERCHANT_ID:"merchant-id",WIDGET_ID:"widget-id",ENV:"env",API_PORT:"api-port",APP_PORT:"app-port",LANG:"lang",ISOLATED_SKU:"isolated-sku",APPLY_SKUS:"apply-skus",FLOW:"flow",BASKET_OPENS_IN:"basket-opens-in",CHECKOUT_OPENS_IN:"checkout-opens-in",USE_SIMPLE_PAGE:"use-simple-page",SHOW_DETAILS:"show-details",SHOW_PRODUCT_PRICE:"show-product-price",PRICE_FROM:"price-from",PRICE_TO:"price-to",CURRENCY_SYMBOL:"currency-symbol",IS_SIMULATION_MODE:"is-simulation-mode",SIMULATION_INLINE_CONFIG:"simulation-inline-config",CONTAINER_MIN_HEIGHT:"container-min-height",APP_ID:"app-id",PLATFORM:"platform",BUNDLE_ID:"bundle-id",PACKAGE_NAME:"package-name",APP_VERSION:"app-version",ATTESTATION_TOKEN:"attestation-token",DEBUG:"debug",CONSOLE:"console",INIT_TIMEOUT_MS:"init-timeout-ms"},se=[i.MERCHANT_ID,i.WIDGET_ID,i.ENV,i.API_PORT,i.APP_PORT,i.LANG,i.ISOLATED_SKU,i.APPLY_SKUS,i.FLOW,i.BASKET_OPENS_IN,i.CHECKOUT_OPENS_IN,i.USE_SIMPLE_PAGE,i.SHOW_DETAILS,i.SHOW_PRODUCT_PRICE,i.PRICE_FROM,i.PRICE_TO,i.CURRENCY_SYMBOL,i.IS_SIMULATION_MODE,i.SIMULATION_INLINE_CONFIG,i.CONTAINER_MIN_HEIGHT,i.APP_ID,i.PLATFORM,i.BUNDLE_ID,i.PACKAGE_NAME,i.APP_VERSION,i.ATTESTATION_TOKEN,i.DEBUG,i.CONSOLE,i.INIT_TIMEOUT_MS],_={ENV_INVALID:"The env attribute contains an invalid value.",MERCHANT_ID_REQUIRED:"The merchant-id attribute is required.",WIDGET_ID_REQUIRED:"The widget-id attribute is required.",INIT_INVALID_RESPONSE:"Invalid init response.",INIT_SESSION_TOKEN_MISSING:"The init API did not return sessionToken.",INIT_VTO_URL_MISSING:"The server did not return a virtual try-on URL (vtoUrl). Please contact the store.",INIT_VTO_URL_INVALID:"The virtual try-on URL returned by the server is invalid. Please contact the store."},ae="The operation timed out.",le={CONFIG_SKIPPED_NO_IFRAME_ORIGIN:"Config not sent: iframeOrigin is missing."},h={GENERIC_TRY_AGAIN_OR_STORE:"Could not start the virtual try-on. Please try again or contact the store.",GENERIC_TRY_AGAIN:"Could not start the virtual try-on. Please try again.",GENERIC_SERVER_OR_CLIENT_MISMATCH:"Could not start the virtual try-on. Please refresh the page or contact the store."},ue="We couldn't connect to the virtual try-on service. If you are developing locally, make sure the API is running, then try again.",M={INVALID_PUBLIC_API_KEY:"We could not open the virtual try-on. If the problem persists, contact the store.",PUBLIC_API_KEY_REQUIRED:"The virtual try-on is not available right now. Please try again later.",TRYON_EMBED_SESSION_TOKEN_MISSING:"We could not verify this session. Please refresh the page or contact the store.",TRYON_EMBED_SESSION_TOKEN_INVALID:"This session is no longer valid. Please refresh the page or start again.",TRYON_EMBED_SESSION_TOKEN_EXPIRED:"This embed session has expired. Refresh the page or start again.",TRYON_EMBED_SESSION_JWT_SECRET_NOT_CONFIGURED:"The virtual try-on is temporarily unavailable. Please try again later.",INVALID_OR_MISSING_MERCHANT_ID:"This integration is missing valid store credentials. Please contact the store.",INVALID_OR_MISSING_WIDGET_ID:"This integration is missing valid widget credentials. Please contact the store.",EMBED_INIT_MERCHANT_MISMATCH:"The store information does not match this widget. Please contact the store.",WIDGET_KEY_OR_CHANNEL_NOT_FOUND:"This widget could not be found or is no longer active. Please contact the store.",EMBED_PARENT_ORIGIN_REQUIRED:"We could not verify where this page is embedded. Please contact the store.",EMBED_PARENT_ORIGIN_NOT_ALLOWED:"This page is not allowed to use the virtual try-on. Please contact the store.",UNIQUE_CONSTRAINT_VIOLATION:"This value conflicts with an existing record. Change it and try again.",FOREIGN_KEY_VIOLATION:"This action references data that does not exist or cannot be linked. Check related records.",VALUE_OUT_OF_RANGE:"One of the values is invalid or too large for the server. Adjust the data and try again.",RECORD_NOT_FOUND:"The record was not found. It may have been removed. Refresh the page and try again.",NULL_CONSTRAINT_VIOLATION:"A required field was empty. Fill in all required fields and try again.",MISSING_REQUIRED_VALUE:"Some required information is missing. Review the form and try again.",RELATION_CONSTRAINT_VIOLATION:"This change is not allowed because of how records are linked. Adjust relationships and try again.",TRANSACTION_CONFLICT:"The operation conflicted with another change. Please try again.",INVALID_DATABASE_INPUT:"The request could not be processed. Check the data format and try again.",UNEXPECTED_DATABASE_ERROR:"Something went wrong while saving. Try again or contact support if it continues."};function S(t){return":host { display:block; width:100%; min-height:"+t+"; box-sizing:border-box; }.vitraun-host { position:relative; width:100%; min-height:"+t+"; box-sizing:border-box; }.vitraun-host > iframe { display:block; width:100%; border:0; min-height:"+t+"; }"}function de(){return'.vitraun-console-fab {position:absolute; bottom:12px; right:12px; z-index:5;padding:8px 12px; border:0; border-radius:8px;background:#0f172a; color:#f8fafc; font:600 12px/1.2 system-ui, sans-serif;cursor:pointer; box-shadow:0 4px 12px rgba(15,23,42,0.35);}.vitraun-console-fab:hover { background:#1e293b; }.vitraun-console-backdrop {position:absolute; inset:0; z-index:6; background:rgba(15,23,42,0.45);display:none; align-items:center; justify-content:center; padding:16px; box-sizing:border-box;}.vitraun-console-backdrop[data-open="true"] { display:flex; }.vitraun-console-modal {width:min(100%, 520px); max-height:min(70vh, 420px); display:flex; flex-direction:column;background:#fff; border-radius:12px; box-shadow:0 16px 40px rgba(15,23,42,0.25); overflow:hidden;}.vitraun-console-header {display:flex; align-items:center; justify-content:space-between; gap:8px;padding:12px 14px; border-bottom:1px solid #e2e8f0; background:#f8fafc;}.vitraun-console-title { font:600 14px/1.2 system-ui, sans-serif; color:#0f172a; margin:0; }.vitraun-console-actions { display:flex; gap:8px; }.vitraun-console-actions button {padding:6px 10px; border:1px solid #cbd5e1; border-radius:6px; background:#fff;font:500 12px/1 system-ui, sans-serif; color:#334155; cursor:pointer;}.vitraun-console-body {margin:0; padding:12px 14px; overflow:auto; flex:1; min-height:120px;font:12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color:#0f172a;white-space:pre-wrap; word-break:break-word; background:#fff;}.vitraun-console-empty { color:#64748b; font-style:italic; }'}function _e(t,e){return S(t)+"."+e+" {min-height:"+t+";display:flex;align-items:center;justify-content:center;border:1px solid #ececec;background:#fafafa;color:#333;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}"}function he(t,e){return S(t)+"."+e+" {min-height:"+t+";display:flex;align-items:center;justify-content:center;border:1px solid #f1d5d5;background:#fff7f7;color:#7a1f1f;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}"}function u(t,e,n){var r=t.getAttribute(e);return r!=null&&r!==""?r:n}function I(t,e){if(t==null||t==="")return e;var n=String(t).toLowerCase();return n==="true"||n==="1"||n==="yes"}function U(t){if(t==null||t==="")return null;var e=parseFloat(String(t));return Number.isFinite(e)?e:null}function ce(t){return!t||typeof t!="string"?[]:t.split(",").map(function(e){return e.trim()}).filter(Boolean)}function Ie(t,e){var n=u(t,e,"");if(!n||typeof n!="string")return null;try{return JSON.parse(n)}catch{return null}}function D(t){try{return JSON.parse(t)}catch{return null}}function N(){return typeof window>"u"||!window.location||!window.location.origin?null:window.location.origin}function fe(){return typeof window>"u"||!window.location||!window.location.href?null:window.location.href}function pe(t){if(!t||typeof t!="string")return null;try{return new URL(t).origin}catch{return null}}function Ee(t){var e=String(t||"").trim().toLowerCase();if(!e)return"";if(!/^[a-z0-9-]+$/.test(e))throw new Error(_.ENV_INVALID);return e}function Te(t){return t?String(t).trim().toLowerCase():"web"}function k(t){if(t==null||t==="")return null;var e=parseInt(String(t),10);return!Number.isInteger(e)||e<=0||e>65535?null:e}function me(t,e){if(t==null||t==="")return"";var n=parseInt(String(t),10);return!Number.isInteger(n)||n<=0||n>65535||e==="https://"&&n===443||e==="http://"&&n===80?"":":"+n}function x(t){return!t||typeof t!="object"?!1:!!Array.isArray(t.message)}function G(t){if(!t||typeof t!="string")return!1;var e=t.toLowerCase();return e.indexOf("should not exist")!==-1||e.indexOf("should not be empty")!==-1||e.indexOf("forbidnonwhitelisted")!==-1||e.indexOf("whitelist")!==-1&&e.indexOf("property")!==-1||e.indexOf("property")!==-1&&e.indexOf("should not")!==-1}function V(t){if(!t||typeof t!="string")return!1;var e=t.trim();if(e.charAt(0)!=="{"||e.indexOf('"message"')===-1||e.indexOf('"statusCode"')===-1)return!1;var n=D(e);return x(n)}function ge(t,e){if(x(t))return h.GENERIC_SERVER_OR_CLIENT_MISMATCH;var n=t&&typeof t.errorCode=="string"?t.errorCode:null;if(n&&Object.prototype.hasOwnProperty.call(M,n))return M[n];var r=t&&typeof t.message=="string"?t.message.trim():"";if(r)return G(r)?h.GENERIC_SERVER_OR_CLIENT_MISMATCH:r;if(n)return h.GENERIC_TRY_AGAIN_OR_STORE;if(e&&String(e).length>0&&String(e).length<600){var o=String(e).trim();return V(o)?h.GENERIC_SERVER_OR_CLIENT_MISMATCH:o.charAt(0)==="{"&&o.indexOf("errorCode")!==-1?h.GENERIC_TRY_AGAIN:o.charAt(0)==="{"?h.GENERIC_SERVER_OR_CLIENT_MISMATCH:o}return h.GENERIC_TRY_AGAIN}function Se(t){if(!t||typeof t.message!="string")return!1;var e=t.name,n=t.message.toLowerCase();return e==="TypeError"&&(n.indexOf("failed to fetch")!==-1||n.indexOf("load failed")!==-1)||n.indexOf("networkerror when attempting to fetch")!==-1||e==="NetworkError"||n.indexOf("network request failed")!==-1}function H(t){if(Se(t))return ue;if(t&&typeof t.message=="string"&&t.message.trim()){var e=t.message.trim();return G(e)||V(e)||e.charAt(0)==="{"&&e.indexOf('"message"')!==-1&&e.indexOf('"statusCode"')!==-1?h.GENERIC_SERVER_OR_CLIENT_MISMATCH:e}return h.GENERIC_TRY_AGAIN}function Ne(t,e){var n=t&&String(t).trim()?W+String(t).trim().toLowerCase()+b:K+b;return y+n+me(e,y)+Y}function ve(t){var e=t.merchantId!=null?String(t.merchantId):"",n=t.widgetId!=null?String(t.widgetId):"",r=t.tryonSessionId!=null?String(t.tryonSessionId):"",o=t.origin!==void 0&&t.origin!==null&&t.origin!==""?String(t.origin):N()||"",a={};return a[z]=o,a[X]=r,a[Q]=e,a[J]=n,t.contentType&&(a[q]=t.contentType),a}function Oe(t,e){return{merchantId:t.merchantId,widgetId:t.widgetId,tryonSessionId:e,env:t.env,lang:t.lang,isSimulationMode:t.isSimulationMode===!0,appPort:t.appPort,app:{appId:t.appId,platform:t.platform,bundleId:t.bundleId,packageName:t.packageName,appVersion:t.appVersion,attestationToken:t.attestationToken},context:{origin:N(),pageUrl:fe(),userAgent:typeof navigator<"u"&&navigator.userAgent?navigator.userAgent:null,referrer:typeof document<"u"&&document.referrer?document.referrer:null,timezone:typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:null}}}function Re(t,e,n,r){return!e||e<=0?t:new Promise(function(o,a){var l=!1,s=setTimeout(function(){if(!l){l=!0;try{r&&typeof r.abort=="function"&&r.abort()}catch{}a(new Error(n||ae))}},e);t.then(function(d){l||(l=!0,clearTimeout(s),o(d))}).catch(function(d){l||(l=!0,clearTimeout(s),a(d))})})}function v(){if(typeof window>"u"||!window.crypto||!window.crypto.randomUUID)return Z;try{var t=sessionStorage.getItem(A);if(t){var e=JSON.parse(t);if(e&&typeof e.id=="string"&&typeof e.exp=="number"&&Date.now()<e.exp)return e.id}}catch{}var n=window.crypto.randomUUID(),r=Date.now()+B;try{sessionStorage.setItem(A,JSON.stringify({id:n,exp:r}))}catch{}return n}function Ae(t,e){var n=e.merchantId!=null?String(e.merchantId).trim():"",r=e.widgetId!=null?String(e.widgetId).trim():"";if(!n||!r)return t;var o;try{o=new URL(t)}catch{return t}o.searchParams.set("merchantId",n),o.searchParams.set("widgetId",r),o.searchParams.set("embed","1");var a=e.tryonSessionId!=null?String(e.tryonSessionId).trim():"";a||(a=v()),a&&o.searchParams.set("tryonSessionId",a);var l=e.sessionToken!=null?String(e.sessionToken).trim():"";return l&&o.searchParams.set("embedSessionToken",l),o.toString()}class Ce extends HTMLElement{static get observedAttributes(){return se.slice()}constructor(){super(),this.attachShadow({mode:"open"}),this._state={merchantId:"",widgetId:"",env:"",apiPort:null,appPort:null,lang:C,isolatedSku:null,applySkus:[],iframeOrigin:null,flow:"checkout",basketOpensIn:"event",checkoutOpensIn:"event",useSimplePage:!0,showDetails:!0,showProductPrice:!1,priceFrom:null,priceTo:null,currencySymbol:null,isSimulationMode:!1,simulationInlineConfig:null,appId:null,platform:"web",bundleId:null,packageName:null,appVersion:null,attestationToken:null,debug:!1,console:!1,sessionToken:null,tryonSessionId:null,resolvedInitUrl:null,resolvedIframeUrl:null,initTimeoutMs:T},this._consoleLog=[],this._consoleModalOpen=!1,this._consoleCaptureTeardown=null,this._boundHandleMessage=this._handleMessage.bind(this),this._initPromise=null,this._initStateKey=null,this._activeInitRequestId=0,this._renderVersion=0,this._abortController=null}connectedCallback(){this._readAttributes(),this._setupConsoleCapture(),this._render(),typeof window<"u"&&window.addEventListener("message",this._boundHandleMessage)}disconnectedCallback(){if(typeof window<"u"&&window.removeEventListener("message",this._boundHandleMessage),this._teardownConsoleCapture(),this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}}attributeChangedCallback(e,n,r){n!==r&&(this._readAttributes(),this._setupConsoleCapture(),this._render())}_log(){if(!(!this._state.debug||typeof console>"u"||!console.log)){var e=Array.prototype.slice.call(arguments);e.unshift(te),console.log.apply(console,e)}}_readAttributes(){var e=Ie(this,i.SIMULATION_INLINE_CONFIG),n=!1;e&&e.features&&typeof e.features.showProductPrice=="boolean"&&(n=e.features.showProductPrice);var r=!0;e&&e.features&&typeof e.features.useSimplePage=="boolean"&&(r=e.features.useSimplePage);var o="checkout";e&&e.features&&(e.features.flow==="catalog"||e.features.flow==="checkout")&&(o=e.features.flow);var a=!0;e&&e.features&&typeof e.features.showDetails=="boolean"&&(a=e.features.showDetails);var l="";try{l=Ee(u(this,i.ENV,""))}catch{l=""}var s=parseInt(u(this,i.INIT_TIMEOUT_MS,String(T)),10);(!Number.isFinite(s)||s<0)&&(s=T),this._state={merchantId:u(this,i.MERCHANT_ID,""),widgetId:u(this,i.WIDGET_ID,""),env:l,apiPort:k(u(this,i.API_PORT,null)),appPort:k(u(this,i.APP_PORT,null)),lang:u(this,i.LANG,C),isolatedSku:u(this,i.ISOLATED_SKU,null)||null,applySkus:ce(u(this,i.APPLY_SKUS,"")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:u(this,i.FLOW,o),basketOpensIn:u(this,i.BASKET_OPENS_IN,"event"),checkoutOpensIn:u(this,i.CHECKOUT_OPENS_IN,"event"),useSimplePage:I(u(this,i.USE_SIMPLE_PAGE,""),r),showDetails:I(u(this,i.SHOW_DETAILS,""),a),showProductPrice:I(u(this,i.SHOW_PRODUCT_PRICE,""),n),priceFrom:U(u(this,i.PRICE_FROM,null)),priceTo:U(u(this,i.PRICE_TO,null)),currencySymbol:u(this,i.CURRENCY_SYMBOL,null)||null,isSimulationMode:I(u(this,i.IS_SIMULATION_MODE,"false"),!1),simulationInlineConfig:e,appId:u(this,i.APP_ID,null)||null,platform:Te(u(this,i.PLATFORM,null)),bundleId:u(this,i.BUNDLE_ID,null)||null,packageName:u(this,i.PACKAGE_NAME,null)||null,appVersion:u(this,i.APP_VERSION,null)||null,attestationToken:u(this,i.ATTESTATION_TOKEN,null)||null,debug:I(u(this,i.DEBUG,"false"),!1),console:I(u(this,i.CONSOLE,"false"),!1),sessionToken:this._state&&this._state.sessionToken?this._state.sessionToken:null,tryonSessionId:this._state&&this._state.tryonSessionId?this._state.tryonSessionId:null,resolvedInitUrl:this._state&&this._state.resolvedInitUrl?this._state.resolvedInitUrl:null,resolvedIframeUrl:this._state&&this._state.resolvedIframeUrl?this._state.resolvedIframeUrl:null,initTimeoutMs:s}}_emit(e,n){this.dispatchEvent(new CustomEvent(e,{detail:n??null,bubbles:!0,composed:!0}))}_teardownConsoleCapture(){typeof this._consoleCaptureTeardown=="function"&&(this._consoleCaptureTeardown(),this._consoleCaptureTeardown=null)}_setupConsoleCapture(){if(this._teardownConsoleCapture(),!!this._state.console){var e=this,n=[];$.forEach(function(r){var o=function(a){e._appendConsoleLog(r,a.detail)};e.addEventListener(r,o),n.push({eventType:r,handler:o})}),this._consoleCaptureTeardown=function(){n.forEach(function(r){e.removeEventListener(r.eventType,r.handler)})}}}_appendConsoleLog(e,n){this._state.console&&(Array.isArray(this._consoleLog)||(this._consoleLog=[]),this._consoleLog.push({type:e,timestamp:new Date().toISOString(),detail:n??null}),this._consoleLog.length>ee&&this._consoleLog.shift(),this._refreshConsoleChrome())}_formatConsoleLogText(){return!this._consoleLog||this._consoleLog.length===0?"":this._consoleLog.map(function(e){var n="";try{n=JSON.stringify(e.detail,null,2)}catch{n=String(e.detail)}return"["+e.timestamp+"] "+e.type+`
|
|
2
|
+
`+n}).join(`
|
|
3
|
+
|
|
4
|
+
`)}_refreshConsoleChrome(){if(!(!this.shadowRoot||!this._state.console)){var e=this.shadowRoot.querySelector(".vitraun-console-fab");if(e){var n=this._consoleLog?this._consoleLog.length:0;e.textContent=n>0?"Events ("+n+")":"Events"}var r=this.shadowRoot.querySelector(".vitraun-console-body");if(r&&this._consoleModalOpen){var o=this._formatConsoleLogText();o?(r.textContent=o,r.classList.remove("vitraun-console-empty")):(r.textContent="No events yet. Interact with the try-on to see activity.",r.classList.add("vitraun-console-empty")),r.scrollTop=r.scrollHeight}}}_setConsoleModalOpen(e){if(this._consoleModalOpen=e===!0,!!this.shadowRoot){var n=this.shadowRoot.querySelector(".vitraun-console-backdrop");n&&n.setAttribute("data-open",this._consoleModalOpen?"true":"false"),this._refreshConsoleChrome()}}_mountConsoleChrome(e){if(!(!e||!this._state.console)){var n=e.querySelector(".vitraun-console-fab");if(n){this._refreshConsoleChrome();return}var r=this,o=document.createElement("button");o.type="button",o.className="vitraun-console-fab",o.setAttribute("aria-label","Open Try-On events console"),o.textContent="Events",o.addEventListener("click",function(){r._setConsoleModalOpen(!0)});var a=document.createElement("div");a.className="vitraun-console-backdrop",a.setAttribute("data-open","false"),a.setAttribute("role","presentation"),a.addEventListener("click",function(R){R.target===a&&r._setConsoleModalOpen(!1)});var l=document.createElement("div");l.className="vitraun-console-modal",l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Try-On events console"),l.addEventListener("click",function(R){R.stopPropagation()});var s=document.createElement("div");s.className="vitraun-console-header";var d=document.createElement("h2");d.className="vitraun-console-title",d.textContent="Try-On events";var c=document.createElement("div");c.className="vitraun-console-actions";var f=document.createElement("button");f.type="button",f.textContent="Clear",f.addEventListener("click",function(){r._consoleLog=[],r._refreshConsoleChrome()});var E=document.createElement("button");E.type="button",E.textContent="Close",E.addEventListener("click",function(){r._setConsoleModalOpen(!1)}),c.appendChild(f),c.appendChild(E),s.appendChild(d),s.appendChild(c);var O=document.createElement("pre");O.className="vitraun-console-body vitraun-console-empty",O.textContent="No events yet. Interact with the try-on to see activity.",l.appendChild(s),l.appendChild(O),a.appendChild(l),e.appendChild(o),e.appendChild(a),this._refreshConsoleChrome()}}_setStatus(e,n){this.setAttribute("data-status",e),this._emit("statusChange",{status:e,detail:n||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(e){var n=e.data;if(!(!n||typeof n!="object")){var r=this._getIframeElement();if(!(!r||!r.contentWindow)&&e.source===r.contentWindow&&!(!this._state.iframeOrigin||e.origin!==this._state.iframeOrigin)){var o=n.type,a=n.detail;if(o==="VTO_USAGE"){this._emit("vtoUsage",a);return}w.indexOf(o)!==-1&&this._emit(o,a)}}}_getInitStateKey(){return JSON.stringify({merchantId:this._state.merchantId,widgetId:this._state.widgetId,env:this._state.env,apiPort:this._state.apiPort,appPort:this._state.appPort,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,simulationInlineConfig:this._state.simulationInlineConfig,appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken})}_buildEmbedInitUrl(){return Ne(this._state.env,this._state.apiPort)}_buildInitPayload(){var e=v();return{tryonSessionId:e,initRequestBody:Oe(this._state,e)}}_normalizeInitResponse(e,n,r){if(!e||typeof e!="object")throw new Error(_.INIT_INVALID_RESPONSE);var o=typeof e.sessionToken=="string"&&e.sessionToken?e.sessionToken:null,a=typeof e.tryonSessionId=="string"&&e.tryonSessionId?e.tryonSessionId:r;if(!o)throw new Error(_.INIT_SESSION_TOKEN_MISSING);var l=typeof e.vtoUrl=="string"&&e.vtoUrl.trim()?e.vtoUrl.trim():null;if(!l&&typeof e.iframeUrl=="string"&&e.iframeUrl.trim()&&(l=e.iframeUrl.trim()),!l)throw new Error(_.INIT_VTO_URL_MISSING);var s=pe(l);if(!s)throw new Error(_.INIT_VTO_URL_INVALID);return{sessionToken:o,tryonSessionId:a,initUrl:n,iframeUrl:l,iframeOrigin:s}}_initializeSessionIfNeeded(){var e=this;if(!this._state.merchantId)return Promise.reject(new Error(_.MERCHANT_ID_REQUIRED));if(!this._state.widgetId)return Promise.reject(new Error(_.WIDGET_ID_REQUIRED));var n=this._getInitStateKey();if(this._initPromise&&this._initStateKey===n)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}this._initStateKey=n,this._activeInitRequestId+=1;var r=this._activeInitRequestId;this._setStatus("loading");var o;try{o=this._buildEmbedInitUrl()}catch(s){return Promise.reject(s)}var a=this._buildInitPayload();this._state.tryonSessionId=a.tryonSessionId,this._abortController=typeof AbortController<"u"?new AbortController:null;var l=fetch(o,{method:"POST",headers:ve({merchantId:this._state.merchantId,widgetId:this._state.widgetId,tryonSessionId:a.tryonSessionId,contentType:j}),body:JSON.stringify(a.initRequestBody),signal:this._abortController?this._abortController.signal:void 0}).then(function(s){return s.ok?s.json():s.text().then(function(d){var c=D(d),f=ge(c,d);throw new Error(f)})}).then(function(s){return e._normalizeInitResponse(s,o,a.tryonSessionId)});return this._initPromise=Re(l,this._state.initTimeoutMs,oe,this._abortController).then(function(s){return r!==e._activeInitRequestId||(e._state.sessionToken=s.sessionToken,e._state.tryonSessionId=s.tryonSessionId,e._state.resolvedInitUrl=s.initUrl,e._state.resolvedIframeUrl=s.iframeUrl,e._state.iframeOrigin=s.iframeOrigin,e._setStatus("ready")),s}).catch(function(s){if(r!==e._activeInitRequestId)throw s;var d=H(s);throw e._state.sessionToken=null,e._state.resolvedInitUrl=null,e._state.resolvedIframeUrl=null,e._state.iframeOrigin=null,e._setStatus("error",{message:d}),new Error(d)}).finally(function(){r===e._activeInitRequestId&&(e._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var e=this._getIframeElement();if(!(!e||!e.contentWindow)){var n=this._state.iframeOrigin;if(!n){this._log(le.CONFIG_SKIPPED_NO_IFRAME_ORIGIN);return}var r={merchantId:this._state.merchantId,widgetId:this._state.widgetId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||v(),lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},embedParentOrigin:N()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(r.inlineVirtualTryonConfig=this._state.simulationInlineConfig),e.contentWindow.postMessage({type:F,payload:r},n)}}_renderLoading(){if(this.shadowRoot){var e=u(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=_e(e,P);var r=document.createElement("div");r.className=P,r.textContent=re,this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(r)}}_renderError(e){if(this.shadowRoot){var n=u(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var r=document.createElement("style");r.textContent=he(n,L);var o=document.createElement("div");o.className=L,o.textContent=e||ie,this.shadowRoot.appendChild(r),this.shadowRoot.appendChild(o)}}_renderIframe(e,n){if(this.shadowRoot&&!(!e||typeof e!="string"||!e.trim())){var r=this,o=u(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="",this._consoleModalOpen=!1;var a=document.createElement("style"),l=S(o);this._state.console&&(l+=de()),a.textContent=l;var s=document.createElement("div");s.className="vitraun-host";var d=document.createElement("iframe");d.src=Ae(e.trim(),this._state),d.title=ne,d.setAttribute("allow","camera"),d.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),d.onload=function(){n===r._renderVersion&&[0,50,150,400,1e3].forEach(function(c){setTimeout(function(){n===r._renderVersion&&r._sendConfigToIframe()},c)})},s.appendChild(d),this._state.console&&this._mountConsoleChrome(s),this.shadowRoot.appendChild(a),this.shadowRoot.appendChild(s)}}_render(){if(this.shadowRoot){this._renderVersion+=1;var e=this._renderVersion;if(!this._state.merchantId){this._setStatus("error",{message:_.MERCHANT_ID_REQUIRED}),this._renderError(_.MERCHANT_ID_REQUIRED);return}if(!this._state.widgetId){this._setStatus("error",{message:_.WIDGET_ID_REQUIRED}),this._renderError(_.WIDGET_ID_REQUIRED);return}this._renderLoading(),this._initializeSessionIfNeeded().then(function(n){e===this._renderVersion&&this._renderIframe(n.iframeUrl,e)}.bind(this)).catch(function(n){if(e===this._renderVersion){var r=H(n instanceof Error?n:new Error(String(n)));this._renderError(r)}}.bind(this))}}open(){return this.style.display="",Promise.resolve()}close(){return this.style.display="none",Promise.resolve()}}typeof customElements<"u"&&!customElements.get(g)&&customElements.define(g,Ce)})();
|
package/dist/widget.min.js
CHANGED
|
@@ -1 +1,4 @@
|
|
|
1
|
-
"use strict";var VitraunWebAR=(()=>{(function(){"use strict";var M="VITRAUN_CONFIG",m="vtrn-vto-session",L=18e5,E=1e4,g="en-US",f="Vitraun",c="vitraun",R="https://",G="app.",V="."+c+".com",k="/v1/public/virtual-tryon-embed-init",H="Content-Type",F="X-Origin",x="X-Tryon-Session-Id",W="X-Merchant-Id",B="X-Widget-Id",K="application/json",Y="00000000-0000-0000-0000-000000000000",q=["addToCart","removeFromCart","redirectToCart","analysisFinished"],T="vitraun-vto",Q="["+T+"]",O=c+"-loading",A=c+"-error",z=f+" VTO",X="Loading "+f+"...",J="Failed to load "+f+".",j="Timed out while initializing the "+f+" session.",i={MERCHANT_ID:"merchant-id",WIDGET_ID:"widget-id",ENV:"env",API_PORT:"api-port",APP_PORT:"app-port",LANG:"lang",ISOLATED_SKU:"isolated-sku",APPLY_SKUS:"apply-skus",FLOW:"flow",BASKET_OPENS_IN:"basket-opens-in",CHECKOUT_OPENS_IN:"checkout-opens-in",USE_SIMPLE_PAGE:"use-simple-page",SHOW_DETAILS:"show-details",SHOW_PRODUCT_PRICE:"show-product-price",PRICE_FROM:"price-from",PRICE_TO:"price-to",CURRENCY_SYMBOL:"currency-symbol",IS_SIMULATION_MODE:"is-simulation-mode",SIMULATION_INLINE_CONFIG:"simulation-inline-config",CONTAINER_MIN_HEIGHT:"container-min-height",APP_ID:"app-id",PLATFORM:"platform",BUNDLE_ID:"bundle-id",PACKAGE_NAME:"package-name",APP_VERSION:"app-version",ATTESTATION_TOKEN:"attestation-token",DEBUG:"debug",INIT_TIMEOUT_MS:"init-timeout-ms"},Z=[i.MERCHANT_ID,i.WIDGET_ID,i.ENV,i.API_PORT,i.APP_PORT,i.LANG,i.ISOLATED_SKU,i.APPLY_SKUS,i.FLOW,i.BASKET_OPENS_IN,i.CHECKOUT_OPENS_IN,i.USE_SIMPLE_PAGE,i.SHOW_DETAILS,i.SHOW_PRODUCT_PRICE,i.PRICE_FROM,i.PRICE_TO,i.CURRENCY_SYMBOL,i.IS_SIMULATION_MODE,i.SIMULATION_INLINE_CONFIG,i.CONTAINER_MIN_HEIGHT,i.APP_ID,i.PLATFORM,i.BUNDLE_ID,i.PACKAGE_NAME,i.APP_VERSION,i.ATTESTATION_TOKEN,i.DEBUG,i.INIT_TIMEOUT_MS],u={ENV_REQUIRED:"The env attribute is required.",ENV_INVALID:"The env attribute contains an invalid value.",MERCHANT_ID_REQUIRED:"The merchant-id attribute is required.",WIDGET_ID_REQUIRED:"The widget-id attribute is required.",INIT_INVALID_RESPONSE:"Invalid init response.",INIT_SESSION_TOKEN_MISSING:"The init API did not return sessionToken.",INIT_VTO_URL_MISSING:"The server did not return a virtual try-on URL (vtoUrl). Please contact the store.",INIT_VTO_URL_INVALID:"The virtual try-on URL returned by the server is invalid. Please contact the store."},$="The operation timed out.",tt={CONFIG_SKIPPED_NO_IFRAME_ORIGIN:"Config not sent: iframeOrigin is missing."},I={GENERIC_TRY_AGAIN_OR_STORE:"Could not start the virtual try-on. Please try again or contact the store.",GENERIC_TRY_AGAIN:"Could not start the virtual try-on. Please try again.",GENERIC_SERVER_OR_CLIENT_MISMATCH:"Could not start the virtual try-on. Please refresh the page or contact the store."},et="We couldn't connect to the virtual try-on service. If you are developing locally, make sure the API is running, then try again.",v={INVALID_PUBLIC_API_KEY:"We could not open the virtual try-on. If the problem persists, contact the store.",PUBLIC_API_KEY_REQUIRED:"The virtual try-on is not available right now. Please try again later.",TRYON_EMBED_SESSION_TOKEN_MISSING:"We could not verify this session. Please refresh the page or contact the store.",TRYON_EMBED_SESSION_TOKEN_INVALID:"This session is no longer valid. Please refresh the page or start again.",TRYON_EMBED_SESSION_JWT_SECRET_NOT_CONFIGURED:"The virtual try-on is temporarily unavailable. Please try again later.",INVALID_OR_MISSING_MERCHANT_ID:"This integration is missing valid store credentials. Please contact the store.",INVALID_OR_MISSING_WIDGET_ID:"This integration is missing valid widget credentials. Please contact the store.",EMBED_INIT_MERCHANT_MISMATCH:"The store information does not match this widget. Please contact the store.",WIDGET_KEY_OR_CHANNEL_NOT_FOUND:"This widget could not be found or is no longer active. Please contact the store.",EMBED_PARENT_ORIGIN_REQUIRED:"We could not verify where this page is embedded. Please contact the store.",EMBED_PARENT_ORIGIN_NOT_ALLOWED:"This page is not allowed to use the virtual try-on. Please contact the store.",UNIQUE_CONSTRAINT_VIOLATION:"This value conflicts with an existing record. Change it and try again.",FOREIGN_KEY_VIOLATION:"This action references data that does not exist or cannot be linked. Check related records.",VALUE_OUT_OF_RANGE:"One of the values is invalid or too large for the server. Adjust the data and try again.",RECORD_NOT_FOUND:"The record was not found. It may have been removed. Refresh the page and try again.",NULL_CONSTRAINT_VIOLATION:"A required field was empty. Fill in all required fields and try again.",MISSING_REQUIRED_VALUE:"Some required information is missing. Review the form and try again.",RELATION_CONSTRAINT_VIOLATION:"This change is not allowed because of how records are linked. Adjust relationships and try again.",TRANSACTION_CONFLICT:"The operation conflicted with another change. Please try again.",INVALID_DATABASE_INPUT:"The request could not be processed. Check the data format and try again.",UNEXPECTED_DATABASE_ERROR:"Something went wrong while saving. Try again or contact support if it continues."};function S(e){return":host { display:block; width:100%; min-height:"+e+"; box-sizing:border-box; }"}function rt(e,t){return S(e)+"."+t+" {min-height:"+e+";display:flex;align-items:center;justify-content:center;border:1px solid #ececec;background:#fafafa;color:#333;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}"}function it(e,t){return S(e)+"."+t+" {min-height:"+e+";display:flex;align-items:center;justify-content:center;border:1px solid #f1d5d5;background:#fff7f7;color:#7a1f1f;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}"}function a(e,t,r){var n=e.getAttribute(t);return n!=null&&n!==""?n:r}function h(e,t){if(e==null||e==="")return t;var r=String(e).toLowerCase();return r==="true"||r==="1"||r==="yes"}function y(e){if(e==null||e==="")return null;var t=parseFloat(String(e));return Number.isFinite(t)?t:null}function nt(e){return!e||typeof e!="string"?[]:e.split(",").map(function(t){return t.trim()}).filter(Boolean)}function st(e,t){var r=a(e,t,"");if(!r||typeof r!="string")return null;try{return JSON.parse(r)}catch(n){return null}}function P(e){try{return JSON.parse(e)}catch(t){return null}}function N(){return typeof window=="undefined"||!window.location||!window.location.origin?null:window.location.origin}function ot(){return typeof window=="undefined"||!window.location||!window.location.href?null:window.location.href}function at(e){if(!e||typeof e!="string")return null;try{return new URL(e).origin}catch(t){return null}}function lt(e){var t=String(e||"").trim().toLowerCase();if(!t)throw new Error(u.ENV_REQUIRED);if(!/^[a-z0-9-]+$/.test(t))throw new Error(u.ENV_INVALID);return t}function _t(e){return e?String(e).trim().toLowerCase():"web"}function C(e){if(e==null||e==="")return null;var t=parseInt(String(e),10);return!Number.isInteger(t)||t<=0||t>65535?null:t}function ut(e,t){if(e==null||e==="")return"";var r=parseInt(String(e),10);return!Number.isInteger(r)||r<=0||r>65535||t==="https://"&&r===443||t==="http://"&&r===80?"":":"+r}function w(e){return!e||typeof e!="object"?!1:!!Array.isArray(e.message)}function U(e){if(!e||typeof e!="string")return!1;var t=e.toLowerCase();return t.indexOf("should not exist")!==-1||t.indexOf("should not be empty")!==-1||t.indexOf("forbidnonwhitelisted")!==-1||t.indexOf("whitelist")!==-1&&t.indexOf("property")!==-1||t.indexOf("property")!==-1&&t.indexOf("should not")!==-1}function D(e){if(!e||typeof e!="string")return!1;var t=e.trim();if(t.charAt(0)!=="{"||t.indexOf('"message"')===-1||t.indexOf('"statusCode"')===-1)return!1;var r=P(t);return w(r)}function It(e,t){if(w(e))return I.GENERIC_SERVER_OR_CLIENT_MISMATCH;var r=e&&typeof e.errorCode=="string"?e.errorCode:null;if(r&&Object.prototype.hasOwnProperty.call(v,r))return v[r];var n=e&&typeof e.message=="string"?e.message.trim():"";if(n)return U(n)?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:n;if(r)return I.GENERIC_TRY_AGAIN_OR_STORE;if(t&&String(t).length>0&&String(t).length<600){var s=String(t).trim();return D(s)?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:s.charAt(0)==="{"&&s.indexOf("errorCode")!==-1?I.GENERIC_TRY_AGAIN:s.charAt(0)==="{"?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:s}return I.GENERIC_TRY_AGAIN}function dt(e){if(!e||typeof e.message!="string")return!1;var t=e.name,r=e.message.toLowerCase();return t==="TypeError"&&(r.indexOf("failed to fetch")!==-1||r.indexOf("load failed")!==-1)||r.indexOf("networkerror when attempting to fetch")!==-1||t==="NetworkError"||r.indexOf("network request failed")!==-1}function b(e){if(dt(e))return et;if(e&&typeof e.message=="string"&&e.message.trim()){var t=e.message.trim();return U(t)||D(t)||t.charAt(0)==="{"&&t.indexOf('"message"')!==-1&&t.indexOf('"statusCode"')!==-1?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:t}return I.GENERIC_TRY_AGAIN}function ht(e,t){return R+G+e+V+ut(t,R)+k}function ft(e){var t=e.merchantId!=null?String(e.merchantId):"",r=e.widgetId!=null?String(e.widgetId):"",n=e.tryonSessionId!=null?String(e.tryonSessionId):"",s=e.origin!==void 0&&e.origin!==null&&e.origin!==""?String(e.origin):N()||"",l={};return l[F]=s,l[x]=n,l[W]=t,l[B]=r,e.contentType&&(l[H]=e.contentType),l}function Et(e,t){return{merchantId:e.merchantId,widgetId:e.widgetId,tryonSessionId:t,env:e.env,lang:e.lang,isSimulationMode:e.isSimulationMode===!0,appPort:e.appPort,app:{appId:e.appId,platform:e.platform,bundleId:e.bundleId,packageName:e.packageName,appVersion:e.appVersion,attestationToken:e.attestationToken},context:{origin:N(),pageUrl:ot(),userAgent:typeof navigator!="undefined"&&navigator.userAgent?navigator.userAgent:null,referrer:typeof document!="undefined"&&document.referrer?document.referrer:null,timezone:typeof Intl!="undefined"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:null}}}function ct(e,t,r,n){return!t||t<=0?e:new Promise(function(s,l){var _=!1,o=setTimeout(function(){if(!_){_=!0;try{n&&typeof n.abort=="function"&&n.abort()}catch(d){}l(new Error(r||$))}},t);e.then(function(d){_||(_=!0,clearTimeout(o),s(d))}).catch(function(d){_||(_=!0,clearTimeout(o),l(d))})})}function p(){if(typeof window=="undefined"||!window.crypto||!window.crypto.randomUUID)return Y;try{var e=sessionStorage.getItem(m);if(e){var t=JSON.parse(e);if(t&&typeof t.id=="string"&&typeof t.exp=="number"&&Date.now()<t.exp)return t.id}}catch(s){}var r=window.crypto.randomUUID(),n=Date.now()+L;try{sessionStorage.setItem(m,JSON.stringify({id:r,exp:n}))}catch(s){}return r}function Tt(e,t){var r=t.merchantId!=null?String(t.merchantId).trim():"",n=t.widgetId!=null?String(t.widgetId).trim():"";if(!r||!n)return e;var s;try{s=new URL(e)}catch(_){return e}s.searchParams.set("merchantId",r),s.searchParams.set("widgetId",n),s.searchParams.set("embed","1");var l=t.tryonSessionId!=null?String(t.tryonSessionId).trim():"";return l||(l=p()),l&&s.searchParams.set("tryonSessionId",l),s.toString()}class St extends HTMLElement{static get observedAttributes(){return Z.slice()}constructor(){super(),this.attachShadow({mode:"open"}),this._state={merchantId:"",widgetId:"",env:"",apiPort:null,appPort:null,lang:g,isolatedSku:null,applySkus:[],iframeOrigin:null,flow:"checkout",basketOpensIn:"event",checkoutOpensIn:"event",useSimplePage:!0,showDetails:!0,showProductPrice:!1,priceFrom:null,priceTo:null,currencySymbol:null,isSimulationMode:!1,simulationInlineConfig:null,appId:null,platform:"web",bundleId:null,packageName:null,appVersion:null,attestationToken:null,debug:!1,sessionToken:null,tryonSessionId:null,resolvedInitUrl:null,resolvedIframeUrl:null,initTimeoutMs:E},this._boundHandleMessage=this._handleMessage.bind(this),this._initPromise=null,this._initStateKey=null,this._activeInitRequestId=0,this._renderVersion=0,this._abortController=null}connectedCallback(){this._readAttributes(),this._render(),typeof window!="undefined"&&window.addEventListener("message",this._boundHandleMessage)}disconnectedCallback(){if(typeof window!="undefined"&&window.removeEventListener("message",this._boundHandleMessage),this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(t){}}attributeChangedCallback(t,r,n){r!==n&&(this._readAttributes(),this._render())}_log(){if(!(!this._state.debug||typeof console=="undefined"||!console.log)){var t=Array.prototype.slice.call(arguments);t.unshift(Q),console.log.apply(console,t)}}_readAttributes(){var t=st(this,i.SIMULATION_INLINE_CONFIG),r=!1;t&&t.features&&typeof t.features.showProductPrice=="boolean"&&(r=t.features.showProductPrice);var n=!0;t&&t.features&&typeof t.features.useSimplePage=="boolean"&&(n=t.features.useSimplePage);var s="checkout";t&&t.features&&(t.features.flow==="catalog"||t.features.flow==="checkout")&&(s=t.features.flow);var l=!0;t&&t.features&&typeof t.features.showDetails=="boolean"&&(l=t.features.showDetails);var _="";try{_=lt(a(this,i.ENV,""))}catch(d){_=""}var o=parseInt(a(this,i.INIT_TIMEOUT_MS,String(E)),10);(!Number.isFinite(o)||o<0)&&(o=E),this._state={merchantId:a(this,i.MERCHANT_ID,""),widgetId:a(this,i.WIDGET_ID,""),env:_,apiPort:C(a(this,i.API_PORT,null)),appPort:C(a(this,i.APP_PORT,null)),lang:a(this,i.LANG,g),isolatedSku:a(this,i.ISOLATED_SKU,null)||null,applySkus:nt(a(this,i.APPLY_SKUS,"")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:a(this,i.FLOW,s),basketOpensIn:a(this,i.BASKET_OPENS_IN,"event"),checkoutOpensIn:a(this,i.CHECKOUT_OPENS_IN,"event"),useSimplePage:h(a(this,i.USE_SIMPLE_PAGE,""),n),showDetails:h(a(this,i.SHOW_DETAILS,""),l),showProductPrice:h(a(this,i.SHOW_PRODUCT_PRICE,""),r),priceFrom:y(a(this,i.PRICE_FROM,null)),priceTo:y(a(this,i.PRICE_TO,null)),currencySymbol:a(this,i.CURRENCY_SYMBOL,null)||null,isSimulationMode:h(a(this,i.IS_SIMULATION_MODE,"false"),!1),simulationInlineConfig:t,appId:a(this,i.APP_ID,null)||null,platform:_t(a(this,i.PLATFORM,null)),bundleId:a(this,i.BUNDLE_ID,null)||null,packageName:a(this,i.PACKAGE_NAME,null)||null,appVersion:a(this,i.APP_VERSION,null)||null,attestationToken:a(this,i.ATTESTATION_TOKEN,null)||null,debug:h(a(this,i.DEBUG,"false"),!1),sessionToken:this._state&&this._state.sessionToken?this._state.sessionToken:null,tryonSessionId:this._state&&this._state.tryonSessionId?this._state.tryonSessionId:null,resolvedInitUrl:this._state&&this._state.resolvedInitUrl?this._state.resolvedInitUrl:null,resolvedIframeUrl:this._state&&this._state.resolvedIframeUrl?this._state.resolvedIframeUrl:null,initTimeoutMs:o}}_emit(t,r){this.dispatchEvent(new CustomEvent(t,{detail:r!=null?r:null,bubbles:!0,composed:!0}))}_setStatus(t,r){this.setAttribute("data-status",t),this._emit("statusChange",{status:t,detail:r||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(t){var r=t.data;if(!(!r||typeof r!="object")){var n=this._getIframeElement();if(!(!n||!n.contentWindow)&&t.source===n.contentWindow&&!(!this._state.iframeOrigin||t.origin!==this._state.iframeOrigin)){var s=r.type,l=r.detail;if(s==="VTO_USAGE"){this._emit("vtoUsage",l);return}q.indexOf(s)!==-1&&this._emit(s,l)}}}_getInitStateKey(){return JSON.stringify({merchantId:this._state.merchantId,widgetId:this._state.widgetId,env:this._state.env,apiPort:this._state.apiPort,appPort:this._state.appPort,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,simulationInlineConfig:this._state.simulationInlineConfig,appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken})}_buildEmbedInitUrl(){if(!this._state.env)throw new Error(u.ENV_REQUIRED);return ht(this._state.env,this._state.apiPort)}_buildInitPayload(){var t=p();return{tryonSessionId:t,initRequestBody:Et(this._state,t)}}_normalizeInitResponse(t,r,n){if(!t||typeof t!="object")throw new Error(u.INIT_INVALID_RESPONSE);var s=typeof t.sessionToken=="string"&&t.sessionToken?t.sessionToken:null,l=typeof t.tryonSessionId=="string"&&t.tryonSessionId?t.tryonSessionId:n;if(!s)throw new Error(u.INIT_SESSION_TOKEN_MISSING);var _=typeof t.vtoUrl=="string"&&t.vtoUrl.trim()?t.vtoUrl.trim():null;if(!_&&typeof t.iframeUrl=="string"&&t.iframeUrl.trim()&&(_=t.iframeUrl.trim()),!_)throw new Error(u.INIT_VTO_URL_MISSING);var o=at(_);if(!o)throw new Error(u.INIT_VTO_URL_INVALID);return{sessionToken:s,tryonSessionId:l,initUrl:r,iframeUrl:_,iframeOrigin:o}}_initializeSessionIfNeeded(){var t=this;if(!this._state.merchantId)return Promise.reject(new Error(u.MERCHANT_ID_REQUIRED));if(!this._state.widgetId)return Promise.reject(new Error(u.WIDGET_ID_REQUIRED));if(!this._state.env)return Promise.reject(new Error(u.ENV_REQUIRED));var r=this._getInitStateKey();if(this._initPromise&&this._initStateKey===r)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(o){}this._initStateKey=r,this._activeInitRequestId+=1;var n=this._activeInitRequestId;this._setStatus("loading");var s;try{s=this._buildEmbedInitUrl()}catch(o){return Promise.reject(o)}var l=this._buildInitPayload();this._state.tryonSessionId=l.tryonSessionId,this._abortController=typeof AbortController!="undefined"?new AbortController:null;var _=fetch(s,{method:"POST",headers:ft({merchantId:this._state.merchantId,widgetId:this._state.widgetId,tryonSessionId:l.tryonSessionId,contentType:K}),body:JSON.stringify(l.initRequestBody),signal:this._abortController?this._abortController.signal:void 0}).then(function(o){return o.ok?o.json():o.text().then(function(d){var Nt=P(d),pt=It(Nt,d);throw new Error(pt)})}).then(function(o){return t._normalizeInitResponse(o,s,l.tryonSessionId)});return this._initPromise=ct(_,this._state.initTimeoutMs,j,this._abortController).then(function(o){return n!==t._activeInitRequestId||(t._state.sessionToken=o.sessionToken,t._state.tryonSessionId=o.tryonSessionId,t._state.resolvedInitUrl=o.initUrl,t._state.resolvedIframeUrl=o.iframeUrl,t._state.iframeOrigin=o.iframeOrigin,t._setStatus("ready")),o}).catch(function(o){if(n!==t._activeInitRequestId)throw o;var d=b(o);throw t._state.sessionToken=null,t._state.resolvedInitUrl=null,t._state.resolvedIframeUrl=null,t._state.iframeOrigin=null,t._setStatus("error",{message:d}),new Error(d)}).finally(function(){n===t._activeInitRequestId&&(t._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var t=this._getIframeElement();if(!(!t||!t.contentWindow)){var r=this._state.iframeOrigin;if(!r){this._log(tt.CONFIG_SKIPPED_NO_IFRAME_ORIGIN);return}var n={merchantId:this._state.merchantId,widgetId:this._state.widgetId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||p(),lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},embedParentOrigin:N()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(n.inlineVirtualTryonConfig=this._state.simulationInlineConfig),t.contentWindow.postMessage({type:M,payload:n},r)}}_renderLoading(){if(this.shadowRoot){var t=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var r=document.createElement("style");r.textContent=rt(t,O);var n=document.createElement("div");n.className=O,n.textContent=X,this.shadowRoot.appendChild(r),this.shadowRoot.appendChild(n)}}_renderError(t){if(this.shadowRoot){var r=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=it(r,A);var s=document.createElement("div");s.className=A,s.textContent=t||J,this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(s)}}_renderIframe(t,r){if(this.shadowRoot&&!(!t||typeof t!="string"||!t.trim())){var n=this,s=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var l=document.createElement("style");l.textContent=S(s);var _=document.createElement("iframe");_.src=Tt(t.trim(),this._state),_.title=z,_.style.cssText="width:100%;height:100%;border:0;min-height:"+s,_.setAttribute("allow","camera"),_.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),_.onload=function(){r===n._renderVersion&&[0,50,150,400,1e3].forEach(function(o){setTimeout(function(){r===n._renderVersion&&n._sendConfigToIframe()},o)})},this.shadowRoot.appendChild(l),this.shadowRoot.appendChild(_)}}_render(){if(this.shadowRoot){this._renderVersion+=1;var t=this._renderVersion;if(!this._state.merchantId){this._setStatus("error",{message:u.MERCHANT_ID_REQUIRED}),this._renderError(u.MERCHANT_ID_REQUIRED);return}if(!this._state.widgetId){this._setStatus("error",{message:u.WIDGET_ID_REQUIRED}),this._renderError(u.WIDGET_ID_REQUIRED);return}if(!this._state.env){this._setStatus("error",{message:u.ENV_REQUIRED}),this._renderError(u.ENV_REQUIRED);return}this._renderLoading(),this._initializeSessionIfNeeded().then(function(r){t===this._renderVersion&&this._renderIframe(r.iframeUrl,t)}.bind(this)).catch(function(r){if(t===this._renderVersion){var n=b(r instanceof Error?r:new Error(String(r)));this._renderError(n)}}.bind(this))}}open(){return this.style.display="",Promise.resolve()}close(){return this.style.display="none",Promise.resolve()}}typeof customElements!="undefined"&&!customElements.get(T)&&customElements.define(T,St)})();})();
|
|
1
|
+
"use strict";var VitraunWebAR=(()=>{(function(){"use strict";var F="VITRAUN_CONFIG",A="vtrn-vto-session",B=18e5,T=1e4,C="en-US",p="Vitraun",m="vitraun",y="https://",W="app.",K="app",b="."+m+".com",Y="/v1/public/virtual-tryon-embed-init",q="Content-Type",z="X-Origin",X="X-Tryon-Session-Id",Q="X-Merchant-Id",J="X-Widget-Id",j="application/json",Z="00000000-0000-0000-0000-000000000000",w=["addToCart","removeFromCart","redirectToCart","analysisFinished"],$=w.concat(["statusChange","vtoUsage"]),ee=150,g="vitraun-vto",te="["+g+"]",P=m+"-loading",L=m+"-error",ne=p+" VTO",re="Loading "+p+"...",ie="Failed to load "+p+".",oe="Timed out while initializing the "+p+" session.",i={MERCHANT_ID:"merchant-id",WIDGET_ID:"widget-id",ENV:"env",API_PORT:"api-port",APP_PORT:"app-port",LANG:"lang",ISOLATED_SKU:"isolated-sku",APPLY_SKUS:"apply-skus",FLOW:"flow",BASKET_OPENS_IN:"basket-opens-in",CHECKOUT_OPENS_IN:"checkout-opens-in",USE_SIMPLE_PAGE:"use-simple-page",SHOW_DETAILS:"show-details",SHOW_PRODUCT_PRICE:"show-product-price",PRICE_FROM:"price-from",PRICE_TO:"price-to",CURRENCY_SYMBOL:"currency-symbol",IS_SIMULATION_MODE:"is-simulation-mode",SIMULATION_INLINE_CONFIG:"simulation-inline-config",CONTAINER_MIN_HEIGHT:"container-min-height",APP_ID:"app-id",PLATFORM:"platform",BUNDLE_ID:"bundle-id",PACKAGE_NAME:"package-name",APP_VERSION:"app-version",ATTESTATION_TOKEN:"attestation-token",DEBUG:"debug",CONSOLE:"console",INIT_TIMEOUT_MS:"init-timeout-ms"},se=[i.MERCHANT_ID,i.WIDGET_ID,i.ENV,i.API_PORT,i.APP_PORT,i.LANG,i.ISOLATED_SKU,i.APPLY_SKUS,i.FLOW,i.BASKET_OPENS_IN,i.CHECKOUT_OPENS_IN,i.USE_SIMPLE_PAGE,i.SHOW_DETAILS,i.SHOW_PRODUCT_PRICE,i.PRICE_FROM,i.PRICE_TO,i.CURRENCY_SYMBOL,i.IS_SIMULATION_MODE,i.SIMULATION_INLINE_CONFIG,i.CONTAINER_MIN_HEIGHT,i.APP_ID,i.PLATFORM,i.BUNDLE_ID,i.PACKAGE_NAME,i.APP_VERSION,i.ATTESTATION_TOKEN,i.DEBUG,i.CONSOLE,i.INIT_TIMEOUT_MS],_={ENV_INVALID:"The env attribute contains an invalid value.",MERCHANT_ID_REQUIRED:"The merchant-id attribute is required.",WIDGET_ID_REQUIRED:"The widget-id attribute is required.",INIT_INVALID_RESPONSE:"Invalid init response.",INIT_SESSION_TOKEN_MISSING:"The init API did not return sessionToken.",INIT_VTO_URL_MISSING:"The server did not return a virtual try-on URL (vtoUrl). Please contact the store.",INIT_VTO_URL_INVALID:"The virtual try-on URL returned by the server is invalid. Please contact the store."},ae="The operation timed out.",le={CONFIG_SKIPPED_NO_IFRAME_ORIGIN:"Config not sent: iframeOrigin is missing."},h={GENERIC_TRY_AGAIN_OR_STORE:"Could not start the virtual try-on. Please try again or contact the store.",GENERIC_TRY_AGAIN:"Could not start the virtual try-on. Please try again.",GENERIC_SERVER_OR_CLIENT_MISMATCH:"Could not start the virtual try-on. Please refresh the page or contact the store."},ue="We couldn't connect to the virtual try-on service. If you are developing locally, make sure the API is running, then try again.",M={INVALID_PUBLIC_API_KEY:"We could not open the virtual try-on. If the problem persists, contact the store.",PUBLIC_API_KEY_REQUIRED:"The virtual try-on is not available right now. Please try again later.",TRYON_EMBED_SESSION_TOKEN_MISSING:"We could not verify this session. Please refresh the page or contact the store.",TRYON_EMBED_SESSION_TOKEN_INVALID:"This session is no longer valid. Please refresh the page or start again.",TRYON_EMBED_SESSION_TOKEN_EXPIRED:"This embed session has expired. Refresh the page or start again.",TRYON_EMBED_SESSION_JWT_SECRET_NOT_CONFIGURED:"The virtual try-on is temporarily unavailable. Please try again later.",INVALID_OR_MISSING_MERCHANT_ID:"This integration is missing valid store credentials. Please contact the store.",INVALID_OR_MISSING_WIDGET_ID:"This integration is missing valid widget credentials. Please contact the store.",EMBED_INIT_MERCHANT_MISMATCH:"The store information does not match this widget. Please contact the store.",WIDGET_KEY_OR_CHANNEL_NOT_FOUND:"This widget could not be found or is no longer active. Please contact the store.",EMBED_PARENT_ORIGIN_REQUIRED:"We could not verify where this page is embedded. Please contact the store.",EMBED_PARENT_ORIGIN_NOT_ALLOWED:"This page is not allowed to use the virtual try-on. Please contact the store.",UNIQUE_CONSTRAINT_VIOLATION:"This value conflicts with an existing record. Change it and try again.",FOREIGN_KEY_VIOLATION:"This action references data that does not exist or cannot be linked. Check related records.",VALUE_OUT_OF_RANGE:"One of the values is invalid or too large for the server. Adjust the data and try again.",RECORD_NOT_FOUND:"The record was not found. It may have been removed. Refresh the page and try again.",NULL_CONSTRAINT_VIOLATION:"A required field was empty. Fill in all required fields and try again.",MISSING_REQUIRED_VALUE:"Some required information is missing. Review the form and try again.",RELATION_CONSTRAINT_VIOLATION:"This change is not allowed because of how records are linked. Adjust relationships and try again.",TRANSACTION_CONFLICT:"The operation conflicted with another change. Please try again.",INVALID_DATABASE_INPUT:"The request could not be processed. Check the data format and try again.",UNEXPECTED_DATABASE_ERROR:"Something went wrong while saving. Try again or contact support if it continues."};function S(t){return":host { display:block; width:100%; min-height:"+t+"; box-sizing:border-box; }.vitraun-host { position:relative; width:100%; min-height:"+t+"; box-sizing:border-box; }.vitraun-host > iframe { display:block; width:100%; border:0; min-height:"+t+"; }"}function de(){return'.vitraun-console-fab {position:absolute; bottom:12px; right:12px; z-index:5;padding:8px 12px; border:0; border-radius:8px;background:#0f172a; color:#f8fafc; font:600 12px/1.2 system-ui, sans-serif;cursor:pointer; box-shadow:0 4px 12px rgba(15,23,42,0.35);}.vitraun-console-fab:hover { background:#1e293b; }.vitraun-console-backdrop {position:absolute; inset:0; z-index:6; background:rgba(15,23,42,0.45);display:none; align-items:center; justify-content:center; padding:16px; box-sizing:border-box;}.vitraun-console-backdrop[data-open="true"] { display:flex; }.vitraun-console-modal {width:min(100%, 520px); max-height:min(70vh, 420px); display:flex; flex-direction:column;background:#fff; border-radius:12px; box-shadow:0 16px 40px rgba(15,23,42,0.25); overflow:hidden;}.vitraun-console-header {display:flex; align-items:center; justify-content:space-between; gap:8px;padding:12px 14px; border-bottom:1px solid #e2e8f0; background:#f8fafc;}.vitraun-console-title { font:600 14px/1.2 system-ui, sans-serif; color:#0f172a; margin:0; }.vitraun-console-actions { display:flex; gap:8px; }.vitraun-console-actions button {padding:6px 10px; border:1px solid #cbd5e1; border-radius:6px; background:#fff;font:500 12px/1 system-ui, sans-serif; color:#334155; cursor:pointer;}.vitraun-console-body {margin:0; padding:12px 14px; overflow:auto; flex:1; min-height:120px;font:12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; color:#0f172a;white-space:pre-wrap; word-break:break-word; background:#fff;}.vitraun-console-empty { color:#64748b; font-style:italic; }'}function _e(t,e){return S(t)+"."+e+" {min-height:"+t+";display:flex;align-items:center;justify-content:center;border:1px solid #ececec;background:#fafafa;color:#333;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}"}function he(t,e){return S(t)+"."+e+" {min-height:"+t+";display:flex;align-items:center;justify-content:center;border:1px solid #f1d5d5;background:#fff7f7;color:#7a1f1f;font:14px/1.4 Arial, sans-serif;padding:16px;box-sizing:border-box;border-radius:8px;text-align:center;}"}function u(t,e,n){var r=t.getAttribute(e);return r!=null&&r!==""?r:n}function I(t,e){if(t==null||t==="")return e;var n=String(t).toLowerCase();return n==="true"||n==="1"||n==="yes"}function U(t){if(t==null||t==="")return null;var e=parseFloat(String(t));return Number.isFinite(e)?e:null}function ce(t){return!t||typeof t!="string"?[]:t.split(",").map(function(e){return e.trim()}).filter(Boolean)}function Ie(t,e){var n=u(t,e,"");if(!n||typeof n!="string")return null;try{return JSON.parse(n)}catch(r){return null}}function D(t){try{return JSON.parse(t)}catch(e){return null}}function N(){return typeof window=="undefined"||!window.location||!window.location.origin?null:window.location.origin}function fe(){return typeof window=="undefined"||!window.location||!window.location.href?null:window.location.href}function pe(t){if(!t||typeof t!="string")return null;try{return new URL(t).origin}catch(e){return null}}function Ee(t){var e=String(t||"").trim().toLowerCase();if(!e)return"";if(!/^[a-z0-9-]+$/.test(e))throw new Error(_.ENV_INVALID);return e}function Te(t){return t?String(t).trim().toLowerCase():"web"}function k(t){if(t==null||t==="")return null;var e=parseInt(String(t),10);return!Number.isInteger(e)||e<=0||e>65535?null:e}function me(t,e){if(t==null||t==="")return"";var n=parseInt(String(t),10);return!Number.isInteger(n)||n<=0||n>65535||e==="https://"&&n===443||e==="http://"&&n===80?"":":"+n}function x(t){return!t||typeof t!="object"?!1:!!Array.isArray(t.message)}function G(t){if(!t||typeof t!="string")return!1;var e=t.toLowerCase();return e.indexOf("should not exist")!==-1||e.indexOf("should not be empty")!==-1||e.indexOf("forbidnonwhitelisted")!==-1||e.indexOf("whitelist")!==-1&&e.indexOf("property")!==-1||e.indexOf("property")!==-1&&e.indexOf("should not")!==-1}function V(t){if(!t||typeof t!="string")return!1;var e=t.trim();if(e.charAt(0)!=="{"||e.indexOf('"message"')===-1||e.indexOf('"statusCode"')===-1)return!1;var n=D(e);return x(n)}function ge(t,e){if(x(t))return h.GENERIC_SERVER_OR_CLIENT_MISMATCH;var n=t&&typeof t.errorCode=="string"?t.errorCode:null;if(n&&Object.prototype.hasOwnProperty.call(M,n))return M[n];var r=t&&typeof t.message=="string"?t.message.trim():"";if(r)return G(r)?h.GENERIC_SERVER_OR_CLIENT_MISMATCH:r;if(n)return h.GENERIC_TRY_AGAIN_OR_STORE;if(e&&String(e).length>0&&String(e).length<600){var o=String(e).trim();return V(o)?h.GENERIC_SERVER_OR_CLIENT_MISMATCH:o.charAt(0)==="{"&&o.indexOf("errorCode")!==-1?h.GENERIC_TRY_AGAIN:o.charAt(0)==="{"?h.GENERIC_SERVER_OR_CLIENT_MISMATCH:o}return h.GENERIC_TRY_AGAIN}function Se(t){if(!t||typeof t.message!="string")return!1;var e=t.name,n=t.message.toLowerCase();return e==="TypeError"&&(n.indexOf("failed to fetch")!==-1||n.indexOf("load failed")!==-1)||n.indexOf("networkerror when attempting to fetch")!==-1||e==="NetworkError"||n.indexOf("network request failed")!==-1}function H(t){if(Se(t))return ue;if(t&&typeof t.message=="string"&&t.message.trim()){var e=t.message.trim();return G(e)||V(e)||e.charAt(0)==="{"&&e.indexOf('"message"')!==-1&&e.indexOf('"statusCode"')!==-1?h.GENERIC_SERVER_OR_CLIENT_MISMATCH:e}return h.GENERIC_TRY_AGAIN}function Ne(t,e){var n=t&&String(t).trim()?W+String(t).trim().toLowerCase()+b:K+b;return y+n+me(e,y)+Y}function ve(t){var e=t.merchantId!=null?String(t.merchantId):"",n=t.widgetId!=null?String(t.widgetId):"",r=t.tryonSessionId!=null?String(t.tryonSessionId):"",o=t.origin!==void 0&&t.origin!==null&&t.origin!==""?String(t.origin):N()||"",a={};return a[z]=o,a[X]=r,a[Q]=e,a[J]=n,t.contentType&&(a[q]=t.contentType),a}function Oe(t,e){return{merchantId:t.merchantId,widgetId:t.widgetId,tryonSessionId:e,env:t.env,lang:t.lang,isSimulationMode:t.isSimulationMode===!0,appPort:t.appPort,app:{appId:t.appId,platform:t.platform,bundleId:t.bundleId,packageName:t.packageName,appVersion:t.appVersion,attestationToken:t.attestationToken},context:{origin:N(),pageUrl:fe(),userAgent:typeof navigator!="undefined"&&navigator.userAgent?navigator.userAgent:null,referrer:typeof document!="undefined"&&document.referrer?document.referrer:null,timezone:typeof Intl!="undefined"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().timeZone:null}}}function Re(t,e,n,r){return!e||e<=0?t:new Promise(function(o,a){var l=!1,s=setTimeout(function(){if(!l){l=!0;try{r&&typeof r.abort=="function"&&r.abort()}catch(d){}a(new Error(n||ae))}},e);t.then(function(d){l||(l=!0,clearTimeout(s),o(d))}).catch(function(d){l||(l=!0,clearTimeout(s),a(d))})})}function v(){if(typeof window=="undefined"||!window.crypto||!window.crypto.randomUUID)return Z;try{var t=sessionStorage.getItem(A);if(t){var e=JSON.parse(t);if(e&&typeof e.id=="string"&&typeof e.exp=="number"&&Date.now()<e.exp)return e.id}}catch(o){}var n=window.crypto.randomUUID(),r=Date.now()+B;try{sessionStorage.setItem(A,JSON.stringify({id:n,exp:r}))}catch(o){}return n}function Ae(t,e){var n=e.merchantId!=null?String(e.merchantId).trim():"",r=e.widgetId!=null?String(e.widgetId).trim():"";if(!n||!r)return t;var o;try{o=new URL(t)}catch(s){return t}o.searchParams.set("merchantId",n),o.searchParams.set("widgetId",r),o.searchParams.set("embed","1");var a=e.tryonSessionId!=null?String(e.tryonSessionId).trim():"";a||(a=v()),a&&o.searchParams.set("tryonSessionId",a);var l=e.sessionToken!=null?String(e.sessionToken).trim():"";return l&&o.searchParams.set("embedSessionToken",l),o.toString()}class Ce extends HTMLElement{static get observedAttributes(){return se.slice()}constructor(){super(),this.attachShadow({mode:"open"}),this._state={merchantId:"",widgetId:"",env:"",apiPort:null,appPort:null,lang:C,isolatedSku:null,applySkus:[],iframeOrigin:null,flow:"checkout",basketOpensIn:"event",checkoutOpensIn:"event",useSimplePage:!0,showDetails:!0,showProductPrice:!1,priceFrom:null,priceTo:null,currencySymbol:null,isSimulationMode:!1,simulationInlineConfig:null,appId:null,platform:"web",bundleId:null,packageName:null,appVersion:null,attestationToken:null,debug:!1,console:!1,sessionToken:null,tryonSessionId:null,resolvedInitUrl:null,resolvedIframeUrl:null,initTimeoutMs:T},this._consoleLog=[],this._consoleModalOpen=!1,this._consoleCaptureTeardown=null,this._boundHandleMessage=this._handleMessage.bind(this),this._initPromise=null,this._initStateKey=null,this._activeInitRequestId=0,this._renderVersion=0,this._abortController=null}connectedCallback(){this._readAttributes(),this._setupConsoleCapture(),this._render(),typeof window!="undefined"&&window.addEventListener("message",this._boundHandleMessage)}disconnectedCallback(){if(typeof window!="undefined"&&window.removeEventListener("message",this._boundHandleMessage),this._teardownConsoleCapture(),this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(e){}}attributeChangedCallback(e,n,r){n!==r&&(this._readAttributes(),this._setupConsoleCapture(),this._render())}_log(){if(!(!this._state.debug||typeof console=="undefined"||!console.log)){var e=Array.prototype.slice.call(arguments);e.unshift(te),console.log.apply(console,e)}}_readAttributes(){var e=Ie(this,i.SIMULATION_INLINE_CONFIG),n=!1;e&&e.features&&typeof e.features.showProductPrice=="boolean"&&(n=e.features.showProductPrice);var r=!0;e&&e.features&&typeof e.features.useSimplePage=="boolean"&&(r=e.features.useSimplePage);var o="checkout";e&&e.features&&(e.features.flow==="catalog"||e.features.flow==="checkout")&&(o=e.features.flow);var a=!0;e&&e.features&&typeof e.features.showDetails=="boolean"&&(a=e.features.showDetails);var l="";try{l=Ee(u(this,i.ENV,""))}catch(d){l=""}var s=parseInt(u(this,i.INIT_TIMEOUT_MS,String(T)),10);(!Number.isFinite(s)||s<0)&&(s=T),this._state={merchantId:u(this,i.MERCHANT_ID,""),widgetId:u(this,i.WIDGET_ID,""),env:l,apiPort:k(u(this,i.API_PORT,null)),appPort:k(u(this,i.APP_PORT,null)),lang:u(this,i.LANG,C),isolatedSku:u(this,i.ISOLATED_SKU,null)||null,applySkus:ce(u(this,i.APPLY_SKUS,"")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:u(this,i.FLOW,o),basketOpensIn:u(this,i.BASKET_OPENS_IN,"event"),checkoutOpensIn:u(this,i.CHECKOUT_OPENS_IN,"event"),useSimplePage:I(u(this,i.USE_SIMPLE_PAGE,""),r),showDetails:I(u(this,i.SHOW_DETAILS,""),a),showProductPrice:I(u(this,i.SHOW_PRODUCT_PRICE,""),n),priceFrom:U(u(this,i.PRICE_FROM,null)),priceTo:U(u(this,i.PRICE_TO,null)),currencySymbol:u(this,i.CURRENCY_SYMBOL,null)||null,isSimulationMode:I(u(this,i.IS_SIMULATION_MODE,"false"),!1),simulationInlineConfig:e,appId:u(this,i.APP_ID,null)||null,platform:Te(u(this,i.PLATFORM,null)),bundleId:u(this,i.BUNDLE_ID,null)||null,packageName:u(this,i.PACKAGE_NAME,null)||null,appVersion:u(this,i.APP_VERSION,null)||null,attestationToken:u(this,i.ATTESTATION_TOKEN,null)||null,debug:I(u(this,i.DEBUG,"false"),!1),console:I(u(this,i.CONSOLE,"false"),!1),sessionToken:this._state&&this._state.sessionToken?this._state.sessionToken:null,tryonSessionId:this._state&&this._state.tryonSessionId?this._state.tryonSessionId:null,resolvedInitUrl:this._state&&this._state.resolvedInitUrl?this._state.resolvedInitUrl:null,resolvedIframeUrl:this._state&&this._state.resolvedIframeUrl?this._state.resolvedIframeUrl:null,initTimeoutMs:s}}_emit(e,n){this.dispatchEvent(new CustomEvent(e,{detail:n!=null?n:null,bubbles:!0,composed:!0}))}_teardownConsoleCapture(){typeof this._consoleCaptureTeardown=="function"&&(this._consoleCaptureTeardown(),this._consoleCaptureTeardown=null)}_setupConsoleCapture(){if(this._teardownConsoleCapture(),!!this._state.console){var e=this,n=[];$.forEach(function(r){var o=function(a){e._appendConsoleLog(r,a.detail)};e.addEventListener(r,o),n.push({eventType:r,handler:o})}),this._consoleCaptureTeardown=function(){n.forEach(function(r){e.removeEventListener(r.eventType,r.handler)})}}}_appendConsoleLog(e,n){this._state.console&&(Array.isArray(this._consoleLog)||(this._consoleLog=[]),this._consoleLog.push({type:e,timestamp:new Date().toISOString(),detail:n!=null?n:null}),this._consoleLog.length>ee&&this._consoleLog.shift(),this._refreshConsoleChrome())}_formatConsoleLogText(){return!this._consoleLog||this._consoleLog.length===0?"":this._consoleLog.map(function(e){var n="";try{n=JSON.stringify(e.detail,null,2)}catch(r){n=String(e.detail)}return"["+e.timestamp+"] "+e.type+`
|
|
2
|
+
`+n}).join(`
|
|
3
|
+
|
|
4
|
+
`)}_refreshConsoleChrome(){if(!(!this.shadowRoot||!this._state.console)){var e=this.shadowRoot.querySelector(".vitraun-console-fab");if(e){var n=this._consoleLog?this._consoleLog.length:0;e.textContent=n>0?"Events ("+n+")":"Events"}var r=this.shadowRoot.querySelector(".vitraun-console-body");if(r&&this._consoleModalOpen){var o=this._formatConsoleLogText();o?(r.textContent=o,r.classList.remove("vitraun-console-empty")):(r.textContent="No events yet. Interact with the try-on to see activity.",r.classList.add("vitraun-console-empty")),r.scrollTop=r.scrollHeight}}}_setConsoleModalOpen(e){if(this._consoleModalOpen=e===!0,!!this.shadowRoot){var n=this.shadowRoot.querySelector(".vitraun-console-backdrop");n&&n.setAttribute("data-open",this._consoleModalOpen?"true":"false"),this._refreshConsoleChrome()}}_mountConsoleChrome(e){if(!(!e||!this._state.console)){var n=e.querySelector(".vitraun-console-fab");if(n){this._refreshConsoleChrome();return}var r=this,o=document.createElement("button");o.type="button",o.className="vitraun-console-fab",o.setAttribute("aria-label","Open Try-On events console"),o.textContent="Events",o.addEventListener("click",function(){r._setConsoleModalOpen(!0)});var a=document.createElement("div");a.className="vitraun-console-backdrop",a.setAttribute("data-open","false"),a.setAttribute("role","presentation"),a.addEventListener("click",function(R){R.target===a&&r._setConsoleModalOpen(!1)});var l=document.createElement("div");l.className="vitraun-console-modal",l.setAttribute("role","dialog"),l.setAttribute("aria-modal","true"),l.setAttribute("aria-label","Try-On events console"),l.addEventListener("click",function(R){R.stopPropagation()});var s=document.createElement("div");s.className="vitraun-console-header";var d=document.createElement("h2");d.className="vitraun-console-title",d.textContent="Try-On events";var c=document.createElement("div");c.className="vitraun-console-actions";var f=document.createElement("button");f.type="button",f.textContent="Clear",f.addEventListener("click",function(){r._consoleLog=[],r._refreshConsoleChrome()});var E=document.createElement("button");E.type="button",E.textContent="Close",E.addEventListener("click",function(){r._setConsoleModalOpen(!1)}),c.appendChild(f),c.appendChild(E),s.appendChild(d),s.appendChild(c);var O=document.createElement("pre");O.className="vitraun-console-body vitraun-console-empty",O.textContent="No events yet. Interact with the try-on to see activity.",l.appendChild(s),l.appendChild(O),a.appendChild(l),e.appendChild(o),e.appendChild(a),this._refreshConsoleChrome()}}_setStatus(e,n){this.setAttribute("data-status",e),this._emit("statusChange",{status:e,detail:n||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(e){var n=e.data;if(!(!n||typeof n!="object")){var r=this._getIframeElement();if(!(!r||!r.contentWindow)&&e.source===r.contentWindow&&!(!this._state.iframeOrigin||e.origin!==this._state.iframeOrigin)){var o=n.type,a=n.detail;if(o==="VTO_USAGE"){this._emit("vtoUsage",a);return}w.indexOf(o)!==-1&&this._emit(o,a)}}}_getInitStateKey(){return JSON.stringify({merchantId:this._state.merchantId,widgetId:this._state.widgetId,env:this._state.env,apiPort:this._state.apiPort,appPort:this._state.appPort,lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,simulationInlineConfig:this._state.simulationInlineConfig,appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken})}_buildEmbedInitUrl(){return Ne(this._state.env,this._state.apiPort)}_buildInitPayload(){var e=v();return{tryonSessionId:e,initRequestBody:Oe(this._state,e)}}_normalizeInitResponse(e,n,r){if(!e||typeof e!="object")throw new Error(_.INIT_INVALID_RESPONSE);var o=typeof e.sessionToken=="string"&&e.sessionToken?e.sessionToken:null,a=typeof e.tryonSessionId=="string"&&e.tryonSessionId?e.tryonSessionId:r;if(!o)throw new Error(_.INIT_SESSION_TOKEN_MISSING);var l=typeof e.vtoUrl=="string"&&e.vtoUrl.trim()?e.vtoUrl.trim():null;if(!l&&typeof e.iframeUrl=="string"&&e.iframeUrl.trim()&&(l=e.iframeUrl.trim()),!l)throw new Error(_.INIT_VTO_URL_MISSING);var s=pe(l);if(!s)throw new Error(_.INIT_VTO_URL_INVALID);return{sessionToken:o,tryonSessionId:a,initUrl:n,iframeUrl:l,iframeOrigin:s}}_initializeSessionIfNeeded(){var e=this;if(!this._state.merchantId)return Promise.reject(new Error(_.MERCHANT_ID_REQUIRED));if(!this._state.widgetId)return Promise.reject(new Error(_.WIDGET_ID_REQUIRED));var n=this._getInitStateKey();if(this._initPromise&&this._initStateKey===n)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(s){}this._initStateKey=n,this._activeInitRequestId+=1;var r=this._activeInitRequestId;this._setStatus("loading");var o;try{o=this._buildEmbedInitUrl()}catch(s){return Promise.reject(s)}var a=this._buildInitPayload();this._state.tryonSessionId=a.tryonSessionId,this._abortController=typeof AbortController!="undefined"?new AbortController:null;var l=fetch(o,{method:"POST",headers:ve({merchantId:this._state.merchantId,widgetId:this._state.widgetId,tryonSessionId:a.tryonSessionId,contentType:j}),body:JSON.stringify(a.initRequestBody),signal:this._abortController?this._abortController.signal:void 0}).then(function(s){return s.ok?s.json():s.text().then(function(d){var c=D(d),f=ge(c,d);throw new Error(f)})}).then(function(s){return e._normalizeInitResponse(s,o,a.tryonSessionId)});return this._initPromise=Re(l,this._state.initTimeoutMs,oe,this._abortController).then(function(s){return r!==e._activeInitRequestId||(e._state.sessionToken=s.sessionToken,e._state.tryonSessionId=s.tryonSessionId,e._state.resolvedInitUrl=s.initUrl,e._state.resolvedIframeUrl=s.iframeUrl,e._state.iframeOrigin=s.iframeOrigin,e._setStatus("ready")),s}).catch(function(s){if(r!==e._activeInitRequestId)throw s;var d=H(s);throw e._state.sessionToken=null,e._state.resolvedInitUrl=null,e._state.resolvedIframeUrl=null,e._state.iframeOrigin=null,e._setStatus("error",{message:d}),new Error(d)}).finally(function(){r===e._activeInitRequestId&&(e._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var e=this._getIframeElement();if(!(!e||!e.contentWindow)){var n=this._state.iframeOrigin;if(!n){this._log(le.CONFIG_SKIPPED_NO_IFRAME_ORIGIN);return}var r={merchantId:this._state.merchantId,widgetId:this._state.widgetId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||v(),lang:this._state.lang,isolatedSku:this._state.isolatedSku,applySkus:this._state.applySkus,flow:this._state.flow,basketOpensIn:this._state.basketOpensIn,checkoutOpensIn:this._state.checkoutOpensIn,useSimplePage:this._state.useSimplePage,showDetails:this._state.showDetails,showProductPrice:this._state.showProductPrice,priceFrom:this._state.priceFrom,priceTo:this._state.priceTo,currencySymbol:this._state.currencySymbol,isSimulationMode:this._state.isSimulationMode,app:{appId:this._state.appId,platform:this._state.platform,bundleId:this._state.bundleId,packageName:this._state.packageName,appVersion:this._state.appVersion,attestationToken:this._state.attestationToken},embedParentOrigin:N()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(r.inlineVirtualTryonConfig=this._state.simulationInlineConfig),e.contentWindow.postMessage({type:F,payload:r},n)}}_renderLoading(){if(this.shadowRoot){var e=u(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=_e(e,P);var r=document.createElement("div");r.className=P,r.textContent=re,this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(r)}}_renderError(e){if(this.shadowRoot){var n=u(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var r=document.createElement("style");r.textContent=he(n,L);var o=document.createElement("div");o.className=L,o.textContent=e||ie,this.shadowRoot.appendChild(r),this.shadowRoot.appendChild(o)}}_renderIframe(e,n){if(this.shadowRoot&&!(!e||typeof e!="string"||!e.trim())){var r=this,o=u(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="",this._consoleModalOpen=!1;var a=document.createElement("style"),l=S(o);this._state.console&&(l+=de()),a.textContent=l;var s=document.createElement("div");s.className="vitraun-host";var d=document.createElement("iframe");d.src=Ae(e.trim(),this._state),d.title=ne,d.setAttribute("allow","camera"),d.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),d.onload=function(){n===r._renderVersion&&[0,50,150,400,1e3].forEach(function(c){setTimeout(function(){n===r._renderVersion&&r._sendConfigToIframe()},c)})},s.appendChild(d),this._state.console&&this._mountConsoleChrome(s),this.shadowRoot.appendChild(a),this.shadowRoot.appendChild(s)}}_render(){if(this.shadowRoot){this._renderVersion+=1;var e=this._renderVersion;if(!this._state.merchantId){this._setStatus("error",{message:_.MERCHANT_ID_REQUIRED}),this._renderError(_.MERCHANT_ID_REQUIRED);return}if(!this._state.widgetId){this._setStatus("error",{message:_.WIDGET_ID_REQUIRED}),this._renderError(_.WIDGET_ID_REQUIRED);return}this._renderLoading(),this._initializeSessionIfNeeded().then(function(n){e===this._renderVersion&&this._renderIframe(n.iframeUrl,e)}.bind(this)).catch(function(n){if(e===this._renderVersion){var r=H(n instanceof Error?n:new Error(String(n)));this._renderError(r)}}.bind(this))}}open(){return this.style.display="",Promise.resolve()}close(){return this.style.display="none",Promise.resolve()}}typeof customElements!="undefined"&&!customElements.get(g)&&customElements.define(g,Ce)})();})();
|