@vitraun/webar 0.2.0 → 0.2.2
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 +1 -1
- package/dist/widget.min.js +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(){"use strict";var M="VITRAUN_CONFIG",p="vtrn-vto-session",L=18e5,E=1e4,g="en-US",f="Vitraun",c="vitraun",m="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",K="X-Widget-Id",B="application/json",Y="00000000-0000-0000-0000-000000000000",q=["addToCart","removeFromCart","redirectToCart","analysisFinished"],T="vitraun-vto",Q="["+T+"]",R=c+"-loading",O=c+"-error",z=f+" VTO",X="Loading "+f+"...",J="Failed to load "+f+".",j="Timed out while initializing the "+f+" session.",r={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=[r.MERCHANT_ID,r.WIDGET_ID,r.ENV,r.API_PORT,r.APP_PORT,r.LANG,r.ISOLATED_SKU,r.APPLY_SKUS,r.FLOW,r.BASKET_OPENS_IN,r.CHECKOUT_OPENS_IN,r.USE_SIMPLE_PAGE,r.SHOW_DETAILS,r.SHOW_PRODUCT_PRICE,r.PRICE_FROM,r.PRICE_TO,r.CURRENCY_SYMBOL,r.IS_SIMULATION_MODE,r.SIMULATION_INLINE_CONFIG,r.CONTAINER_MIN_HEIGHT,r.APP_ID,r.PLATFORM,r.BUNDLE_ID,r.PACKAGE_NAME,r.APP_VERSION,r.ATTESTATION_TOKEN,r.DEBUG,r.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.",A={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 it(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 rt(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,i){var n=e.getAttribute(t);return n!=null&&n!==""?n:i}function h(e,t){if(e==null||e==="")return t;var i=String(e).toLowerCase();return i==="true"||i==="1"||i==="yes"}function v(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 i=a(e,t,"");if(!i||typeof i!="string")return null;try{return JSON.parse(i)}catch{return null}}function y(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 P(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 i=parseInt(String(e),10);return!Number.isInteger(i)||i<=0||i>65535||t==="https://"&&i===443||t==="http://"&&i===80?"":":"+i}function C(e){return!e||typeof e!="object"?!1:!!Array.isArray(e.message)}function w(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 U(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 i=y(t);return C(i)}function It(e,t){if(C(e))return I.GENERIC_SERVER_OR_CLIENT_MISMATCH;var i=e&&typeof e.errorCode=="string"?e.errorCode:null;if(i&&Object.prototype.hasOwnProperty.call(A,i))return A[i];var n=e&&typeof e.message=="string"?e.message.trim():"";if(n)return w(n)?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:n;if(i)return I.GENERIC_TRY_AGAIN_OR_STORE;if(t&&String(t).length>0&&String(t).length<600){var s=String(t).trim();return U(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,i=e.message.toLowerCase();return t==="TypeError"&&(i.indexOf("failed to fetch")!==-1||i.indexOf("load failed")!==-1)||i.indexOf("networkerror when attempting to fetch")!==-1||t==="NetworkError"||i.indexOf("network request failed")!==-1}function D(e){if(dt(e))return et;if(e&&typeof e.message=="string"&&e.message.trim()){var t=e.message.trim();return w(t)||U(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 m+G+e+V+ut(t,m)+k}function ft(e){var t=e.merchantId!=null?String(e.merchantId):"",i=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()||"",_={};return _[F]=s,_[x]=n,_[W]=t,_[K]=i,e.contentType&&(_[H]=e.contentType),_}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,i,n){return!t||t<=0?e:new Promise(function(s,_){var l=!1,o=setTimeout(function(){if(!l){l=!0;try{n&&typeof n.abort=="function"&&n.abort()}catch{}_(new Error(i||$))}},t);e.then(function(d){l||(l=!0,clearTimeout(o),s(d))}).catch(function(d){l||(l=!0,clearTimeout(o),_(d))})})}function b(){if(typeof window>"u"||!window.crypto||!window.crypto.randomUUID)return Y;try{var e=sessionStorage.getItem(p);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 i=window.crypto.randomUUID(),n=Date.now()+L;try{sessionStorage.setItem(p,JSON.stringify({id:i,exp:n}))}catch{}return i}class Tt 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,i,n){i!==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,r.SIMULATION_INLINE_CONFIG),i=!1;t&&t.features&&typeof t.features.showProductPrice=="boolean"&&(i=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 _=!0;t&&t.features&&typeof t.features.showDetails=="boolean"&&(_=t.features.showDetails);var l="";try{l=lt(a(this,r.ENV,""))}catch{l=""}var o=parseInt(a(this,r.INIT_TIMEOUT_MS,String(E)),10);(!Number.isFinite(o)||o<0)&&(o=E),this._state={merchantId:a(this,r.MERCHANT_ID,""),widgetId:a(this,r.WIDGET_ID,""),env:l,apiPort:P(a(this,r.API_PORT,null)),appPort:P(a(this,r.APP_PORT,null)),lang:a(this,r.LANG,g),isolatedSku:a(this,r.ISOLATED_SKU,null)||null,applySkus:nt(a(this,r.APPLY_SKUS,"")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:a(this,r.FLOW,s),basketOpensIn:a(this,r.BASKET_OPENS_IN,"event"),checkoutOpensIn:a(this,r.CHECKOUT_OPENS_IN,"event"),useSimplePage:h(a(this,r.USE_SIMPLE_PAGE,""),n),showDetails:h(a(this,r.SHOW_DETAILS,""),_),showProductPrice:h(a(this,r.SHOW_PRODUCT_PRICE,""),i),priceFrom:v(a(this,r.PRICE_FROM,null)),priceTo:v(a(this,r.PRICE_TO,null)),currencySymbol:a(this,r.CURRENCY_SYMBOL,null)||null,isSimulationMode:h(a(this,r.IS_SIMULATION_MODE,"false"),!1),simulationInlineConfig:t,appId:a(this,r.APP_ID,null)||null,platform:_t(a(this,r.PLATFORM,null)),bundleId:a(this,r.BUNDLE_ID,null)||null,packageName:a(this,r.PACKAGE_NAME,null)||null,appVersion:a(this,r.APP_VERSION,null)||null,attestationToken:a(this,r.ATTESTATION_TOKEN,null)||null,debug:h(a(this,r.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,i){this.dispatchEvent(new CustomEvent(t,{detail:i??null,bubbles:!0,composed:!0}))}_setStatus(t,i){this.setAttribute("data-status",t),this._emit("statusChange",{status:t,detail:i||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(t){var i=t.data;if(!(!i||typeof i!="object")){var n=this._getIframeElement();if(!(!n||!n.contentWindow)&&t.source===n.contentWindow&&!(!this._state.iframeOrigin||t.origin!==this._state.iframeOrigin)){var s=i.type,_=i.detail;if(s==="VTO_USAGE"){this._emit("vtoUsage",_);return}q.indexOf(s)!==-1&&this._emit(s,_)}}}_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=b();return{tryonSessionId:t,initRequestBody:Et(this._state,t)}}_normalizeInitResponse(t,i,n){if(!t||typeof t!="object")throw new Error(u.INIT_INVALID_RESPONSE);var s=typeof t.sessionToken=="string"&&t.sessionToken?t.sessionToken:null,_=typeof t.tryonSessionId=="string"&&t.tryonSessionId?t.tryonSessionId:n;if(!s)throw new Error(u.INIT_SESSION_TOKEN_MISSING);var l=typeof t.vtoUrl=="string"&&t.vtoUrl.trim()?t.vtoUrl.trim():null;if(!l&&typeof t.iframeUrl=="string"&&t.iframeUrl.trim()&&(l=t.iframeUrl.trim()),!l)throw new Error(u.INIT_VTO_URL_MISSING);var o=at(l);if(!o)throw new Error(u.INIT_VTO_URL_INVALID);return{sessionToken:s,tryonSessionId:_,initUrl:i,iframeUrl:l,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 i=this._getInitStateKey();if(this._initPromise&&this._initStateKey===i)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch{}this._initStateKey=i,this._activeInitRequestId+=1;var n=this._activeInitRequestId;this._setStatus("loading");var s;try{s=this._buildEmbedInitUrl()}catch(o){return Promise.reject(o)}var _=this._buildInitPayload();this._state.tryonSessionId=_.tryonSessionId,this._abortController=typeof AbortController<"u"?new AbortController:null;var l=fetch(s,{method:"POST",headers:ft({merchantId:this._state.merchantId,widgetId:this._state.widgetId,tryonSessionId:_.tryonSessionId,contentType:B}),body:JSON.stringify(_.initRequestBody),signal:this._abortController?this._abortController.signal:void 0}).then(function(o){return o.ok?o.json():o.text().then(function(d){var St=y(d),Nt=It(St,d);throw new Error(Nt)})}).then(function(o){return t._normalizeInitResponse(o,s,_.tryonSessionId)});return this._initPromise=ct(l,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=D(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 i=this._state.iframeOrigin;if(!i){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||b(),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},i)}}_renderLoading(){if(this.shadowRoot){var t=a(this,r.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var i=document.createElement("style");i.textContent=it(t,R);var n=document.createElement("div");n.className=R,n.textContent=X,this.shadowRoot.appendChild(i),this.shadowRoot.appendChild(n)}}_renderError(t){if(this.shadowRoot){var i=a(this,r.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=rt(i,O);var s=document.createElement("div");s.className=O,s.textContent=t||J,this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(s)}}_renderIframe(t,i){if(this.shadowRoot&&!(!t||typeof t!="string"||!t.trim())){var n=this,s=a(this,r.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var _=document.createElement("style");_.textContent=S(s);var l=document.createElement("iframe");l.src=t,l.title=z,l.style.cssText="width:100%;height:100%;border:0;min-height:"+s,l.setAttribute("allow","camera"),l.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),l.onload=function(){i===n._renderVersion&&[0,50,150,400,1e3].forEach(function(o){setTimeout(function(){i===n._renderVersion&&n._sendConfigToIframe()},o)})},this.shadowRoot.appendChild(_),this.shadowRoot.appendChild(l)}}_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(i){t===this._renderVersion&&this._renderIframe(i.iframeUrl,t)}.bind(this)).catch(function(i){if(t===this._renderVersion){var n=D(i instanceof Error?i:new Error(String(i)));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,Tt)})();
|
|
1
|
+
(function(){"use strict";var M="VITRAUN_CONFIG",p="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.",ee={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."},te="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(t){return":host { display:block; width:100%; min-height:"+t+"; box-sizing:border-box; }"}function re(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 ie(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 a(t,e,r){var n=t.getAttribute(e);return n!=null&&n!==""?n:r}function h(t,e){if(t==null||t==="")return e;var r=String(t).toLowerCase();return r==="true"||r==="1"||r==="yes"}function y(t){if(t==null||t==="")return null;var e=parseFloat(String(t));return Number.isFinite(e)?e:null}function ne(t){return!t||typeof t!="string"?[]:t.split(",").map(function(e){return e.trim()}).filter(Boolean)}function se(t,e){var r=a(t,e,"");if(!r||typeof r!="string")return null;try{return JSON.parse(r)}catch{return null}}function P(t){try{return JSON.parse(t)}catch{return null}}function m(){return typeof window>"u"||!window.location||!window.location.origin?null:window.location.origin}function oe(){return typeof window>"u"||!window.location||!window.location.href?null:window.location.href}function ae(t){if(!t||typeof t!="string")return null;try{return new URL(t).origin}catch{return null}}function le(t){var e=String(t||"").trim().toLowerCase();if(!e)throw new Error(u.ENV_REQUIRED);if(!/^[a-z0-9-]+$/.test(e))throw new Error(u.ENV_INVALID);return e}function _e(t){return t?String(t).trim().toLowerCase():"web"}function C(t){if(t==null||t==="")return null;var e=parseInt(String(t),10);return!Number.isInteger(e)||e<=0||e>65535?null:e}function ue(t,e){if(t==null||t==="")return"";var r=parseInt(String(t),10);return!Number.isInteger(r)||r<=0||r>65535||e==="https://"&&r===443||e==="http://"&&r===80?"":":"+r}function w(t){return!t||typeof t!="object"?!1:!!Array.isArray(t.message)}function U(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 D(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 r=P(e);return w(r)}function Ie(t,e){if(w(t))return I.GENERIC_SERVER_OR_CLIENT_MISMATCH;var r=t&&typeof t.errorCode=="string"?t.errorCode:null;if(r&&Object.prototype.hasOwnProperty.call(v,r))return v[r];var n=t&&typeof t.message=="string"?t.message.trim():"";if(n)return U(n)?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:n;if(r)return I.GENERIC_TRY_AGAIN_OR_STORE;if(e&&String(e).length>0&&String(e).length<600){var s=String(e).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 de(t){if(!t||typeof t.message!="string")return!1;var e=t.name,r=t.message.toLowerCase();return e==="TypeError"&&(r.indexOf("failed to fetch")!==-1||r.indexOf("load failed")!==-1)||r.indexOf("networkerror when attempting to fetch")!==-1||e==="NetworkError"||r.indexOf("network request failed")!==-1}function b(t){if(de(t))return te;if(t&&typeof t.message=="string"&&t.message.trim()){var e=t.message.trim();return U(e)||D(e)||e.charAt(0)==="{"&&e.indexOf('"message"')!==-1&&e.indexOf('"statusCode"')!==-1?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:e}return I.GENERIC_TRY_AGAIN}function he(t,e){return R+G+t+V+ue(e,R)+k}function fe(t){var e=t.merchantId!=null?String(t.merchantId):"",r=t.widgetId!=null?String(t.widgetId):"",n=t.tryonSessionId!=null?String(t.tryonSessionId):"",s=t.origin!==void 0&&t.origin!==null&&t.origin!==""?String(t.origin):m()||"",l={};return l[F]=s,l[x]=n,l[W]=e,l[B]=r,t.contentType&&(l[H]=t.contentType),l}function Ee(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:m(),pageUrl:oe(),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 ce(t,e,r,n){return!e||e<=0?t: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||$))}},e);t.then(function(d){_||(_=!0,clearTimeout(o),s(d))}).catch(function(d){_||(_=!0,clearTimeout(o),l(d))})})}function N(){if(typeof window>"u"||!window.crypto||!window.crypto.randomUUID)return Y;try{var t=sessionStorage.getItem(p);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 r=window.crypto.randomUUID(),n=Date.now()+L;try{sessionStorage.setItem(p,JSON.stringify({id:r,exp:n}))}catch{}return r}function Te(t,e){var r=e.merchantId!=null?String(e.merchantId).trim():"",n=e.widgetId!=null?String(e.widgetId).trim():"";if(!r||!n)return t;var s;try{s=new URL(t)}catch{return t}s.searchParams.set("merchantId",r),s.searchParams.set("widgetId",n),s.searchParams.set("embed","1");var l=e.tryonSessionId!=null?String(e.tryonSessionId).trim():"";l||(l=N()),l&&s.searchParams.set("tryonSessionId",l);var _=e.sessionToken!=null?String(e.sessionToken).trim():"";return _&&s.searchParams.set("embedSessionToken",_),s.toString()}class Se 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(e,r,n){r!==n&&(this._readAttributes(),this._render())}_log(){if(!(!this._state.debug||typeof console>"u"||!console.log)){var e=Array.prototype.slice.call(arguments);e.unshift(Q),console.log.apply(console,e)}}_readAttributes(){var e=se(this,i.SIMULATION_INLINE_CONFIG),r=!1;e&&e.features&&typeof e.features.showProductPrice=="boolean"&&(r=e.features.showProductPrice);var n=!0;e&&e.features&&typeof e.features.useSimplePage=="boolean"&&(n=e.features.useSimplePage);var s="checkout";e&&e.features&&(e.features.flow==="catalog"||e.features.flow==="checkout")&&(s=e.features.flow);var l=!0;e&&e.features&&typeof e.features.showDetails=="boolean"&&(l=e.features.showDetails);var _="";try{_=le(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:ne(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:e,appId:a(this,i.APP_ID,null)||null,platform:_e(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(e,r){this.dispatchEvent(new CustomEvent(e,{detail:r??null,bubbles:!0,composed:!0}))}_setStatus(e,r){this.setAttribute("data-status",e),this._emit("statusChange",{status:e,detail:r||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(e){var r=e.data;if(!(!r||typeof r!="object")){var n=this._getIframeElement();if(!(!n||!n.contentWindow)&&e.source===n.contentWindow&&!(!this._state.iframeOrigin||e.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 he(this._state.env,this._state.apiPort)}_buildInitPayload(){var e=N();return{tryonSessionId:e,initRequestBody:Ee(this._state,e)}}_normalizeInitResponse(e,r,n){if(!e||typeof e!="object")throw new Error(u.INIT_INVALID_RESPONSE);var s=typeof e.sessionToken=="string"&&e.sessionToken?e.sessionToken:null,l=typeof e.tryonSessionId=="string"&&e.tryonSessionId?e.tryonSessionId:n;if(!s)throw new Error(u.INIT_SESSION_TOKEN_MISSING);var _=typeof e.vtoUrl=="string"&&e.vtoUrl.trim()?e.vtoUrl.trim():null;if(!_&&typeof e.iframeUrl=="string"&&e.iframeUrl.trim()&&(_=e.iframeUrl.trim()),!_)throw new Error(u.INIT_VTO_URL_MISSING);var o=ae(_);if(!o)throw new Error(u.INIT_VTO_URL_INVALID);return{sessionToken:s,tryonSessionId:l,initUrl:r,iframeUrl:_,iframeOrigin:o}}_initializeSessionIfNeeded(){var e=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:fe({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 me=P(d),Ne=Ie(me,d);throw new Error(Ne)})}).then(function(o){return e._normalizeInitResponse(o,s,l.tryonSessionId)});return this._initPromise=ce(_,this._state.initTimeoutMs,j,this._abortController).then(function(o){return n!==e._activeInitRequestId||(e._state.sessionToken=o.sessionToken,e._state.tryonSessionId=o.tryonSessionId,e._state.resolvedInitUrl=o.initUrl,e._state.resolvedIframeUrl=o.iframeUrl,e._state.iframeOrigin=o.iframeOrigin,e._setStatus("ready")),o}).catch(function(o){if(n!==e._activeInitRequestId)throw o;var d=b(o);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(){n===e._activeInitRequestId&&(e._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var e=this._getIframeElement();if(!(!e||!e.contentWindow)){var r=this._state.iframeOrigin;if(!r){this._log(ee.CONFIG_SKIPPED_NO_IFRAME_ORIGIN);return}var n={merchantId:this._state.merchantId,widgetId:this._state.widgetId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||N(),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:m()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(n.inlineVirtualTryonConfig=this._state.simulationInlineConfig),e.contentWindow.postMessage({type:M,payload:n},r)}}_renderLoading(){if(this.shadowRoot){var e=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var r=document.createElement("style");r.textContent=re(e,O);var n=document.createElement("div");n.className=O,n.textContent=X,this.shadowRoot.appendChild(r),this.shadowRoot.appendChild(n)}}_renderError(e){if(this.shadowRoot){var r=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=ie(r,A);var s=document.createElement("div");s.className=A,s.textContent=e||J,this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(s)}}_renderIframe(e,r){if(this.shadowRoot&&!(!e||typeof e!="string"||!e.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=Te(e.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 e=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){e===this._renderVersion&&this._renderIframe(r.iframeUrl,e)}.bind(this)).catch(function(r){if(e===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,Se)})();
|
package/dist/widget.min.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var VitraunWebAR=(()=>{(function(){"use strict";var M="VITRAUN_CONFIG",p="vtrn-vto-session",L=18e5,E=1e4,g="en-US",f="Vitraun",c="vitraun",m="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",K="X-Widget-Id",B="application/json",Y="00000000-0000-0000-0000-000000000000",q=["addToCart","removeFromCart","redirectToCart","analysisFinished"],T="vitraun-vto",Q="["+T+"]",R=c+"-loading",O=c+"-error",z=f+" VTO",X="Loading "+f+"...",J="Failed to load "+f+".",j="Timed out while initializing the "+f+" session.",r={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=[r.MERCHANT_ID,r.WIDGET_ID,r.ENV,r.API_PORT,r.APP_PORT,r.LANG,r.ISOLATED_SKU,r.APPLY_SKUS,r.FLOW,r.BASKET_OPENS_IN,r.CHECKOUT_OPENS_IN,r.USE_SIMPLE_PAGE,r.SHOW_DETAILS,r.SHOW_PRODUCT_PRICE,r.PRICE_FROM,r.PRICE_TO,r.CURRENCY_SYMBOL,r.IS_SIMULATION_MODE,r.SIMULATION_INLINE_CONFIG,r.CONTAINER_MIN_HEIGHT,r.APP_ID,r.PLATFORM,r.BUNDLE_ID,r.PACKAGE_NAME,r.APP_VERSION,r.ATTESTATION_TOKEN,r.DEBUG,r.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.",A={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 it(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 rt(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,i){var n=e.getAttribute(t);return n!=null&&n!==""?n:i}function h(e,t){if(e==null||e==="")return t;var i=String(e).toLowerCase();return i==="true"||i==="1"||i==="yes"}function v(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 i=a(e,t,"");if(!i||typeof i!="string")return null;try{return JSON.parse(i)}catch(n){return null}}function y(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 P(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 i=parseInt(String(e),10);return!Number.isInteger(i)||i<=0||i>65535||t==="https://"&&i===443||t==="http://"&&i===80?"":":"+i}function C(e){return!e||typeof e!="object"?!1:!!Array.isArray(e.message)}function w(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 U(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 i=y(t);return C(i)}function It(e,t){if(C(e))return I.GENERIC_SERVER_OR_CLIENT_MISMATCH;var i=e&&typeof e.errorCode=="string"?e.errorCode:null;if(i&&Object.prototype.hasOwnProperty.call(A,i))return A[i];var n=e&&typeof e.message=="string"?e.message.trim():"";if(n)return w(n)?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:n;if(i)return I.GENERIC_TRY_AGAIN_OR_STORE;if(t&&String(t).length>0&&String(t).length<600){var s=String(t).trim();return U(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,i=e.message.toLowerCase();return t==="TypeError"&&(i.indexOf("failed to fetch")!==-1||i.indexOf("load failed")!==-1)||i.indexOf("networkerror when attempting to fetch")!==-1||t==="NetworkError"||i.indexOf("network request failed")!==-1}function D(e){if(dt(e))return et;if(e&&typeof e.message=="string"&&e.message.trim()){var t=e.message.trim();return w(t)||U(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 m+G+e+V+ut(t,m)+k}function ft(e){var t=e.merchantId!=null?String(e.merchantId):"",i=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()||"",_={};return _[F]=s,_[x]=n,_[W]=t,_[K]=i,e.contentType&&(_[H]=e.contentType),_}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,i,n){return!t||t<=0?e:new Promise(function(s,_){var l=!1,o=setTimeout(function(){if(!l){l=!0;try{n&&typeof n.abort=="function"&&n.abort()}catch(d){}_(new Error(i||$))}},t);e.then(function(d){l||(l=!0,clearTimeout(o),s(d))}).catch(function(d){l||(l=!0,clearTimeout(o),_(d))})})}function b(){if(typeof window=="undefined"||!window.crypto||!window.crypto.randomUUID)return Y;try{var e=sessionStorage.getItem(p);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 i=window.crypto.randomUUID(),n=Date.now()+L;try{sessionStorage.setItem(p,JSON.stringify({id:i,exp:n}))}catch(s){}return i}class Tt 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,i,n){i!==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,r.SIMULATION_INLINE_CONFIG),i=!1;t&&t.features&&typeof t.features.showProductPrice=="boolean"&&(i=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 _=!0;t&&t.features&&typeof t.features.showDetails=="boolean"&&(_=t.features.showDetails);var l="";try{l=lt(a(this,r.ENV,""))}catch(d){l=""}var o=parseInt(a(this,r.INIT_TIMEOUT_MS,String(E)),10);(!Number.isFinite(o)||o<0)&&(o=E),this._state={merchantId:a(this,r.MERCHANT_ID,""),widgetId:a(this,r.WIDGET_ID,""),env:l,apiPort:P(a(this,r.API_PORT,null)),appPort:P(a(this,r.APP_PORT,null)),lang:a(this,r.LANG,g),isolatedSku:a(this,r.ISOLATED_SKU,null)||null,applySkus:nt(a(this,r.APPLY_SKUS,"")),iframeOrigin:this._state&&this._state.iframeOrigin?this._state.iframeOrigin:null,flow:a(this,r.FLOW,s),basketOpensIn:a(this,r.BASKET_OPENS_IN,"event"),checkoutOpensIn:a(this,r.CHECKOUT_OPENS_IN,"event"),useSimplePage:h(a(this,r.USE_SIMPLE_PAGE,""),n),showDetails:h(a(this,r.SHOW_DETAILS,""),_),showProductPrice:h(a(this,r.SHOW_PRODUCT_PRICE,""),i),priceFrom:v(a(this,r.PRICE_FROM,null)),priceTo:v(a(this,r.PRICE_TO,null)),currencySymbol:a(this,r.CURRENCY_SYMBOL,null)||null,isSimulationMode:h(a(this,r.IS_SIMULATION_MODE,"false"),!1),simulationInlineConfig:t,appId:a(this,r.APP_ID,null)||null,platform:_t(a(this,r.PLATFORM,null)),bundleId:a(this,r.BUNDLE_ID,null)||null,packageName:a(this,r.PACKAGE_NAME,null)||null,appVersion:a(this,r.APP_VERSION,null)||null,attestationToken:a(this,r.ATTESTATION_TOKEN,null)||null,debug:h(a(this,r.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,i){this.dispatchEvent(new CustomEvent(t,{detail:i!=null?i:null,bubbles:!0,composed:!0}))}_setStatus(t,i){this.setAttribute("data-status",t),this._emit("statusChange",{status:t,detail:i||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(t){var i=t.data;if(!(!i||typeof i!="object")){var n=this._getIframeElement();if(!(!n||!n.contentWindow)&&t.source===n.contentWindow&&!(!this._state.iframeOrigin||t.origin!==this._state.iframeOrigin)){var s=i.type,_=i.detail;if(s==="VTO_USAGE"){this._emit("vtoUsage",_);return}q.indexOf(s)!==-1&&this._emit(s,_)}}}_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=b();return{tryonSessionId:t,initRequestBody:Et(this._state,t)}}_normalizeInitResponse(t,i,n){if(!t||typeof t!="object")throw new Error(u.INIT_INVALID_RESPONSE);var s=typeof t.sessionToken=="string"&&t.sessionToken?t.sessionToken:null,_=typeof t.tryonSessionId=="string"&&t.tryonSessionId?t.tryonSessionId:n;if(!s)throw new Error(u.INIT_SESSION_TOKEN_MISSING);var l=typeof t.vtoUrl=="string"&&t.vtoUrl.trim()?t.vtoUrl.trim():null;if(!l&&typeof t.iframeUrl=="string"&&t.iframeUrl.trim()&&(l=t.iframeUrl.trim()),!l)throw new Error(u.INIT_VTO_URL_MISSING);var o=at(l);if(!o)throw new Error(u.INIT_VTO_URL_INVALID);return{sessionToken:s,tryonSessionId:_,initUrl:i,iframeUrl:l,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 i=this._getInitStateKey();if(this._initPromise&&this._initStateKey===i)return this._initPromise;if(this._abortController&&typeof this._abortController.abort=="function")try{this._abortController.abort()}catch(o){}this._initStateKey=i,this._activeInitRequestId+=1;var n=this._activeInitRequestId;this._setStatus("loading");var s;try{s=this._buildEmbedInitUrl()}catch(o){return Promise.reject(o)}var _=this._buildInitPayload();this._state.tryonSessionId=_.tryonSessionId,this._abortController=typeof AbortController!="undefined"?new AbortController:null;var l=fetch(s,{method:"POST",headers:ft({merchantId:this._state.merchantId,widgetId:this._state.widgetId,tryonSessionId:_.tryonSessionId,contentType:B}),body:JSON.stringify(_.initRequestBody),signal:this._abortController?this._abortController.signal:void 0}).then(function(o){return o.ok?o.json():o.text().then(function(d){var St=y(d),Nt=It(St,d);throw new Error(Nt)})}).then(function(o){return t._normalizeInitResponse(o,s,_.tryonSessionId)});return this._initPromise=ct(l,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=D(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 i=this._state.iframeOrigin;if(!i){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||b(),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},i)}}_renderLoading(){if(this.shadowRoot){var t=a(this,r.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var i=document.createElement("style");i.textContent=it(t,R);var n=document.createElement("div");n.className=R,n.textContent=X,this.shadowRoot.appendChild(i),this.shadowRoot.appendChild(n)}}_renderError(t){if(this.shadowRoot){var i=a(this,r.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=rt(i,O);var s=document.createElement("div");s.className=O,s.textContent=t||J,this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(s)}}_renderIframe(t,i){if(this.shadowRoot&&!(!t||typeof t!="string"||!t.trim())){var n=this,s=a(this,r.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var _=document.createElement("style");_.textContent=S(s);var l=document.createElement("iframe");l.src=t,l.title=z,l.style.cssText="width:100%;height:100%;border:0;min-height:"+s,l.setAttribute("allow","camera"),l.setAttribute("referrerpolicy","strict-origin-when-cross-origin"),l.onload=function(){i===n._renderVersion&&[0,50,150,400,1e3].forEach(function(o){setTimeout(function(){i===n._renderVersion&&n._sendConfigToIframe()},o)})},this.shadowRoot.appendChild(_),this.shadowRoot.appendChild(l)}}_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(i){t===this._renderVersion&&this._renderIframe(i.iframeUrl,t)}.bind(this)).catch(function(i){if(t===this._renderVersion){var n=D(i instanceof Error?i:new Error(String(i)));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,Tt)})();})();
|
|
1
|
+
"use strict";var VitraunWebAR=(()=>{(function(){"use strict";var M="VITRAUN_CONFIG",p="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.",ee={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."},te="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(t){return":host { display:block; width:100%; min-height:"+t+"; box-sizing:border-box; }"}function re(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 ie(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 a(t,e,r){var n=t.getAttribute(e);return n!=null&&n!==""?n:r}function h(t,e){if(t==null||t==="")return e;var r=String(t).toLowerCase();return r==="true"||r==="1"||r==="yes"}function y(t){if(t==null||t==="")return null;var e=parseFloat(String(t));return Number.isFinite(e)?e:null}function ne(t){return!t||typeof t!="string"?[]:t.split(",").map(function(e){return e.trim()}).filter(Boolean)}function se(t,e){var r=a(t,e,"");if(!r||typeof r!="string")return null;try{return JSON.parse(r)}catch(n){return null}}function P(t){try{return JSON.parse(t)}catch(e){return null}}function m(){return typeof window=="undefined"||!window.location||!window.location.origin?null:window.location.origin}function oe(){return typeof window=="undefined"||!window.location||!window.location.href?null:window.location.href}function ae(t){if(!t||typeof t!="string")return null;try{return new URL(t).origin}catch(e){return null}}function le(t){var e=String(t||"").trim().toLowerCase();if(!e)throw new Error(u.ENV_REQUIRED);if(!/^[a-z0-9-]+$/.test(e))throw new Error(u.ENV_INVALID);return e}function _e(t){return t?String(t).trim().toLowerCase():"web"}function C(t){if(t==null||t==="")return null;var e=parseInt(String(t),10);return!Number.isInteger(e)||e<=0||e>65535?null:e}function ue(t,e){if(t==null||t==="")return"";var r=parseInt(String(t),10);return!Number.isInteger(r)||r<=0||r>65535||e==="https://"&&r===443||e==="http://"&&r===80?"":":"+r}function w(t){return!t||typeof t!="object"?!1:!!Array.isArray(t.message)}function U(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 D(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 r=P(e);return w(r)}function Ie(t,e){if(w(t))return I.GENERIC_SERVER_OR_CLIENT_MISMATCH;var r=t&&typeof t.errorCode=="string"?t.errorCode:null;if(r&&Object.prototype.hasOwnProperty.call(v,r))return v[r];var n=t&&typeof t.message=="string"?t.message.trim():"";if(n)return U(n)?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:n;if(r)return I.GENERIC_TRY_AGAIN_OR_STORE;if(e&&String(e).length>0&&String(e).length<600){var s=String(e).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 de(t){if(!t||typeof t.message!="string")return!1;var e=t.name,r=t.message.toLowerCase();return e==="TypeError"&&(r.indexOf("failed to fetch")!==-1||r.indexOf("load failed")!==-1)||r.indexOf("networkerror when attempting to fetch")!==-1||e==="NetworkError"||r.indexOf("network request failed")!==-1}function b(t){if(de(t))return te;if(t&&typeof t.message=="string"&&t.message.trim()){var e=t.message.trim();return U(e)||D(e)||e.charAt(0)==="{"&&e.indexOf('"message"')!==-1&&e.indexOf('"statusCode"')!==-1?I.GENERIC_SERVER_OR_CLIENT_MISMATCH:e}return I.GENERIC_TRY_AGAIN}function he(t,e){return R+G+t+V+ue(e,R)+k}function fe(t){var e=t.merchantId!=null?String(t.merchantId):"",r=t.widgetId!=null?String(t.widgetId):"",n=t.tryonSessionId!=null?String(t.tryonSessionId):"",s=t.origin!==void 0&&t.origin!==null&&t.origin!==""?String(t.origin):m()||"",l={};return l[F]=s,l[x]=n,l[W]=e,l[B]=r,t.contentType&&(l[H]=t.contentType),l}function Ee(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:m(),pageUrl:oe(),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 ce(t,e,r,n){return!e||e<=0?t: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||$))}},e);t.then(function(d){_||(_=!0,clearTimeout(o),s(d))}).catch(function(d){_||(_=!0,clearTimeout(o),l(d))})})}function N(){if(typeof window=="undefined"||!window.crypto||!window.crypto.randomUUID)return Y;try{var t=sessionStorage.getItem(p);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(s){}var r=window.crypto.randomUUID(),n=Date.now()+L;try{sessionStorage.setItem(p,JSON.stringify({id:r,exp:n}))}catch(s){}return r}function Te(t,e){var r=e.merchantId!=null?String(e.merchantId).trim():"",n=e.widgetId!=null?String(e.widgetId).trim():"";if(!r||!n)return t;var s;try{s=new URL(t)}catch(o){return t}s.searchParams.set("merchantId",r),s.searchParams.set("widgetId",n),s.searchParams.set("embed","1");var l=e.tryonSessionId!=null?String(e.tryonSessionId).trim():"";l||(l=N()),l&&s.searchParams.set("tryonSessionId",l);var _=e.sessionToken!=null?String(e.sessionToken).trim():"";return _&&s.searchParams.set("embedSessionToken",_),s.toString()}class Se 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(e){}}attributeChangedCallback(e,r,n){r!==n&&(this._readAttributes(),this._render())}_log(){if(!(!this._state.debug||typeof console=="undefined"||!console.log)){var e=Array.prototype.slice.call(arguments);e.unshift(Q),console.log.apply(console,e)}}_readAttributes(){var e=se(this,i.SIMULATION_INLINE_CONFIG),r=!1;e&&e.features&&typeof e.features.showProductPrice=="boolean"&&(r=e.features.showProductPrice);var n=!0;e&&e.features&&typeof e.features.useSimplePage=="boolean"&&(n=e.features.useSimplePage);var s="checkout";e&&e.features&&(e.features.flow==="catalog"||e.features.flow==="checkout")&&(s=e.features.flow);var l=!0;e&&e.features&&typeof e.features.showDetails=="boolean"&&(l=e.features.showDetails);var _="";try{_=le(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:ne(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:e,appId:a(this,i.APP_ID,null)||null,platform:_e(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(e,r){this.dispatchEvent(new CustomEvent(e,{detail:r!=null?r:null,bubbles:!0,composed:!0}))}_setStatus(e,r){this.setAttribute("data-status",e),this._emit("statusChange",{status:e,detail:r||null})}_getIframeElement(){return this.shadowRoot?this.shadowRoot.querySelector("iframe"):null}_handleMessage(e){var r=e.data;if(!(!r||typeof r!="object")){var n=this._getIframeElement();if(!(!n||!n.contentWindow)&&e.source===n.contentWindow&&!(!this._state.iframeOrigin||e.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 he(this._state.env,this._state.apiPort)}_buildInitPayload(){var e=N();return{tryonSessionId:e,initRequestBody:Ee(this._state,e)}}_normalizeInitResponse(e,r,n){if(!e||typeof e!="object")throw new Error(u.INIT_INVALID_RESPONSE);var s=typeof e.sessionToken=="string"&&e.sessionToken?e.sessionToken:null,l=typeof e.tryonSessionId=="string"&&e.tryonSessionId?e.tryonSessionId:n;if(!s)throw new Error(u.INIT_SESSION_TOKEN_MISSING);var _=typeof e.vtoUrl=="string"&&e.vtoUrl.trim()?e.vtoUrl.trim():null;if(!_&&typeof e.iframeUrl=="string"&&e.iframeUrl.trim()&&(_=e.iframeUrl.trim()),!_)throw new Error(u.INIT_VTO_URL_MISSING);var o=ae(_);if(!o)throw new Error(u.INIT_VTO_URL_INVALID);return{sessionToken:s,tryonSessionId:l,initUrl:r,iframeUrl:_,iframeOrigin:o}}_initializeSessionIfNeeded(){var e=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:fe({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 me=P(d),Ne=Ie(me,d);throw new Error(Ne)})}).then(function(o){return e._normalizeInitResponse(o,s,l.tryonSessionId)});return this._initPromise=ce(_,this._state.initTimeoutMs,j,this._abortController).then(function(o){return n!==e._activeInitRequestId||(e._state.sessionToken=o.sessionToken,e._state.tryonSessionId=o.tryonSessionId,e._state.resolvedInitUrl=o.initUrl,e._state.resolvedIframeUrl=o.iframeUrl,e._state.iframeOrigin=o.iframeOrigin,e._setStatus("ready")),o}).catch(function(o){if(n!==e._activeInitRequestId)throw o;var d=b(o);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(){n===e._activeInitRequestId&&(e._initPromise=null)}),this._initPromise}_sendConfigToIframe(){var e=this._getIframeElement();if(!(!e||!e.contentWindow)){var r=this._state.iframeOrigin;if(!r){this._log(ee.CONFIG_SKIPPED_NO_IFRAME_ORIGIN);return}var n={merchantId:this._state.merchantId,widgetId:this._state.widgetId,sessionToken:this._state.sessionToken,tryonSessionId:this._state.tryonSessionId||N(),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:m()};this._state.isSimulationMode&&this._state.simulationInlineConfig&&typeof this._state.simulationInlineConfig=="object"&&(n.inlineVirtualTryonConfig=this._state.simulationInlineConfig),e.contentWindow.postMessage({type:M,payload:n},r)}}_renderLoading(){if(this.shadowRoot){var e=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var r=document.createElement("style");r.textContent=re(e,O);var n=document.createElement("div");n.className=O,n.textContent=X,this.shadowRoot.appendChild(r),this.shadowRoot.appendChild(n)}}_renderError(e){if(this.shadowRoot){var r=a(this,i.CONTAINER_MIN_HEIGHT,"80vh");this.shadowRoot.innerHTML="";var n=document.createElement("style");n.textContent=ie(r,A);var s=document.createElement("div");s.className=A,s.textContent=e||J,this.shadowRoot.appendChild(n),this.shadowRoot.appendChild(s)}}_renderIframe(e,r){if(this.shadowRoot&&!(!e||typeof e!="string"||!e.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=Te(e.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 e=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){e===this._renderVersion&&this._renderIframe(r.iframeUrl,e)}.bind(this)).catch(function(r){if(e===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,Se)})();})();
|