@liquidcommerce/cloud-sdk 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t,r,i,a,s,n,o,c,l,h,d,I,u,A,E,S,p,v,R,m=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(e=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).DEV="dev",e.STAGE="stage",function(e){e.ON_DEMAND="onDemand",e.SHIPPING="shipping"}(t||(t={})),function(e){e.MONDAY="monday",e.TUESDAY="tuesday",e.WEDNESDAY="wednesday",e.THURSDAY="thursday",e.FRIDAY="friday",e.SATURDAY="saturday",e.SUNDAY="sunday"}(r||(r={})),function(e){e.AL="AL",e.AK="AK",e.AR="AR",e.CA="CA",e.CO="CO",e.CT="CT",e.DE="DE",e.DC="DC",e.FL="FL",e.GA="GA",e.HI="HI",e.ID="ID",e.IL="IL",e.IN="IN",e.IA="IA",e.KS="KS",e.KY="KY",e.LA="LA",e.ME="ME",e.MD="MD",e.MA="MA",e.MI="MI",e.MN="MN",e.MS="MS",e.MO="MO",e.MT="MT",e.NE="NE",e.NV="NV",e.NH="NH",e.NJ="NJ",e.NM="NM",e.NY="NY",e.NC="NC",e.ND="ND",e.OH="OH",e.OK="OK",e.OR="OR",e.PA="PA",e.RI="RI",e.SC="SC",e.SD="SD",e.TN="TN",e.TX="TX",e.UT="UT",e.VT="VT",e.VA="VA",e.WA="WA",e.WV="WV",e.WI="WI",e.WY="WY"}(i||(i={})),function(e){e.ALABAMA="AL",e.ALASKA="AK",e.ARKANSAS="AR",e.CALIFORNIA="CA",e.COLORADO="CO",e.CONNECTICUT="CT",e.DELAWARE="DE",e.DISTRICT_OF_COLUMBIA="DC",e.FLORIDA="FL",e.GEORGIA="GA",e.HAWAII="HI",e.IDAHO="ID",e.ILLINOIS="IL",e.INDIANA="IN",e.IOWA="IA",e.KANSAS="KS",e.KENTUCKY="KY",e.LOUISIANA="LA",e.MAINE="ME",e.MARYLAND="MD",e.MASSACHUSETTS="MA",e.MICHIGAN="MI",e.MINNESOTA="MN",e.MISSISSIPPI="MS",e.MISSOURI="MO",e.MONTANA="MT",e.NEBRASKA="NE",e.NEVADA="NV",e.NEW_HAMPSHIRE="NH",e.NEW_JERSEY="NJ",e.NEW_MEXICO="NM",e.NEW_YORK="NY",e.NORTH_CAROLINA="NC",e.NORTH_DAKOTA="ND",e.OHIO="OH",e.OKLAHOMA="OK",e.OREGON="OR",e.PENNSYLVANIA="PA",e.RHODE_ISLAND="RI",e.SOUTH_CAROLINA="SC",e.SOUTH_DAKOTA="SD",e.TENNESSEE="TN",e.TEXAS="TX",e.UTAH="UT",e.VERMONT="VT",e.VIRGINIA="VA",e.WASHINGTON="WA",e.WEST_VIRGINIA="WV",e.WISCONSIN="WI",e.WYOMING="WY"}(a||(a={})),function(e){e.ALE="BEER > ALE",e.LAGER="BEER > LAGER",e.MAIN="BEER",e.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",e.OTHER_BEER="BEER > OTHER BEER"}(s||(s={})),function(e){e.BASE="FOOD",e.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(n||(n={})),function(e){e.BASE="MERCHANDISE",e.GLASSWARE="MERCHANDISE > GLASSWARE",e.HUMIDOR="MERCHANDISE > HUMIDOR"}(o||(o={})),function(e){e.BASE="MISCELLANEOUS",e.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",e.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",e.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(c||(c={})),function(e){e.BASE="NON ALCOHOLIC",e.BITTERS="NON ALCOHOLIC > BITTERS",e.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",e.COFFEE="NON ALCOHOLIC > COFFEE",e.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",e.JUICE="NON ALCOHOLIC > JUICE",e.SODA="NON ALCOHOLIC > SODA",e.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",e.SPIRITS="NON ALCOHOLIC > SPIRITS",e.TEA="NON ALCOHOLIC > TEA",e.WATER="NON ALCOHOLIC > WATER",e.WINE="NON ALCOHOLIC > WINE"}(l||(l={})),function(e){e.BASE="READY TO DRINK",e.HARD_CIDER="READY TO DRINK > HARD CIDER",e.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",e.HARD_TEA="READY TO DRINK > HARD TEA",e.MALT_BASED="READY TO DRINK > MALT BASED",e.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",e.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",e.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",e.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",e.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",e.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(h||(h={})),function(e){e.BASE="SPIRITS",e.BAIJIU="SPIRITS > BAIJIU",e.BITTERS="SPIRITS > BITTERS",e.BRANDY="SPIRITS > BRANDY",e.CACHACA="SPIRITS > CACHACA",e.GIN="SPIRITS > GIN",e.LAGER="SPIRITS > LAGER",e.LIQUEUR="SPIRITS > LIQUEUR",e.MEZCAL="SPIRITS > MEZCAL",e.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",e.RUM="SPIRITS > RUM",e.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",e.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",e.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",e.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",e.RUM_OTHER="SPIRITS > RUM > OTHER",e.RUM_SPICED="SPIRITS > RUM > SPICED",e.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",e.SOJU="SPIRITS > SOJU",e.TEQUILA="SPIRITS > TEQUILA",e.VODKA="SPIRITS > VODKA",e.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",e.WHISKEY="SPIRITS > WHISKEY",e.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",e.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",e.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",e.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",e.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(d||(d={})),function(e){e.BASE="WINE",e.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",e.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",e.COOKING="WINE > COOKING",e.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",e.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",e.RED_WINE="WINE > RED WINE",e.ROSE_WINE="WINE > ROSE WINE",e.SAKE="WINE > SAKE",e.WHITE_WINE="WINE > WHITE WINE"}(I||(I={})),function(e){e.BRANDS="brands",e.FLAVOR="flavor",e.REGION="region",e.VARIETY="variety",e.PRICE="price",e.AVAILABILITY="availability",e.CATEGORIES="categories",e.SIZES="sizes",e.COLORS="colors",e.APPELLATION="appellation",e.COUNTRY="country",e.VINTAGE="vintage",e.MATERIALS="materials"}(u||(u={})),function(e){e.ASC="asc",e.DESC="desc"}(A||(A={})),function(e){e.PRICE="price"}(E||(E={})),function(e){e.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",e.IN_STOCK="IN_STOCK",e.OUT_OF_STOCK="OUT_OF_STOCK",e.PREORDER="PREORDER",e.BACKORDER="BACKORDER"}(S||(S={})),function(e){e.INVALID_ITEMS_TYPE="Items must be a non-empty array",e.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",e.INVALID_PART_NUMBER="The partnerNumber provided is invalid",e.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(p||(p={})),function(e){e.OOS="OutOfStock",e.ITEMS_NOT_ADDED="ItemsNotAdded",e.ITEM_NOT_ENGRAVED="ItemEngravingError",e.ADDRESS_CHANGE="AddressChange",e.RETAILER_MIN="RetailerMinNotMet",e.NO_ITEMS_IN_CART="NoItemsInCart",e.INVALID_ID="InvalidId",e.NO_ID="NoId",e.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",e.NEW_CART="NewCart",e.DEFAULT="CartError",e.ITEM_QTY_CHANGE="ItemQuantityChange"}(v||(v={})),function(e){e.SHIPPING="shipping",e.BILLING="billing"}(R||(R={}));const C={[exports.LIQUID_COMMERCE_ENV.DEV]:"https://dev.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api"};class N{constructor(e){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(e,t)=>new Promise(((r,i)=>{const a=new XMLHttpRequest;a.open(t.method||"GET",e),Object.entries(t.headers).forEach((([e,t])=>{a.setRequestHeader(e,t)})),a.onload=()=>{r({ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,headers:a.getAllResponseHeaders().split("\r\n").reduce(((e,t)=>{const[r,i]=t.split(": ");return r&&(e[r]=i),e}),{}),json:()=>Promise.resolve(JSON.parse(a.responseText)),text:()=>Promise.resolve(a.responseText)})},a.onerror=()=>{i(new TypeError("Network request failed"))},a.send(t.body)})),this.apiKey=e.apiKey,this.baseURL=e.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(e){return N.instance||(N.instance=new N(e)),N.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):"undefined"!=typeof window&&window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(e){return async(t,r)=>{var i;const a=await e(t,r);let s;return"function"==typeof(null===(i=a.headers)||void 0===i?void 0:i.entries)?s=Object.fromEntries(a.headers.entries()):(s={},a.headers.forEach(((e,t)=>{s[t]=e}))),{ok:a.ok,status:a.status,statusText:a.statusText,headers:s,json:()=>a.json(),text:()=>a.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var e,t;if(this.isAuthenticating)await new Promise((e=>{const t=()=>{this.isAuthenticating?setTimeout(t,100):e(void 0)};t()}));else{this.isAuthenticating=!0;try{const r=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.token,this.tokenExpiration=Date.now()+1e3*(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.exp)}catch(e){throw console.error("Authentication failed:",e),new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(e,t){const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...t.headers},a={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(r.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(e,t){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...t.headers},a={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(r.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}async get(e,t){return this.request(e,{method:"GET",headers:t})}async post(e,t,r){return this.request(e,{method:"POST",body:t,headers:r})}async put(e,t,r){return this.request(e,{method:"PUT",body:t,headers:r})}async delete(e,t){return this.request(e,{method:"DELETE",headers:t})}}N.instance=null;class O{constructor(e){this.locationHelperService=e}validateAndNormalizeParams(e){const t={...e};return t.id=this.validateId(t.id),t.items=this.validateAndNormalizeItems(t.items),this.locationHelperService.validateAndNormalizeLocation(t.loc),t.refresh=Boolean(t.refresh),t}validateId(e){return e&&"string"==typeof e&&0!==e.trim().length?e.trim():""}validateAndNormalizeItems(e){if(!Array.isArray(e)||0===e.length)throw new Error(p.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(p.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(p.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(p.INVALID_FULFILLMENT_ID);return t.quantity=Math.max(0,Math.floor(t.quantity)),t.engravingLines&&(t.engravingLines=t.engravingLines.map((e=>e.trim())).filter((e=>e.length>0))),t}validatePartNumber(e){if(!e||"string"!=typeof e)return!1;const t=e.split("_");return 2===t.length&&14===t[0].length&&t[1].length>0}}class T{constructor(e){this.locationServiceHelper=e,this.taxonomyValues=new Set([...Object.values(s),...Object.values(n),...Object.values(o),...Object.values(l),...Object.values(h),...Object.values(d),...Object.values(I)])}validateAndNormalizeParams(e){const t={...e};return this.validateUPCs(t.upcs),this.locationServiceHelper.validateAndNormalizeLocation(t.loc),t}validateAndNormalizeSearchParams(e){const t=[],r={...e};return this.validateOrderBy(r.orderBy,t),this.validateOrderDirection(r.orderDirection,t),this.validateFilters(r.filters,t),this.validatePagination(r.page,r.perPage,t),this.locationServiceHelper.validateAndNormalizeLocation(r.loc),t.length>0?{...r,error:t.join(". ")}:r}validateUPCs(e){if(!Array.isArray(e)||0===e.length)throw new Error("UPCs must be a non-empty array of strings");if(!e.every((e=>"string"==typeof e&&e.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(e,t){e&&!Object.values(E).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(A).includes(e)&&t.push(`Invalid orderDirection value: ${e}`)}validateFilters(e,t){e&&(e.length>10&&t.push("Maximum of 10 filters allowed"),e.forEach((e=>{switch(Object.values(u).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case u.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case u.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case u.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case u.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(S).includes(e)||t.push(`Invalid availability value: ${e}`)}validateArrayFilter(e,t,r,i){Array.isArray(e)?e.length>t&&i.push(`${r} filter can have a maximum of ${t} values`):i.push(`${r} filter must be an array`)}validateCategoriesFilter(e,t){Array.isArray(e)?e.every((e=>this.taxonomyValues.has(e)))||t.push("Invalid category value(s) in categories filter"):t.push("Categories filter must be an array")}validatePagination(e,t,r){void 0!==e&&("number"!=typeof e||e<0)&&r.push("Page must be a non-negative number"),void 0!==t&&("number"!=typeof t||t<=0)&&r.push("PerPage must be a positive number")}}class y{constructor(e){this.locationHelperService=e}validateAndNormalizePrepareParams(e){const t={...e};if(!t.cartId||"string"!=typeof t.cartId)throw new Error("Invalid cartId");return this.validateRecipient(t.recipient),t.billingAddress&&this.validateAddress(t.billingAddress),t.hasSubstitutionPolicy=Boolean(t.hasSubstitutionPolicy),t.isGift=Boolean(t.isGift),t.billingSameAsShipping=Boolean(t.billingSameAsShipping),t.isGift&&this.validateGiftOptions(t.giftOptions),this.validateMarketingPreferences(t.marketingPreferences),t.deliveryTips&&this.validateDeliveryTips(t.deliveryTips),t.refresh=Boolean(t.refresh),t}validateAndNormalizeCompleteParams(e){const t={...e};if(!t.token||"string"!=typeof t.token)throw new Error("Invalid token");if(!t.payment||"string"!=typeof t.payment)throw new Error("Invalid payment token");return void 0!==t.refresh&&(t.refresh=Boolean(t.refresh)),t}validateRecipient(e){if(!e||"object"!=typeof e)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid recipient ${t}`)})),e.hasAgeVerify=Boolean(e.hasAgeVerify)}validateAddress(e){if(!e||"object"!=typeof e)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid address ${t}`)})),this.locationHelperService.validateAndNormalizeLocation({address:e})}validateGiftOptions(e){if(!e||"object"!=typeof e)throw new Error("Invalid giftOptions");if(e.message&&"string"!=typeof e.message)throw new Error("Invalid gift message");if(e.recipient){const{name:t,phone:r,email:i}=e.recipient;if(t&&"string"!=typeof t)throw new Error("Invalid gift recipient name");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient phone");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(e){if(!e||"object"!=typeof e)throw new Error("Invalid marketingPreferences");e.canEmail=Boolean(e.canEmail),e.canSms=Boolean(e.canSms)}validateDeliveryTips(e){if(!Array.isArray(e))throw new Error("Invalid deliveryTips");e.forEach((e=>{if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof e.tip||e.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class g{validateAndNormalizeLocation(e){if(!e||"object"!=typeof e)throw new Error("Location must be a valid object");if(e.coords)this.validateCoordinates(e.coords);else{if(!e.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(e.address)}}validateCoordinates(e){if("number"!=typeof e.lat||"number"!=typeof e.long)throw new Error("Coordinates must be valid numbers");if(e.lat<-90||e.lat>90||e.long<-180||e.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(e){if(!e.state||"string"!=typeof e.state)throw new Error("State is required and must be a string");if(e.state=this.normalizeState(e.state),!e.city||"string"!=typeof e.city)throw new Error("City is required and must be a string");if(!e.zip||"string"!=typeof e.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(e){const t=e.toUpperCase();if(i[t])return i[t];const r=e.toUpperCase();if(a[r])return a[r];throw new Error(`Invalid state: ${e}`)}}class f{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(e){if(!document.getElementById(e.elementId))throw new Error(`Element with id "${e.elementId}" not found`);try{this.stripe=await m.loadStripe(e.key)}catch(e){throw console.error("Failed to load Stripe:",e),new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const t={clientSecret:e.clientSecret,appearance:this.mapAppearance(e.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(t);const r=this.mapElementOptions(e.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${e.elementId}`)}async generateToken(){var e,t,r,i,a,s,n,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:c}=await this.elements.submit();if(c)return{type:"validation_error",message:c.message,code:c.code};const{error:l,paymentMethod:h}=await this.stripe.createPaymentMethod({elements:this.elements});return l?{type:"validation_error"===l.type?"validation_error":"api_error",message:l.message,code:l.code,param:l.param}:h?{id:h.id,type:h.type,card:(null==h?void 0:h.card)?{brand:null!==(t=null===(e=h.card)||void 0===e?void 0:e.brand)&&void 0!==t?t:"",country:null!==(r=h.card.country)&&void 0!==r?r:"",expMonth:null!==(i=h.card.exp_month)&&void 0!==i?i:0,expYear:null!==(a=h.card.exp_year)&&void 0!==a?a:0,last4:null!==(s=h.card.last4)&&void 0!==s?s:"",funding:null!==(n=h.card.funding)&&void 0!==n?n:""}:void 0,created:null!==(o=null==h?void 0:h.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.on(e,t)}unsubscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.off(e,t)}mapAppearance(e){if(e)return{theme:"night"===e.theme?"night":"stripe"}}mapElementOptions(e){return{layout:null==e?void 0:e.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class D{constructor(e){this.client=e}async autocomplete(e,t){try{return await this.client.post("/address/autocomplete",{...e,key:t})}catch(e){throw console.error("Address autocomplete request failed:",e),e}}async details(e,t){try{return await this.client.post("/address/details",{...e,key:t})}catch(e){throw console.error("Address details request failed:",e),e}}}class L{constructor(e,t){this.client=e,this.cartHelperService=t,this.servicePath="/cart/update"}async get(e,t){try{let r=this.cartHelperService.validateId(e);if(r=""!==r&&r,r){const e={id:r};return"boolean"==typeof t&&(e.refresh=t),await this.client.post(this.servicePath,e)}return await this.client.post(this.servicePath)}catch(e){throw console.error("Cart update request failed:",e),e}}async update(e){try{const t=this.cartHelperService.validateAndNormalizeParams(e);return await this.client.post(this.servicePath,t)}catch(e){throw console.error("Cart update request failed:",e),e}}}class w{constructor(e,t){this.client=e,this.catalogHelperService=t,this.servicePath="/catalog/"}async availability(e){try{const t=this.catalogHelperService.validateAndNormalizeParams(e);return await this.client.post(`${this.servicePath}availability`,t)}catch(e){throw console.error("Catalog availability request failed:",e),e}}async search(e){try{const t=this.catalogHelperService.validateAndNormalizeSearchParams(e);if(null==t?void 0:t.error)throw new Error(null==t?void 0:t.error);return await this.client.post(`${this.servicePath}search`,t)}catch(e){throw console.error("Catalog search request failed:",e),e}}}class P{constructor(e,t){this.client=e,this.checkoutHelperService=t,this.servicePath="/checkout"}async prepare(e){try{const t=this.checkoutHelperService.validateAndNormalizePrepareParams(e);return await this.client.post(`${this.servicePath}/prepare`,t)}catch(e){throw console.error("Checkout prepare request failed:",e),e}}async complete(e){try{const t=this.checkoutHelperService.validateAndNormalizeCompleteParams(e);return await this.client.post(`${this.servicePath}/complete`,t)}catch(e){throw console.error("Checkout complete request failed:",e),e}}}class M{constructor(e){this.paymentProvider=e}async mount(e){try{await this.paymentProvider.mount(e)}catch(e){throw console.error("Failed to inject payment element:",e),e}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(e,t){this.paymentProvider.subscribe(e,t)}unsubscribe(e,t){this.paymentProvider.unsubscribe(e,t)}}class _{constructor(e){this.client=e,this.servicePath="/users"}async createOrUpdateSession(e){try{if(!(null==e?void 0:e.id)&&!(null==e?void 0:e.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,e)}catch(e){throw console.error("User session creation/update request failed:",e),e}}async purge(e){try{if(!e)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${e}`)}catch(e){throw console.error("User purge request failed:",e),e}}async updateAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,e)}catch(e){throw console.error("User address update request failed:",e),e}}async purgeAddress(e){try{if(!e)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${e}`)}catch(e){throw console.error("Address purge request failed:",e),e}}}class H{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return H.instance||(H.instance=new H),H.instance}setLiquidCommerceClientConstructor(e){this.liquidCommerceClientConstructor=e}async getLiquidCommerceClient(e,t){const r=`LiquidCommerceClient_${e}_${JSON.stringify(t)}`;if(!this.services.has(r)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const i=new this.liquidCommerceClientConstructor(e,t);await i.init(),this.services.set(r,i)}return this.services.get(r)}getOrCreateService(e,t,...r){if(!this.services.has(e)){const i="getInstance"in t?t.getInstance(...r):new t(...r);this.services.set(e,i)}return this.services.get(e)}getAuthenticatedClient(e){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(e)}`,N,e)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",g)}getAddressService(e){return this.getOrCreateService(`AddressService_${e.getUniqueKey()}`,D,e)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",T,this.getLocationHelperService())}getCatalogService(e){return this.getOrCreateService(`CatalogService_${e.getUniqueKey()}`,w,e,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",O,this.getLocationHelperService())}getCartService(e){return this.getOrCreateService(`CartService_${e.getUniqueKey()}`,L,e,this.getCartHelperService())}getUserService(e){return this.getOrCreateService(`UserService_${e.getUniqueKey()}`,_,e)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",f)}getPaymentService(){return this.getOrCreateService("PaymentService",M,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",y,this.getLocationHelperService())}getCheckoutService(e){return this.getOrCreateService(`CheckoutService_${e.getUniqueKey()}`,P,e,this.getCheckoutHelperService())}}H.instance=null;class U{constructor(e,t){this.address={autocomplete:async e=>(await this.ensureAuthenticated(),this.addressService.autocomplete(e,this.config.googlePlacesApiKey)),details:async e=>(await this.ensureAuthenticated(),this.addressService.details(e,this.config.googlePlacesApiKey))},this.catalog={availability:async e=>(await this.ensureAuthenticated(),this.catalogService.availability(e)),search:async e=>(await this.ensureAuthenticated(),this.catalogService.search(e))},this.cart={get:async(e,t)=>(await this.ensureAuthenticated(),this.cartService.get(e,t)),update:async e=>(await this.ensureAuthenticated(),this.cartService.update(e))},this.user={session:async e=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(e)),purge:async e=>(await this.ensureAuthenticated(),this.userService.purge(e)),updateAddress:async e=>(await this.ensureAuthenticated(),this.userService.updateAddress(e)),purgeAddress:async e=>(await this.ensureAuthenticated(),this.userService.purgeAddress(e))},this.payment={mount:async e=>(await this.ensureAuthenticated(),this.paymentService.mount(e)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(e,t)=>{this.paymentService.subscribe(e,t)},unsubscribe:(e,t)=>{this.paymentService.unsubscribe(e,t)}},this.checkout={prepare:async e=>(await this.ensureAuthenticated(),this.checkoutService.prepare(e)),complete:async e=>(await this.ensureAuthenticated(),this.checkoutService.complete(e))},this.config=t,this.singletonManager=H.getInstance();const r=this.determineBaseURL(t);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:e,baseURL:r}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const t=e.env||exports.LIQUID_COMMERCE_ENV.STAGE;return C[t]}async init(){try{await this.authenticatedClient.authenticate()}catch(e){throw console.error("Failed to initialize LiquidCommerceClient:",e),new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}exports.LiquidCommerce=async function(e,t){const r=H.getInstance();return r.setLiquidCommerceClientConstructor(U),await r.getLiquidCommerceClient(e,t)};
1
+ "use strict";var e,t,r,i,s,a,n,o,c,l,E,I,h,d,A,S,u,p,R,N=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(e=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).LOC="loc",e.STAGE="stage",e.PROD="prod",e.DEV="dev",exports.ENUM_MODALITIES=void 0,(t=exports.ENUM_MODALITIES||(exports.ENUM_MODALITIES={})).ON_DEMAND="onDemand",t.SHIPPING="shipping",exports.DAYS_OF_WEEK=void 0,(r=exports.DAYS_OF_WEEK||(exports.DAYS_OF_WEEK={})).MONDAY="monday",r.TUESDAY="tuesday",r.WEDNESDAY="wednesday",r.THURSDAY="thursday",r.FRIDAY="friday",r.SATURDAY="saturday",r.SUNDAY="sunday",exports.STATES_CODE=void 0,(i=exports.STATES_CODE||(exports.STATES_CODE={})).AL="AL",i.AK="AK",i.AR="AR",i.CA="CA",i.CO="CO",i.CT="CT",i.DE="DE",i.DC="DC",i.FL="FL",i.GA="GA",i.HI="HI",i.ID="ID",i.IL="IL",i.IN="IN",i.IA="IA",i.KS="KS",i.KY="KY",i.LA="LA",i.ME="ME",i.MD="MD",i.MA="MA",i.MI="MI",i.MN="MN",i.MS="MS",i.MO="MO",i.MT="MT",i.NE="NE",i.NV="NV",i.NH="NH",i.NJ="NJ",i.NM="NM",i.NY="NY",i.NC="NC",i.ND="ND",i.OH="OH",i.OK="OK",i.OR="OR",i.PA="PA",i.RI="RI",i.SC="SC",i.SD="SD",i.TN="TN",i.TX="TX",i.UT="UT",i.VT="VT",i.VA="VA",i.WA="WA",i.WV="WV",i.WI="WI",i.WY="WY",exports.STATES_NAME=void 0,(s=exports.STATES_NAME||(exports.STATES_NAME={})).ALABAMA="AL",s.ALASKA="AK",s.ARKANSAS="AR",s.CALIFORNIA="CA",s.COLORADO="CO",s.CONNECTICUT="CT",s.DELAWARE="DE",s.DISTRICT_OF_COLUMBIA="DC",s.FLORIDA="FL",s.GEORGIA="GA",s.HAWAII="HI",s.IDAHO="ID",s.ILLINOIS="IL",s.INDIANA="IN",s.IOWA="IA",s.KANSAS="KS",s.KENTUCKY="KY",s.LOUISIANA="LA",s.MAINE="ME",s.MARYLAND="MD",s.MASSACHUSETTS="MA",s.MICHIGAN="MI",s.MINNESOTA="MN",s.MISSISSIPPI="MS",s.MISSOURI="MO",s.MONTANA="MT",s.NEBRASKA="NE",s.NEVADA="NV",s.NEW_HAMPSHIRE="NH",s.NEW_JERSEY="NJ",s.NEW_MEXICO="NM",s.NEW_YORK="NY",s.NORTH_CAROLINA="NC",s.NORTH_DAKOTA="ND",s.OHIO="OH",s.OKLAHOMA="OK",s.OREGON="OR",s.PENNSYLVANIA="PA",s.RHODE_ISLAND="RI",s.SOUTH_CAROLINA="SC",s.SOUTH_DAKOTA="SD",s.TENNESSEE="TN",s.TEXAS="TX",s.UTAH="UT",s.VERMONT="VT",s.VIRGINIA="VA",s.WASHINGTON="WA",s.WEST_VIRGINIA="WV",s.WISCONSIN="WI",s.WYOMING="WY",exports.ENUM_BEER=void 0,(a=exports.ENUM_BEER||(exports.ENUM_BEER={})).ALE="BEER > ALE",a.LAGER="BEER > LAGER",a.MAIN="BEER",a.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",a.OTHER_BEER="BEER > OTHER BEER",exports.ENUM_FOOD=void 0,(n=exports.ENUM_FOOD||(exports.ENUM_FOOD={})).BASE="FOOD",n.PANTRY_OTHER="FOOD > PANTRY > OTHER",exports.ENUM_MERCHANDISE=void 0,(o=exports.ENUM_MERCHANDISE||(exports.ENUM_MERCHANDISE={})).BASE="MERCHANDISE",o.GLASSWARE="MERCHANDISE > GLASSWARE",o.HUMIDOR="MERCHANDISE > HUMIDOR",exports.ENUM_MISCELLANEOUS=void 0,(c=exports.ENUM_MISCELLANEOUS||(exports.ENUM_MISCELLANEOUS={})).BASE="MISCELLANEOUS",c.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",c.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",c.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP",exports.ENUM_NON_ALCOHOLIC=void 0,(l=exports.ENUM_NON_ALCOHOLIC||(exports.ENUM_NON_ALCOHOLIC={})).BASE="NON ALCOHOLIC",l.BITTERS="NON ALCOHOLIC > BITTERS",l.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",l.COFFEE="NON ALCOHOLIC > COFFEE",l.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",l.JUICE="NON ALCOHOLIC > JUICE",l.SODA="NON ALCOHOLIC > SODA",l.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",l.SPIRITS="NON ALCOHOLIC > SPIRITS",l.TEA="NON ALCOHOLIC > TEA",l.WATER="NON ALCOHOLIC > WATER",l.WINE="NON ALCOHOLIC > WINE",exports.ENUM_READY_TO_DRINK=void 0,(E=exports.ENUM_READY_TO_DRINK||(exports.ENUM_READY_TO_DRINK={})).BASE="READY TO DRINK",E.HARD_CIDER="READY TO DRINK > HARD CIDER",E.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",E.HARD_TEA="READY TO DRINK > HARD TEA",E.MALT_BASED="READY TO DRINK > MALT BASED",E.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",E.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",E.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",E.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",E.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",E.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS",exports.ENUM_SPIRITS=void 0,(I=exports.ENUM_SPIRITS||(exports.ENUM_SPIRITS={})).BASE="SPIRITS",I.BAIJIU="SPIRITS > BAIJIU",I.BITTERS="SPIRITS > BITTERS",I.BRANDY="SPIRITS > BRANDY",I.CACHACA="SPIRITS > CACHACA",I.GIN="SPIRITS > GIN",I.LAGER="SPIRITS > LAGER",I.LIQUEUR="SPIRITS > LIQUEUR",I.MEZCAL="SPIRITS > MEZCAL",I.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",I.RUM="SPIRITS > RUM",I.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",I.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",I.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",I.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",I.RUM_OTHER="SPIRITS > RUM > OTHER",I.RUM_SPICED="SPIRITS > RUM > SPICED",I.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",I.SOJU="SPIRITS > SOJU",I.TEQUILA="SPIRITS > TEQUILA",I.VODKA="SPIRITS > VODKA",I.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",I.WHISKEY="SPIRITS > WHISKEY",I.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",I.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",I.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",I.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",I.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH",exports.ENUM_WINE=void 0,(h=exports.ENUM_WINE||(exports.ENUM_WINE={})).BASE="WINE",h.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",h.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",h.COOKING="WINE > COOKING",h.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",h.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",h.RED_WINE="WINE > RED WINE",h.ROSE_WINE="WINE > ROSE WINE",h.SAKE="WINE > SAKE",h.WHITE_WINE="WINE > WHITE WINE",exports.ENUM_FILTER_KEYS=void 0,(d=exports.ENUM_FILTER_KEYS||(exports.ENUM_FILTER_KEYS={})).BRANDS="brands",d.FLAVOR="flavor",d.REGION="region",d.VARIETY="variety",d.PRICE="price",d.AVAILABILITY="availability",d.CATEGORIES="categories",d.SIZES="sizes",d.COLORS="colors",d.APPELLATION="appellation",d.COUNTRY="country",d.VINTAGE="vintage",d.MATERIALS="materials",exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE=void 0,(A=exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE||(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE={})).ASC="asc",A.DESC="desc",exports.ENUM_ORDER_BY=void 0,(exports.ENUM_ORDER_BY||(exports.ENUM_ORDER_BY={})).PRICE="price",exports.ENUM_AVAILABILITY_VALUE=void 0,(S=exports.ENUM_AVAILABILITY_VALUE||(exports.ENUM_AVAILABILITY_VALUE={})).UNSPECIFIED="AVAILABILITY_UNSPECIFIED",S.IN_STOCK="IN_STOCK",S.OUT_OF_STOCK="OUT_OF_STOCK",S.PREORDER="PREORDER",S.BACKORDER="BACKORDER",exports.CART_PARAM_ERROR_ENUM=void 0,(u=exports.CART_PARAM_ERROR_ENUM||(exports.CART_PARAM_ERROR_ENUM={})).INVALID_ITEMS_TYPE="Items must be a non-empty array",u.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",u.INVALID_PART_NUMBER="The partnerNumber provided is invalid",u.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid",exports.CART_EVENT_ENUM=void 0,(p=exports.CART_EVENT_ENUM||(exports.CART_EVENT_ENUM={})).OOS="OutOfStock",p.ITEMS_NOT_ADDED="ItemsNotAdded",p.ITEM_NOT_ENGRAVED="ItemEngravingError",p.ADDRESS_CHANGE="AddressChange",p.RETAILER_MIN="RetailerMinNotMet",p.NO_ITEMS_IN_CART="NoItemsInCart",p.INVALID_ID="InvalidId",p.NO_ID="NoId",p.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",p.NEW_CART="NewCart",p.DEFAULT="CartError",p.ITEM_QTY_CHANGE="ItemQuantityChange",exports.ENUM_ADDRESS_TYPE=void 0,(R=exports.ENUM_ADDRESS_TYPE||(exports.ENUM_ADDRESS_TYPE={})).SHIPPING="shipping",R.BILLING="billing";const O={[exports.LIQUID_COMMERCE_ENV.LOC]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.DEV]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class T{constructor(e){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(e,t)=>new Promise(((r,i)=>{const s=new XMLHttpRequest;s.open(t.method||"GET",e),Object.entries(t.headers).forEach((([e,t])=>{s.setRequestHeader(e,t)})),s.onload=()=>{r({ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,headers:s.getAllResponseHeaders().split("\r\n").reduce(((e,t)=>{const[r,i]=t.split(": ");return r&&(e[r]=i),e}),{}),json:()=>Promise.resolve(JSON.parse(s.responseText)),text:()=>Promise.resolve(s.responseText)})},s.onerror=()=>{i(new TypeError("Network request failed"))},s.send(t.body)})),this.apiKey=e.apiKey,this.baseURL=e.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(e){return T.instance||(T.instance=new T(e)),T.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):"undefined"!=typeof window&&window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(e){return async(t,r)=>{var i;const s=await e(t,r);let a;return"function"==typeof(null===(i=s.headers)||void 0===i?void 0:i.entries)?a=Object.fromEntries(s.headers.entries()):(a={},s.headers.forEach(((e,t)=>{a[t]=e}))),{ok:s.ok,status:s.status,statusText:s.statusText,headers:a,json:()=>s.json(),text:()=>s.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var e,t;if(this.isAuthenticating)await new Promise((e=>{const t=()=>{this.isAuthenticating?setTimeout(t,100):e(void 0)};t()}));else{this.isAuthenticating=!0;try{const r=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.token,this.tokenExpiration=Date.now()+1e3*(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.exp)}catch(e){throw console.error("Authentication failed:",e),new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(e,t){const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...t.headers},s={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},a=await this.httpClient(r.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(e,t){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...t.headers},s={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},a=await this.httpClient(r.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}async get(e,t){return this.request(e,{method:"GET",headers:t})}async post(e,t,r){return this.request(e,{method:"POST",body:t,headers:r})}async put(e,t,r){return this.request(e,{method:"PUT",body:t,headers:r})}async delete(e,t){return this.request(e,{method:"DELETE",headers:t})}}T.instance=null;class v{constructor(e){this.locationHelperService=e}validateAndNormalizeParams(e){const t={...e};return t.id=this.validateId(t.id),t.items=this.validateAndNormalizeItems(t.items),this.locationHelperService.validateAndNormalizeLocation(t.loc),t.refresh=Boolean(t.refresh),t}validateId(e){return e&&"string"==typeof e&&0!==e.trim().length?e.trim():""}validateAndNormalizeItems(e){if(!Array.isArray(e)||0===e.length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_FULFILLMENT_ID);return t.quantity=Math.max(0,Math.floor(t.quantity)),t.engravingLines&&(t.engravingLines=t.engravingLines.map((e=>e.trim())).filter((e=>e.length>0))),t}validatePartNumber(e){if(!e||"string"!=typeof e)return!1;const t=e.split("_");return 2===t.length&&14===t[0].length&&t[1].length>0}}class C{constructor(e){this.locationServiceHelper=e,this.taxonomyValues=new Set([...Object.values(exports.ENUM_BEER),...Object.values(exports.ENUM_FOOD),...Object.values(exports.ENUM_MERCHANDISE),...Object.values(exports.ENUM_NON_ALCOHOLIC),...Object.values(exports.ENUM_READY_TO_DRINK),...Object.values(exports.ENUM_SPIRITS),...Object.values(exports.ENUM_WINE)])}validateAndNormalizeParams(e){const t={...e};return this.validateUPCs(t.upcs),this.locationServiceHelper.validateAndNormalizeLocation(t.loc),t}validateAndNormalizeSearchParams(e){const t=[],r={...e};return this.validateOrderBy(r.orderBy,t),this.validateOrderDirection(r.orderDirection,t),this.validateFilters(r.filters,t),this.validatePagination(r.page,r.perPage,t),this.locationServiceHelper.validateAndNormalizeLocation(r.loc),t.length>0?{...r,error:t.join(". ")}:r}validateUPCs(e){if(!Array.isArray(e)||0===e.length)throw new Error("UPCs must be a non-empty array of strings");if(!e.every((e=>"string"==typeof e&&e.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(e,t){e&&!Object.values(exports.ENUM_ORDER_BY).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE).includes(e)&&t.push(`Invalid orderDirection value: ${e}`)}validateFilters(e,t){e&&(e.length>10&&t.push("Maximum of 10 filters allowed"),e.forEach((e=>{switch(Object.values(exports.ENUM_FILTER_KEYS).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case exports.ENUM_FILTER_KEYS.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case exports.ENUM_FILTER_KEYS.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case exports.ENUM_FILTER_KEYS.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case exports.ENUM_FILTER_KEYS.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(exports.ENUM_AVAILABILITY_VALUE).includes(e)||t.push(`Invalid availability value: ${e}`)}validateArrayFilter(e,t,r,i){Array.isArray(e)?e.length>t&&i.push(`${r} filter can have a maximum of ${t} values`):i.push(`${r} filter must be an array`)}validateCategoriesFilter(e,t){Array.isArray(e)?e.every((e=>this.taxonomyValues.has(e)))||t.push("Invalid category value(s) in categories filter"):t.push("Categories filter must be an array")}validatePagination(e,t,r){void 0!==e&&("number"!=typeof e||e<0)&&r.push("Page must be a non-negative number"),void 0!==t&&("number"!=typeof t||t<=0)&&r.push("PerPage must be a positive number")}}class _{constructor(e){this.locationHelperService=e}validateAndNormalizePrepareParams(e){const t={...e};if(!t.cartId||"string"!=typeof t.cartId)throw new Error("Invalid cartId");return this.validateRecipient(t.recipient),t.billingAddress&&this.validateAddress(t.billingAddress),t.hasSubstitutionPolicy=Boolean(t.hasSubstitutionPolicy),t.isGift=Boolean(t.isGift),t.billingSameAsShipping=Boolean(t.billingSameAsShipping),t.isGift&&this.validateGiftOptions(t.giftOptions),this.validateMarketingPreferences(t.marketingPreferences),t.deliveryTips&&this.validateDeliveryTips(t.deliveryTips),t.refresh=Boolean(t.refresh),t}validateAndNormalizeCompleteParams(e){const t={...e};if(!t.token||"string"!=typeof t.token)throw new Error("Invalid token");if(!t.payment||"string"!=typeof t.payment)throw new Error("Invalid payment token");return void 0!==t.refresh&&(t.refresh=Boolean(t.refresh)),t}validateRecipient(e){if(!e||"object"!=typeof e)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid recipient ${t}`)})),e.hasAgeVerify=Boolean(e.hasAgeVerify)}validateAddress(e){if(!e||"object"!=typeof e)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid address ${t}`)})),this.locationHelperService.validateAndNormalizeLocation({address:e})}validateGiftOptions(e){if(!e||"object"!=typeof e)throw new Error("Invalid giftOptions");if(e.message&&"string"!=typeof e.message)throw new Error("Invalid gift message");if(e.recipient){const{name:t,phone:r,email:i}=e.recipient;if(t&&"string"!=typeof t)throw new Error("Invalid gift recipient name");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient phone");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(e){if(!e||"object"!=typeof e)throw new Error("Invalid marketingPreferences");e.canEmail=Boolean(e.canEmail),e.canSms=Boolean(e.canSms)}validateDeliveryTips(e){if(!Array.isArray(e))throw new Error("Invalid deliveryTips");e.forEach((e=>{if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof e.tip||e.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class m{validateAndNormalizeLocation(e){if(!e||"object"!=typeof e)throw new Error("Location must be a valid object");if(e.coords)this.validateCoordinates(e.coords);else{if(!e.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(e.address)}}validateCoordinates(e){if("number"!=typeof e.lat||"number"!=typeof e.long)throw new Error("Coordinates must be valid numbers");if(e.lat<-90||e.lat>90||e.long<-180||e.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(e){if(!e.state||"string"!=typeof e.state)throw new Error("State is required and must be a string");if(e.state=this.normalizeState(e.state),!e.city||"string"!=typeof e.city)throw new Error("City is required and must be a string");if(!e.zip||"string"!=typeof e.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(e){const t=e.toUpperCase();if(exports.STATES_CODE[t])return exports.STATES_CODE[t];const r=e.toUpperCase();if(exports.STATES_NAME[r])return exports.STATES_NAME[r];throw new Error(`Invalid state: ${e}`)}}class y{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(e){if(!document.getElementById(e.elementId))throw new Error(`Element with id "${e.elementId}" not found`);try{this.stripe=await N.loadStripe(e.key)}catch(e){throw console.error("Failed to load Stripe:",e),new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const t={clientSecret:e.clientSecret,appearance:this.mapAppearance(e.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(t);const r=this.mapElementOptions(e.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${e.elementId}`)}async generateToken(){var e,t,r,i,s,a,n,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:c}=await this.elements.submit();if(c)return{type:"validation_error",message:c.message,code:c.code};const{error:l,paymentMethod:E}=await this.stripe.createPaymentMethod({elements:this.elements});return l?{type:"validation_error"===l.type?"validation_error":"api_error",message:l.message,code:l.code,param:l.param}:E?{id:E.id,type:E.type,card:(null==E?void 0:E.card)?{brand:null!==(t=null===(e=E.card)||void 0===e?void 0:e.brand)&&void 0!==t?t:"",country:null!==(r=E.card.country)&&void 0!==r?r:"",expMonth:null!==(i=E.card.exp_month)&&void 0!==i?i:0,expYear:null!==(s=E.card.exp_year)&&void 0!==s?s:0,last4:null!==(a=E.card.last4)&&void 0!==a?a:"",funding:null!==(n=E.card.funding)&&void 0!==n?n:""}:void 0,created:null!==(o=null==E?void 0:E.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.on(e,t)}unsubscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.off(e,t)}mapAppearance(e){if(e)return{theme:"night"===e.theme?"night":"stripe"}}mapElementOptions(e){return{layout:null==e?void 0:e.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class g{constructor(e){this.client=e}async autocomplete(e,t){try{return await this.client.post("/address/autocomplete",{...e,key:t})}catch(e){throw console.error("Address autocomplete request failed:",e),e}}async details(e,t){try{return await this.client.post("/address/details",{...e,key:t})}catch(e){throw console.error("Address details request failed:",e),e}}}class M{constructor(e,t){this.client=e,this.cartHelperService=t,this.servicePath="/cart/update"}async get(e,t){try{let r=this.cartHelperService.validateId(e);if(r=""!==r&&r,r){const e={id:r};return"boolean"==typeof t&&(e.refresh=t),await this.client.post(this.servicePath,e)}return await this.client.post(this.servicePath)}catch(e){throw console.error("Cart update request failed:",e),e}}async update(e){try{const t=this.cartHelperService.validateAndNormalizeParams(e);return await this.client.post(this.servicePath,t)}catch(e){throw console.error("Cart update request failed:",e),e}}}class D{constructor(e,t){this.client=e,this.catalogHelperService=t,this.servicePath="/catalog/"}async availability(e){try{const t=this.catalogHelperService.validateAndNormalizeParams(e);return await this.client.post(`${this.servicePath}availability`,t)}catch(e){throw console.error("Catalog availability request failed:",e),e}}async search(e){try{const t=this.catalogHelperService.validateAndNormalizeSearchParams(e);if(null==t?void 0:t.error)throw new Error(null==t?void 0:t.error);return await this.client.post(`${this.servicePath}search`,t)}catch(e){throw console.error("Catalog search request failed:",e),e}}}class L{constructor(e,t){this.client=e,this.checkoutHelperService=t,this.servicePath="/checkout"}async prepare(e){try{const t=this.checkoutHelperService.validateAndNormalizePrepareParams(e);return await this.client.post(`${this.servicePath}/prepare`,t)}catch(e){throw console.error("Checkout prepare request failed:",e),e}}async complete(e){try{const t=this.checkoutHelperService.validateAndNormalizeCompleteParams(e);return await this.client.post(`${this.servicePath}/complete`,t)}catch(e){throw console.error("Checkout complete request failed:",e),e}}}class f{constructor(e){this.paymentProvider=e}async mount(e){try{await this.paymentProvider.mount(e)}catch(e){throw console.error("Failed to inject payment element:",e),e}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(e,t){this.paymentProvider.subscribe(e,t)}unsubscribe(e,t){this.paymentProvider.unsubscribe(e,t)}}class U{constructor(e){this.client=e,this.servicePath="/users"}async createOrUpdateSession(e){try{if(!(null==e?void 0:e.id)&&!(null==e?void 0:e.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,e)}catch(e){throw console.error("User session creation/update request failed:",e),e}}async purge(e){try{if(!e)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${e}`)}catch(e){throw console.error("User purge request failed:",e),e}}async updateAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,e)}catch(e){throw console.error("User address update request failed:",e),e}}async purgeAddress(e){try{if(!e)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${e}`)}catch(e){throw console.error("Address purge request failed:",e),e}}}class P{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return P.instance||(P.instance=new P),P.instance}setLiquidCommerceClientConstructor(e){this.liquidCommerceClientConstructor=e}async getLiquidCommerceClient(e,t){const r=`LiquidCommerceClient_${e}_${JSON.stringify(t)}`;if(!this.services.has(r)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const i=new this.liquidCommerceClientConstructor(e,t);await i.init(),this.services.set(r,i)}return this.services.get(r)}getOrCreateService(e,t,...r){if(!this.services.has(e)){const i="getInstance"in t?t.getInstance(...r):new t(...r);this.services.set(e,i)}return this.services.get(e)}getAuthenticatedClient(e){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(e)}`,T,e)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",m)}getAddressService(e){return this.getOrCreateService(`AddressService_${e.getUniqueKey()}`,g,e)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",C,this.getLocationHelperService())}getCatalogService(e){return this.getOrCreateService(`CatalogService_${e.getUniqueKey()}`,D,e,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",v,this.getLocationHelperService())}getCartService(e){return this.getOrCreateService(`CartService_${e.getUniqueKey()}`,M,e,this.getCartHelperService())}getUserService(e){return this.getOrCreateService(`UserService_${e.getUniqueKey()}`,U,e)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",y)}getPaymentService(){return this.getOrCreateService("PaymentService",f,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",_,this.getLocationHelperService())}getCheckoutService(e){return this.getOrCreateService(`CheckoutService_${e.getUniqueKey()}`,L,e,this.getCheckoutHelperService())}}P.instance=null;class w{constructor(e,t){this.address={autocomplete:async e=>(await this.ensureAuthenticated(),this.addressService.autocomplete(e,this.config.googlePlacesApiKey)),details:async e=>(await this.ensureAuthenticated(),this.addressService.details(e,this.config.googlePlacesApiKey))},this.catalog={availability:async e=>(await this.ensureAuthenticated(),this.catalogService.availability(e)),search:async e=>(await this.ensureAuthenticated(),this.catalogService.search(e))},this.cart={get:async(e,t)=>(await this.ensureAuthenticated(),this.cartService.get(e,t)),update:async e=>(await this.ensureAuthenticated(),this.cartService.update(e))},this.user={session:async e=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(e)),purge:async e=>(await this.ensureAuthenticated(),this.userService.purge(e)),updateAddress:async e=>(await this.ensureAuthenticated(),this.userService.updateAddress(e)),purgeAddress:async e=>(await this.ensureAuthenticated(),this.userService.purgeAddress(e))},this.payment={mount:async e=>(await this.ensureAuthenticated(),this.paymentService.mount(e)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(e,t)=>{this.paymentService.subscribe(e,t)},unsubscribe:(e,t)=>{this.paymentService.unsubscribe(e,t)}},this.checkout={prepare:async e=>(await this.ensureAuthenticated(),this.checkoutService.prepare(e)),complete:async e=>(await this.ensureAuthenticated(),this.checkoutService.complete(e))},this.config=t,this.singletonManager=P.getInstance();const r=this.determineBaseURL(t);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:e,baseURL:r}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const t=e.env||exports.LIQUID_COMMERCE_ENV.STAGE;return O[t]}async init(){try{await this.authenticatedClient.authenticate()}catch(e){throw console.error("Failed to initialize LiquidCommerceClient:",e),new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}exports.LiquidCommerce=async function(e,t){const r=P.getInstance();return r.setLiquidCommerceClientConstructor(w),await r.getLiquidCommerceClient(e,t)};
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{loadStripe as e}from"@stripe/stripe-js";var t,i,r,a,s,n,o,c,l,h,d,I,u,A,S,E,p,v,R,m;!function(e){e.DEV="dev",e.STAGE="stage"}(t||(t={})),function(e){e.ON_DEMAND="onDemand",e.SHIPPING="shipping"}(i||(i={})),function(e){e.MONDAY="monday",e.TUESDAY="tuesday",e.WEDNESDAY="wednesday",e.THURSDAY="thursday",e.FRIDAY="friday",e.SATURDAY="saturday",e.SUNDAY="sunday"}(r||(r={})),function(e){e.AL="AL",e.AK="AK",e.AR="AR",e.CA="CA",e.CO="CO",e.CT="CT",e.DE="DE",e.DC="DC",e.FL="FL",e.GA="GA",e.HI="HI",e.ID="ID",e.IL="IL",e.IN="IN",e.IA="IA",e.KS="KS",e.KY="KY",e.LA="LA",e.ME="ME",e.MD="MD",e.MA="MA",e.MI="MI",e.MN="MN",e.MS="MS",e.MO="MO",e.MT="MT",e.NE="NE",e.NV="NV",e.NH="NH",e.NJ="NJ",e.NM="NM",e.NY="NY",e.NC="NC",e.ND="ND",e.OH="OH",e.OK="OK",e.OR="OR",e.PA="PA",e.RI="RI",e.SC="SC",e.SD="SD",e.TN="TN",e.TX="TX",e.UT="UT",e.VT="VT",e.VA="VA",e.WA="WA",e.WV="WV",e.WI="WI",e.WY="WY"}(a||(a={})),function(e){e.ALABAMA="AL",e.ALASKA="AK",e.ARKANSAS="AR",e.CALIFORNIA="CA",e.COLORADO="CO",e.CONNECTICUT="CT",e.DELAWARE="DE",e.DISTRICT_OF_COLUMBIA="DC",e.FLORIDA="FL",e.GEORGIA="GA",e.HAWAII="HI",e.IDAHO="ID",e.ILLINOIS="IL",e.INDIANA="IN",e.IOWA="IA",e.KANSAS="KS",e.KENTUCKY="KY",e.LOUISIANA="LA",e.MAINE="ME",e.MARYLAND="MD",e.MASSACHUSETTS="MA",e.MICHIGAN="MI",e.MINNESOTA="MN",e.MISSISSIPPI="MS",e.MISSOURI="MO",e.MONTANA="MT",e.NEBRASKA="NE",e.NEVADA="NV",e.NEW_HAMPSHIRE="NH",e.NEW_JERSEY="NJ",e.NEW_MEXICO="NM",e.NEW_YORK="NY",e.NORTH_CAROLINA="NC",e.NORTH_DAKOTA="ND",e.OHIO="OH",e.OKLAHOMA="OK",e.OREGON="OR",e.PENNSYLVANIA="PA",e.RHODE_ISLAND="RI",e.SOUTH_CAROLINA="SC",e.SOUTH_DAKOTA="SD",e.TENNESSEE="TN",e.TEXAS="TX",e.UTAH="UT",e.VERMONT="VT",e.VIRGINIA="VA",e.WASHINGTON="WA",e.WEST_VIRGINIA="WV",e.WISCONSIN="WI",e.WYOMING="WY"}(s||(s={})),function(e){e.ALE="BEER > ALE",e.LAGER="BEER > LAGER",e.MAIN="BEER",e.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",e.OTHER_BEER="BEER > OTHER BEER"}(n||(n={})),function(e){e.BASE="FOOD",e.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(o||(o={})),function(e){e.BASE="MERCHANDISE",e.GLASSWARE="MERCHANDISE > GLASSWARE",e.HUMIDOR="MERCHANDISE > HUMIDOR"}(c||(c={})),function(e){e.BASE="MISCELLANEOUS",e.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",e.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",e.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(l||(l={})),function(e){e.BASE="NON ALCOHOLIC",e.BITTERS="NON ALCOHOLIC > BITTERS",e.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",e.COFFEE="NON ALCOHOLIC > COFFEE",e.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",e.JUICE="NON ALCOHOLIC > JUICE",e.SODA="NON ALCOHOLIC > SODA",e.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",e.SPIRITS="NON ALCOHOLIC > SPIRITS",e.TEA="NON ALCOHOLIC > TEA",e.WATER="NON ALCOHOLIC > WATER",e.WINE="NON ALCOHOLIC > WINE"}(h||(h={})),function(e){e.BASE="READY TO DRINK",e.HARD_CIDER="READY TO DRINK > HARD CIDER",e.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",e.HARD_TEA="READY TO DRINK > HARD TEA",e.MALT_BASED="READY TO DRINK > MALT BASED",e.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",e.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",e.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",e.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",e.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",e.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(d||(d={})),function(e){e.BASE="SPIRITS",e.BAIJIU="SPIRITS > BAIJIU",e.BITTERS="SPIRITS > BITTERS",e.BRANDY="SPIRITS > BRANDY",e.CACHACA="SPIRITS > CACHACA",e.GIN="SPIRITS > GIN",e.LAGER="SPIRITS > LAGER",e.LIQUEUR="SPIRITS > LIQUEUR",e.MEZCAL="SPIRITS > MEZCAL",e.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",e.RUM="SPIRITS > RUM",e.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",e.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",e.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",e.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",e.RUM_OTHER="SPIRITS > RUM > OTHER",e.RUM_SPICED="SPIRITS > RUM > SPICED",e.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",e.SOJU="SPIRITS > SOJU",e.TEQUILA="SPIRITS > TEQUILA",e.VODKA="SPIRITS > VODKA",e.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",e.WHISKEY="SPIRITS > WHISKEY",e.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",e.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",e.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",e.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",e.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(I||(I={})),function(e){e.BASE="WINE",e.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",e.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",e.COOKING="WINE > COOKING",e.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",e.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",e.RED_WINE="WINE > RED WINE",e.ROSE_WINE="WINE > ROSE WINE",e.SAKE="WINE > SAKE",e.WHITE_WINE="WINE > WHITE WINE"}(u||(u={})),function(e){e.BRANDS="brands",e.FLAVOR="flavor",e.REGION="region",e.VARIETY="variety",e.PRICE="price",e.AVAILABILITY="availability",e.CATEGORIES="categories",e.SIZES="sizes",e.COLORS="colors",e.APPELLATION="appellation",e.COUNTRY="country",e.VINTAGE="vintage",e.MATERIALS="materials"}(A||(A={})),function(e){e.ASC="asc",e.DESC="desc"}(S||(S={})),function(e){e.PRICE="price"}(E||(E={})),function(e){e.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",e.IN_STOCK="IN_STOCK",e.OUT_OF_STOCK="OUT_OF_STOCK",e.PREORDER="PREORDER",e.BACKORDER="BACKORDER"}(p||(p={})),function(e){e.INVALID_ITEMS_TYPE="Items must be a non-empty array",e.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",e.INVALID_PART_NUMBER="The partnerNumber provided is invalid",e.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(v||(v={})),function(e){e.OOS="OutOfStock",e.ITEMS_NOT_ADDED="ItemsNotAdded",e.ITEM_NOT_ENGRAVED="ItemEngravingError",e.ADDRESS_CHANGE="AddressChange",e.RETAILER_MIN="RetailerMinNotMet",e.NO_ITEMS_IN_CART="NoItemsInCart",e.INVALID_ID="InvalidId",e.NO_ID="NoId",e.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",e.NEW_CART="NewCart",e.DEFAULT="CartError",e.ITEM_QTY_CHANGE="ItemQuantityChange"}(R||(R={})),function(e){e.SHIPPING="shipping",e.BILLING="billing"}(m||(m={}));const C={[t.DEV]:"https://dev.cloud.liquidcommerce.co/api",[t.STAGE]:"https://staging.cloud.liquidcommerce.co/api"};class N{constructor(e){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(e,t)=>new Promise(((i,r)=>{const a=new XMLHttpRequest;a.open(t.method||"GET",e),Object.entries(t.headers).forEach((([e,t])=>{a.setRequestHeader(e,t)})),a.onload=()=>{i({ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,headers:a.getAllResponseHeaders().split("\r\n").reduce(((e,t)=>{const[i,r]=t.split(": ");return i&&(e[i]=r),e}),{}),json:()=>Promise.resolve(JSON.parse(a.responseText)),text:()=>Promise.resolve(a.responseText)})},a.onerror=()=>{r(new TypeError("Network request failed"))},a.send(t.body)})),this.apiKey=e.apiKey,this.baseURL=e.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(e){return N.instance||(N.instance=new N(e)),N.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):"undefined"!=typeof window&&window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(e){return async(t,i)=>{var r;const a=await e(t,i);let s;return"function"==typeof(null===(r=a.headers)||void 0===r?void 0:r.entries)?s=Object.fromEntries(a.headers.entries()):(s={},a.headers.forEach(((e,t)=>{s[t]=e}))),{ok:a.ok,status:a.status,statusText:a.statusText,headers:s,json:()=>a.json(),text:()=>a.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var e,t;if(this.isAuthenticating)await new Promise((e=>{const t=()=>{this.isAuthenticating?setTimeout(t,100):e(void 0)};t()}));else{this.isAuthenticating=!0;try{const i=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(e=null==i?void 0:i.data)||void 0===e?void 0:e.token,this.tokenExpiration=Date.now()+1e3*(null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.exp)}catch(e){throw console.error("Authentication failed:",e),new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(e,t){const i=new URL(`api${e}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...t.headers},a={method:t.method,headers:r,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(i.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(e,t){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const i=new URL(`api${e}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...t.headers},a={method:t.method,headers:r,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(i.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}async get(e,t){return this.request(e,{method:"GET",headers:t})}async post(e,t,i){return this.request(e,{method:"POST",body:t,headers:i})}async put(e,t,i){return this.request(e,{method:"PUT",body:t,headers:i})}async delete(e,t){return this.request(e,{method:"DELETE",headers:t})}}N.instance=null;class O{constructor(e){this.locationHelperService=e}validateAndNormalizeParams(e){const t={...e};return t.id=this.validateId(t.id),t.items=this.validateAndNormalizeItems(t.items),this.locationHelperService.validateAndNormalizeLocation(t.loc),t.refresh=Boolean(t.refresh),t}validateId(e){return e&&"string"==typeof e&&0!==e.trim().length?e.trim():""}validateAndNormalizeItems(e){if(!Array.isArray(e)||0===e.length)throw new Error(v.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(v.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(v.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(v.INVALID_FULFILLMENT_ID);return t.quantity=Math.max(0,Math.floor(t.quantity)),t.engravingLines&&(t.engravingLines=t.engravingLines.map((e=>e.trim())).filter((e=>e.length>0))),t}validatePartNumber(e){if(!e||"string"!=typeof e)return!1;const t=e.split("_");return 2===t.length&&14===t[0].length&&t[1].length>0}}class T{constructor(e){this.locationServiceHelper=e,this.taxonomyValues=new Set([...Object.values(n),...Object.values(o),...Object.values(c),...Object.values(h),...Object.values(d),...Object.values(I),...Object.values(u)])}validateAndNormalizeParams(e){const t={...e};return this.validateUPCs(t.upcs),this.locationServiceHelper.validateAndNormalizeLocation(t.loc),t}validateAndNormalizeSearchParams(e){const t=[],i={...e};return this.validateOrderBy(i.orderBy,t),this.validateOrderDirection(i.orderDirection,t),this.validateFilters(i.filters,t),this.validatePagination(i.page,i.perPage,t),this.locationServiceHelper.validateAndNormalizeLocation(i.loc),t.length>0?{...i,error:t.join(". ")}:i}validateUPCs(e){if(!Array.isArray(e)||0===e.length)throw new Error("UPCs must be a non-empty array of strings");if(!e.every((e=>"string"==typeof e&&e.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(e,t){e&&!Object.values(E).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(S).includes(e)&&t.push(`Invalid orderDirection value: ${e}`)}validateFilters(e,t){e&&(e.length>10&&t.push("Maximum of 10 filters allowed"),e.forEach((e=>{switch(Object.values(A).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case A.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case A.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case A.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case A.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(p).includes(e)||t.push(`Invalid availability value: ${e}`)}validateArrayFilter(e,t,i,r){Array.isArray(e)?e.length>t&&r.push(`${i} filter can have a maximum of ${t} values`):r.push(`${i} filter must be an array`)}validateCategoriesFilter(e,t){Array.isArray(e)?e.every((e=>this.taxonomyValues.has(e)))||t.push("Invalid category value(s) in categories filter"):t.push("Categories filter must be an array")}validatePagination(e,t,i){void 0!==e&&("number"!=typeof e||e<0)&&i.push("Page must be a non-negative number"),void 0!==t&&("number"!=typeof t||t<=0)&&i.push("PerPage must be a positive number")}}class y{constructor(e){this.locationHelperService=e}validateAndNormalizePrepareParams(e){const t={...e};if(!t.cartId||"string"!=typeof t.cartId)throw new Error("Invalid cartId");return this.validateRecipient(t.recipient),t.billingAddress&&this.validateAddress(t.billingAddress),t.hasSubstitutionPolicy=Boolean(t.hasSubstitutionPolicy),t.isGift=Boolean(t.isGift),t.billingSameAsShipping=Boolean(t.billingSameAsShipping),t.isGift&&this.validateGiftOptions(t.giftOptions),this.validateMarketingPreferences(t.marketingPreferences),t.deliveryTips&&this.validateDeliveryTips(t.deliveryTips),t.refresh=Boolean(t.refresh),t}validateAndNormalizeCompleteParams(e){const t={...e};if(!t.token||"string"!=typeof t.token)throw new Error("Invalid token");if(!t.payment||"string"!=typeof t.payment)throw new Error("Invalid payment token");return void 0!==t.refresh&&(t.refresh=Boolean(t.refresh)),t}validateRecipient(e){if(!e||"object"!=typeof e)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid recipient ${t}`)})),e.hasAgeVerify=Boolean(e.hasAgeVerify)}validateAddress(e){if(!e||"object"!=typeof e)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid address ${t}`)})),this.locationHelperService.validateAndNormalizeLocation({address:e})}validateGiftOptions(e){if(!e||"object"!=typeof e)throw new Error("Invalid giftOptions");if(e.message&&"string"!=typeof e.message)throw new Error("Invalid gift message");if(e.recipient){const{name:t,phone:i,email:r}=e.recipient;if(t&&"string"!=typeof t)throw new Error("Invalid gift recipient name");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient phone");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(e){if(!e||"object"!=typeof e)throw new Error("Invalid marketingPreferences");e.canEmail=Boolean(e.canEmail),e.canSms=Boolean(e.canSms)}validateDeliveryTips(e){if(!Array.isArray(e))throw new Error("Invalid deliveryTips");e.forEach((e=>{if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof e.tip||e.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class g{validateAndNormalizeLocation(e){if(!e||"object"!=typeof e)throw new Error("Location must be a valid object");if(e.coords)this.validateCoordinates(e.coords);else{if(!e.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(e.address)}}validateCoordinates(e){if("number"!=typeof e.lat||"number"!=typeof e.long)throw new Error("Coordinates must be valid numbers");if(e.lat<-90||e.lat>90||e.long<-180||e.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(e){if(!e.state||"string"!=typeof e.state)throw new Error("State is required and must be a string");if(e.state=this.normalizeState(e.state),!e.city||"string"!=typeof e.city)throw new Error("City is required and must be a string");if(!e.zip||"string"!=typeof e.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(e){const t=e.toUpperCase();if(a[t])return a[t];const i=e.toUpperCase();if(s[i])return s[i];throw new Error(`Invalid state: ${e}`)}}class f{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await e(t.key)}catch(e){throw console.error("Failed to load Stripe:",e),new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const i={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(i);const r=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var e,t,i,r,a,s,n,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:c}=await this.elements.submit();if(c)return{type:"validation_error",message:c.message,code:c.code};const{error:l,paymentMethod:h}=await this.stripe.createPaymentMethod({elements:this.elements});return l?{type:"validation_error"===l.type?"validation_error":"api_error",message:l.message,code:l.code,param:l.param}:h?{id:h.id,type:h.type,card:(null==h?void 0:h.card)?{brand:null!==(t=null===(e=h.card)||void 0===e?void 0:e.brand)&&void 0!==t?t:"",country:null!==(i=h.card.country)&&void 0!==i?i:"",expMonth:null!==(r=h.card.exp_month)&&void 0!==r?r:0,expYear:null!==(a=h.card.exp_year)&&void 0!==a?a:0,last4:null!==(s=h.card.last4)&&void 0!==s?s:"",funding:null!==(n=h.card.funding)&&void 0!==n?n:""}:void 0,created:null!==(o=null==h?void 0:h.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.on(e,t)}unsubscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.off(e,t)}mapAppearance(e){if(e)return{theme:"night"===e.theme?"night":"stripe"}}mapElementOptions(e){return{layout:null==e?void 0:e.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class D{constructor(e){this.client=e}async autocomplete(e,t){try{return await this.client.post("/address/autocomplete",{...e,key:t})}catch(e){throw console.error("Address autocomplete request failed:",e),e}}async details(e,t){try{return await this.client.post("/address/details",{...e,key:t})}catch(e){throw console.error("Address details request failed:",e),e}}}class L{constructor(e,t){this.client=e,this.cartHelperService=t,this.servicePath="/cart/update"}async get(e,t){try{let i=this.cartHelperService.validateId(e);if(i=""!==i&&i,i){const e={id:i};return"boolean"==typeof t&&(e.refresh=t),await this.client.post(this.servicePath,e)}return await this.client.post(this.servicePath)}catch(e){throw console.error("Cart update request failed:",e),e}}async update(e){try{const t=this.cartHelperService.validateAndNormalizeParams(e);return await this.client.post(this.servicePath,t)}catch(e){throw console.error("Cart update request failed:",e),e}}}class w{constructor(e,t){this.client=e,this.catalogHelperService=t,this.servicePath="/catalog/"}async availability(e){try{const t=this.catalogHelperService.validateAndNormalizeParams(e);return await this.client.post(`${this.servicePath}availability`,t)}catch(e){throw console.error("Catalog availability request failed:",e),e}}async search(e){try{const t=this.catalogHelperService.validateAndNormalizeSearchParams(e);if(null==t?void 0:t.error)throw new Error(null==t?void 0:t.error);return await this.client.post(`${this.servicePath}search`,t)}catch(e){throw console.error("Catalog search request failed:",e),e}}}class P{constructor(e,t){this.client=e,this.checkoutHelperService=t,this.servicePath="/checkout"}async prepare(e){try{const t=this.checkoutHelperService.validateAndNormalizePrepareParams(e);return await this.client.post(`${this.servicePath}/prepare`,t)}catch(e){throw console.error("Checkout prepare request failed:",e),e}}async complete(e){try{const t=this.checkoutHelperService.validateAndNormalizeCompleteParams(e);return await this.client.post(`${this.servicePath}/complete`,t)}catch(e){throw console.error("Checkout complete request failed:",e),e}}}class M{constructor(e){this.paymentProvider=e}async mount(e){try{await this.paymentProvider.mount(e)}catch(e){throw console.error("Failed to inject payment element:",e),e}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(e,t){this.paymentProvider.subscribe(e,t)}unsubscribe(e,t){this.paymentProvider.unsubscribe(e,t)}}class _{constructor(e){this.client=e,this.servicePath="/users"}async createOrUpdateSession(e){try{if(!(null==e?void 0:e.id)&&!(null==e?void 0:e.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,e)}catch(e){throw console.error("User session creation/update request failed:",e),e}}async purge(e){try{if(!e)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${e}`)}catch(e){throw console.error("User purge request failed:",e),e}}async updateAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,e)}catch(e){throw console.error("User address update request failed:",e),e}}async purgeAddress(e){try{if(!e)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${e}`)}catch(e){throw console.error("Address purge request failed:",e),e}}}class H{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return H.instance||(H.instance=new H),H.instance}setLiquidCommerceClientConstructor(e){this.liquidCommerceClientConstructor=e}async getLiquidCommerceClient(e,t){const i=`LiquidCommerceClient_${e}_${JSON.stringify(t)}`;if(!this.services.has(i)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const r=new this.liquidCommerceClientConstructor(e,t);await r.init(),this.services.set(i,r)}return this.services.get(i)}getOrCreateService(e,t,...i){if(!this.services.has(e)){const r="getInstance"in t?t.getInstance(...i):new t(...i);this.services.set(e,r)}return this.services.get(e)}getAuthenticatedClient(e){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(e)}`,N,e)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",g)}getAddressService(e){return this.getOrCreateService(`AddressService_${e.getUniqueKey()}`,D,e)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",T,this.getLocationHelperService())}getCatalogService(e){return this.getOrCreateService(`CatalogService_${e.getUniqueKey()}`,w,e,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",O,this.getLocationHelperService())}getCartService(e){return this.getOrCreateService(`CartService_${e.getUniqueKey()}`,L,e,this.getCartHelperService())}getUserService(e){return this.getOrCreateService(`UserService_${e.getUniqueKey()}`,_,e)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",f)}getPaymentService(){return this.getOrCreateService("PaymentService",M,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",y,this.getLocationHelperService())}getCheckoutService(e){return this.getOrCreateService(`CheckoutService_${e.getUniqueKey()}`,P,e,this.getCheckoutHelperService())}}H.instance=null;class b{constructor(e,t){this.address={autocomplete:async e=>(await this.ensureAuthenticated(),this.addressService.autocomplete(e,this.config.googlePlacesApiKey)),details:async e=>(await this.ensureAuthenticated(),this.addressService.details(e,this.config.googlePlacesApiKey))},this.catalog={availability:async e=>(await this.ensureAuthenticated(),this.catalogService.availability(e)),search:async e=>(await this.ensureAuthenticated(),this.catalogService.search(e))},this.cart={get:async(e,t)=>(await this.ensureAuthenticated(),this.cartService.get(e,t)),update:async e=>(await this.ensureAuthenticated(),this.cartService.update(e))},this.user={session:async e=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(e)),purge:async e=>(await this.ensureAuthenticated(),this.userService.purge(e)),updateAddress:async e=>(await this.ensureAuthenticated(),this.userService.updateAddress(e)),purgeAddress:async e=>(await this.ensureAuthenticated(),this.userService.purgeAddress(e))},this.payment={mount:async e=>(await this.ensureAuthenticated(),this.paymentService.mount(e)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(e,t)=>{this.paymentService.subscribe(e,t)},unsubscribe:(e,t)=>{this.paymentService.unsubscribe(e,t)}},this.checkout={prepare:async e=>(await this.ensureAuthenticated(),this.checkoutService.prepare(e)),complete:async e=>(await this.ensureAuthenticated(),this.checkoutService.complete(e))},this.config=t,this.singletonManager=H.getInstance();const i=this.determineBaseURL(t);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:e,baseURL:i}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const i=e.env||t.STAGE;return C[i]}async init(){try{await this.authenticatedClient.authenticate()}catch(e){throw console.error("Failed to initialize LiquidCommerceClient:",e),new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}async function U(e,t){const i=H.getInstance();i.setLiquidCommerceClientConstructor(b);return await i.getLiquidCommerceClient(e,t)}export{t as LIQUID_COMMERCE_ENV,U as LiquidCommerce};
1
+ import{loadStripe as e}from"@stripe/stripe-js";var t,i,r,a,s,n,o,c,l,h,d,I,u,A,S,E,p,v,R,m;!function(e){e.LOC="loc",e.STAGE="stage",e.PROD="prod",e.DEV="dev"}(t||(t={})),function(e){e.ON_DEMAND="onDemand",e.SHIPPING="shipping"}(i||(i={})),function(e){e.MONDAY="monday",e.TUESDAY="tuesday",e.WEDNESDAY="wednesday",e.THURSDAY="thursday",e.FRIDAY="friday",e.SATURDAY="saturday",e.SUNDAY="sunday"}(r||(r={})),function(e){e.AL="AL",e.AK="AK",e.AR="AR",e.CA="CA",e.CO="CO",e.CT="CT",e.DE="DE",e.DC="DC",e.FL="FL",e.GA="GA",e.HI="HI",e.ID="ID",e.IL="IL",e.IN="IN",e.IA="IA",e.KS="KS",e.KY="KY",e.LA="LA",e.ME="ME",e.MD="MD",e.MA="MA",e.MI="MI",e.MN="MN",e.MS="MS",e.MO="MO",e.MT="MT",e.NE="NE",e.NV="NV",e.NH="NH",e.NJ="NJ",e.NM="NM",e.NY="NY",e.NC="NC",e.ND="ND",e.OH="OH",e.OK="OK",e.OR="OR",e.PA="PA",e.RI="RI",e.SC="SC",e.SD="SD",e.TN="TN",e.TX="TX",e.UT="UT",e.VT="VT",e.VA="VA",e.WA="WA",e.WV="WV",e.WI="WI",e.WY="WY"}(a||(a={})),function(e){e.ALABAMA="AL",e.ALASKA="AK",e.ARKANSAS="AR",e.CALIFORNIA="CA",e.COLORADO="CO",e.CONNECTICUT="CT",e.DELAWARE="DE",e.DISTRICT_OF_COLUMBIA="DC",e.FLORIDA="FL",e.GEORGIA="GA",e.HAWAII="HI",e.IDAHO="ID",e.ILLINOIS="IL",e.INDIANA="IN",e.IOWA="IA",e.KANSAS="KS",e.KENTUCKY="KY",e.LOUISIANA="LA",e.MAINE="ME",e.MARYLAND="MD",e.MASSACHUSETTS="MA",e.MICHIGAN="MI",e.MINNESOTA="MN",e.MISSISSIPPI="MS",e.MISSOURI="MO",e.MONTANA="MT",e.NEBRASKA="NE",e.NEVADA="NV",e.NEW_HAMPSHIRE="NH",e.NEW_JERSEY="NJ",e.NEW_MEXICO="NM",e.NEW_YORK="NY",e.NORTH_CAROLINA="NC",e.NORTH_DAKOTA="ND",e.OHIO="OH",e.OKLAHOMA="OK",e.OREGON="OR",e.PENNSYLVANIA="PA",e.RHODE_ISLAND="RI",e.SOUTH_CAROLINA="SC",e.SOUTH_DAKOTA="SD",e.TENNESSEE="TN",e.TEXAS="TX",e.UTAH="UT",e.VERMONT="VT",e.VIRGINIA="VA",e.WASHINGTON="WA",e.WEST_VIRGINIA="WV",e.WISCONSIN="WI",e.WYOMING="WY"}(s||(s={})),function(e){e.ALE="BEER > ALE",e.LAGER="BEER > LAGER",e.MAIN="BEER",e.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",e.OTHER_BEER="BEER > OTHER BEER"}(n||(n={})),function(e){e.BASE="FOOD",e.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(o||(o={})),function(e){e.BASE="MERCHANDISE",e.GLASSWARE="MERCHANDISE > GLASSWARE",e.HUMIDOR="MERCHANDISE > HUMIDOR"}(c||(c={})),function(e){e.BASE="MISCELLANEOUS",e.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",e.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",e.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(l||(l={})),function(e){e.BASE="NON ALCOHOLIC",e.BITTERS="NON ALCOHOLIC > BITTERS",e.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",e.COFFEE="NON ALCOHOLIC > COFFEE",e.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",e.JUICE="NON ALCOHOLIC > JUICE",e.SODA="NON ALCOHOLIC > SODA",e.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",e.SPIRITS="NON ALCOHOLIC > SPIRITS",e.TEA="NON ALCOHOLIC > TEA",e.WATER="NON ALCOHOLIC > WATER",e.WINE="NON ALCOHOLIC > WINE"}(h||(h={})),function(e){e.BASE="READY TO DRINK",e.HARD_CIDER="READY TO DRINK > HARD CIDER",e.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",e.HARD_TEA="READY TO DRINK > HARD TEA",e.MALT_BASED="READY TO DRINK > MALT BASED",e.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",e.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",e.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",e.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",e.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",e.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(d||(d={})),function(e){e.BASE="SPIRITS",e.BAIJIU="SPIRITS > BAIJIU",e.BITTERS="SPIRITS > BITTERS",e.BRANDY="SPIRITS > BRANDY",e.CACHACA="SPIRITS > CACHACA",e.GIN="SPIRITS > GIN",e.LAGER="SPIRITS > LAGER",e.LIQUEUR="SPIRITS > LIQUEUR",e.MEZCAL="SPIRITS > MEZCAL",e.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",e.RUM="SPIRITS > RUM",e.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",e.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",e.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",e.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",e.RUM_OTHER="SPIRITS > RUM > OTHER",e.RUM_SPICED="SPIRITS > RUM > SPICED",e.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",e.SOJU="SPIRITS > SOJU",e.TEQUILA="SPIRITS > TEQUILA",e.VODKA="SPIRITS > VODKA",e.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",e.WHISKEY="SPIRITS > WHISKEY",e.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",e.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",e.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",e.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",e.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(I||(I={})),function(e){e.BASE="WINE",e.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",e.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",e.COOKING="WINE > COOKING",e.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",e.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",e.RED_WINE="WINE > RED WINE",e.ROSE_WINE="WINE > ROSE WINE",e.SAKE="WINE > SAKE",e.WHITE_WINE="WINE > WHITE WINE"}(u||(u={})),function(e){e.BRANDS="brands",e.FLAVOR="flavor",e.REGION="region",e.VARIETY="variety",e.PRICE="price",e.AVAILABILITY="availability",e.CATEGORIES="categories",e.SIZES="sizes",e.COLORS="colors",e.APPELLATION="appellation",e.COUNTRY="country",e.VINTAGE="vintage",e.MATERIALS="materials"}(A||(A={})),function(e){e.ASC="asc",e.DESC="desc"}(S||(S={})),function(e){e.PRICE="price"}(E||(E={})),function(e){e.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",e.IN_STOCK="IN_STOCK",e.OUT_OF_STOCK="OUT_OF_STOCK",e.PREORDER="PREORDER",e.BACKORDER="BACKORDER"}(p||(p={})),function(e){e.INVALID_ITEMS_TYPE="Items must be a non-empty array",e.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",e.INVALID_PART_NUMBER="The partnerNumber provided is invalid",e.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(v||(v={})),function(e){e.OOS="OutOfStock",e.ITEMS_NOT_ADDED="ItemsNotAdded",e.ITEM_NOT_ENGRAVED="ItemEngravingError",e.ADDRESS_CHANGE="AddressChange",e.RETAILER_MIN="RetailerMinNotMet",e.NO_ITEMS_IN_CART="NoItemsInCart",e.INVALID_ID="InvalidId",e.NO_ID="NoId",e.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",e.NEW_CART="NewCart",e.DEFAULT="CartError",e.ITEM_QTY_CHANGE="ItemQuantityChange"}(R||(R={})),function(e){e.SHIPPING="shipping",e.BILLING="billing"}(m||(m={}));const C={[t.LOC]:"https://staging.cloud.liquidcommerce.co/api",[t.DEV]:"https://staging.cloud.liquidcommerce.co/api",[t.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[t.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class N{constructor(e){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(e,t)=>new Promise(((i,r)=>{const a=new XMLHttpRequest;a.open(t.method||"GET",e),Object.entries(t.headers).forEach((([e,t])=>{a.setRequestHeader(e,t)})),a.onload=()=>{i({ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,headers:a.getAllResponseHeaders().split("\r\n").reduce(((e,t)=>{const[i,r]=t.split(": ");return i&&(e[i]=r),e}),{}),json:()=>Promise.resolve(JSON.parse(a.responseText)),text:()=>Promise.resolve(a.responseText)})},a.onerror=()=>{r(new TypeError("Network request failed"))},a.send(t.body)})),this.apiKey=e.apiKey,this.baseURL=e.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(e){return N.instance||(N.instance=new N(e)),N.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):"undefined"!=typeof window&&window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(e){return async(t,i)=>{var r;const a=await e(t,i);let s;return"function"==typeof(null===(r=a.headers)||void 0===r?void 0:r.entries)?s=Object.fromEntries(a.headers.entries()):(s={},a.headers.forEach(((e,t)=>{s[t]=e}))),{ok:a.ok,status:a.status,statusText:a.statusText,headers:s,json:()=>a.json(),text:()=>a.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var e,t;if(this.isAuthenticating)await new Promise((e=>{const t=()=>{this.isAuthenticating?setTimeout(t,100):e(void 0)};t()}));else{this.isAuthenticating=!0;try{const i=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(e=null==i?void 0:i.data)||void 0===e?void 0:e.token,this.tokenExpiration=Date.now()+1e3*(null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.exp)}catch(e){throw console.error("Authentication failed:",e),new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(e,t){const i=new URL(`api${e}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...t.headers},a={method:t.method,headers:r,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(i.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(e,t){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const i=new URL(`api${e}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...t.headers},a={method:t.method,headers:r,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(i.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}async get(e,t){return this.request(e,{method:"GET",headers:t})}async post(e,t,i){return this.request(e,{method:"POST",body:t,headers:i})}async put(e,t,i){return this.request(e,{method:"PUT",body:t,headers:i})}async delete(e,t){return this.request(e,{method:"DELETE",headers:t})}}N.instance=null;class O{constructor(e){this.locationHelperService=e}validateAndNormalizeParams(e){const t={...e};return t.id=this.validateId(t.id),t.items=this.validateAndNormalizeItems(t.items),this.locationHelperService.validateAndNormalizeLocation(t.loc),t.refresh=Boolean(t.refresh),t}validateId(e){return e&&"string"==typeof e&&0!==e.trim().length?e.trim():""}validateAndNormalizeItems(e){if(!Array.isArray(e)||0===e.length)throw new Error(v.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(v.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(v.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(v.INVALID_FULFILLMENT_ID);return t.quantity=Math.max(0,Math.floor(t.quantity)),t.engravingLines&&(t.engravingLines=t.engravingLines.map((e=>e.trim())).filter((e=>e.length>0))),t}validatePartNumber(e){if(!e||"string"!=typeof e)return!1;const t=e.split("_");return 2===t.length&&14===t[0].length&&t[1].length>0}}class T{constructor(e){this.locationServiceHelper=e,this.taxonomyValues=new Set([...Object.values(n),...Object.values(o),...Object.values(c),...Object.values(h),...Object.values(d),...Object.values(I),...Object.values(u)])}validateAndNormalizeParams(e){const t={...e};return this.validateUPCs(t.upcs),this.locationServiceHelper.validateAndNormalizeLocation(t.loc),t}validateAndNormalizeSearchParams(e){const t=[],i={...e};return this.validateOrderBy(i.orderBy,t),this.validateOrderDirection(i.orderDirection,t),this.validateFilters(i.filters,t),this.validatePagination(i.page,i.perPage,t),this.locationServiceHelper.validateAndNormalizeLocation(i.loc),t.length>0?{...i,error:t.join(". ")}:i}validateUPCs(e){if(!Array.isArray(e)||0===e.length)throw new Error("UPCs must be a non-empty array of strings");if(!e.every((e=>"string"==typeof e&&e.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(e,t){e&&!Object.values(E).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(S).includes(e)&&t.push(`Invalid orderDirection value: ${e}`)}validateFilters(e,t){e&&(e.length>10&&t.push("Maximum of 10 filters allowed"),e.forEach((e=>{switch(Object.values(A).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case A.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case A.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case A.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case A.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(p).includes(e)||t.push(`Invalid availability value: ${e}`)}validateArrayFilter(e,t,i,r){Array.isArray(e)?e.length>t&&r.push(`${i} filter can have a maximum of ${t} values`):r.push(`${i} filter must be an array`)}validateCategoriesFilter(e,t){Array.isArray(e)?e.every((e=>this.taxonomyValues.has(e)))||t.push("Invalid category value(s) in categories filter"):t.push("Categories filter must be an array")}validatePagination(e,t,i){void 0!==e&&("number"!=typeof e||e<0)&&i.push("Page must be a non-negative number"),void 0!==t&&("number"!=typeof t||t<=0)&&i.push("PerPage must be a positive number")}}class y{constructor(e){this.locationHelperService=e}validateAndNormalizePrepareParams(e){const t={...e};if(!t.cartId||"string"!=typeof t.cartId)throw new Error("Invalid cartId");return this.validateRecipient(t.recipient),t.billingAddress&&this.validateAddress(t.billingAddress),t.hasSubstitutionPolicy=Boolean(t.hasSubstitutionPolicy),t.isGift=Boolean(t.isGift),t.billingSameAsShipping=Boolean(t.billingSameAsShipping),t.isGift&&this.validateGiftOptions(t.giftOptions),this.validateMarketingPreferences(t.marketingPreferences),t.deliveryTips&&this.validateDeliveryTips(t.deliveryTips),t.refresh=Boolean(t.refresh),t}validateAndNormalizeCompleteParams(e){const t={...e};if(!t.token||"string"!=typeof t.token)throw new Error("Invalid token");if(!t.payment||"string"!=typeof t.payment)throw new Error("Invalid payment token");return void 0!==t.refresh&&(t.refresh=Boolean(t.refresh)),t}validateRecipient(e){if(!e||"object"!=typeof e)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid recipient ${t}`)})),e.hasAgeVerify=Boolean(e.hasAgeVerify)}validateAddress(e){if(!e||"object"!=typeof e)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid address ${t}`)})),this.locationHelperService.validateAndNormalizeLocation({address:e})}validateGiftOptions(e){if(!e||"object"!=typeof e)throw new Error("Invalid giftOptions");if(e.message&&"string"!=typeof e.message)throw new Error("Invalid gift message");if(e.recipient){const{name:t,phone:i,email:r}=e.recipient;if(t&&"string"!=typeof t)throw new Error("Invalid gift recipient name");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient phone");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(e){if(!e||"object"!=typeof e)throw new Error("Invalid marketingPreferences");e.canEmail=Boolean(e.canEmail),e.canSms=Boolean(e.canSms)}validateDeliveryTips(e){if(!Array.isArray(e))throw new Error("Invalid deliveryTips");e.forEach((e=>{if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof e.tip||e.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class g{validateAndNormalizeLocation(e){if(!e||"object"!=typeof e)throw new Error("Location must be a valid object");if(e.coords)this.validateCoordinates(e.coords);else{if(!e.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(e.address)}}validateCoordinates(e){if("number"!=typeof e.lat||"number"!=typeof e.long)throw new Error("Coordinates must be valid numbers");if(e.lat<-90||e.lat>90||e.long<-180||e.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(e){if(!e.state||"string"!=typeof e.state)throw new Error("State is required and must be a string");if(e.state=this.normalizeState(e.state),!e.city||"string"!=typeof e.city)throw new Error("City is required and must be a string");if(!e.zip||"string"!=typeof e.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(e){const t=e.toUpperCase();if(a[t])return a[t];const i=e.toUpperCase();if(s[i])return s[i];throw new Error(`Invalid state: ${e}`)}}class f{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await e(t.key)}catch(e){throw console.error("Failed to load Stripe:",e),new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const i={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(i);const r=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var e,t,i,r,a,s,n,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:c}=await this.elements.submit();if(c)return{type:"validation_error",message:c.message,code:c.code};const{error:l,paymentMethod:h}=await this.stripe.createPaymentMethod({elements:this.elements});return l?{type:"validation_error"===l.type?"validation_error":"api_error",message:l.message,code:l.code,param:l.param}:h?{id:h.id,type:h.type,card:(null==h?void 0:h.card)?{brand:null!==(t=null===(e=h.card)||void 0===e?void 0:e.brand)&&void 0!==t?t:"",country:null!==(i=h.card.country)&&void 0!==i?i:"",expMonth:null!==(r=h.card.exp_month)&&void 0!==r?r:0,expYear:null!==(a=h.card.exp_year)&&void 0!==a?a:0,last4:null!==(s=h.card.last4)&&void 0!==s?s:"",funding:null!==(n=h.card.funding)&&void 0!==n?n:""}:void 0,created:null!==(o=null==h?void 0:h.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.on(e,t)}unsubscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.off(e,t)}mapAppearance(e){if(e)return{theme:"night"===e.theme?"night":"stripe"}}mapElementOptions(e){return{layout:null==e?void 0:e.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class D{constructor(e){this.client=e}async autocomplete(e,t){try{return await this.client.post("/address/autocomplete",{...e,key:t})}catch(e){throw console.error("Address autocomplete request failed:",e),e}}async details(e,t){try{return await this.client.post("/address/details",{...e,key:t})}catch(e){throw console.error("Address details request failed:",e),e}}}class L{constructor(e,t){this.client=e,this.cartHelperService=t,this.servicePath="/cart/update"}async get(e,t){try{let i=this.cartHelperService.validateId(e);if(i=""!==i&&i,i){const e={id:i};return"boolean"==typeof t&&(e.refresh=t),await this.client.post(this.servicePath,e)}return await this.client.post(this.servicePath)}catch(e){throw console.error("Cart update request failed:",e),e}}async update(e){try{const t=this.cartHelperService.validateAndNormalizeParams(e);return await this.client.post(this.servicePath,t)}catch(e){throw console.error("Cart update request failed:",e),e}}}class w{constructor(e,t){this.client=e,this.catalogHelperService=t,this.servicePath="/catalog/"}async availability(e){try{const t=this.catalogHelperService.validateAndNormalizeParams(e);return await this.client.post(`${this.servicePath}availability`,t)}catch(e){throw console.error("Catalog availability request failed:",e),e}}async search(e){try{const t=this.catalogHelperService.validateAndNormalizeSearchParams(e);if(null==t?void 0:t.error)throw new Error(null==t?void 0:t.error);return await this.client.post(`${this.servicePath}search`,t)}catch(e){throw console.error("Catalog search request failed:",e),e}}}class P{constructor(e,t){this.client=e,this.checkoutHelperService=t,this.servicePath="/checkout"}async prepare(e){try{const t=this.checkoutHelperService.validateAndNormalizePrepareParams(e);return await this.client.post(`${this.servicePath}/prepare`,t)}catch(e){throw console.error("Checkout prepare request failed:",e),e}}async complete(e){try{const t=this.checkoutHelperService.validateAndNormalizeCompleteParams(e);return await this.client.post(`${this.servicePath}/complete`,t)}catch(e){throw console.error("Checkout complete request failed:",e),e}}}class M{constructor(e){this.paymentProvider=e}async mount(e){try{await this.paymentProvider.mount(e)}catch(e){throw console.error("Failed to inject payment element:",e),e}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(e,t){this.paymentProvider.subscribe(e,t)}unsubscribe(e,t){this.paymentProvider.unsubscribe(e,t)}}class _{constructor(e){this.client=e,this.servicePath="/users"}async createOrUpdateSession(e){try{if(!(null==e?void 0:e.id)&&!(null==e?void 0:e.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,e)}catch(e){throw console.error("User session creation/update request failed:",e),e}}async purge(e){try{if(!e)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${e}`)}catch(e){throw console.error("User purge request failed:",e),e}}async updateAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,e)}catch(e){throw console.error("User address update request failed:",e),e}}async purgeAddress(e){try{if(!e)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${e}`)}catch(e){throw console.error("Address purge request failed:",e),e}}}class H{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return H.instance||(H.instance=new H),H.instance}setLiquidCommerceClientConstructor(e){this.liquidCommerceClientConstructor=e}async getLiquidCommerceClient(e,t){const i=`LiquidCommerceClient_${e}_${JSON.stringify(t)}`;if(!this.services.has(i)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const r=new this.liquidCommerceClientConstructor(e,t);await r.init(),this.services.set(i,r)}return this.services.get(i)}getOrCreateService(e,t,...i){if(!this.services.has(e)){const r="getInstance"in t?t.getInstance(...i):new t(...i);this.services.set(e,r)}return this.services.get(e)}getAuthenticatedClient(e){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(e)}`,N,e)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",g)}getAddressService(e){return this.getOrCreateService(`AddressService_${e.getUniqueKey()}`,D,e)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",T,this.getLocationHelperService())}getCatalogService(e){return this.getOrCreateService(`CatalogService_${e.getUniqueKey()}`,w,e,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",O,this.getLocationHelperService())}getCartService(e){return this.getOrCreateService(`CartService_${e.getUniqueKey()}`,L,e,this.getCartHelperService())}getUserService(e){return this.getOrCreateService(`UserService_${e.getUniqueKey()}`,_,e)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",f)}getPaymentService(){return this.getOrCreateService("PaymentService",M,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",y,this.getLocationHelperService())}getCheckoutService(e){return this.getOrCreateService(`CheckoutService_${e.getUniqueKey()}`,P,e,this.getCheckoutHelperService())}}H.instance=null;class b{constructor(e,t){this.address={autocomplete:async e=>(await this.ensureAuthenticated(),this.addressService.autocomplete(e,this.config.googlePlacesApiKey)),details:async e=>(await this.ensureAuthenticated(),this.addressService.details(e,this.config.googlePlacesApiKey))},this.catalog={availability:async e=>(await this.ensureAuthenticated(),this.catalogService.availability(e)),search:async e=>(await this.ensureAuthenticated(),this.catalogService.search(e))},this.cart={get:async(e,t)=>(await this.ensureAuthenticated(),this.cartService.get(e,t)),update:async e=>(await this.ensureAuthenticated(),this.cartService.update(e))},this.user={session:async e=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(e)),purge:async e=>(await this.ensureAuthenticated(),this.userService.purge(e)),updateAddress:async e=>(await this.ensureAuthenticated(),this.userService.updateAddress(e)),purgeAddress:async e=>(await this.ensureAuthenticated(),this.userService.purgeAddress(e))},this.payment={mount:async e=>(await this.ensureAuthenticated(),this.paymentService.mount(e)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(e,t)=>{this.paymentService.subscribe(e,t)},unsubscribe:(e,t)=>{this.paymentService.unsubscribe(e,t)}},this.checkout={prepare:async e=>(await this.ensureAuthenticated(),this.checkoutService.prepare(e)),complete:async e=>(await this.ensureAuthenticated(),this.checkoutService.complete(e))},this.config=t,this.singletonManager=H.getInstance();const i=this.determineBaseURL(t);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:e,baseURL:i}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const i=e.env||t.STAGE;return C[i]}async init(){try{await this.authenticatedClient.authenticate()}catch(e){throw console.error("Failed to initialize LiquidCommerceClient:",e),new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}async function U(e,t){const i=H.getInstance();i.setLiquidCommerceClientConstructor(b);return await i.getLiquidCommerceClient(e,t)}export{R as CART_EVENT_ENUM,v as CART_PARAM_ERROR_ENUM,r as DAYS_OF_WEEK,m as ENUM_ADDRESS_TYPE,p as ENUM_AVAILABILITY_VALUE,n as ENUM_BEER,A as ENUM_FILTER_KEYS,o as ENUM_FOOD,c as ENUM_MERCHANDISE,l as ENUM_MISCELLANEOUS,i as ENUM_MODALITIES,S as ENUM_NAVIGATION_ORDER_DIRECTION_TYPE,h as ENUM_NON_ALCOHOLIC,E as ENUM_ORDER_BY,d as ENUM_READY_TO_DRINK,I as ENUM_SPIRITS,u as ENUM_WINE,t as LIQUID_COMMERCE_ENV,U as LiquidCommerce,a as STATES_CODE,s as STATES_NAME};
@@ -1 +1 @@
1
- "use strict";var LIQUID_COMMERCE_ENV,t,e,i,r,s,a,n,o,h,c,l,d,u,I,E,S,w,y,p,A=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(LIQUID_COMMERCE_ENV=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).DEV="dev",LIQUID_COMMERCE_ENV.STAGE="stage",function(t){t.ON_DEMAND="onDemand",t.SHIPPING="shipping"}(t||(t={})),function(t){t.MONDAY="monday",t.TUESDAY="tuesday",t.WEDNESDAY="wednesday",t.THURSDAY="thursday",t.FRIDAY="friday",t.SATURDAY="saturday",t.SUNDAY="sunday"}(e||(e={})),function(t){t.AL="AL",t.AK="AK",t.AR="AR",t.CA="CA",t.CO="CO",t.CT="CT",t.DE="DE",t.DC="DC",t.FL="FL",t.GA="GA",t.HI="HI",t.ID="ID",t.IL="IL",t.IN="IN",t.IA="IA",t.KS="KS",t.KY="KY",t.LA="LA",t.ME="ME",t.MD="MD",t.MA="MA",t.MI="MI",t.MN="MN",t.MS="MS",t.MO="MO",t.MT="MT",t.NE="NE",t.NV="NV",t.NH="NH",t.NJ="NJ",t.NM="NM",t.NY="NY",t.NC="NC",t.ND="ND",t.OH="OH",t.OK="OK",t.OR="OR",t.PA="PA",t.RI="RI",t.SC="SC",t.SD="SD",t.TN="TN",t.TX="TX",t.UT="UT",t.VT="VT",t.VA="VA",t.WA="WA",t.WV="WV",t.WI="WI",t.WY="WY"}(i||(i={})),function(t){t.ALABAMA="AL",t.ALASKA="AK",t.ARKANSAS="AR",t.CALIFORNIA="CA",t.COLORADO="CO",t.CONNECTICUT="CT",t.DELAWARE="DE",t.DISTRICT_OF_COLUMBIA="DC",t.FLORIDA="FL",t.GEORGIA="GA",t.HAWAII="HI",t.IDAHO="ID",t.ILLINOIS="IL",t.INDIANA="IN",t.IOWA="IA",t.KANSAS="KS",t.KENTUCKY="KY",t.LOUISIANA="LA",t.MAINE="ME",t.MARYLAND="MD",t.MASSACHUSETTS="MA",t.MICHIGAN="MI",t.MINNESOTA="MN",t.MISSISSIPPI="MS",t.MISSOURI="MO",t.MONTANA="MT",t.NEBRASKA="NE",t.NEVADA="NV",t.NEW_HAMPSHIRE="NH",t.NEW_JERSEY="NJ",t.NEW_MEXICO="NM",t.NEW_YORK="NY",t.NORTH_CAROLINA="NC",t.NORTH_DAKOTA="ND",t.OHIO="OH",t.OKLAHOMA="OK",t.OREGON="OR",t.PENNSYLVANIA="PA",t.RHODE_ISLAND="RI",t.SOUTH_CAROLINA="SC",t.SOUTH_DAKOTA="SD",t.TENNESSEE="TN",t.TEXAS="TX",t.UTAH="UT",t.VERMONT="VT",t.VIRGINIA="VA",t.WASHINGTON="WA",t.WEST_VIRGINIA="WV",t.WISCONSIN="WI",t.WYOMING="WY"}(r||(r={})),function(t){t.ALE="BEER > ALE",t.LAGER="BEER > LAGER",t.MAIN="BEER",t.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",t.OTHER_BEER="BEER > OTHER BEER"}(s||(s={})),function(t){t.BASE="FOOD",t.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(a||(a={})),function(t){t.BASE="MERCHANDISE",t.GLASSWARE="MERCHANDISE > GLASSWARE",t.HUMIDOR="MERCHANDISE > HUMIDOR"}(n||(n={})),function(t){t.BASE="MISCELLANEOUS",t.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",t.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",t.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(o||(o={})),function(t){t.BASE="NON ALCOHOLIC",t.BITTERS="NON ALCOHOLIC > BITTERS",t.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",t.COFFEE="NON ALCOHOLIC > COFFEE",t.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",t.JUICE="NON ALCOHOLIC > JUICE",t.SODA="NON ALCOHOLIC > SODA",t.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",t.SPIRITS="NON ALCOHOLIC > SPIRITS",t.TEA="NON ALCOHOLIC > TEA",t.WATER="NON ALCOHOLIC > WATER",t.WINE="NON ALCOHOLIC > WINE"}(h||(h={})),function(t){t.BASE="READY TO DRINK",t.HARD_CIDER="READY TO DRINK > HARD CIDER",t.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",t.HARD_TEA="READY TO DRINK > HARD TEA",t.MALT_BASED="READY TO DRINK > MALT BASED",t.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",t.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",t.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",t.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",t.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",t.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(c||(c={})),function(t){t.BASE="SPIRITS",t.BAIJIU="SPIRITS > BAIJIU",t.BITTERS="SPIRITS > BITTERS",t.BRANDY="SPIRITS > BRANDY",t.CACHACA="SPIRITS > CACHACA",t.GIN="SPIRITS > GIN",t.LAGER="SPIRITS > LAGER",t.LIQUEUR="SPIRITS > LIQUEUR",t.MEZCAL="SPIRITS > MEZCAL",t.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",t.RUM="SPIRITS > RUM",t.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",t.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",t.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",t.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",t.RUM_OTHER="SPIRITS > RUM > OTHER",t.RUM_SPICED="SPIRITS > RUM > SPICED",t.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",t.SOJU="SPIRITS > SOJU",t.TEQUILA="SPIRITS > TEQUILA",t.VODKA="SPIRITS > VODKA",t.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",t.WHISKEY="SPIRITS > WHISKEY",t.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",t.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",t.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",t.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",t.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(l||(l={})),function(t){t.BASE="WINE",t.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",t.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",t.COOKING="WINE > COOKING",t.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",t.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",t.RED_WINE="WINE > RED WINE",t.ROSE_WINE="WINE > ROSE WINE",t.SAKE="WINE > SAKE",t.WHITE_WINE="WINE > WHITE WINE"}(d||(d={})),function(t){t.BRANDS="brands",t.FLAVOR="flavor",t.REGION="region",t.VARIETY="variety",t.PRICE="price",t.AVAILABILITY="availability",t.CATEGORIES="categories",t.SIZES="sizes",t.COLORS="colors",t.APPELLATION="appellation",t.COUNTRY="country",t.VINTAGE="vintage",t.MATERIALS="materials"}(u||(u={})),function(t){t.ASC="asc",t.DESC="desc"}(I||(I={})),function(t){t.PRICE="price"}(E||(E={})),function(t){t.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",t.IN_STOCK="IN_STOCK",t.OUT_OF_STOCK="OUT_OF_STOCK",t.PREORDER="PREORDER",t.BACKORDER="BACKORDER"}(S||(S={})),function(t){t.INVALID_ITEMS_TYPE="Items must be a non-empty array",t.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",t.INVALID_PART_NUMBER="The partnerNumber provided is invalid",t.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(w||(w={})),function(t){t.OOS="OutOfStock",t.ITEMS_NOT_ADDED="ItemsNotAdded",t.ITEM_NOT_ENGRAVED="ItemEngravingError",t.ADDRESS_CHANGE="AddressChange",t.RETAILER_MIN="RetailerMinNotMet",t.NO_ITEMS_IN_CART="NoItemsInCart",t.INVALID_ID="InvalidId",t.NO_ID="NoId",t.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",t.NEW_CART="NewCart",t.DEFAULT="CartError",t.ITEM_QTY_CHANGE="ItemQuantityChange"}(y||(y={})),function(t){t.SHIPPING="shipping",t.BILLING="billing"}(p||(p={}));const m={[exports.LIQUID_COMMERCE_ENV.DEV]:"https://dev.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api"};class R{constructor(t){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(t,e)=>new Promise(((i,r)=>{const s=new XMLHttpRequest;s.open(e.method||"GET",t),Object.entries(e.headers).forEach((([t,e])=>{s.setRequestHeader(t,e)})),s.onload=()=>{i({ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,headers:s.getAllResponseHeaders().split("\r\n").reduce(((t,e)=>{const[i,r]=e.split(": ");return i&&(t[i]=r),t}),{}),json:()=>Promise.resolve(JSON.parse(s.responseText)),text:()=>Promise.resolve(s.responseText)})},s.onerror=()=>{r(new TypeError("Network request failed"))},s.send(e.body)})),this.apiKey=t.apiKey,this.baseURL=t.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(t){return R.instance||(R.instance=new R(t)),R.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):this.xhrFetch}fetchAdapter(t){return async(e,i)=>{var r;const s=await t(e,i);let a;return"function"==typeof(null===(r=s.headers)||void 0===r?void 0:r.entries)?a=Object.fromEntries(s.headers.entries()):(a={},s.headers.forEach(((t,e)=>{a[e]=t}))),{ok:s.ok,status:s.status,statusText:s.statusText,headers:a,json:()=>s.json(),text:()=>s.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var t,e;if(this.isAuthenticating)await new Promise((t=>{const e=()=>{this.isAuthenticating?setTimeout(e,100):t(void 0)};e()}));else{this.isAuthenticating=!0;try{const i=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.token,this.tokenExpiration=Date.now()+1e3*(null===(e=null==i?void 0:i.data)||void 0===e?void 0:e.exp)}catch(t){throw new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(t,e){const i=new URL(`api${t}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...e.headers},s={method:e.method,headers:r,body:e.body?JSON.stringify(e.body):void 0},a=await this.httpClient(i.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(t,e){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const i=new URL(`api${t}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...e.headers},s={method:e.method,headers:r,body:e.body?JSON.stringify(e.body):void 0},a=await this.httpClient(i.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}async get(t,e){return this.request(t,{method:"GET",headers:e})}async post(t,e,i){return this.request(t,{method:"POST",body:e,headers:i})}async put(t,e,i){return this.request(t,{method:"PUT",body:e,headers:i})}async delete(t,e){return this.request(t,{method:"DELETE",headers:e})}}R.instance=null;class f{constructor(t){this.locationHelperService=t}validateAndNormalizeParams(t){const e={...t};return e.id=this.validateId(e.id),e.items=this.validateAndNormalizeItems(e.items),this.locationHelperService.validateAndNormalizeLocation(e.loc),e.refresh=Boolean(e.refresh),e}validateId(t){return t&&"string"==typeof t&&0!==t.trim().length?t.trim():""}validateAndNormalizeItems(t){if(!Array.isArray(t)||0===t.length)throw new Error(w.INVALID_ITEMS_TYPE);if(t.length>25)throw new Error(w.INVALID_ITEMS_MAX);return t.map((t=>this.validateAndNormalizeItem(t)))}validateAndNormalizeItem(t){const e={...t};if(!this.validatePartNumber(e.partNumber))throw new Error(w.INVALID_PART_NUMBER);if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId||0===e.fulfillmentId.trim().length)throw new Error(w.INVALID_FULFILLMENT_ID);return e.quantity=Math.max(0,Math.floor(e.quantity)),e.engravingLines&&(e.engravingLines=e.engravingLines.map((t=>t.trim())).filter((t=>t.length>0))),e}validatePartNumber(t){if(!t||"string"!=typeof t)return!1;const e=t.split("_");return 2===e.length&&14===e[0].length&&e[1].length>0}}class v{constructor(t){this.locationServiceHelper=t,this.taxonomyValues=new Set([...Object.values(s),...Object.values(a),...Object.values(n),...Object.values(h),...Object.values(c),...Object.values(l),...Object.values(d)])}validateAndNormalizeParams(t){const e={...t};return this.validateUPCs(e.upcs),this.locationServiceHelper.validateAndNormalizeLocation(e.loc),e}validateAndNormalizeSearchParams(t){const e=[],i={...t};return this.validateOrderBy(i.orderBy,e),this.validateOrderDirection(i.orderDirection,e),this.validateFilters(i.filters,e),this.validatePagination(i.page,i.perPage,e),this.locationServiceHelper.validateAndNormalizeLocation(i.loc),e.length>0?{...i,error:e.join(". ")}:i}validateUPCs(t){if(!Array.isArray(t)||0===t.length)throw new Error("UPCs must be a non-empty array of strings");if(!t.every((t=>"string"==typeof t&&t.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(t,e){t&&!Object.values(E).includes(t)&&e.push(`Invalid orderBy value: ${t}`)}validateOrderDirection(t,e){t&&!Object.values(I).includes(t)&&e.push(`Invalid orderDirection value: ${t}`)}validateFilters(t,e){t&&(t.length>10&&e.push("Maximum of 10 filters allowed"),t.forEach((t=>{switch(Object.values(u).includes(t.key)||e.push(`Invalid filter key: ${t.key}`),t.key){case u.AVAILABILITY:this.validateAvailabilityFilter(t.values,e);break;case u.BRANDS:this.validateArrayFilter(t.values,30,"brands",e);break;case u.CATEGORIES:this.validateCategoriesFilter(t.values,e);break;case u.COLORS:this.validateArrayFilter(t.values,75,"colors",e)}})))}validateAvailabilityFilter(t,e){Object.values(S).includes(t)||e.push(`Invalid availability value: ${t}`)}validateArrayFilter(t,e,i,r){Array.isArray(t)?t.length>e&&r.push(`${i} filter can have a maximum of ${e} values`):r.push(`${i} filter must be an array`)}validateCategoriesFilter(t,e){Array.isArray(t)?t.every((t=>this.taxonomyValues.has(t)))||e.push("Invalid category value(s) in categories filter"):e.push("Categories filter must be an array")}validatePagination(t,e,i){void 0!==t&&("number"!=typeof t||t<0)&&i.push("Page must be a non-negative number"),void 0!==e&&("number"!=typeof e||e<=0)&&i.push("PerPage must be a positive number")}}class O{constructor(t){this.locationHelperService=t}validateAndNormalizePrepareParams(t){const e={...t};if(!e.cartId||"string"!=typeof e.cartId)throw new Error("Invalid cartId");return this.validateRecipient(e.recipient),e.billingAddress&&this.validateAddress(e.billingAddress),e.hasSubstitutionPolicy=Boolean(e.hasSubstitutionPolicy),e.isGift=Boolean(e.isGift),e.billingSameAsShipping=Boolean(e.billingSameAsShipping),e.isGift&&this.validateGiftOptions(e.giftOptions),this.validateMarketingPreferences(e.marketingPreferences),e.deliveryTips&&this.validateDeliveryTips(e.deliveryTips),e.refresh=Boolean(e.refresh),e}validateAndNormalizeCompleteParams(t){const e={...t};if(!e.token||"string"!=typeof e.token)throw new Error("Invalid token");if(!e.payment||"string"!=typeof e.payment)throw new Error("Invalid payment token");return void 0!==e.refresh&&(e.refresh=Boolean(e.refresh)),e}validateRecipient(t){if(!t||"object"!=typeof t)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid recipient ${e}`)})),t.hasAgeVerify=Boolean(t.hasAgeVerify)}validateAddress(t){if(!t||"object"!=typeof t)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid address ${e}`)})),this.locationHelperService.validateAndNormalizeLocation({address:t})}validateGiftOptions(t){if(!t||"object"!=typeof t)throw new Error("Invalid giftOptions");if(t.message&&"string"!=typeof t.message)throw new Error("Invalid gift message");if(t.recipient){const{name:e,phone:i,email:r}=t.recipient;if(e&&"string"!=typeof e)throw new Error("Invalid gift recipient name");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient phone");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(t){if(!t||"object"!=typeof t)throw new Error("Invalid marketingPreferences");t.canEmail=Boolean(t.canEmail),t.canSms=Boolean(t.canSms)}validateDeliveryTips(t){if(!Array.isArray(t))throw new Error("Invalid deliveryTips");t.forEach((t=>{if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof t.tip||t.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class N{validateAndNormalizeLocation(t){if(!t||"object"!=typeof t)throw new Error("Location must be a valid object");if(t.coords)this.validateCoordinates(t.coords);else{if(!t.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(t.address)}}validateCoordinates(t){if("number"!=typeof t.lat||"number"!=typeof t.long)throw new Error("Coordinates must be valid numbers");if(t.lat<-90||t.lat>90||t.long<-180||t.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(t){if(!t.state||"string"!=typeof t.state)throw new Error("State is required and must be a string");if(t.state=this.normalizeState(t.state),!t.city||"string"!=typeof t.city)throw new Error("City is required and must be a string");if(!t.zip||"string"!=typeof t.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(t){const e=t.toUpperCase();if(i[e])return i[e];const s=t.toUpperCase();if(r[s])return r[s];throw new Error(`Invalid state: ${t}`)}}class T{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await A.loadStripe(t.key)}catch(t){throw new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const e={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(e);const i=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",i),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var t,e,i,r,s,a,n,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:h}=await this.elements.submit();if(h)return{type:"validation_error",message:h.message,code:h.code};const{error:c,paymentMethod:l}=await this.stripe.createPaymentMethod({elements:this.elements});return c?{type:"validation_error"===c.type?"validation_error":"api_error",message:c.message,code:c.code,param:c.param}:l?{id:l.id,type:l.type,card:(null==l?void 0:l.card)?{brand:null!==(e=null===(t=l.card)||void 0===t?void 0:t.brand)&&void 0!==e?e:"",country:null!==(i=l.card.country)&&void 0!==i?i:"",expMonth:null!==(r=l.card.exp_month)&&void 0!==r?r:0,expYear:null!==(s=l.card.exp_year)&&void 0!==s?s:0,last4:null!==(a=l.card.last4)&&void 0!==a?a:"",funding:null!==(n=l.card.funding)&&void 0!==n?n:""}:void 0,created:null!==(o=null==l?void 0:l.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.on(t,e)}unsubscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.off(t,e)}mapAppearance(t){if(t)return{theme:"night"===t.theme?"night":"stripe"}}mapElementOptions(t){return{layout:null==t?void 0:t.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class C{constructor(t){this.client=t}async autocomplete(t,e){try{return await this.client.post("/address/autocomplete",{...t,key:e})}catch(t){throw t}}async details(t,e){try{return await this.client.post("/address/details",{...t,key:e})}catch(t){throw t}}}class g{constructor(t,e){this.client=t,this.cartHelperService=e,this.servicePath="/cart/update"}async get(t,e){try{let i=this.cartHelperService.validateId(t);if(i=""!==i&&i,i){const t={id:i};return"boolean"==typeof e&&(t.refresh=e),await this.client.post(this.servicePath,t)}return await this.client.post(this.servicePath)}catch(t){throw t}}async update(t){try{const e=this.cartHelperService.validateAndNormalizeParams(t);return await this.client.post(this.servicePath,e)}catch(t){throw t}}}class D{constructor(t,e){this.client=t,this.catalogHelperService=e,this.servicePath="/catalog/"}async availability(t){try{const e=this.catalogHelperService.validateAndNormalizeParams(t);return await this.client.post(`${this.servicePath}availability`,e)}catch(t){throw t}}async search(t){try{const e=this.catalogHelperService.validateAndNormalizeSearchParams(t);if(null==e?void 0:e.error)throw new Error(null==e?void 0:e.error);return await this.client.post(`${this.servicePath}search`,e)}catch(t){throw t}}}class P{constructor(t,e){this.client=t,this.checkoutHelperService=e,this.servicePath="/checkout"}async prepare(t){try{const e=this.checkoutHelperService.validateAndNormalizePrepareParams(t);return await this.client.post(`${this.servicePath}/prepare`,e)}catch(t){throw t}}async complete(t){try{const e=this.checkoutHelperService.validateAndNormalizeCompleteParams(t);return await this.client.post(`${this.servicePath}/complete`,e)}catch(t){throw t}}}class L{constructor(t){this.paymentProvider=t}async mount(t){try{await this.paymentProvider.mount(t)}catch(t){throw t}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(t,e){this.paymentProvider.subscribe(t,e)}unsubscribe(t,e){this.paymentProvider.unsubscribe(t,e)}}class b{constructor(t){this.client=t,this.servicePath="/users"}async createOrUpdateSession(t){try{if(!(null==t?void 0:t.id)&&!(null==t?void 0:t.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,t)}catch(t){throw t}}async purge(t){try{if(!t)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${t}`)}catch(t){throw t}}async updateAddress(t){try{if(!(t.customerId&&t.one&&t.city&&t.state&&t.zip&&t.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,t)}catch(t){throw t}}async purgeAddress(t){try{if(!t)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${t}`)}catch(t){throw t}}}class M{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return M.instance||(M.instance=new M),M.instance}setLiquidCommerceClientConstructor(t){this.liquidCommerceClientConstructor=t}async getLiquidCommerceClient(t,e){const i=`LiquidCommerceClient_${t}_${JSON.stringify(e)}`;if(!this.services.has(i)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const r=new this.liquidCommerceClientConstructor(t,e);await r.init(),this.services.set(i,r)}return this.services.get(i)}getOrCreateService(t,e,...i){if(!this.services.has(t)){const r="getInstance"in e?e.getInstance(...i):new e(...i);this.services.set(t,r)}return this.services.get(t)}getAuthenticatedClient(t){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(t)}`,R,t)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",N)}getAddressService(t){return this.getOrCreateService(`AddressService_${t.getUniqueKey()}`,C,t)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",v,this.getLocationHelperService())}getCatalogService(t){return this.getOrCreateService(`CatalogService_${t.getUniqueKey()}`,D,t,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",f,this.getLocationHelperService())}getCartService(t){return this.getOrCreateService(`CartService_${t.getUniqueKey()}`,g,t,this.getCartHelperService())}getUserService(t){return this.getOrCreateService(`UserService_${t.getUniqueKey()}`,b,t)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",T)}getPaymentService(){return this.getOrCreateService("PaymentService",L,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",O,this.getLocationHelperService())}getCheckoutService(t){return this.getOrCreateService(`CheckoutService_${t.getUniqueKey()}`,P,t,this.getCheckoutHelperService())}}M.instance=null;class H{constructor(t,e){this.address={autocomplete:async t=>(await this.ensureAuthenticated(),this.addressService.autocomplete(t,this.config.googlePlacesApiKey)),details:async t=>(await this.ensureAuthenticated(),this.addressService.details(t,this.config.googlePlacesApiKey))},this.catalog={availability:async t=>(await this.ensureAuthenticated(),this.catalogService.availability(t)),search:async t=>(await this.ensureAuthenticated(),this.catalogService.search(t))},this.cart={get:async(t,e)=>(await this.ensureAuthenticated(),this.cartService.get(t,e)),update:async t=>(await this.ensureAuthenticated(),this.cartService.update(t))},this.user={session:async t=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(t)),purge:async t=>(await this.ensureAuthenticated(),this.userService.purge(t)),updateAddress:async t=>(await this.ensureAuthenticated(),this.userService.updateAddress(t)),purgeAddress:async t=>(await this.ensureAuthenticated(),this.userService.purgeAddress(t))},this.payment={mount:async t=>(await this.ensureAuthenticated(),this.paymentService.mount(t)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(t,e)=>{this.paymentService.subscribe(t,e)},unsubscribe:(t,e)=>{this.paymentService.unsubscribe(t,e)}},this.checkout={prepare:async t=>(await this.ensureAuthenticated(),this.checkoutService.prepare(t)),complete:async t=>(await this.ensureAuthenticated(),this.checkoutService.complete(t))},this.config=e,this.singletonManager=M.getInstance();const i=this.determineBaseURL(e);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:t,baseURL:i}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(t){const e=t.env||exports.LIQUID_COMMERCE_ENV.STAGE;return m[e]}async init(){try{await this.authenticatedClient.authenticate()}catch(t){throw new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}exports.LiquidCommerce=async function(t,e){const i=M.getInstance();return i.setLiquidCommerceClientConstructor(H),await i.getLiquidCommerceClient(t,e)};
1
+ "use strict";var LIQUID_COMMERCE_ENV,t,e,r,i,s,o,a,n,h,c,d,l,p,I,u,E,S,w,y=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(LIQUID_COMMERCE_ENV=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).LOC="loc",LIQUID_COMMERCE_ENV.STAGE="stage",LIQUID_COMMERCE_ENV.PROD="prod",LIQUID_COMMERCE_ENV.DEV="dev",exports.ENUM_MODALITIES=void 0,(t=exports.ENUM_MODALITIES||(exports.ENUM_MODALITIES={})).ON_DEMAND="onDemand",t.SHIPPING="shipping",exports.DAYS_OF_WEEK=void 0,(e=exports.DAYS_OF_WEEK||(exports.DAYS_OF_WEEK={})).MONDAY="monday",e.TUESDAY="tuesday",e.WEDNESDAY="wednesday",e.THURSDAY="thursday",e.FRIDAY="friday",e.SATURDAY="saturday",e.SUNDAY="sunday",exports.STATES_CODE=void 0,(r=exports.STATES_CODE||(exports.STATES_CODE={})).AL="AL",r.AK="AK",r.AR="AR",r.CA="CA",r.CO="CO",r.CT="CT",r.DE="DE",r.DC="DC",r.FL="FL",r.GA="GA",r.HI="HI",r.ID="ID",r.IL="IL",r.IN="IN",r.IA="IA",r.KS="KS",r.KY="KY",r.LA="LA",r.ME="ME",r.MD="MD",r.MA="MA",r.MI="MI",r.MN="MN",r.MS="MS",r.MO="MO",r.MT="MT",r.NE="NE",r.NV="NV",r.NH="NH",r.NJ="NJ",r.NM="NM",r.NY="NY",r.NC="NC",r.ND="ND",r.OH="OH",r.OK="OK",r.OR="OR",r.PA="PA",r.RI="RI",r.SC="SC",r.SD="SD",r.TN="TN",r.TX="TX",r.UT="UT",r.VT="VT",r.VA="VA",r.WA="WA",r.WV="WV",r.WI="WI",r.WY="WY",exports.STATES_NAME=void 0,(i=exports.STATES_NAME||(exports.STATES_NAME={})).ALABAMA="AL",i.ALASKA="AK",i.ARKANSAS="AR",i.CALIFORNIA="CA",i.COLORADO="CO",i.CONNECTICUT="CT",i.DELAWARE="DE",i.DISTRICT_OF_COLUMBIA="DC",i.FLORIDA="FL",i.GEORGIA="GA",i.HAWAII="HI",i.IDAHO="ID",i.ILLINOIS="IL",i.INDIANA="IN",i.IOWA="IA",i.KANSAS="KS",i.KENTUCKY="KY",i.LOUISIANA="LA",i.MAINE="ME",i.MARYLAND="MD",i.MASSACHUSETTS="MA",i.MICHIGAN="MI",i.MINNESOTA="MN",i.MISSISSIPPI="MS",i.MISSOURI="MO",i.MONTANA="MT",i.NEBRASKA="NE",i.NEVADA="NV",i.NEW_HAMPSHIRE="NH",i.NEW_JERSEY="NJ",i.NEW_MEXICO="NM",i.NEW_YORK="NY",i.NORTH_CAROLINA="NC",i.NORTH_DAKOTA="ND",i.OHIO="OH",i.OKLAHOMA="OK",i.OREGON="OR",i.PENNSYLVANIA="PA",i.RHODE_ISLAND="RI",i.SOUTH_CAROLINA="SC",i.SOUTH_DAKOTA="SD",i.TENNESSEE="TN",i.TEXAS="TX",i.UTAH="UT",i.VERMONT="VT",i.VIRGINIA="VA",i.WASHINGTON="WA",i.WEST_VIRGINIA="WV",i.WISCONSIN="WI",i.WYOMING="WY",exports.ENUM_BEER=void 0,(s=exports.ENUM_BEER||(exports.ENUM_BEER={})).ALE="BEER > ALE",s.LAGER="BEER > LAGER",s.MAIN="BEER",s.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",s.OTHER_BEER="BEER > OTHER BEER",exports.ENUM_FOOD=void 0,(o=exports.ENUM_FOOD||(exports.ENUM_FOOD={})).BASE="FOOD",o.PANTRY_OTHER="FOOD > PANTRY > OTHER",exports.ENUM_MERCHANDISE=void 0,(a=exports.ENUM_MERCHANDISE||(exports.ENUM_MERCHANDISE={})).BASE="MERCHANDISE",a.GLASSWARE="MERCHANDISE > GLASSWARE",a.HUMIDOR="MERCHANDISE > HUMIDOR",exports.ENUM_MISCELLANEOUS=void 0,(n=exports.ENUM_MISCELLANEOUS||(exports.ENUM_MISCELLANEOUS={})).BASE="MISCELLANEOUS",n.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",n.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",n.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP",exports.ENUM_NON_ALCOHOLIC=void 0,(h=exports.ENUM_NON_ALCOHOLIC||(exports.ENUM_NON_ALCOHOLIC={})).BASE="NON ALCOHOLIC",h.BITTERS="NON ALCOHOLIC > BITTERS",h.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",h.COFFEE="NON ALCOHOLIC > COFFEE",h.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",h.JUICE="NON ALCOHOLIC > JUICE",h.SODA="NON ALCOHOLIC > SODA",h.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",h.SPIRITS="NON ALCOHOLIC > SPIRITS",h.TEA="NON ALCOHOLIC > TEA",h.WATER="NON ALCOHOLIC > WATER",h.WINE="NON ALCOHOLIC > WINE",exports.ENUM_READY_TO_DRINK=void 0,(c=exports.ENUM_READY_TO_DRINK||(exports.ENUM_READY_TO_DRINK={})).BASE="READY TO DRINK",c.HARD_CIDER="READY TO DRINK > HARD CIDER",c.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",c.HARD_TEA="READY TO DRINK > HARD TEA",c.MALT_BASED="READY TO DRINK > MALT BASED",c.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",c.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",c.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",c.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",c.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",c.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS",exports.ENUM_SPIRITS=void 0,(d=exports.ENUM_SPIRITS||(exports.ENUM_SPIRITS={})).BASE="SPIRITS",d.BAIJIU="SPIRITS > BAIJIU",d.BITTERS="SPIRITS > BITTERS",d.BRANDY="SPIRITS > BRANDY",d.CACHACA="SPIRITS > CACHACA",d.GIN="SPIRITS > GIN",d.LAGER="SPIRITS > LAGER",d.LIQUEUR="SPIRITS > LIQUEUR",d.MEZCAL="SPIRITS > MEZCAL",d.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",d.RUM="SPIRITS > RUM",d.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",d.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",d.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",d.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",d.RUM_OTHER="SPIRITS > RUM > OTHER",d.RUM_SPICED="SPIRITS > RUM > SPICED",d.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",d.SOJU="SPIRITS > SOJU",d.TEQUILA="SPIRITS > TEQUILA",d.VODKA="SPIRITS > VODKA",d.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",d.WHISKEY="SPIRITS > WHISKEY",d.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",d.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",d.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",d.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",d.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH",exports.ENUM_WINE=void 0,(l=exports.ENUM_WINE||(exports.ENUM_WINE={})).BASE="WINE",l.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",l.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",l.COOKING="WINE > COOKING",l.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",l.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",l.RED_WINE="WINE > RED WINE",l.ROSE_WINE="WINE > ROSE WINE",l.SAKE="WINE > SAKE",l.WHITE_WINE="WINE > WHITE WINE",exports.ENUM_FILTER_KEYS=void 0,(p=exports.ENUM_FILTER_KEYS||(exports.ENUM_FILTER_KEYS={})).BRANDS="brands",p.FLAVOR="flavor",p.REGION="region",p.VARIETY="variety",p.PRICE="price",p.AVAILABILITY="availability",p.CATEGORIES="categories",p.SIZES="sizes",p.COLORS="colors",p.APPELLATION="appellation",p.COUNTRY="country",p.VINTAGE="vintage",p.MATERIALS="materials",exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE=void 0,(I=exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE||(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE={})).ASC="asc",I.DESC="desc",exports.ENUM_ORDER_BY=void 0,(exports.ENUM_ORDER_BY||(exports.ENUM_ORDER_BY={})).PRICE="price",exports.ENUM_AVAILABILITY_VALUE=void 0,(u=exports.ENUM_AVAILABILITY_VALUE||(exports.ENUM_AVAILABILITY_VALUE={})).UNSPECIFIED="AVAILABILITY_UNSPECIFIED",u.IN_STOCK="IN_STOCK",u.OUT_OF_STOCK="OUT_OF_STOCK",u.PREORDER="PREORDER",u.BACKORDER="BACKORDER",exports.CART_PARAM_ERROR_ENUM=void 0,(E=exports.CART_PARAM_ERROR_ENUM||(exports.CART_PARAM_ERROR_ENUM={})).INVALID_ITEMS_TYPE="Items must be a non-empty array",E.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",E.INVALID_PART_NUMBER="The partnerNumber provided is invalid",E.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid",exports.CART_EVENT_ENUM=void 0,(S=exports.CART_EVENT_ENUM||(exports.CART_EVENT_ENUM={})).OOS="OutOfStock",S.ITEMS_NOT_ADDED="ItemsNotAdded",S.ITEM_NOT_ENGRAVED="ItemEngravingError",S.ADDRESS_CHANGE="AddressChange",S.RETAILER_MIN="RetailerMinNotMet",S.NO_ITEMS_IN_CART="NoItemsInCart",S.INVALID_ID="InvalidId",S.NO_ID="NoId",S.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",S.NEW_CART="NewCart",S.DEFAULT="CartError",S.ITEM_QTY_CHANGE="ItemQuantityChange",exports.ENUM_ADDRESS_TYPE=void 0,(w=exports.ENUM_ADDRESS_TYPE||(exports.ENUM_ADDRESS_TYPE={})).SHIPPING="shipping",w.BILLING="billing";const v={[exports.LIQUID_COMMERCE_ENV.LOC]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.DEV]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class A{constructor(t){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(t,e)=>new Promise(((r,i)=>{const s=new XMLHttpRequest;s.open(e.method||"GET",t),Object.entries(e.headers).forEach((([t,e])=>{s.setRequestHeader(t,e)})),s.onload=()=>{r({ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,headers:s.getAllResponseHeaders().split("\r\n").reduce(((t,e)=>{const[r,i]=e.split(": ");return r&&(t[r]=i),t}),{}),json:()=>Promise.resolve(JSON.parse(s.responseText)),text:()=>Promise.resolve(s.responseText)})},s.onerror=()=>{i(new TypeError("Network request failed"))},s.send(e.body)})),this.apiKey=t.apiKey,this.baseURL=t.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(t){return A.instance||(A.instance=new A(t)),A.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):this.xhrFetch}fetchAdapter(t){return async(e,r)=>{var i;const s=await t(e,r);let o;return"function"==typeof(null===(i=s.headers)||void 0===i?void 0:i.entries)?o=Object.fromEntries(s.headers.entries()):(o={},s.headers.forEach(((t,e)=>{o[e]=t}))),{ok:s.ok,status:s.status,statusText:s.statusText,headers:o,json:()=>s.json(),text:()=>s.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var t,e;if(this.isAuthenticating)await new Promise((t=>{const e=()=>{this.isAuthenticating?setTimeout(e,100):t(void 0)};e()}));else{this.isAuthenticating=!0;try{const r=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.token,this.tokenExpiration=Date.now()+1e3*(null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.exp)}catch(t){throw new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(t,e){const r=new URL(`api${t}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...e.headers},s={method:e.method,headers:i,body:e.body?JSON.stringify(e.body):void 0},o=await this.httpClient(r.toString(),s);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return o.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(t,e){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const r=new URL(`api${t}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...e.headers},s={method:e.method,headers:i,body:e.body?JSON.stringify(e.body):void 0},o=await this.httpClient(r.toString(),s);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return o.json()}async get(t,e){return this.request(t,{method:"GET",headers:e})}async post(t,e,r){return this.request(t,{method:"POST",body:e,headers:r})}async put(t,e,r){return this.request(t,{method:"PUT",body:e,headers:r})}async delete(t,e){return this.request(t,{method:"DELETE",headers:e})}}A.instance=null;class m{constructor(t){this.locationHelperService=t}validateAndNormalizeParams(t){const e={...t};return e.id=this.validateId(e.id),e.items=this.validateAndNormalizeItems(e.items),this.locationHelperService.validateAndNormalizeLocation(e.loc),e.refresh=Boolean(e.refresh),e}validateId(t){return t&&"string"==typeof t&&0!==t.trim().length?t.trim():""}validateAndNormalizeItems(t){if(!Array.isArray(t)||0===t.length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_TYPE);if(t.length>25)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_MAX);return t.map((t=>this.validateAndNormalizeItem(t)))}validateAndNormalizeItem(t){const e={...t};if(!this.validatePartNumber(e.partNumber))throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_PART_NUMBER);if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId||0===e.fulfillmentId.trim().length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_FULFILLMENT_ID);return e.quantity=Math.max(0,Math.floor(e.quantity)),e.engravingLines&&(e.engravingLines=e.engravingLines.map((t=>t.trim())).filter((t=>t.length>0))),e}validatePartNumber(t){if(!t||"string"!=typeof t)return!1;const e=t.split("_");return 2===e.length&&14===e[0].length&&e[1].length>0}}class R{constructor(t){this.locationServiceHelper=t,this.taxonomyValues=new Set([...Object.values(exports.ENUM_BEER),...Object.values(exports.ENUM_FOOD),...Object.values(exports.ENUM_MERCHANDISE),...Object.values(exports.ENUM_NON_ALCOHOLIC),...Object.values(exports.ENUM_READY_TO_DRINK),...Object.values(exports.ENUM_SPIRITS),...Object.values(exports.ENUM_WINE)])}validateAndNormalizeParams(t){const e={...t};return this.validateUPCs(e.upcs),this.locationServiceHelper.validateAndNormalizeLocation(e.loc),e}validateAndNormalizeSearchParams(t){const e=[],r={...t};return this.validateOrderBy(r.orderBy,e),this.validateOrderDirection(r.orderDirection,e),this.validateFilters(r.filters,e),this.validatePagination(r.page,r.perPage,e),this.locationServiceHelper.validateAndNormalizeLocation(r.loc),e.length>0?{...r,error:e.join(". ")}:r}validateUPCs(t){if(!Array.isArray(t)||0===t.length)throw new Error("UPCs must be a non-empty array of strings");if(!t.every((t=>"string"==typeof t&&t.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(t,e){t&&!Object.values(exports.ENUM_ORDER_BY).includes(t)&&e.push(`Invalid orderBy value: ${t}`)}validateOrderDirection(t,e){t&&!Object.values(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE).includes(t)&&e.push(`Invalid orderDirection value: ${t}`)}validateFilters(t,e){t&&(t.length>10&&e.push("Maximum of 10 filters allowed"),t.forEach((t=>{switch(Object.values(exports.ENUM_FILTER_KEYS).includes(t.key)||e.push(`Invalid filter key: ${t.key}`),t.key){case exports.ENUM_FILTER_KEYS.AVAILABILITY:this.validateAvailabilityFilter(t.values,e);break;case exports.ENUM_FILTER_KEYS.BRANDS:this.validateArrayFilter(t.values,30,"brands",e);break;case exports.ENUM_FILTER_KEYS.CATEGORIES:this.validateCategoriesFilter(t.values,e);break;case exports.ENUM_FILTER_KEYS.COLORS:this.validateArrayFilter(t.values,75,"colors",e)}})))}validateAvailabilityFilter(t,e){Object.values(exports.ENUM_AVAILABILITY_VALUE).includes(t)||e.push(`Invalid availability value: ${t}`)}validateArrayFilter(t,e,r,i){Array.isArray(t)?t.length>e&&i.push(`${r} filter can have a maximum of ${e} values`):i.push(`${r} filter must be an array`)}validateCategoriesFilter(t,e){Array.isArray(t)?t.every((t=>this.taxonomyValues.has(t)))||e.push("Invalid category value(s) in categories filter"):e.push("Categories filter must be an array")}validatePagination(t,e,r){void 0!==t&&("number"!=typeof t||t<0)&&r.push("Page must be a non-negative number"),void 0!==e&&("number"!=typeof e||e<=0)&&r.push("PerPage must be a positive number")}}class O{constructor(t){this.locationHelperService=t}validateAndNormalizePrepareParams(t){const e={...t};if(!e.cartId||"string"!=typeof e.cartId)throw new Error("Invalid cartId");return this.validateRecipient(e.recipient),e.billingAddress&&this.validateAddress(e.billingAddress),e.hasSubstitutionPolicy=Boolean(e.hasSubstitutionPolicy),e.isGift=Boolean(e.isGift),e.billingSameAsShipping=Boolean(e.billingSameAsShipping),e.isGift&&this.validateGiftOptions(e.giftOptions),this.validateMarketingPreferences(e.marketingPreferences),e.deliveryTips&&this.validateDeliveryTips(e.deliveryTips),e.refresh=Boolean(e.refresh),e}validateAndNormalizeCompleteParams(t){const e={...t};if(!e.token||"string"!=typeof e.token)throw new Error("Invalid token");if(!e.payment||"string"!=typeof e.payment)throw new Error("Invalid payment token");return void 0!==e.refresh&&(e.refresh=Boolean(e.refresh)),e}validateRecipient(t){if(!t||"object"!=typeof t)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid recipient ${e}`)})),t.hasAgeVerify=Boolean(t.hasAgeVerify)}validateAddress(t){if(!t||"object"!=typeof t)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid address ${e}`)})),this.locationHelperService.validateAndNormalizeLocation({address:t})}validateGiftOptions(t){if(!t||"object"!=typeof t)throw new Error("Invalid giftOptions");if(t.message&&"string"!=typeof t.message)throw new Error("Invalid gift message");if(t.recipient){const{name:e,phone:r,email:i}=t.recipient;if(e&&"string"!=typeof e)throw new Error("Invalid gift recipient name");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient phone");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(t){if(!t||"object"!=typeof t)throw new Error("Invalid marketingPreferences");t.canEmail=Boolean(t.canEmail),t.canSms=Boolean(t.canSms)}validateDeliveryTips(t){if(!Array.isArray(t))throw new Error("Invalid deliveryTips");t.forEach((t=>{if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof t.tip||t.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class f{validateAndNormalizeLocation(t){if(!t||"object"!=typeof t)throw new Error("Location must be a valid object");if(t.coords)this.validateCoordinates(t.coords);else{if(!t.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(t.address)}}validateCoordinates(t){if("number"!=typeof t.lat||"number"!=typeof t.long)throw new Error("Coordinates must be valid numbers");if(t.lat<-90||t.lat>90||t.long<-180||t.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(t){if(!t.state||"string"!=typeof t.state)throw new Error("State is required and must be a string");if(t.state=this.normalizeState(t.state),!t.city||"string"!=typeof t.city)throw new Error("City is required and must be a string");if(!t.zip||"string"!=typeof t.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(t){const e=t.toUpperCase();if(exports.STATES_CODE[e])return exports.STATES_CODE[e];const r=t.toUpperCase();if(exports.STATES_NAME[r])return exports.STATES_NAME[r];throw new Error(`Invalid state: ${t}`)}}class N{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await y.loadStripe(t.key)}catch(t){throw new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const e={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(e);const r=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var t,e,r,i,s,o,a,n;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:h}=await this.elements.submit();if(h)return{type:"validation_error",message:h.message,code:h.code};const{error:c,paymentMethod:d}=await this.stripe.createPaymentMethod({elements:this.elements});return c?{type:"validation_error"===c.type?"validation_error":"api_error",message:c.message,code:c.code,param:c.param}:d?{id:d.id,type:d.type,card:(null==d?void 0:d.card)?{brand:null!==(e=null===(t=d.card)||void 0===t?void 0:t.brand)&&void 0!==e?e:"",country:null!==(r=d.card.country)&&void 0!==r?r:"",expMonth:null!==(i=d.card.exp_month)&&void 0!==i?i:0,expYear:null!==(s=d.card.exp_year)&&void 0!==s?s:0,last4:null!==(o=d.card.last4)&&void 0!==o?o:"",funding:null!==(a=d.card.funding)&&void 0!==a?a:""}:void 0,created:null!==(n=null==d?void 0:d.created)&&void 0!==n?n:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.on(t,e)}unsubscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.off(t,e)}mapAppearance(t){if(t)return{theme:"night"===t.theme?"night":"stripe"}}mapElementOptions(t){return{layout:null==t?void 0:t.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class T{constructor(t){this.client=t}async autocomplete(t,e){try{return await this.client.post("/address/autocomplete",{...t,key:e})}catch(t){throw t}}async details(t,e){try{return await this.client.post("/address/details",{...t,key:e})}catch(t){throw t}}}class C{constructor(t,e){this.client=t,this.cartHelperService=e,this.servicePath="/cart/update"}async get(t,e){try{let r=this.cartHelperService.validateId(t);if(r=""!==r&&r,r){const t={id:r};return"boolean"==typeof e&&(t.refresh=e),await this.client.post(this.servicePath,t)}return await this.client.post(this.servicePath)}catch(t){throw t}}async update(t){try{const e=this.cartHelperService.validateAndNormalizeParams(t);return await this.client.post(this.servicePath,e)}catch(t){throw t}}}class g{constructor(t,e){this.client=t,this.catalogHelperService=e,this.servicePath="/catalog/"}async availability(t){try{const e=this.catalogHelperService.validateAndNormalizeParams(t);return await this.client.post(`${this.servicePath}availability`,e)}catch(t){throw t}}async search(t){try{const e=this.catalogHelperService.validateAndNormalizeSearchParams(t);if(null==e?void 0:e.error)throw new Error(null==e?void 0:e.error);return await this.client.post(`${this.servicePath}search`,e)}catch(t){throw t}}}class x{constructor(t,e){this.client=t,this.checkoutHelperService=e,this.servicePath="/checkout"}async prepare(t){try{const e=this.checkoutHelperService.validateAndNormalizePrepareParams(t);return await this.client.post(`${this.servicePath}/prepare`,e)}catch(t){throw t}}async complete(t){try{const e=this.checkoutHelperService.validateAndNormalizeCompleteParams(t);return await this.client.post(`${this.servicePath}/complete`,e)}catch(t){throw t}}}class D{constructor(t){this.paymentProvider=t}async mount(t){try{await this.paymentProvider.mount(t)}catch(t){throw t}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(t,e){this.paymentProvider.subscribe(t,e)}unsubscribe(t,e){this.paymentProvider.unsubscribe(t,e)}}class P{constructor(t){this.client=t,this.servicePath="/users"}async createOrUpdateSession(t){try{if(!(null==t?void 0:t.id)&&!(null==t?void 0:t.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,t)}catch(t){throw t}}async purge(t){try{if(!t)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${t}`)}catch(t){throw t}}async updateAddress(t){try{if(!(t.customerId&&t.one&&t.city&&t.state&&t.zip&&t.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,t)}catch(t){throw t}}async purgeAddress(t){try{if(!t)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${t}`)}catch(t){throw t}}}class L{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return L.instance||(L.instance=new L),L.instance}setLiquidCommerceClientConstructor(t){this.liquidCommerceClientConstructor=t}async getLiquidCommerceClient(t,e){const r=`LiquidCommerceClient_${t}_${JSON.stringify(e)}`;if(!this.services.has(r)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const i=new this.liquidCommerceClientConstructor(t,e);await i.init(),this.services.set(r,i)}return this.services.get(r)}getOrCreateService(t,e,...r){if(!this.services.has(t)){const i="getInstance"in e?e.getInstance(...r):new e(...r);this.services.set(t,i)}return this.services.get(t)}getAuthenticatedClient(t){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(t)}`,A,t)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",f)}getAddressService(t){return this.getOrCreateService(`AddressService_${t.getUniqueKey()}`,T,t)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",R,this.getLocationHelperService())}getCatalogService(t){return this.getOrCreateService(`CatalogService_${t.getUniqueKey()}`,g,t,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",m,this.getLocationHelperService())}getCartService(t){return this.getOrCreateService(`CartService_${t.getUniqueKey()}`,C,t,this.getCartHelperService())}getUserService(t){return this.getOrCreateService(`UserService_${t.getUniqueKey()}`,P,t)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",N)}getPaymentService(){return this.getOrCreateService("PaymentService",D,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",O,this.getLocationHelperService())}getCheckoutService(t){return this.getOrCreateService(`CheckoutService_${t.getUniqueKey()}`,x,t,this.getCheckoutHelperService())}}L.instance=null;class b{constructor(t,e){this.address={autocomplete:async t=>(await this.ensureAuthenticated(),this.addressService.autocomplete(t,this.config.googlePlacesApiKey)),details:async t=>(await this.ensureAuthenticated(),this.addressService.details(t,this.config.googlePlacesApiKey))},this.catalog={availability:async t=>(await this.ensureAuthenticated(),this.catalogService.availability(t)),search:async t=>(await this.ensureAuthenticated(),this.catalogService.search(t))},this.cart={get:async(t,e)=>(await this.ensureAuthenticated(),this.cartService.get(t,e)),update:async t=>(await this.ensureAuthenticated(),this.cartService.update(t))},this.user={session:async t=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(t)),purge:async t=>(await this.ensureAuthenticated(),this.userService.purge(t)),updateAddress:async t=>(await this.ensureAuthenticated(),this.userService.updateAddress(t)),purgeAddress:async t=>(await this.ensureAuthenticated(),this.userService.purgeAddress(t))},this.payment={mount:async t=>(await this.ensureAuthenticated(),this.paymentService.mount(t)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(t,e)=>{this.paymentService.subscribe(t,e)},unsubscribe:(t,e)=>{this.paymentService.unsubscribe(t,e)}},this.checkout={prepare:async t=>(await this.ensureAuthenticated(),this.checkoutService.prepare(t)),complete:async t=>(await this.ensureAuthenticated(),this.checkoutService.complete(t))},this.config=e,this.singletonManager=L.getInstance();const r=this.determineBaseURL(e);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:t,baseURL:r}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(t){const e=t.env||exports.LIQUID_COMMERCE_ENV.STAGE;return v[e]}async init(){try{await this.authenticatedClient.authenticate()}catch(t){throw new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}exports.LiquidCommerce=async function(t,e){const r=L.getInstance();return r.setLiquidCommerceClientConstructor(b),await r.getLiquidCommerceClient(t,e)};
@@ -1,4 +1,6 @@
1
1
  export declare const DEFAULT_BASE_URLS: {
2
+ loc: string;
2
3
  dev: string;
3
4
  stage: string;
5
+ prod: string;
4
6
  };
@@ -1,6 +1,8 @@
1
1
  export declare enum LIQUID_COMMERCE_ENV {
2
- DEV = "dev",
3
- STAGE = "stage"
2
+ LOC = "loc",
3
+ STAGE = "stage",
4
+ PROD = "prod",
5
+ DEV = "dev"
4
6
  }
5
7
  export declare enum ENUM_MODALITIES {
6
8
  ON_DEMAND = "onDemand",
@@ -1 +1,2 @@
1
- export { LIQUID_COMMERCE_ENV, LiquidCommerce } from './liquid-commerce-client';
1
+ export * from './enums';
2
+ export * from './liquid-commerce-client';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liquidcommerce/cloud-sdk",
3
- "version": "1.0.1",
3
+ "version": "1.1.0",
4
4
  "description": "LiquidCommerce Cloud SDK",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.esm.js",
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).LiquidCommerce={})}(this,(function(t){"use strict";var LIQUID_COMMERCE_ENV,e,i,r,n,s,a,o,h,c,l,u,d,I,E,w,f,S,y,p;t.LIQUID_COMMERCE_ENV=void 0,(LIQUID_COMMERCE_ENV=t.LIQUID_COMMERCE_ENV||(t.LIQUID_COMMERCE_ENV={})).DEV="dev",LIQUID_COMMERCE_ENV.STAGE="stage",function(t){t.ON_DEMAND="onDemand",t.SHIPPING="shipping"}(e||(e={})),function(t){t.MONDAY="monday",t.TUESDAY="tuesday",t.WEDNESDAY="wednesday",t.THURSDAY="thursday",t.FRIDAY="friday",t.SATURDAY="saturday",t.SUNDAY="sunday"}(i||(i={})),function(t){t.AL="AL",t.AK="AK",t.AR="AR",t.CA="CA",t.CO="CO",t.CT="CT",t.DE="DE",t.DC="DC",t.FL="FL",t.GA="GA",t.HI="HI",t.ID="ID",t.IL="IL",t.IN="IN",t.IA="IA",t.KS="KS",t.KY="KY",t.LA="LA",t.ME="ME",t.MD="MD",t.MA="MA",t.MI="MI",t.MN="MN",t.MS="MS",t.MO="MO",t.MT="MT",t.NE="NE",t.NV="NV",t.NH="NH",t.NJ="NJ",t.NM="NM",t.NY="NY",t.NC="NC",t.ND="ND",t.OH="OH",t.OK="OK",t.OR="OR",t.PA="PA",t.RI="RI",t.SC="SC",t.SD="SD",t.TN="TN",t.TX="TX",t.UT="UT",t.VT="VT",t.VA="VA",t.WA="WA",t.WV="WV",t.WI="WI",t.WY="WY"}(r||(r={})),function(t){t.ALABAMA="AL",t.ALASKA="AK",t.ARKANSAS="AR",t.CALIFORNIA="CA",t.COLORADO="CO",t.CONNECTICUT="CT",t.DELAWARE="DE",t.DISTRICT_OF_COLUMBIA="DC",t.FLORIDA="FL",t.GEORGIA="GA",t.HAWAII="HI",t.IDAHO="ID",t.ILLINOIS="IL",t.INDIANA="IN",t.IOWA="IA",t.KANSAS="KS",t.KENTUCKY="KY",t.LOUISIANA="LA",t.MAINE="ME",t.MARYLAND="MD",t.MASSACHUSETTS="MA",t.MICHIGAN="MI",t.MINNESOTA="MN",t.MISSISSIPPI="MS",t.MISSOURI="MO",t.MONTANA="MT",t.NEBRASKA="NE",t.NEVADA="NV",t.NEW_HAMPSHIRE="NH",t.NEW_JERSEY="NJ",t.NEW_MEXICO="NM",t.NEW_YORK="NY",t.NORTH_CAROLINA="NC",t.NORTH_DAKOTA="ND",t.OHIO="OH",t.OKLAHOMA="OK",t.OREGON="OR",t.PENNSYLVANIA="PA",t.RHODE_ISLAND="RI",t.SOUTH_CAROLINA="SC",t.SOUTH_DAKOTA="SD",t.TENNESSEE="TN",t.TEXAS="TX",t.UTAH="UT",t.VERMONT="VT",t.VIRGINIA="VA",t.WASHINGTON="WA",t.WEST_VIRGINIA="WV",t.WISCONSIN="WI",t.WYOMING="WY"}(n||(n={})),function(t){t.ALE="BEER > ALE",t.LAGER="BEER > LAGER",t.MAIN="BEER",t.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",t.OTHER_BEER="BEER > OTHER BEER"}(s||(s={})),function(t){t.BASE="FOOD",t.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(a||(a={})),function(t){t.BASE="MERCHANDISE",t.GLASSWARE="MERCHANDISE > GLASSWARE",t.HUMIDOR="MERCHANDISE > HUMIDOR"}(o||(o={})),function(t){t.BASE="MISCELLANEOUS",t.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",t.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",t.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(h||(h={})),function(t){t.BASE="NON ALCOHOLIC",t.BITTERS="NON ALCOHOLIC > BITTERS",t.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",t.COFFEE="NON ALCOHOLIC > COFFEE",t.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",t.JUICE="NON ALCOHOLIC > JUICE",t.SODA="NON ALCOHOLIC > SODA",t.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",t.SPIRITS="NON ALCOHOLIC > SPIRITS",t.TEA="NON ALCOHOLIC > TEA",t.WATER="NON ALCOHOLIC > WATER",t.WINE="NON ALCOHOLIC > WINE"}(c||(c={})),function(t){t.BASE="READY TO DRINK",t.HARD_CIDER="READY TO DRINK > HARD CIDER",t.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",t.HARD_TEA="READY TO DRINK > HARD TEA",t.MALT_BASED="READY TO DRINK > MALT BASED",t.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",t.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",t.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",t.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",t.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",t.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(l||(l={})),function(t){t.BASE="SPIRITS",t.BAIJIU="SPIRITS > BAIJIU",t.BITTERS="SPIRITS > BITTERS",t.BRANDY="SPIRITS > BRANDY",t.CACHACA="SPIRITS > CACHACA",t.GIN="SPIRITS > GIN",t.LAGER="SPIRITS > LAGER",t.LIQUEUR="SPIRITS > LIQUEUR",t.MEZCAL="SPIRITS > MEZCAL",t.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",t.RUM="SPIRITS > RUM",t.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",t.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",t.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",t.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",t.RUM_OTHER="SPIRITS > RUM > OTHER",t.RUM_SPICED="SPIRITS > RUM > SPICED",t.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",t.SOJU="SPIRITS > SOJU",t.TEQUILA="SPIRITS > TEQUILA",t.VODKA="SPIRITS > VODKA",t.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",t.WHISKEY="SPIRITS > WHISKEY",t.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",t.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",t.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",t.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",t.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(u||(u={})),function(t){t.BASE="WINE",t.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",t.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",t.COOKING="WINE > COOKING",t.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",t.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",t.RED_WINE="WINE > RED WINE",t.ROSE_WINE="WINE > ROSE WINE",t.SAKE="WINE > SAKE",t.WHITE_WINE="WINE > WHITE WINE"}(d||(d={})),function(t){t.BRANDS="brands",t.FLAVOR="flavor",t.REGION="region",t.VARIETY="variety",t.PRICE="price",t.AVAILABILITY="availability",t.CATEGORIES="categories",t.SIZES="sizes",t.COLORS="colors",t.APPELLATION="appellation",t.COUNTRY="country",t.VINTAGE="vintage",t.MATERIALS="materials"}(I||(I={})),function(t){t.ASC="asc",t.DESC="desc"}(E||(E={})),function(t){t.PRICE="price"}(w||(w={})),function(t){t.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",t.IN_STOCK="IN_STOCK",t.OUT_OF_STOCK="OUT_OF_STOCK",t.PREORDER="PREORDER",t.BACKORDER="BACKORDER"}(f||(f={})),function(t){t.INVALID_ITEMS_TYPE="Items must be a non-empty array",t.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",t.INVALID_PART_NUMBER="The partnerNumber provided is invalid",t.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(S||(S={})),function(t){t.OOS="OutOfStock",t.ITEMS_NOT_ADDED="ItemsNotAdded",t.ITEM_NOT_ENGRAVED="ItemEngravingError",t.ADDRESS_CHANGE="AddressChange",t.RETAILER_MIN="RetailerMinNotMet",t.NO_ITEMS_IN_CART="NoItemsInCart",t.INVALID_ID="InvalidId",t.NO_ID="NoId",t.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",t.NEW_CART="NewCart",t.DEFAULT="CartError",t.ITEM_QTY_CHANGE="ItemQuantityChange"}(y||(y={})),function(t){t.SHIPPING="shipping",t.BILLING="billing"}(p||(p={}));const m={[t.LIQUID_COMMERCE_ENV.DEV]:"https://dev.cloud.liquidcommerce.co/api",[t.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api"};class v{constructor(t){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(t,e)=>new Promise(((i,r)=>{const n=new XMLHttpRequest;n.open(e.method||"GET",t),Object.entries(e.headers).forEach((([t,e])=>{n.setRequestHeader(t,e)})),n.onload=()=>{i({ok:n.status>=200&&n.status<300,status:n.status,statusText:n.statusText,headers:n.getAllResponseHeaders().split("\r\n").reduce(((t,e)=>{const[i,r]=e.split(": ");return i&&(t[i]=r),t}),{}),json:()=>Promise.resolve(JSON.parse(n.responseText)),text:()=>Promise.resolve(n.responseText)})},n.onerror=()=>{r(new TypeError("Network request failed"))},n.send(e.body)})),this.apiKey=t.apiKey,this.baseURL=t.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(t){return v.instance||(v.instance=new v(t)),v.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(t){return async(e,i)=>{var r;const n=await t(e,i);let s;return"function"==typeof(null===(r=n.headers)||void 0===r?void 0:r.entries)?s=Object.fromEntries(n.headers.entries()):(s={},n.headers.forEach(((t,e)=>{s[e]=t}))),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var t,e;if(this.isAuthenticating)await new Promise((t=>{const e=()=>{this.isAuthenticating?setTimeout(e,100):t(void 0)};e()}));else{this.isAuthenticating=!0;try{const i=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.token,this.tokenExpiration=Date.now()+1e3*(null===(e=null==i?void 0:i.data)||void 0===e?void 0:e.exp)}catch(t){throw new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(t,e){const i=new URL(`api${t}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...e.headers},n={method:e.method,headers:r,body:e.body?JSON.stringify(e.body):void 0},s=await this.httpClient(i.toString(),n);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(t,e){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const i=new URL(`api${t}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...e.headers},n={method:e.method,headers:r,body:e.body?JSON.stringify(e.body):void 0},s=await this.httpClient(i.toString(),n);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}async get(t,e){return this.request(t,{method:"GET",headers:e})}async post(t,e,i){return this.request(t,{method:"POST",body:e,headers:i})}async put(t,e,i){return this.request(t,{method:"PUT",body:e,headers:i})}async delete(t,e){return this.request(t,{method:"DELETE",headers:e})}}v.instance=null;class A{constructor(t){this.locationHelperService=t}validateAndNormalizeParams(t){const e={...t};return e.id=this.validateId(e.id),e.items=this.validateAndNormalizeItems(e.items),this.locationHelperService.validateAndNormalizeLocation(e.loc),e.refresh=Boolean(e.refresh),e}validateId(t){return t&&"string"==typeof t&&0!==t.trim().length?t.trim():""}validateAndNormalizeItems(t){if(!Array.isArray(t)||0===t.length)throw new Error(S.INVALID_ITEMS_TYPE);if(t.length>25)throw new Error(S.INVALID_ITEMS_MAX);return t.map((t=>this.validateAndNormalizeItem(t)))}validateAndNormalizeItem(t){const e={...t};if(!this.validatePartNumber(e.partNumber))throw new Error(S.INVALID_PART_NUMBER);if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId||0===e.fulfillmentId.trim().length)throw new Error(S.INVALID_FULFILLMENT_ID);return e.quantity=Math.max(0,Math.floor(e.quantity)),e.engravingLines&&(e.engravingLines=e.engravingLines.map((t=>t.trim())).filter((t=>t.length>0))),e}validatePartNumber(t){if(!t||"string"!=typeof t)return!1;const e=t.split("_");return 2===e.length&&14===e[0].length&&e[1].length>0}}class R{constructor(t){this.locationServiceHelper=t,this.taxonomyValues=new Set([...Object.values(s),...Object.values(a),...Object.values(o),...Object.values(c),...Object.values(l),...Object.values(u),...Object.values(d)])}validateAndNormalizeParams(t){const e={...t};return this.validateUPCs(e.upcs),this.locationServiceHelper.validateAndNormalizeLocation(e.loc),e}validateAndNormalizeSearchParams(t){const e=[],i={...t};return this.validateOrderBy(i.orderBy,e),this.validateOrderDirection(i.orderDirection,e),this.validateFilters(i.filters,e),this.validatePagination(i.page,i.perPage,e),this.locationServiceHelper.validateAndNormalizeLocation(i.loc),e.length>0?{...i,error:e.join(". ")}:i}validateUPCs(t){if(!Array.isArray(t)||0===t.length)throw new Error("UPCs must be a non-empty array of strings");if(!t.every((t=>"string"==typeof t&&t.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(t,e){t&&!Object.values(w).includes(t)&&e.push(`Invalid orderBy value: ${t}`)}validateOrderDirection(t,e){t&&!Object.values(E).includes(t)&&e.push(`Invalid orderDirection value: ${t}`)}validateFilters(t,e){t&&(t.length>10&&e.push("Maximum of 10 filters allowed"),t.forEach((t=>{switch(Object.values(I).includes(t.key)||e.push(`Invalid filter key: ${t.key}`),t.key){case I.AVAILABILITY:this.validateAvailabilityFilter(t.values,e);break;case I.BRANDS:this.validateArrayFilter(t.values,30,"brands",e);break;case I.CATEGORIES:this.validateCategoriesFilter(t.values,e);break;case I.COLORS:this.validateArrayFilter(t.values,75,"colors",e)}})))}validateAvailabilityFilter(t,e){Object.values(f).includes(t)||e.push(`Invalid availability value: ${t}`)}validateArrayFilter(t,e,i,r){Array.isArray(t)?t.length>e&&r.push(`${i} filter can have a maximum of ${e} values`):r.push(`${i} filter must be an array`)}validateCategoriesFilter(t,e){Array.isArray(t)?t.every((t=>this.taxonomyValues.has(t)))||e.push("Invalid category value(s) in categories filter"):e.push("Categories filter must be an array")}validatePagination(t,e,i){void 0!==t&&("number"!=typeof t||t<0)&&i.push("Page must be a non-negative number"),void 0!==e&&("number"!=typeof e||e<=0)&&i.push("PerPage must be a positive number")}}class O{constructor(t){this.locationHelperService=t}validateAndNormalizePrepareParams(t){const e={...t};if(!e.cartId||"string"!=typeof e.cartId)throw new Error("Invalid cartId");return this.validateRecipient(e.recipient),e.billingAddress&&this.validateAddress(e.billingAddress),e.hasSubstitutionPolicy=Boolean(e.hasSubstitutionPolicy),e.isGift=Boolean(e.isGift),e.billingSameAsShipping=Boolean(e.billingSameAsShipping),e.isGift&&this.validateGiftOptions(e.giftOptions),this.validateMarketingPreferences(e.marketingPreferences),e.deliveryTips&&this.validateDeliveryTips(e.deliveryTips),e.refresh=Boolean(e.refresh),e}validateAndNormalizeCompleteParams(t){const e={...t};if(!e.token||"string"!=typeof e.token)throw new Error("Invalid token");if(!e.payment||"string"!=typeof e.payment)throw new Error("Invalid payment token");return void 0!==e.refresh&&(e.refresh=Boolean(e.refresh)),e}validateRecipient(t){if(!t||"object"!=typeof t)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid recipient ${e}`)})),t.hasAgeVerify=Boolean(t.hasAgeVerify)}validateAddress(t){if(!t||"object"!=typeof t)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid address ${e}`)})),this.locationHelperService.validateAndNormalizeLocation({address:t})}validateGiftOptions(t){if(!t||"object"!=typeof t)throw new Error("Invalid giftOptions");if(t.message&&"string"!=typeof t.message)throw new Error("Invalid gift message");if(t.recipient){const{name:e,phone:i,email:r}=t.recipient;if(e&&"string"!=typeof e)throw new Error("Invalid gift recipient name");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient phone");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(t){if(!t||"object"!=typeof t)throw new Error("Invalid marketingPreferences");t.canEmail=Boolean(t.canEmail),t.canSms=Boolean(t.canSms)}validateDeliveryTips(t){if(!Array.isArray(t))throw new Error("Invalid deliveryTips");t.forEach((t=>{if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof t.tip||t.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class T{validateAndNormalizeLocation(t){if(!t||"object"!=typeof t)throw new Error("Location must be a valid object");if(t.coords)this.validateCoordinates(t.coords);else{if(!t.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(t.address)}}validateCoordinates(t){if("number"!=typeof t.lat||"number"!=typeof t.long)throw new Error("Coordinates must be valid numbers");if(t.lat<-90||t.lat>90||t.long<-180||t.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(t){if(!t.state||"string"!=typeof t.state)throw new Error("State is required and must be a string");if(t.state=this.normalizeState(t.state),!t.city||"string"!=typeof t.city)throw new Error("City is required and must be a string");if(!t.zip||"string"!=typeof t.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(t){const e=t.toUpperCase();if(r[e])return r[e];const i=t.toUpperCase();if(n[i])return n[i];throw new Error(`Invalid state: ${t}`)}}var N,C="https://js.stripe.com/v3",g=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,P=function(t){var e=document.createElement("script");e.src="".concat(C).concat("");var i=document.head||document.body;if(!i)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return i.appendChild(e),e},D=null,b=null,L=null,M=function(){return N||(N=(null!==D?D:(D=new Promise((function(t,e){if("undefined"!=typeof document)if(window.Stripe,window.Stripe)t(window.Stripe);else try{var i=function(){for(var t=document.querySelectorAll('script[src^="'.concat(C,'"]')),e=0;e<t.length;e++){var i=t[e];if(g.test(i.src))return i}return null}();if(i){if(i&&null!==L&&null!==b){var r;i.removeEventListener("load",L),i.removeEventListener("error",b),null===(r=i.parentNode)||void 0===r||r.removeChild(i),i=P()}}else i=P();L=function(t,e){return function(){window.Stripe?t(window.Stripe):e(new Error("Stripe.js not available"))}}(t,e),b=function(t){return function(){t(new Error("Failed to load Stripe.js"))}}(e),i.addEventListener("load",L),i.addEventListener("error",b)}catch(t){return void e(t)}else t(null)}))).catch((function(t){return D=null,Promise.reject(t)}))).catch((function(t){return N=null,Promise.reject(t)})))};Promise.resolve().then((function(){return M()})).catch((function(t){}));class H{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];var r=Date.now();return M().then((function(t){return function(t,e,i){if(null===t)return null;var r=t.apply(void 0,e);return function(t,e){t&&t.t&&t.t({name:"stripe-js",version:"4.3.0",startTime:e})}(r,i),r}(t,e,r)}))}(t.key)}catch(t){throw new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const e={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(e);const i=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",i),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var t,e,i,r,n,s,a,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:h}=await this.elements.submit();if(h)return{type:"validation_error",message:h.message,code:h.code};const{error:c,paymentMethod:l}=await this.stripe.createPaymentMethod({elements:this.elements});return c?{type:"validation_error"===c.type?"validation_error":"api_error",message:c.message,code:c.code,param:c.param}:l?{id:l.id,type:l.type,card:(null==l?void 0:l.card)?{brand:null!==(e=null===(t=l.card)||void 0===t?void 0:t.brand)&&void 0!==e?e:"",country:null!==(i=l.card.country)&&void 0!==i?i:"",expMonth:null!==(r=l.card.exp_month)&&void 0!==r?r:0,expYear:null!==(n=l.card.exp_year)&&void 0!==n?n:0,last4:null!==(s=l.card.last4)&&void 0!==s?s:"",funding:null!==(a=l.card.funding)&&void 0!==a?a:""}:void 0,created:null!==(o=null==l?void 0:l.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.on(t,e)}unsubscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.off(t,e)}mapAppearance(t){if(t)return{theme:"night"===t.theme?"night":"stripe"}}mapElementOptions(t){return{layout:null==t?void 0:t.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class K{constructor(t){this.client=t}async autocomplete(t,e){try{return await this.client.post("/address/autocomplete",{...t,key:e})}catch(t){throw t}}async details(t,e){try{return await this.client.post("/address/details",{...t,key:e})}catch(t){throw t}}}class U{constructor(t,e){this.client=t,this.cartHelperService=e,this.servicePath="/cart/update"}async get(t,e){try{let i=this.cartHelperService.validateId(t);if(i=""!==i&&i,i){const t={id:i};return"boolean"==typeof e&&(t.refresh=e),await this.client.post(this.servicePath,t)}return await this.client.post(this.servicePath)}catch(t){throw t}}async update(t){try{const e=this.cartHelperService.validateAndNormalizeParams(t);return await this.client.post(this.servicePath,e)}catch(t){throw t}}}class W{constructor(t,e){this.client=t,this.catalogHelperService=e,this.servicePath="/catalog/"}async availability(t){try{const e=this.catalogHelperService.validateAndNormalizeParams(t);return await this.client.post(`${this.servicePath}availability`,e)}catch(t){throw t}}async search(t){try{const e=this.catalogHelperService.validateAndNormalizeSearchParams(t);if(null==e?void 0:e.error)throw new Error(null==e?void 0:e.error);return await this.client.post(`${this.servicePath}search`,e)}catch(t){throw t}}}class Y{constructor(t,e){this.client=t,this.checkoutHelperService=e,this.servicePath="/checkout"}async prepare(t){try{const e=this.checkoutHelperService.validateAndNormalizePrepareParams(t);return await this.client.post(`${this.servicePath}/prepare`,e)}catch(t){throw t}}async complete(t){try{const e=this.checkoutHelperService.validateAndNormalizeCompleteParams(t);return await this.client.post(`${this.servicePath}/complete`,e)}catch(t){throw t}}}class ${constructor(t){this.paymentProvider=t}async mount(t){try{await this.paymentProvider.mount(t)}catch(t){throw t}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(t,e){this.paymentProvider.subscribe(t,e)}unsubscribe(t,e){this.paymentProvider.unsubscribe(t,e)}}class B{constructor(t){this.client=t,this.servicePath="/users"}async createOrUpdateSession(t){try{if(!(null==t?void 0:t.id)&&!(null==t?void 0:t.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,t)}catch(t){throw t}}async purge(t){try{if(!t)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${t}`)}catch(t){throw t}}async updateAddress(t){try{if(!(t.customerId&&t.one&&t.city&&t.state&&t.zip&&t.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,t)}catch(t){throw t}}async purgeAddress(t){try{if(!t)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${t}`)}catch(t){throw t}}}class j{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return j.instance||(j.instance=new j),j.instance}setLiquidCommerceClientConstructor(t){this.liquidCommerceClientConstructor=t}async getLiquidCommerceClient(t,e){const i=`LiquidCommerceClient_${t}_${JSON.stringify(e)}`;if(!this.services.has(i)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const r=new this.liquidCommerceClientConstructor(t,e);await r.init(),this.services.set(i,r)}return this.services.get(i)}getOrCreateService(t,e,...i){if(!this.services.has(t)){const r="getInstance"in e?e.getInstance(...i):new e(...i);this.services.set(t,r)}return this.services.get(t)}getAuthenticatedClient(t){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(t)}`,v,t)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",T)}getAddressService(t){return this.getOrCreateService(`AddressService_${t.getUniqueKey()}`,K,t)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",R,this.getLocationHelperService())}getCatalogService(t){return this.getOrCreateService(`CatalogService_${t.getUniqueKey()}`,W,t,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",A,this.getLocationHelperService())}getCartService(t){return this.getOrCreateService(`CartService_${t.getUniqueKey()}`,U,t,this.getCartHelperService())}getUserService(t){return this.getOrCreateService(`UserService_${t.getUniqueKey()}`,B,t)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",H)}getPaymentService(){return this.getOrCreateService("PaymentService",$,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",O,this.getLocationHelperService())}getCheckoutService(t){return this.getOrCreateService(`CheckoutService_${t.getUniqueKey()}`,Y,t,this.getCheckoutHelperService())}}j.instance=null;class k{constructor(t,e){this.address={autocomplete:async t=>(await this.ensureAuthenticated(),this.addressService.autocomplete(t,this.config.googlePlacesApiKey)),details:async t=>(await this.ensureAuthenticated(),this.addressService.details(t,this.config.googlePlacesApiKey))},this.catalog={availability:async t=>(await this.ensureAuthenticated(),this.catalogService.availability(t)),search:async t=>(await this.ensureAuthenticated(),this.catalogService.search(t))},this.cart={get:async(t,e)=>(await this.ensureAuthenticated(),this.cartService.get(t,e)),update:async t=>(await this.ensureAuthenticated(),this.cartService.update(t))},this.user={session:async t=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(t)),purge:async t=>(await this.ensureAuthenticated(),this.userService.purge(t)),updateAddress:async t=>(await this.ensureAuthenticated(),this.userService.updateAddress(t)),purgeAddress:async t=>(await this.ensureAuthenticated(),this.userService.purgeAddress(t))},this.payment={mount:async t=>(await this.ensureAuthenticated(),this.paymentService.mount(t)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(t,e)=>{this.paymentService.subscribe(t,e)},unsubscribe:(t,e)=>{this.paymentService.unsubscribe(t,e)}},this.checkout={prepare:async t=>(await this.ensureAuthenticated(),this.checkoutService.prepare(t)),complete:async t=>(await this.ensureAuthenticated(),this.checkoutService.complete(t))},this.config=e,this.singletonManager=j.getInstance();const i=this.determineBaseURL(e);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:t,baseURL:i}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const i=e.env||t.LIQUID_COMMERCE_ENV.STAGE;return m[i]}async init(){try{await this.authenticatedClient.authenticate()}catch(t){throw new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}async function LiquidCommerce(t,e){const i=j.getInstance();return i.setLiquidCommerceClientConstructor(k),await i.getLiquidCommerceClient(t,e)}window.LiquidCommerce=LiquidCommerce,window.LIQUID_COMMERCE_ENV=t.LIQUID_COMMERCE_ENV,t.LiquidCommerce=LiquidCommerce}));
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).LiquidCommerce={})}(this,(function(t){"use strict";var LIQUID_COMMERCE_ENV,e,i,r,n,s,a,o,h,c,l,u,d,I,E,w,f,S,p,y;t.LIQUID_COMMERCE_ENV=void 0,(LIQUID_COMMERCE_ENV=t.LIQUID_COMMERCE_ENV||(t.LIQUID_COMMERCE_ENV={})).LOC="loc",LIQUID_COMMERCE_ENV.STAGE="stage",LIQUID_COMMERCE_ENV.PROD="prod",LIQUID_COMMERCE_ENV.DEV="dev",function(t){t.ON_DEMAND="onDemand",t.SHIPPING="shipping"}(e||(e={})),function(t){t.MONDAY="monday",t.TUESDAY="tuesday",t.WEDNESDAY="wednesday",t.THURSDAY="thursday",t.FRIDAY="friday",t.SATURDAY="saturday",t.SUNDAY="sunday"}(i||(i={})),function(t){t.AL="AL",t.AK="AK",t.AR="AR",t.CA="CA",t.CO="CO",t.CT="CT",t.DE="DE",t.DC="DC",t.FL="FL",t.GA="GA",t.HI="HI",t.ID="ID",t.IL="IL",t.IN="IN",t.IA="IA",t.KS="KS",t.KY="KY",t.LA="LA",t.ME="ME",t.MD="MD",t.MA="MA",t.MI="MI",t.MN="MN",t.MS="MS",t.MO="MO",t.MT="MT",t.NE="NE",t.NV="NV",t.NH="NH",t.NJ="NJ",t.NM="NM",t.NY="NY",t.NC="NC",t.ND="ND",t.OH="OH",t.OK="OK",t.OR="OR",t.PA="PA",t.RI="RI",t.SC="SC",t.SD="SD",t.TN="TN",t.TX="TX",t.UT="UT",t.VT="VT",t.VA="VA",t.WA="WA",t.WV="WV",t.WI="WI",t.WY="WY"}(r||(r={})),function(t){t.ALABAMA="AL",t.ALASKA="AK",t.ARKANSAS="AR",t.CALIFORNIA="CA",t.COLORADO="CO",t.CONNECTICUT="CT",t.DELAWARE="DE",t.DISTRICT_OF_COLUMBIA="DC",t.FLORIDA="FL",t.GEORGIA="GA",t.HAWAII="HI",t.IDAHO="ID",t.ILLINOIS="IL",t.INDIANA="IN",t.IOWA="IA",t.KANSAS="KS",t.KENTUCKY="KY",t.LOUISIANA="LA",t.MAINE="ME",t.MARYLAND="MD",t.MASSACHUSETTS="MA",t.MICHIGAN="MI",t.MINNESOTA="MN",t.MISSISSIPPI="MS",t.MISSOURI="MO",t.MONTANA="MT",t.NEBRASKA="NE",t.NEVADA="NV",t.NEW_HAMPSHIRE="NH",t.NEW_JERSEY="NJ",t.NEW_MEXICO="NM",t.NEW_YORK="NY",t.NORTH_CAROLINA="NC",t.NORTH_DAKOTA="ND",t.OHIO="OH",t.OKLAHOMA="OK",t.OREGON="OR",t.PENNSYLVANIA="PA",t.RHODE_ISLAND="RI",t.SOUTH_CAROLINA="SC",t.SOUTH_DAKOTA="SD",t.TENNESSEE="TN",t.TEXAS="TX",t.UTAH="UT",t.VERMONT="VT",t.VIRGINIA="VA",t.WASHINGTON="WA",t.WEST_VIRGINIA="WV",t.WISCONSIN="WI",t.WYOMING="WY"}(n||(n={})),function(t){t.ALE="BEER > ALE",t.LAGER="BEER > LAGER",t.MAIN="BEER",t.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",t.OTHER_BEER="BEER > OTHER BEER"}(s||(s={})),function(t){t.BASE="FOOD",t.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(a||(a={})),function(t){t.BASE="MERCHANDISE",t.GLASSWARE="MERCHANDISE > GLASSWARE",t.HUMIDOR="MERCHANDISE > HUMIDOR"}(o||(o={})),function(t){t.BASE="MISCELLANEOUS",t.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",t.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",t.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(h||(h={})),function(t){t.BASE="NON ALCOHOLIC",t.BITTERS="NON ALCOHOLIC > BITTERS",t.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",t.COFFEE="NON ALCOHOLIC > COFFEE",t.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",t.JUICE="NON ALCOHOLIC > JUICE",t.SODA="NON ALCOHOLIC > SODA",t.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",t.SPIRITS="NON ALCOHOLIC > SPIRITS",t.TEA="NON ALCOHOLIC > TEA",t.WATER="NON ALCOHOLIC > WATER",t.WINE="NON ALCOHOLIC > WINE"}(c||(c={})),function(t){t.BASE="READY TO DRINK",t.HARD_CIDER="READY TO DRINK > HARD CIDER",t.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",t.HARD_TEA="READY TO DRINK > HARD TEA",t.MALT_BASED="READY TO DRINK > MALT BASED",t.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",t.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",t.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",t.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",t.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",t.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(l||(l={})),function(t){t.BASE="SPIRITS",t.BAIJIU="SPIRITS > BAIJIU",t.BITTERS="SPIRITS > BITTERS",t.BRANDY="SPIRITS > BRANDY",t.CACHACA="SPIRITS > CACHACA",t.GIN="SPIRITS > GIN",t.LAGER="SPIRITS > LAGER",t.LIQUEUR="SPIRITS > LIQUEUR",t.MEZCAL="SPIRITS > MEZCAL",t.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",t.RUM="SPIRITS > RUM",t.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",t.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",t.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",t.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",t.RUM_OTHER="SPIRITS > RUM > OTHER",t.RUM_SPICED="SPIRITS > RUM > SPICED",t.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",t.SOJU="SPIRITS > SOJU",t.TEQUILA="SPIRITS > TEQUILA",t.VODKA="SPIRITS > VODKA",t.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",t.WHISKEY="SPIRITS > WHISKEY",t.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",t.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",t.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",t.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",t.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(u||(u={})),function(t){t.BASE="WINE",t.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",t.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",t.COOKING="WINE > COOKING",t.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",t.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",t.RED_WINE="WINE > RED WINE",t.ROSE_WINE="WINE > ROSE WINE",t.SAKE="WINE > SAKE",t.WHITE_WINE="WINE > WHITE WINE"}(d||(d={})),function(t){t.BRANDS="brands",t.FLAVOR="flavor",t.REGION="region",t.VARIETY="variety",t.PRICE="price",t.AVAILABILITY="availability",t.CATEGORIES="categories",t.SIZES="sizes",t.COLORS="colors",t.APPELLATION="appellation",t.COUNTRY="country",t.VINTAGE="vintage",t.MATERIALS="materials"}(I||(I={})),function(t){t.ASC="asc",t.DESC="desc"}(E||(E={})),function(t){t.PRICE="price"}(w||(w={})),function(t){t.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",t.IN_STOCK="IN_STOCK",t.OUT_OF_STOCK="OUT_OF_STOCK",t.PREORDER="PREORDER",t.BACKORDER="BACKORDER"}(f||(f={})),function(t){t.INVALID_ITEMS_TYPE="Items must be a non-empty array",t.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",t.INVALID_PART_NUMBER="The partnerNumber provided is invalid",t.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(S||(S={})),function(t){t.OOS="OutOfStock",t.ITEMS_NOT_ADDED="ItemsNotAdded",t.ITEM_NOT_ENGRAVED="ItemEngravingError",t.ADDRESS_CHANGE="AddressChange",t.RETAILER_MIN="RetailerMinNotMet",t.NO_ITEMS_IN_CART="NoItemsInCart",t.INVALID_ID="InvalidId",t.NO_ID="NoId",t.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",t.NEW_CART="NewCart",t.DEFAULT="CartError",t.ITEM_QTY_CHANGE="ItemQuantityChange"}(p||(p={})),function(t){t.SHIPPING="shipping",t.BILLING="billing"}(y||(y={}));const m={[t.LIQUID_COMMERCE_ENV.LOC]:"https://staging.cloud.liquidcommerce.co/api",[t.LIQUID_COMMERCE_ENV.DEV]:"https://staging.cloud.liquidcommerce.co/api",[t.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[t.LIQUID_COMMERCE_ENV.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class v{constructor(t){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(t,e)=>new Promise(((i,r)=>{const n=new XMLHttpRequest;n.open(e.method||"GET",t),Object.entries(e.headers).forEach((([t,e])=>{n.setRequestHeader(t,e)})),n.onload=()=>{i({ok:n.status>=200&&n.status<300,status:n.status,statusText:n.statusText,headers:n.getAllResponseHeaders().split("\r\n").reduce(((t,e)=>{const[i,r]=e.split(": ");return i&&(t[i]=r),t}),{}),json:()=>Promise.resolve(JSON.parse(n.responseText)),text:()=>Promise.resolve(n.responseText)})},n.onerror=()=>{r(new TypeError("Network request failed"))},n.send(e.body)})),this.apiKey=t.apiKey,this.baseURL=t.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(t){return v.instance||(v.instance=new v(t)),v.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(t){return async(e,i)=>{var r;const n=await t(e,i);let s;return"function"==typeof(null===(r=n.headers)||void 0===r?void 0:r.entries)?s=Object.fromEntries(n.headers.entries()):(s={},n.headers.forEach(((t,e)=>{s[e]=t}))),{ok:n.ok,status:n.status,statusText:n.statusText,headers:s,json:()=>n.json(),text:()=>n.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var t,e;if(this.isAuthenticating)await new Promise((t=>{const e=()=>{this.isAuthenticating?setTimeout(e,100):t(void 0)};e()}));else{this.isAuthenticating=!0;try{const i=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.token,this.tokenExpiration=Date.now()+1e3*(null===(e=null==i?void 0:i.data)||void 0===e?void 0:e.exp)}catch(t){throw new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(t,e){const i=new URL(`api${t}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...e.headers},n={method:e.method,headers:r,body:e.body?JSON.stringify(e.body):void 0},s=await this.httpClient(i.toString(),n);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(t,e){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const i=new URL(`api${t}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...e.headers},n={method:e.method,headers:r,body:e.body?JSON.stringify(e.body):void 0},s=await this.httpClient(i.toString(),n);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}async get(t,e){return this.request(t,{method:"GET",headers:e})}async post(t,e,i){return this.request(t,{method:"POST",body:e,headers:i})}async put(t,e,i){return this.request(t,{method:"PUT",body:e,headers:i})}async delete(t,e){return this.request(t,{method:"DELETE",headers:e})}}v.instance=null;class A{constructor(t){this.locationHelperService=t}validateAndNormalizeParams(t){const e={...t};return e.id=this.validateId(e.id),e.items=this.validateAndNormalizeItems(e.items),this.locationHelperService.validateAndNormalizeLocation(e.loc),e.refresh=Boolean(e.refresh),e}validateId(t){return t&&"string"==typeof t&&0!==t.trim().length?t.trim():""}validateAndNormalizeItems(t){if(!Array.isArray(t)||0===t.length)throw new Error(S.INVALID_ITEMS_TYPE);if(t.length>25)throw new Error(S.INVALID_ITEMS_MAX);return t.map((t=>this.validateAndNormalizeItem(t)))}validateAndNormalizeItem(t){const e={...t};if(!this.validatePartNumber(e.partNumber))throw new Error(S.INVALID_PART_NUMBER);if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId||0===e.fulfillmentId.trim().length)throw new Error(S.INVALID_FULFILLMENT_ID);return e.quantity=Math.max(0,Math.floor(e.quantity)),e.engravingLines&&(e.engravingLines=e.engravingLines.map((t=>t.trim())).filter((t=>t.length>0))),e}validatePartNumber(t){if(!t||"string"!=typeof t)return!1;const e=t.split("_");return 2===e.length&&14===e[0].length&&e[1].length>0}}class R{constructor(t){this.locationServiceHelper=t,this.taxonomyValues=new Set([...Object.values(s),...Object.values(a),...Object.values(o),...Object.values(c),...Object.values(l),...Object.values(u),...Object.values(d)])}validateAndNormalizeParams(t){const e={...t};return this.validateUPCs(e.upcs),this.locationServiceHelper.validateAndNormalizeLocation(e.loc),e}validateAndNormalizeSearchParams(t){const e=[],i={...t};return this.validateOrderBy(i.orderBy,e),this.validateOrderDirection(i.orderDirection,e),this.validateFilters(i.filters,e),this.validatePagination(i.page,i.perPage,e),this.locationServiceHelper.validateAndNormalizeLocation(i.loc),e.length>0?{...i,error:e.join(". ")}:i}validateUPCs(t){if(!Array.isArray(t)||0===t.length)throw new Error("UPCs must be a non-empty array of strings");if(!t.every((t=>"string"==typeof t&&t.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(t,e){t&&!Object.values(w).includes(t)&&e.push(`Invalid orderBy value: ${t}`)}validateOrderDirection(t,e){t&&!Object.values(E).includes(t)&&e.push(`Invalid orderDirection value: ${t}`)}validateFilters(t,e){t&&(t.length>10&&e.push("Maximum of 10 filters allowed"),t.forEach((t=>{switch(Object.values(I).includes(t.key)||e.push(`Invalid filter key: ${t.key}`),t.key){case I.AVAILABILITY:this.validateAvailabilityFilter(t.values,e);break;case I.BRANDS:this.validateArrayFilter(t.values,30,"brands",e);break;case I.CATEGORIES:this.validateCategoriesFilter(t.values,e);break;case I.COLORS:this.validateArrayFilter(t.values,75,"colors",e)}})))}validateAvailabilityFilter(t,e){Object.values(f).includes(t)||e.push(`Invalid availability value: ${t}`)}validateArrayFilter(t,e,i,r){Array.isArray(t)?t.length>e&&r.push(`${i} filter can have a maximum of ${e} values`):r.push(`${i} filter must be an array`)}validateCategoriesFilter(t,e){Array.isArray(t)?t.every((t=>this.taxonomyValues.has(t)))||e.push("Invalid category value(s) in categories filter"):e.push("Categories filter must be an array")}validatePagination(t,e,i){void 0!==t&&("number"!=typeof t||t<0)&&i.push("Page must be a non-negative number"),void 0!==e&&("number"!=typeof e||e<=0)&&i.push("PerPage must be a positive number")}}class O{constructor(t){this.locationHelperService=t}validateAndNormalizePrepareParams(t){const e={...t};if(!e.cartId||"string"!=typeof e.cartId)throw new Error("Invalid cartId");return this.validateRecipient(e.recipient),e.billingAddress&&this.validateAddress(e.billingAddress),e.hasSubstitutionPolicy=Boolean(e.hasSubstitutionPolicy),e.isGift=Boolean(e.isGift),e.billingSameAsShipping=Boolean(e.billingSameAsShipping),e.isGift&&this.validateGiftOptions(e.giftOptions),this.validateMarketingPreferences(e.marketingPreferences),e.deliveryTips&&this.validateDeliveryTips(e.deliveryTips),e.refresh=Boolean(e.refresh),e}validateAndNormalizeCompleteParams(t){const e={...t};if(!e.token||"string"!=typeof e.token)throw new Error("Invalid token");if(!e.payment||"string"!=typeof e.payment)throw new Error("Invalid payment token");return void 0!==e.refresh&&(e.refresh=Boolean(e.refresh)),e}validateRecipient(t){if(!t||"object"!=typeof t)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid recipient ${e}`)})),t.hasAgeVerify=Boolean(t.hasAgeVerify)}validateAddress(t){if(!t||"object"!=typeof t)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid address ${e}`)})),this.locationHelperService.validateAndNormalizeLocation({address:t})}validateGiftOptions(t){if(!t||"object"!=typeof t)throw new Error("Invalid giftOptions");if(t.message&&"string"!=typeof t.message)throw new Error("Invalid gift message");if(t.recipient){const{name:e,phone:i,email:r}=t.recipient;if(e&&"string"!=typeof e)throw new Error("Invalid gift recipient name");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient phone");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(t){if(!t||"object"!=typeof t)throw new Error("Invalid marketingPreferences");t.canEmail=Boolean(t.canEmail),t.canSms=Boolean(t.canSms)}validateDeliveryTips(t){if(!Array.isArray(t))throw new Error("Invalid deliveryTips");t.forEach((t=>{if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof t.tip||t.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class T{validateAndNormalizeLocation(t){if(!t||"object"!=typeof t)throw new Error("Location must be a valid object");if(t.coords)this.validateCoordinates(t.coords);else{if(!t.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(t.address)}}validateCoordinates(t){if("number"!=typeof t.lat||"number"!=typeof t.long)throw new Error("Coordinates must be valid numbers");if(t.lat<-90||t.lat>90||t.long<-180||t.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(t){if(!t.state||"string"!=typeof t.state)throw new Error("State is required and must be a string");if(t.state=this.normalizeState(t.state),!t.city||"string"!=typeof t.city)throw new Error("City is required and must be a string");if(!t.zip||"string"!=typeof t.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(t){const e=t.toUpperCase();if(r[e])return r[e];const i=t.toUpperCase();if(n[i])return n[i];throw new Error(`Invalid state: ${t}`)}}var N,C="https://js.stripe.com/v3",g=/^https:\/\/js\.stripe\.com\/v3\/?(\?.*)?$/,P=function(t){var e=document.createElement("script");e.src="".concat(C).concat("");var i=document.head||document.body;if(!i)throw new Error("Expected document.body not to be null. Stripe.js requires a <body> element.");return i.appendChild(e),e},D=null,b=null,L=null,M=function(){return N||(N=(null!==D?D:(D=new Promise((function(t,e){if("undefined"!=typeof document)if(window.Stripe,window.Stripe)t(window.Stripe);else try{var i=function(){for(var t=document.querySelectorAll('script[src^="'.concat(C,'"]')),e=0;e<t.length;e++){var i=t[e];if(g.test(i.src))return i}return null}();if(i){if(i&&null!==L&&null!==b){var r;i.removeEventListener("load",L),i.removeEventListener("error",b),null===(r=i.parentNode)||void 0===r||r.removeChild(i),i=P()}}else i=P();L=function(t,e){return function(){window.Stripe?t(window.Stripe):e(new Error("Stripe.js not available"))}}(t,e),b=function(t){return function(){t(new Error("Failed to load Stripe.js"))}}(e),i.addEventListener("load",L),i.addEventListener("error",b)}catch(t){return void e(t)}else t(null)}))).catch((function(t){return D=null,Promise.reject(t)}))).catch((function(t){return N=null,Promise.reject(t)})))};Promise.resolve().then((function(){return M()})).catch((function(t){}));class H{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];var r=Date.now();return M().then((function(t){return function(t,e,i){if(null===t)return null;var r=t.apply(void 0,e);return function(t,e){t&&t.t&&t.t({name:"stripe-js",version:"4.3.0",startTime:e})}(r,i),r}(t,e,r)}))}(t.key)}catch(t){throw new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const e={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(e);const i=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",i),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var t,e,i,r,n,s,a,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:h}=await this.elements.submit();if(h)return{type:"validation_error",message:h.message,code:h.code};const{error:c,paymentMethod:l}=await this.stripe.createPaymentMethod({elements:this.elements});return c?{type:"validation_error"===c.type?"validation_error":"api_error",message:c.message,code:c.code,param:c.param}:l?{id:l.id,type:l.type,card:(null==l?void 0:l.card)?{brand:null!==(e=null===(t=l.card)||void 0===t?void 0:t.brand)&&void 0!==e?e:"",country:null!==(i=l.card.country)&&void 0!==i?i:"",expMonth:null!==(r=l.card.exp_month)&&void 0!==r?r:0,expYear:null!==(n=l.card.exp_year)&&void 0!==n?n:0,last4:null!==(s=l.card.last4)&&void 0!==s?s:"",funding:null!==(a=l.card.funding)&&void 0!==a?a:""}:void 0,created:null!==(o=null==l?void 0:l.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.on(t,e)}unsubscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.off(t,e)}mapAppearance(t){if(t)return{theme:"night"===t.theme?"night":"stripe"}}mapElementOptions(t){return{layout:null==t?void 0:t.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class K{constructor(t){this.client=t}async autocomplete(t,e){try{return await this.client.post("/address/autocomplete",{...t,key:e})}catch(t){throw t}}async details(t,e){try{return await this.client.post("/address/details",{...t,key:e})}catch(t){throw t}}}class U{constructor(t,e){this.client=t,this.cartHelperService=e,this.servicePath="/cart/update"}async get(t,e){try{let i=this.cartHelperService.validateId(t);if(i=""!==i&&i,i){const t={id:i};return"boolean"==typeof e&&(t.refresh=e),await this.client.post(this.servicePath,t)}return await this.client.post(this.servicePath)}catch(t){throw t}}async update(t){try{const e=this.cartHelperService.validateAndNormalizeParams(t);return await this.client.post(this.servicePath,e)}catch(t){throw t}}}class W{constructor(t,e){this.client=t,this.catalogHelperService=e,this.servicePath="/catalog/"}async availability(t){try{const e=this.catalogHelperService.validateAndNormalizeParams(t);return await this.client.post(`${this.servicePath}availability`,e)}catch(t){throw t}}async search(t){try{const e=this.catalogHelperService.validateAndNormalizeSearchParams(t);if(null==e?void 0:e.error)throw new Error(null==e?void 0:e.error);return await this.client.post(`${this.servicePath}search`,e)}catch(t){throw t}}}class Y{constructor(t,e){this.client=t,this.checkoutHelperService=e,this.servicePath="/checkout"}async prepare(t){try{const e=this.checkoutHelperService.validateAndNormalizePrepareParams(t);return await this.client.post(`${this.servicePath}/prepare`,e)}catch(t){throw t}}async complete(t){try{const e=this.checkoutHelperService.validateAndNormalizeCompleteParams(t);return await this.client.post(`${this.servicePath}/complete`,e)}catch(t){throw t}}}class ${constructor(t){this.paymentProvider=t}async mount(t){try{await this.paymentProvider.mount(t)}catch(t){throw t}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(t,e){this.paymentProvider.subscribe(t,e)}unsubscribe(t,e){this.paymentProvider.unsubscribe(t,e)}}class B{constructor(t){this.client=t,this.servicePath="/users"}async createOrUpdateSession(t){try{if(!(null==t?void 0:t.id)&&!(null==t?void 0:t.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,t)}catch(t){throw t}}async purge(t){try{if(!t)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${t}`)}catch(t){throw t}}async updateAddress(t){try{if(!(t.customerId&&t.one&&t.city&&t.state&&t.zip&&t.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,t)}catch(t){throw t}}async purgeAddress(t){try{if(!t)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${t}`)}catch(t){throw t}}}class j{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return j.instance||(j.instance=new j),j.instance}setLiquidCommerceClientConstructor(t){this.liquidCommerceClientConstructor=t}async getLiquidCommerceClient(t,e){const i=`LiquidCommerceClient_${t}_${JSON.stringify(e)}`;if(!this.services.has(i)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const r=new this.liquidCommerceClientConstructor(t,e);await r.init(),this.services.set(i,r)}return this.services.get(i)}getOrCreateService(t,e,...i){if(!this.services.has(t)){const r="getInstance"in e?e.getInstance(...i):new e(...i);this.services.set(t,r)}return this.services.get(t)}getAuthenticatedClient(t){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(t)}`,v,t)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",T)}getAddressService(t){return this.getOrCreateService(`AddressService_${t.getUniqueKey()}`,K,t)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",R,this.getLocationHelperService())}getCatalogService(t){return this.getOrCreateService(`CatalogService_${t.getUniqueKey()}`,W,t,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",A,this.getLocationHelperService())}getCartService(t){return this.getOrCreateService(`CartService_${t.getUniqueKey()}`,U,t,this.getCartHelperService())}getUserService(t){return this.getOrCreateService(`UserService_${t.getUniqueKey()}`,B,t)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",H)}getPaymentService(){return this.getOrCreateService("PaymentService",$,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",O,this.getLocationHelperService())}getCheckoutService(t){return this.getOrCreateService(`CheckoutService_${t.getUniqueKey()}`,Y,t,this.getCheckoutHelperService())}}j.instance=null;class k{constructor(t,e){this.address={autocomplete:async t=>(await this.ensureAuthenticated(),this.addressService.autocomplete(t,this.config.googlePlacesApiKey)),details:async t=>(await this.ensureAuthenticated(),this.addressService.details(t,this.config.googlePlacesApiKey))},this.catalog={availability:async t=>(await this.ensureAuthenticated(),this.catalogService.availability(t)),search:async t=>(await this.ensureAuthenticated(),this.catalogService.search(t))},this.cart={get:async(t,e)=>(await this.ensureAuthenticated(),this.cartService.get(t,e)),update:async t=>(await this.ensureAuthenticated(),this.cartService.update(t))},this.user={session:async t=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(t)),purge:async t=>(await this.ensureAuthenticated(),this.userService.purge(t)),updateAddress:async t=>(await this.ensureAuthenticated(),this.userService.updateAddress(t)),purgeAddress:async t=>(await this.ensureAuthenticated(),this.userService.purgeAddress(t))},this.payment={mount:async t=>(await this.ensureAuthenticated(),this.paymentService.mount(t)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(t,e)=>{this.paymentService.subscribe(t,e)},unsubscribe:(t,e)=>{this.paymentService.unsubscribe(t,e)}},this.checkout={prepare:async t=>(await this.ensureAuthenticated(),this.checkoutService.prepare(t)),complete:async t=>(await this.ensureAuthenticated(),this.checkoutService.complete(t))},this.config=e,this.singletonManager=j.getInstance();const i=this.determineBaseURL(e);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:t,baseURL:i}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const i=e.env||t.LIQUID_COMMERCE_ENV.STAGE;return m[i]}async init(){try{await this.authenticatedClient.authenticate()}catch(t){throw new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}async function LiquidCommerce(t,e){const i=j.getInstance();return i.setLiquidCommerceClientConstructor(k),await i.getLiquidCommerceClient(t,e)}window.LiquidCommerce=LiquidCommerce,window.LIQUID_COMMERCE_ENV=t.LIQUID_COMMERCE_ENV,t.LiquidCommerce=LiquidCommerce}));