@faststore/api 4.5.1 → 4.6.0-dev.1
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/cjs/index.js +45 -43
- package/dist/cjs/index.js.map +1 -1
- package/dist/es/index.mjs +885 -883
- package/dist/es/index.mjs.map +1 -1
- package/dist/src/observability/telemetry.d.ts +1 -1
- package/dist/src/observability/telemetry.d.ts.map +1 -1
- package/dist/src/platforms/vtex/index.d.ts +1 -1
- package/dist/src/platforms/vtex/index.d.ts.map +1 -1
- package/dist/src/typings/globals.d.ts +2 -5
- package/dist/src/typings/globals.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/observability/telemetry.ts +54 -37
- package/src/platforms/vtex/index.ts +18 -23
- package/src/typings/globals.ts +2 -5
package/dist/cjs/index.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const tn=require("@graphql-tools/merge"),rn=require("@graphql-tools/schema"),z=require("@graphql-tools/utils"),L=require("@faststore/diagnostics"),oe=require("graphql"),zn=require("isomorphic-unfetch"),te=require("cookie"),Te=require("p-limit"),ue=require("dataloader"),qn=require("sanitize-html"),ke=require("fast-deep-equal"),Vn=require("node:crypto");var an=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(an||{}),on=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(on||{}),sn=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(sn||{}),cn=(e=>(e.DiscountDesc="discount_desc",e.NameAsc="name_asc",e.NameDesc="name_desc",e.OrdersDesc="orders_desc",e.PriceAsc="price_asc",e.PriceDesc="price_desc",e.ReleaseDesc="release_desc",e.ScoreDesc="score_desc",e))(cn||{}),ln=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(ln||{}),dn=(e=>(e.Input="Input",e.Output="Output",e))(dn||{});const xn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new x("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},jn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new Q("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new Q("Authentication required"):r===403?new x("You are not allowed to access this resource"):new Q("Authentication required")}},Wn="auth",un={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{if(z.getDirective(e,n,Wn)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await jn(o),r?.(i,a,o,s))}return n}})},Gn="cacheControl",Hn=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},Ue=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,Xn=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,pn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{const t=z.getDirective(e,n,Gn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,c,l,g)=>(l.cacheControl={sMaxAge:Ue(l.cacheControl?.sMaxAge,r),staleWhileRevalidate:Ue(l.cacheControl?.staleWhileRevalidate,i),scope:Xn(l.cacheControl?.scope,a)},o?.(s,c,l,g))}return n}})},gn=e=>(n,t)=>{const r=tn.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,rn.makeExecutableSchema({typeDefs:r,resolvers:n}))},me="@faststore/api",he="4.5.1-dev.2",_e={name:me,version:he},Yn=(e,n)=>(t,r,i,a)=>{if((i?.OTEL?.enabled??!1)===!1)return e(t,r,i,a);const o=L.OTELAPI.trace.getTracer(me,he),s=L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),i.OTEL);return L.OTELAPI.context.with(s,()=>{const c=o.startSpan(n??"Unknown Graphql Resolver",{startTime:Date.now(),kind:L.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":he,"@faststore_package_name":me,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!c)return e(t,r,i,a);try{const l=e(t,r,i,a);return l instanceof Promise?l.then(g=>(c.end(),g)):(c.end(),l)}catch(l){throw c.end(),console.error(`Error when executing resolver: ${n}`,l),l}})};class W extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class T extends W{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Q extends W{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class x extends W{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class B extends W{constructor(n){super({status:404,type:"NotFoundError"},n)}}const Jn=e=>e?.name==="FastStoreError",Kn=e=>e?.extensions?.type==="BadRequestError",Qn=e=>e?.extensions?.type==="UnauthorizedError",mn=e=>e?.extensions?.type==="ForbiddenError",q=e=>e?.extensions?.type==="NotFoundError",Zn=`${_e.name}@${_e.version}`,I=async(e,n,t)=>{const r=await zn(e,{...n,headers:{...n?.headers??{},"User-Agent":Zn}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new T(i);case 401:throw new Q(i);case 403:throw new x(i);case 404:throw new B(i);default:throw new W({status:r.status,type:"UnknownError"},i)}throw new Error(i)},et=({account:e,environment:n})=>{const t=`https://${e}.${n}.com.br`;return{getLocalizedProduct:(r,i)=>I(`${t}/api/catalog-dataplane/product/${r}`,{method:"GET",headers:{"Accept-Language":i,"Content-Type":"application/json"}})}},hn=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const a=i.trim();if(a){const o=a.indexOf("=");if(o>0){const s=a.substring(0,o),c=a.substring(o+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},nt=/^([^=]+)=([^;]*)/,tt=(e,n)=>{const t=n.match(nt);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},rt=(e,n)=>{n.getSetCookie().forEach(t=>tt(e,t))},it=e=>n=>rt(e,n),fe=e=>{if(!e.headers?.cookie)return null;const n=hn(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>at(r,i,a),n)},fn=e=>function(t){const r=fe(e);return r?{...t,cookie:r}:t},V=(e,n)=>{const t=hn(e);return te.parse(t)[`VtexIdclientAutCookie_${n}`]||""},at=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function Z(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const ot="storefront/faststore.recommendation-shelf@v4",X={method:"POST",headers:{"content-type":"application/json"}},st=e=>e.split("/").map(encodeURIComponent).join("/"),ge=e=>e?{headers:{"Accept-Language":e}}:void 0,ct=/^\d{4}-\d{2}-\d{2}$/,lt=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function dt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o}){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`listUserQuotes: invalid page "${e}" — must be a positive integer`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`listUserQuotes: invalid perPage "${n}" — must be a positive integer`);for(const[s,c]of[["createdAtFrom",r],["createdAtTo",i],["expiresAtFrom",a],["expiresAtTo",o]])if(c&&!ct.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!lt.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function ut({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:a,expiresAtTo:o,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(l=>c.append("status",l)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),a&&c.append("expiresAtFrom",a),o&&c.append("expiresAtTo",o),s?.trim()&&c.append("label",s.trim()),c}const pt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=it(i),s=fn(i),c=xn(),l=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",g=r&&r.map(d=>d+".").find(d=>l.includes(d))||"",u=l.replace(g,""),h=`${a}/api/recommend-bff/v2`,f=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${ot}`}),v=(d={})=>{const p=V(fe(i)??"",e);return s({...d,"X-FORWARDED-HOST":u,...p?{[`VtexIdclientAutCookie_${e}`]:p}:{}})};return{catalog:{salesChannel:d=>I(`${a}/api/catalog_system/pub/saleschannel/${d}`,void 0,{storeCookies:o}),brand:{list:()=>I(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(d=3)=>I(`${a}/api/catalog_system/pub/category/tree/${d}`,void 0,{storeCookies:o})},portal:{pagetype:d=>I(`${a}/api/catalog_system/pub/portal/pagetype/${d}`,void 0,{storeCookies:o})},byLinkId:{category:async(d,p)=>{try{return await I(`${a}/api/catalog_system/pub/category/by-linkid/${st(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}},brand:async(d,p)=>{try{return await I(`${a}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}},collection:async(d,p)=>{try{return await I(`${a}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}}},products:{crossselling:({type:d,productId:p,groupByProduct:m=!0})=>{const y=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return I(`${a}/api/catalog_system/pub/products/crossselling/${d}/${p}?${y}`,void 0,{storeCookies:o})}}},checkout:{simulation:(d,{salesChannel:p}=i.storage.channel)=>{const m=new URLSearchParams({sc:p}),y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...X,headers:y,body:JSON.stringify(d)},{storeCookies:o})},shippingData:({id:d,index:p,deliveryMode:m,selectedAddresses:y},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,b={logisticsInfo:Array.from({length:p},(S,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:y,clearAddressIfPostalCodeNotFound:t},A=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/attachments/shippingData`,{...X,headers:A,body:JSON.stringify(b)},{storeCookies:o})},marketingData:({id:d,marketingData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/attachments/marketingData`,{headers:m,body:JSON.stringify(p),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:d,clientPreferencesData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(p),method:"POST"},{storeCookies:o})},orderForm:({id:d,refreshOutdatedData:p=!0,channel:m=i.storage.channel})=>{const{salesChannel:y}=m,O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),w=new URLSearchParams({sc:y});d&&w.set("refreshOutdatedData",p.toString());const b=`${a}/api/checkout/pub/orderForm${d?`/${d}`:""}?${w.toString()}`;return I(b,{...X,headers:O,...d?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/messages/clear`,{...X,headers:p,body:"{}"})},updateOrderFormItems:({id:d,orderItems:p,allowOutdatedData:m="paymentData",salesChannel:y=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:y}),b=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/items?${w}`,{headers:b,body:JSON.stringify({orderItems:p,noSplitItem:!O}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:d,appId:p,key:m,value:y})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}/customData/${p}/${m}`,{headers:O,body:JSON.stringify({value:y}),method:"PUT"})},region:async({postalCode:d,geoCoordinates:p,country:m,salesChannel:y})=>{const O=new URLSearchParams({country:m,sc:y??""});d?O.append("postalCode",d):O.append("geoCoordinates",`${p?.longitude};${p?.latitude}`);const w=`${a}/api/checkout/pub/regions/?${O.toString()}`,b=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(w,{headers:b},{storeCookies:o})},address:async({postalCode:d,country:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/postal-code/${p}/${d}`,{headers:m},{storeCookies:o})},cancelOrder:({orderId:d,customerEmail:p,reason:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orders/${d}/user-cancel-request`,{method:"POST",headers:y,body:JSON.stringify({customerEmail:p,reason:m})},{})},pickupPoints:({geoCoordinates:d})=>{if(!d)throw new Error("Missing required parameter for listing pickup points.");const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:p,body:JSON.stringify({coordinate:d})},{storeCookies:o})}},session:d=>{const p=new URLSearchParams(d);p.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,shopper.availableContracts,shopper.activeContractId,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol,authentication.customerId,authentication.storeUserId,authentication.storeUserEmail,authentication.unitId,authentication.unitName,checkout.regionId,public.postalCode");const m=s({"content-type":"application/json"}),y=te.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${a}/api/sessions?${p.toString()}`,{method:y?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:o})},subscribeToNewsletter:d=>I(`${a}/api/dataentities/NL/documents/`,{...X,body:JSON.stringify({...d,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async d=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/profile-system/pvt/profiles/${d}/addresses`,{headers:p},{storeCookies:o})}},oms:{userOrder:({orderId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/oms/user/orders/${d}`,{method:"GET",headers:p},{storeCookies:o})},listUserOrders:({page:d,status:p,dateInitial:m,dateFinal:y,text:O,clientEmail:w,perPage:b,pendingMyApproval:A})=>{const S=new URLSearchParams;if(m){const P=new Date(m).setHours(0,0,0,0);m=new Date(P).toISOString()}if(y){const P=new Date(y).setHours(23,59,59,999);y=new Date(P).toISOString()}O&&S.append("text",O),p&&p.length>0&&S.append("status",p.filter(Boolean).join(",")),m&&y?S.append("creation_date",`creationDate:[${m} TO ${y}]`):m?S.append("creation_date",`creationDate:[${m} TO *]`):y&&S.append("creation_date",`creationDate:[* TO ${y}]`),w&&S.append("clientEmail",w),d&&S.append("page",d.toString()),b&&S.append("per_page",b.toString()),A&&S.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/oms/user/orders?${S.toString()}`,{method:"GET",headers:D},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/${e}/commercial-authorizations/order/${d}`,{method:"GET",headers:p},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:d,dimensionId:p,ruleId:m,approved:y})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),A={params:{ruleId:m,dimensionId:p,score:y?100:0}};return I(`${a}/${e}/commercial-authorizations/${d}/callback`,{method:"POST",headers:O,body:JSON.stringify(A)},{storeCookies:o})}},units:{getUnitByUserId:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/units/v1/${d}/unit`,{method:"GET",headers:p},{})},getOrgUnitById:({orgUnitId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/units/v1/${d}`,{method:"GET",headers:p},{})},getScopesByOrgUnit:({orgUnitId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/units/v1/${d}/scopes`,{method:"GET",headers:p},{})}},licenseManager:{getUserById:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/license-manager/users/${d}`,{method:"GET",headers:p},{})},getUserByEmail:({email:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/license-manager/pvt/users/${d}`,{method:"GET",headers:p},{})},getUserRoles:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/license-manager/storefront/users/${d}/roles`,{method:"GET",headers:p},{})}},masterData:{getContractById:({contractId:d})=>{if(!d)throw new T("Missing contractId to fetch CL fields.");const p=v({Accept:"application/json","content-type":"application/json"});return I(`${a}/api/dataentities/CL/documents/${d}?_fields=_all`,{method:"GET",headers:p},{})},getShopperById:({userId:d})=>{if(!d)throw new T("Missing userId to fetch shopper name.");const p=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),m=d.replace(/-/g,"");return I(`${a}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${d})&_fields=_all&_schema=v1`,{method:"GET",headers:p},{})}},quotes:{listUserQuotes:d=>{dt(d);const p=ut(d),m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/quoting/quotes?${p.toString()}`,{method:"GET",headers:m},{storeCookies:o})}},vtexid:{validate:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u}),p=V(fe(i)??"",e);return I(`${a}/api/vtexid/credential/validate`,{headers:d,body:JSON.stringify({token:p}),method:"POST"},{storeCookies:o})}},orderEntry:{uploadFile:({fileBuffer:d,fileName:p,mimeType:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),O=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
|
|
2
|
-
`,A=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",S=p.replaceAll(/[\r\n"]/g,"_"),D=[`--${O}`,`Content-Disposition: form-data; name="file"; filename="${S}"`,`Content-Type: ${A}`,"",""].join(w),P=`${w}--${O}--${w}`,k=Buffer.from(D),C=Buffer.from(P),E=new Uint8Array(k.byteLength+d.byteLength+C.byteLength);let U=0;return E.set(k,U),U+=k.byteLength,E.set(d,U),U+=d.byteLength,E.set(C,U),I(`${a}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...y,"content-type":`multipart/form-data; boundary=${O}`},body:E.buffer},{})},startOperation:({objectKey:d,orderFormId:p,sessionToken:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),O=JSON.stringify({objectKey:d,orderFormId:p,operation:"CreateCart",...m?{sessionToken:m}:{}});return I(`${a}/api/order-entry/operation?an=${e}`,{method:"POST",headers:y,body:O},{})},getOperation:({operationId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/order-entry/operation/${d}?an=${e}`,{method:"GET",headers:p},{})},createOrderForm:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:d,body:"{}"},{})},getOrderFormItems:({orderFormId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${d}`,{method:"GET",headers:p},{})}},recommendation:{recommendations:({campaignVrn:d,userId:p,products:m=[],salesChannel:y,locale:O})=>{const w=new URLSearchParams({an:e,campaignVrn:d});return p&&w.append("userId",p),m.length>0&&w.append("products",m.join(",")),y&&w.append("salesChannel",y),O&&w.append("locale",O),I(`${h}/recommendations?${w.toString()}`,{headers:f},{storeCookies:o})},startRecommendationSession:()=>{const d=new URLSearchParams({an:e});return I(`${h}/users/start-session?${d.toString()}`,{method:"POST",headers:f},{storeCookies:o})}}}},ee=e=>e.discoveryConfig?.localization??{},ne=e=>ee(e).enabled===!0,gt=e=>Object.keys(ee(e).locales??{}),mt=e=>ee(e).defaultLocale,ie=e=>ne(e)&&e.storage.locale||void 0,Se="fuzzy",ye="operator",Ie="pickupPoint",Re="shipping",Fe="delivery-options",ht="in-stock",ft="trade-policy",St="region-id",yt=new Set([ft,St,Se,ye,Ie]),It=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),Ne=e=>encodeURI(decodeURI(e)),vt=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),Ot=/^pickup-in-point-(.+)$/;function Sn(e){if(!e)return{};try{const t=te.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function bt(e){const n={},t=[];for(const r of e.split(";")){const i=r.indexOf("=");if(i<0)continue;const a=r.slice(0,i),o=r.slice(i+1);!a||!o||(It.has(a)?n[a]=o:t.push({key:a,value:o}))}return{shipping:n,extraFacets:t}}function Ct(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=bt(n);return{segmentParams:{sc:e.channel,regionId:e.regionId,country:e.countryCode??t.country,locale:e.cultureInfo,"zip-code":t["zip-code"],coordinates:t.coordinates,pickupPoint:t.pickupPoint,deliveryZonesHash:t.deliveryZonesHash,pickupPointHash:t.pickupPointsHash,utmSource:e.utm_source??void 0,utmCampaign:e.utm_campaign??void 0,utmiCampaign:e.utmi_campaign??void 0,campaigns:typeof e.campaigns=="string"?e.campaigns:void 0,priceTables:e.priceTables??void 0},extraFacets:r}}function yn(e,n){const t=[["sc",n.sc],["regionId",n.regionId],["country",n.country],["locale",n.locale],["zip-code",n["zip-code"]],["coordinates",n.coordinates],["pickupPoint",n.pickupPoint],["deliveryZonesHash",n.deliveryZonesHash],["pickupPointHash",n.pickupPointHash],["utmSource",n.utmSource],["utmCampaign",n.utmCampaign],["utmiCampaign",n.utmiCampaign],["campaigns",n.campaigns],["priceTables",n.priceTables]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function In(e){return Ot.exec(e)?.[1]}function wt(e){const n=e.find(r=>r.key==="shipping"),t=n?In(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function Dt(e,n){const t=wt(n);return t===void 0?e:{...e,pickupPoint:t}}function Pt(e){return e.map(n=>n.key!=="shipping"||In(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function At(e,n){let t=[...e];const r=t.some(i=>i.key==="shipping");for(const i of n)(!r||i.key!=="shipping")&&t.push(i);return t.some(i=>i.key==="shipping"&&i.value==="ignore")&&(t=t.filter(i=>i.key!=="shipping")),Pt(t)}function Tt(e){return e.reduce((n,t)=>{let{key:r,value:i}=t;return r==="priceRange"&&(r="price",i=i.replace(" TO ",":")),r==="ft"?n:`${n}${Ne(r)}/${vt(Ne(i)).replaceAll(/ |%20/g,"-")}/`},"")}const kt=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),Et=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function Ut(e,n){const{segmentParams:t,extraFacets:r}=Ct(e??{}),i=n?.salesChannel??t.sc,a=n?.regionId??t.regionId,o=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...a?{regionId:a}:{},locale:o},extraFacets:r}}function _t(e,n){const t=e.filter(({key:c})=>!yt.has(c)),r=e.find(({key:c,value:l})=>c===Re&&l!=="all-delivery-methods")??null,i=e.find(({key:c,value:l})=>c===Fe&&l!=="all-delivery-options")??null,a=[...t],o=a.some(({key:c})=>c===Re),s=a.some(({key:c})=>c===Fe);return r!==null&&!o&&a.push(r),i!==null&&!s&&a.push(i),At(a,n)}function Rt(e,n){const t=e.find(({key:a})=>a===Se)??null,r=e.find(({key:a})=>a===ye)??null,i=e.find(({key:a})=>a===Ie)??null;t&&kt(t)&&n.append(Se,t.value),r&&Et(r)&&n.append(ye,r.value),i&&n.append(Ie,i.value)}function Le(e,n,t,r){const{query:i="",page:a,count:o,sort:s,selectedFacets:c=[],showInvisibleItems:l,sponsoredCount:g,hideUnavailableItems:u,allowRedirect:h=!1}=e,f=new URLSearchParams;if(r.includePagination&&a!==void 0&&o!==void 0){const p=a*o,m=o===0?p:p+o-1;f.append("from",p.toString()),f.append("to",m.toString())}i&&f.append("query",i),r.includeSort&&s&&f.append("sort",s);const v=Dt(t.segmentParams,c);if(yn(f,v??t.segmentParams),Rt(c,f),l&&f.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const p=c.find(({key:y})=>y===ht),m=p?p.value:u?.toString()??n.hideUnavailableItems.toString();f.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&f.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&f.append("showSponsored",n.showSponsored.toString()),g!==void 0&&f.append("sponsoredCount",g.toString()),h!==void 0&&f.append("allowRedirect",h.toString());const d=Tt(_t(c,t.extraFacets));return{params:f,path:d}}function Ft(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:a}=e,o=new URLSearchParams({field:t??"",value:r??""});return yn(o,n),i&&o.append("hideUnavailableItems","true"),a&&o.append("show-invisible-items","true"),o}function Y(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function J(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,a=Ut(t,r);switch(n){case"product-search":case"facets":{const{params:o,path:s}=Le(i,r,a,{includePagination:!0,includeSort:!0});return Y(s,o)}case"catalog-count":{const{params:o,path:s}=Le(i,r,a,{includePagination:!1,includeSort:!1});return Y(s,o)}case"products":{const o=Ft(i,a.segmentParams);return Y("",o)}case"search-suggestions":{const o=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??a.segmentParams.locale??""});return Y("",o)}case"top-searches":{const o=new URLSearchParams({locale:r?.locale??a.segmentParams.locale??""});return Y("",o)}default:{const o=n;throw new Error(`Unknown intelligent-search endpoint: ${o}`)}}}const Nt=10;function Lt(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function Bt(e){const t=Sn(e.headers?.cookie).cultureInfo||"";return ne(e)?e.storage.locale||t:t||e.storage.locale||""}const $t=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br`,c=fn(o),l=Sn(o.headers?.cookie),g=()=>({salesChannel:o.storage.channel.salesChannel,regionId:Lt(o),locale:Bt(o),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),u=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",h=a&&a.map(S=>S+".").find(S=>u.includes(S))||"",f=u.replace(h,""),v=c({"content-type":"application/json","X-FORWARDED-HOST":f}),d=({type:S,...D})=>{const P=S==="facets"?"facets":"product-search",k=J({endpoint:P,segment:l,defaults:g(),args:D});return I(`${s}/api/intelligent-search/v1/${P}/${k.path}?${k.params.toString()}`,{headers:v})},p=S=>d({...S,type:"product_search"}),m=({field:S,value:D,hideUnavailableItems:P,showInvisibleItems:k})=>{const C=J({endpoint:"products",segment:l,defaults:g(),args:{field:S,value:D,hideUnavailableItems:P,showInvisibleItems:k}});return I(`${s}/api/intelligent-search/v1/products?${C.params.toString()}`,{headers:v})};return{facets:S=>d({...S,type:"facets"}),products:p,fetchProduct:m,productsByIdentifier:async({field:S,values:D,showInvisibleItems:P,hideUnavailableItems:k})=>{const C=Te(Nt);return(await Promise.all(D.map(U=>C(async()=>{try{return await m({field:S,value:U,hideUnavailableItems:k,showInvisibleItems:P})}catch{return null}})))).filter(U=>U!==null)},suggestedTerms:S=>{const D=J({endpoint:"search-suggestions",segment:l,defaults:g(),args:{query:S.query}});return I(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:v})},topSearches:()=>{const S=J({endpoint:"top-searches",segment:l,defaults:g()});return I(`${s}/api/intelligent-search/v1/top-searches?${S.params.toString()}`,{headers:v})},productCount:S=>{const D=J({endpoint:"catalog-count",segment:l,defaults:g(),args:S});return I(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:v})}}},Mt=(e,n)=>{const t=$t(e,n),r=pt(e,n),i=et(e);return{search:t,commerce:r,catalog:i}},zt=20,qt=e=>e.entityType==="category",ve=e=>e.entityType==="brand",Be=e=>e.entityType==="collection",Vt=(e,n)=>{const t=Te(zt),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=a.slug.toLowerCase(),s=a.locale,c=await n.commerce.catalog.byLinkId.category(o,s);if(c)return{...c,entityType:"category",slug:o};const l=await n.commerce.catalog.byLinkId.brand(o,s);if(l)return{...l,entityType:"brand"};const g=await n.commerce.catalog.byLinkId.collection(o,s);if(g)return{...g,entityType:"collection"};throw new B(`No catalog entity found for slug: ${a.slug}. Cascade exhausted (category → brand → collection).`)})));return new ue(r,{batch:!1,cacheKeyFn:({slug:i,locale:a})=>`${i.toLowerCase()}::${a??""}`})},xt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new ue(t)},jt=1,Wt=(e,n)=>{const t=Te(jt),r=async a=>{const o=a.reduce((u,{items:h})=>[...u,h],[]),s=[...o.flat()],c=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),l=c.items.reduce((u,h)=>{const f=h.requestIndex;return typeof f=="number"&&f<u.length&&(u[f]=h),u},Array(s.length).fill(null)),g=o.reduce((u,h)=>[...u,h.length+u[u.length-1]],[0]);return o.map((u,h)=>({...c,items:l.slice(g[h],g[h+1]).filter(f=>!!f)}))},i=async a=>t(r,a);return new ue(i,{maxBatchSize:50})},Gt=(e,n)=>qn(e,n);function Ht(e){return{...e,description:e.description?Gt(e.description):e.description}}const N=(e,n)=>({...e,isVariantOf:Ht(n)}),Xt=({flags:e},n)=>{const t=async r=>{const i=r.map(g=>g.split("-")[0]),a=r.some(g=>g.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:a,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((g,u)=>{for(const h of u.items)g[h.itemId]=N(h,u);return g},{}),c=i.map(g=>s[g]),l=i.filter(g=>!s[g]);if(l.length>0)throw new B(`Search API did not found the following skus: ${l.join(",")}`);return c};return new ue(t,{maxBatchSize:99})},Yt=(e,n)=>{const{clients:t}=n,r=Xt(e,t),i=Wt(e,t),a=Vt(e,t),o=xt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:a,salesChannelLoader:o}},$=e=>e.AvailableQuantity>0,j=e=>e.spotPrice??0,Jt=e=>e.Price??0,$e=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",vn=(e,n)=>$(e)&&!$(n)?-1:!$(e)&&$(n)?1:j(e)-j(n),Kt=e=>e==="available",M=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},Qt=(e,n={includeTaxes:!1})=>{const t=e.filter($),r=t[t.length-1],i=r?j(r):0;return n.includeTaxes?M(i,r?.Tax,r?.product?.unitMultiplier):i},Me=(e,n={includeTaxes:!1})=>{const[t]=e.filter($),r=t?j(t):0;return n.includeTaxes?M(r,t?.Tax,t?.product?.unitMultiplier):r},Zt={highPrice:e=>Qt(e),lowPrice:e=>Me(e),lowPriceWithTaxes:e=>Me(e,{includeTaxes:!0}),offerCount:e=>e.length,priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:e=>e},er={ratingValue:()=>5,reviewCount:()=>0},ze="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",nr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",tr=e=>{let n=e.slice(0);for(let t=0;t<ze.length;t++)n=n.replace(new RegExp(ze.charAt(t),"g"),nr.charAt(t));return n},rr=e=>e.replace(/[·/_,:]/,"-");function se(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return rr(tr(t)).toLowerCase()}const K=e=>qt(e)?e.slug:ve(e)?e.linkId:e.linkId??se(e.name),On={id:({id:e})=>e.toString(),slug:e=>K(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>ve(e)?"Brand":Be(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=K(e);if(ve(e))return{selectedFacets:[{key:"brand",value:r}]};if(Be(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=ee(t),a=r.split("/").filter(Boolean),o=a.map((l,g)=>a.slice(0,g+1).join("/")),{loaders:{collectionLoader:s}}=t;return{selectedFacets:(await Promise.all(o.map(l=>s.load({slug:l,locale:ie(t)})))).map((l,g)=>({key:`category-${g+1}`,value:i&&l.availableLinkIds?.[i]||l.linkId}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,a=K(e).split("/").filter(Boolean),o=a.map((c,l)=>a.slice(0,l+1).join("/")),s=await Promise.all(o.map(c=>r.load({slug:c,locale:ie(t)})));return{itemListElement:s.map((c,l)=>({item:`/${K(c)}`,name:c.name,position:l+1})),numberOfItems:s.length}},otherLocales:async(e,n,t)=>{const r=ee(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const a=t.storage.locale,o=K(e),s=o.split("/").filter(Boolean);if(s.length===0)return null;const{loaders:{collectionLoader:c}}=t,l=s.map((u,h)=>s.slice(0,h+1).join("/"));let g;try{g=await Promise.all(l.map(u=>c.load({slug:u,locale:ie(t)})))}catch(u){return console.warn("[otherLocales] failed to load collection entities:",u),null}return i.map(u=>{if(u===a)return{locale:u,slug:o};const h=[];for(const f of g){const v=f.availableLinkIds?.[u];if(!v)return null;h.push(v)}return h.length>0?{locale:u,slug:h.join("/")}:null}).filter(u=>u!==null)}},bn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},qe=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},Ve=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},ir=e=>typeof bn[e]=="string",ar=e=>{const n=e?.filter(t=>ir(t.key));if(Array.isArray(n)&&n.length>1)throw new T(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},or=e=>e?.find(n=>n.key==="slug")?.value??null,sr=e=>e?.find(n=>n.key==="id")?.value??null,xe=e=>e?.find(n=>n.key==="locale")?.value??null,je=e=>e?.find(n=>n.key==="channel")?.value??null,Oe=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},cr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},lr={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},dr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Oe(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??o,absolute:o}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ve(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Oe(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},ur={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},pr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new T("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function Cn(e){if(!e||e.status!=="pending")return null;for(const n of e.dimensionStatus){if(n.status!=="pending")continue;const t=n.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:e.id,dimensionId:n.id}}return null}function gr(e){if(!e||e.status!=="pending")return!1;const n=e.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return n.length===0?!1:n.every(t=>!t.isUserNextAuthorizer)}const mr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=Cn(r);return{isPendingForOtherAuthorizer:!i&&gr(r),ruleForAuthorization:i}},hr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new T("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},fr=async(e,n,t)=>{if(!(await t.clients.commerce.recommendation.startRecommendationSession())?.recommendationsUserId)throw new Error("Failed to start recommendation session: no session data returned");return!0},Sr=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),yr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new T("Missing required fields: fileContent, fileName, mimeType");const o=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(o.length*3/4)>s)throw new T("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(o))throw new T("Invalid Base64 fileContent");const g=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:g,fileName:i,mimeType:a})};class ce{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}const be=(e,n)=>{e.storage.channel=ce.parse(n)},Ce=(e,n)=>{e.storage.locale=n},wn=e=>Vn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function Dn(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function Ir(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function Pn(e){return wn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const vr=e=>{const n=e.postalCode,t=e.geoCoordinates,r={addressType:e.addressType||null,postalCode:n||null,city:null,state:null,country:e.country||null,street:null,number:null,neighborhood:null,complement:null,reference:null,geoCoordinates:[]};if(t){const i=typeof t=="object"&&"latitude"in t?t.latitude:null,a=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&a!==null?[a,i]:[]}return[r]},Or=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,a=e?.shippingData?.availableAddresses??[],o=e?.shippingData?.selectedAddresses??[];if(!t&&o.length>0)return[o[0]];if(t&&a.length>0)for(const s of a){if(r&&i&&(s.postalCode===r||s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude))return[s];if(r&&!i&&s.postalCode===r)return[s];if(i&&!r&&s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude)return[s]}return null},An=(e,n)=>{if(!br(n))return{updateShipping:!1,addressChanged:!1};if(!Pr(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(Cr(t,n.postalCode)||wr(t,n.geoCoordinates)||Dr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Ar(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},br=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,Cr=(e,n)=>typeof n=="string"&&e?.postalCode!==n,wr=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Dr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Pr=e=>e.items.length!==0,Ar=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const l=t&&o!==t,g=r&&s!==r;return c?.some(u=>l&&u.deliveryChannel===t||g&&u.id===r?!0:i&&a&&u.deliveryChannel===t&&u.id===r&&(!u?.deliveryWindow||u?.deliveryWindow?.startDateUtc!==i||u?.deliveryWindow?.endDateUtc!==a)&&u.availableDeliveryWindows?.some(h=>h?.startDateUtc===i&&h?.endDateUtc===a))})},Tn=e=>e.valueReference===re.attachment,we=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Tn).map(Pn).join("-")].filter(Boolean).join("::"),le=(e,n)=>({listPrice:e.listPrice/100,price:e.sellingPrice/100,quantity:e.quantity,seller:{identifier:e.seller},itemOffered:{sku:e.id,image:[],name:e.name,additionalProperty:e.attachments.map(Dn)},index:n}),Tr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Tn)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),We=e=>e.reduce((n,t)=>{const r=we(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),kr=(e,n)=>{const t=({priceToken:s,...c},l)=>({...c,itemOffered:{sku:c.itemOffered.sku},index:l}),r=n.items.map(le).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=ke(r,i);return a&&o};function kn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function En(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const Ge=e=>{const n=e.items.reduce((t,r,i)=>{const a=En(e.items,r.id)||kn(e.items,r.id)?`${we(le(r))}::${i}`:we(le(r));return t[a]||(t[a]=[]),t[a].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((o,s)=>o+s.quantity,0),a=t.reduce((o,s)=>o+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:a/i}})}},He=async(e,n,t)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async r=>({...r,product:await n.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:e.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),Un=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return wn(JSON.stringify({sessionId:n?.id??"",items:t}))},Xe=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:Un(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const nn=require("@graphql-tools/merge"),tn=require("@graphql-tools/schema"),z=require("@graphql-tools/utils"),ae=require("graphql"),B=require("@faststore/diagnostics"),qn=require("isomorphic-unfetch"),te=require("cookie"),Ae=require("p-limit"),ue=require("dataloader"),Vn=require("sanitize-html"),Pe=require("fast-deep-equal"),xn=require("node:crypto");var rn=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(rn||{}),on=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(on||{}),an=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(an||{}),sn=(e=>(e.DiscountDesc="discount_desc",e.NameAsc="name_asc",e.NameDesc="name_desc",e.OrdersDesc="orders_desc",e.PriceAsc="price_asc",e.PriceDesc="price_desc",e.ReleaseDesc="release_desc",e.ScoreDesc="score_desc",e))(sn||{}),cn=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(cn||{}),ln=(e=>(e.Input="Input",e.Output="Output",e))(ln||{});const jn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new x("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Wn=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new Q("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new Q("Authentication required"):r===403?new x("You are not allowed to access this resource"):new Q("Authentication required")}},Gn="auth",dn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{if(z.getDirective(e,n,Gn)?.[0]){const r=n.resolve;n.resolve=async(i,o,a,s)=>(await Wn(a),r?.(i,o,a,s))}return n}})},Hn="cacheControl",Xn=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},Te=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,Yn=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,un={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>z.mapSchema(e,{[z.MapperKind.OBJECT_FIELD]:n=>{const t=z.getDirective(e,n,Hn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:o}=t,a=n.resolve;n.resolve=(s,c,l,g)=>(l.cacheControl={sMaxAge:Te(l.cacheControl?.sMaxAge,r),staleWhileRevalidate:Te(l.cacheControl?.staleWhileRevalidate,i),scope:Yn(l.cacheControl?.scope,o)},a?.(s,c,l,g))}return n}})},pn=e=>(n,t)=>{const r=nn.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:o})=>o?.(i)??i,tn.makeExecutableSchema({typeDefs:r,resolvers:n}))},gn="@faststore/api",mn="4.6.0-dev.0",ke={name:gn,version:mn},Jn=B.logger("@faststore/api"),Kn=(e,n="Unknown Graphql Resolver")=>(t,r,i,o)=>{if(!i?.OTEL_ENABLED)return e(t,r,i,o);const a=B.OTELAPI.trace.getTracer("Graphql").startSpan(n,{kind:B.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":mn,"@faststore_package_name":gn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV,"@faststore_resolver_parent_type":o?.parentType?.name,"@faststore_resolver_field_name":o?.fieldName}}),s=B.OTELAPI.trace.setSpan(B.OTELAPI.context.active(),a);try{const c=B.OTELAPI.context.with(s,()=>e(t,r,i,o));return c instanceof Promise?c.then(l=>(a.end(),l),l=>Ue(l,a,n)):(a.end(),c)}catch(c){return Ue(c,a,n)}};function Ue(e,n,t){throw n.setStatus({code:B.OTELAPI.SpanStatusCode.ERROR}),n.recordException(e),n.end(),console.error(`Error at resolver: ${t}:
|
|
2
|
+
%o`,e),Jn("error",`Error at resolver: %s
|
|
3
|
+
%o`,t,e),e}class W extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class E extends W{constructor(n){super({status:400,type:"BadRequestError"},n)}}class Q extends W{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class x extends W{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class L extends W{constructor(n){super({status:404,type:"NotFoundError"},n)}}const Qn=e=>e?.name==="FastStoreError",Zn=e=>e?.extensions?.type==="BadRequestError",et=e=>e?.extensions?.type==="UnauthorizedError",hn=e=>e?.extensions?.type==="ForbiddenError",q=e=>e?.extensions?.type==="NotFoundError",nt=`${ke.name}@${ke.version}`,I=async(e,n,t)=>{const r=await qn(e,{...n,headers:{...n?.headers??{},"User-Agent":nt}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(e,n,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new E(i);case 401:throw new Q(i);case 403:throw new x(i);case 404:throw new L(i);default:throw new W({status:r.status,type:"UnknownError"},i)}throw new Error(i)},tt=({account:e,environment:n})=>{const t=`https://${e}.${n}.com.br`;return{getLocalizedProduct:(r,i)=>I(`${t}/api/catalog-dataplane/product/${r}`,{method:"GET",headers:{"Accept-Language":i,"Content-Type":"application/json"}})}},fn=e=>{if(!e)return e;const n=new Map,t=e.split(";"),r=[];return t.forEach(i=>{const o=i.trim();if(o){const a=o.indexOf("=");if(a>0){const s=o.substring(0,a),c=o.substring(a+1);n.has(s)||r.push(s),n.set(s,c)}}}),r.map(i=>`${i}=${n.get(i)}`).join("; ")},rt=/^([^=]+)=([^;]*)/,it=(e,n)=>{const t=n.match(rt);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},ot=(e,n)=>{n.getSetCookie().forEach(t=>it(e,t))},at=e=>n=>ot(e,n),me=e=>{if(!e.headers?.cookie)return null;const n=fn(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:o}])=>st(r,i,o),n)},Sn=e=>function(t){const r=me(e);return r?{...t,cookie:r}:t},V=(e,n)=>{const t=fn(e);return te.parse(t)[`VtexIdclientAutCookie_${n}`]||""},st=(e,n,t)=>{const r=new RegExp(`(${n})=([^;]*)`),i=e.match(r);return i?e.replace(i[0],`${i[1]}=${t}`):`${e};${n}=${t}`};function Z(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const ct="storefront/faststore.recommendation-shelf@v4",X={method:"POST",headers:{"content-type":"application/json"}},lt=e=>e.split("/").map(encodeURIComponent).join("/"),ge=e=>e?{headers:{"Accept-Language":e}}:void 0,dt=/^\d{4}-\d{2}-\d{2}$/,ut=new Set(["Draft","Requested","InReview","Reviewed","Approved","Declined","Expired","ConvertedToCart","ConvertedToOrder"]);function pt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a}){if(e!==void 0&&(!Number.isInteger(e)||e<1))throw new Error(`listUserQuotes: invalid page "${e}" — must be a positive integer`);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error(`listUserQuotes: invalid perPage "${n}" — must be a positive integer`);for(const[s,c]of[["createdAtFrom",r],["createdAtTo",i],["expiresAtFrom",o],["expiresAtTo",a]])if(c&&!dt.test(c))throw new Error(`listUserQuotes: invalid ${s} "${c}" — must be YYYY-MM-DD`);if(t&&t.length>0){const s=t.filter(c=>!ut.has(c));if(s.length>0)throw new Error(`listUserQuotes: invalid status values: ${s.join(", ")}`)}}function gt({page:e,perPage:n,status:t,createdAtFrom:r,createdAtTo:i,expiresAtFrom:o,expiresAtTo:a,label:s}){const c=new URLSearchParams;return e&&c.append("pageNumber",e.toString()),n&&c.append("pageSize",n.toString()),t?.forEach(l=>c.append("status",l)),r&&c.append("createdAtFrom",r),i&&c.append("createdAtTo",i),o&&c.append("expiresAtFrom",o),a&&c.append("expiresAtTo",a),s?.trim()&&c.append("label",s.trim()),c}const mt=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const o=`https://${e}.${n}.com.br`,a=at(i),s=Sn(i),c=jn(),l=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",g=r&&r.map(d=>d+".").find(d=>l.includes(d))||"",u=l.replace(g,""),h=`${o}/api/recommend-bff/v2`,f=s({accept:"application/json","content-type":"application/json","x-vtex-rec-origin":`${e}/${ct}`}),v=(d={})=>{const p=V(me(i)??"",e);return s({...d,"X-FORWARDED-HOST":u,...p?{[`VtexIdclientAutCookie_${e}`]:p}:{}})};return{catalog:{salesChannel:d=>I(`${o}/api/catalog_system/pub/saleschannel/${d}`,void 0,{storeCookies:a}),brand:{list:()=>I(`${o}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:a})},category:{tree:(d=3)=>I(`${o}/api/catalog_system/pub/category/tree/${d}`,void 0,{storeCookies:a})},portal:{pagetype:d=>I(`${o}/api/catalog_system/pub/portal/pagetype/${d}`,void 0,{storeCookies:a})},byLinkId:{category:async(d,p)=>{try{return await I(`${o}/api/catalog_system/pub/category/by-linkid/${lt(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}},brand:async(d,p)=>{try{return await I(`${o}/api/catalog_system/pub/brand/by-linkid/${encodeURIComponent(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}},collection:async(d,p)=>{try{return await I(`${o}/api/catalog_system/pub/collection/by-linkid/${encodeURIComponent(d)}`,ge(p))}catch(m){if(q(m))return null;throw m}}},products:{crossselling:({type:d,productId:p,groupByProduct:m=!0})=>{const y=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:m.toString()});return I(`${o}/api/catalog_system/pub/products/crossselling/${d}/${p}?${y}`,void 0,{storeCookies:a})}}},checkout:{simulation:(d,{salesChannel:p}=i.storage.channel)=>{const m=new URLSearchParams({sc:p}),y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForms/simulation?${m.toString()}`,{...X,headers:y,body:JSON.stringify(d)},{storeCookies:a})},shippingData:({id:d,index:p,deliveryMode:m,selectedAddresses:y},O)=>{const w=O?{startDateUtc:m?.deliveryWindow?.startDate,endDateUtc:m?.deliveryWindow?.endDate}:null,C={logisticsInfo:Array.from({length:p},(S,D)=>({itemIndex:D,selectedDeliveryChannel:m?.deliveryChannel||null,selectedSla:m?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:y,clearAddressIfPostalCodeNotFound:t},P=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/shippingData`,{...X,headers:P,body:JSON.stringify(C)},{storeCookies:a})},marketingData:({id:d,marketingData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/marketingData`,{headers:m,body:JSON.stringify(p),method:"POST"},{storeCookies:a})},clientPreferencesData:({id:d,clientPreferencesData:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/attachments/clientPreferencesData`,{headers:m,body:JSON.stringify(p),method:"POST"},{storeCookies:a})},orderForm:({id:d,refreshOutdatedData:p=!0,channel:m=i.storage.channel})=>{const{salesChannel:y}=m,O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),w=new URLSearchParams({sc:y});d&&w.set("refreshOutdatedData",p.toString());const C=`${o}/api/checkout/pub/orderForm${d?`/${d}`:""}?${w.toString()}`;return I(C,{...X,headers:O,...d?{}:{body:"{}"}},{storeCookies:a})},clearOrderFormMessages:({id:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/messages/clear`,{...X,headers:p,body:"{}"})},updateOrderFormItems:({id:d,orderItems:p,allowOutdatedData:m="paymentData",salesChannel:y=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const w=new URLSearchParams({allowOutdatedData:m,sc:y}),C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/items?${w}`,{headers:C,body:JSON.stringify({orderItems:p,noSplitItem:!O}),method:"PATCH"},{storeCookies:a})},setCustomData:({id:d,appId:p,key:m,value:y})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}/customData/${p}/${m}`,{headers:O,body:JSON.stringify({value:y}),method:"PUT"})},region:async({postalCode:d,geoCoordinates:p,country:m,salesChannel:y})=>{const O=new URLSearchParams({country:m,sc:y??""});d?O.append("postalCode",d):O.append("geoCoordinates",`${p?.longitude};${p?.latitude}`);const w=`${o}/api/checkout/pub/regions/?${O.toString()}`,C=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(w,{headers:C},{storeCookies:a})},address:async({postalCode:d,country:p})=>{const m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/postal-code/${p}/${d}`,{headers:m},{storeCookies:a})},cancelOrder:({orderId:d,customerEmail:p,reason:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orders/${d}/user-cancel-request`,{method:"POST",headers:y,body:JSON.stringify({customerEmail:p,reason:m})},{})},pickupPoints:({geoCoordinates:d})=>{if(!d)throw new Error("Missing required parameter for listing pickup points.");const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:p,body:JSON.stringify({coordinate:d})},{storeCookies:a})}},session:d=>{const p=new URLSearchParams(d);p.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,shopper.availableContracts,shopper.activeContractId,store.channel,store.countryCode,store.cultureInfo,store.currencyCode,store.currencySymbol,authentication.customerId,authentication.storeUserId,authentication.storeUserEmail,authentication.unitId,authentication.unitName,checkout.regionId,public.postalCode");const m=s({"content-type":"application/json"}),y=te.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${o}/api/sessions?${p.toString()}`,{method:y?"PATCH":"POST",headers:m,body:"{}"},{storeCookies:a})},subscribeToNewsletter:d=>I(`${o}/api/dataentities/NL/documents/`,{...X,body:JSON.stringify({...d,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:a}),profile:{addresses:async d=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/profile-system/pvt/profiles/${d}/addresses`,{headers:p},{storeCookies:a})}},oms:{userOrder:({orderId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/oms/user/orders/${d}`,{method:"GET",headers:p},{storeCookies:a})},listUserOrders:({page:d,status:p,dateInitial:m,dateFinal:y,text:O,clientEmail:w,perPage:C,pendingMyApproval:P})=>{const S=new URLSearchParams;if(m){const A=new Date(m).setHours(0,0,0,0);m=new Date(A).toISOString()}if(y){const A=new Date(y).setHours(23,59,59,999);y=new Date(A).toISOString()}O&&S.append("text",O),p&&p.length>0&&S.append("status",p.filter(Boolean).join(",")),m&&y?S.append("creation_date",`creationDate:[${m} TO ${y}]`):m?S.append("creation_date",`creationDate:[${m} TO *]`):y&&S.append("creation_date",`creationDate:[* TO ${y}]`),w&&S.append("clientEmail",w),d&&S.append("page",d.toString()),C&&S.append("per_page",C.toString()),P&&S.append("my_pending_approvals",String(!0));const D=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/oms/user/orders?${S.toString()}`,{method:"GET",headers:D},{storeCookies:a})},getCommercialAuthorizationsByOrderId:({orderId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/${e}/commercial-authorizations/order/${d}`,{method:"GET",headers:p},{storeCookies:a})},processOrderAuthorization:async({orderAuthorizationId:d,dimensionId:p,ruleId:m,approved:y})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),P={params:{ruleId:m,dimensionId:p,score:y?100:0}};return I(`${o}/${e}/commercial-authorizations/${d}/callback`,{method:"POST",headers:O,body:JSON.stringify(P)},{storeCookies:a})}},units:{getUnitByUserId:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}/unit`,{method:"GET",headers:p},{})},getOrgUnitById:({orgUnitId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}`,{method:"GET",headers:p},{})},getScopesByOrgUnit:({orgUnitId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/units/v1/${d}/scopes`,{method:"GET",headers:p},{})}},licenseManager:{getUserById:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/users/${d}`,{method:"GET",headers:p},{})},getUserByEmail:({email:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/pvt/users/${d}`,{method:"GET",headers:p},{})},getUserRoles:({userId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/license-manager/storefront/users/${d}/roles`,{method:"GET",headers:p},{})}},masterData:{getContractById:({contractId:d})=>{if(!d)throw new E("Missing contractId to fetch CL fields.");const p=v({Accept:"application/json","content-type":"application/json"});return I(`${o}/api/dataentities/CL/documents/${d}?_fields=_all`,{method:"GET",headers:p},{})},getShopperById:({userId:d})=>{if(!d)throw new E("Missing userId to fetch shopper name.");const p=c({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),m=d.replace(/-/g,"");return I(`${o}/api/dataentities/shopper/search?_where=(userId=${m} OR userId=${d})&_fields=_all&_schema=v1`,{method:"GET",headers:p},{})}},quotes:{listUserQuotes:d=>{pt(d);const p=gt(d),m=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/quoting/quotes?${p.toString()}`,{method:"GET",headers:m},{storeCookies:a})}},vtexid:{validate:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u}),p=V(me(i)??"",e);return I(`${o}/api/vtexid/credential/validate`,{headers:d,body:JSON.stringify({token:p}),method:"POST"},{storeCookies:a})}},orderEntry:{uploadFile:({fileBuffer:d,fileName:p,mimeType:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),O=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
|
|
4
|
+
`,P=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(m)?m:"application/octet-stream",S=p.replaceAll(/[\r\n"]/g,"_"),D=[`--${O}`,`Content-Disposition: form-data; name="file"; filename="${S}"`,`Content-Type: ${P}`,"",""].join(w),A=`${w}--${O}--${w}`,T=Buffer.from(D),b=Buffer.from(A),k=new Uint8Array(T.byteLength+d.byteLength+b.byteLength);let U=0;return k.set(T,U),U+=T.byteLength,k.set(d,U),U+=d.byteLength,k.set(b,U),I(`${o}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...y,"content-type":`multipart/form-data; boundary=${O}`},body:k.buffer},{})},startOperation:({objectKey:d,orderFormId:p,sessionToken:m})=>{const y=s({"content-type":"application/json","X-FORWARDED-HOST":u}),O=JSON.stringify({objectKey:d,orderFormId:p,operation:"CreateCart",...m?{sessionToken:m}:{}});return I(`${o}/api/order-entry/operation?an=${e}`,{method:"POST",headers:y,body:O},{})},getOperation:({operationId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/order-entry/operation/${d}?an=${e}`,{method:"GET",headers:p},{})},createOrderForm:()=>{const d=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:d,body:"{}"},{})},getOrderFormItems:({orderFormId:d})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${o}/api/checkout/pub/orderForm/${d}`,{method:"GET",headers:p},{})}},recommendation:{recommendations:({campaignVrn:d,userId:p,products:m=[],salesChannel:y,locale:O})=>{const w=new URLSearchParams({an:e,campaignVrn:d});return p&&w.append("userId",p),m.length>0&&w.append("products",m.join(",")),y&&w.append("salesChannel",y),O&&w.append("locale",O),I(`${h}/recommendations?${w.toString()}`,{headers:f},{storeCookies:a})},startRecommendationSession:()=>{const d=new URLSearchParams({an:e});return I(`${h}/users/start-session?${d.toString()}`,{method:"POST",headers:f},{storeCookies:a})}}}},ee=e=>e.discoveryConfig?.localization??{},ne=e=>ee(e).enabled===!0,ht=e=>Object.keys(ee(e).locales??{}),ft=e=>ee(e).defaultLocale,ie=e=>ne(e)&&e.storage.locale||void 0,he="fuzzy",fe="operator",Se="pickupPoint",_e="shipping",Re="delivery-options",St="in-stock",yt="trade-policy",It="region-id",vt=new Set([yt,It,he,fe,Se]),Ot=new Set(["zip-code","pickupPoint","country","coordinates","deliveryZonesHash","pickupPointsHash"]),Fe=e=>encodeURI(decodeURI(e)),Ct=e=>encodeURIComponent(decodeURIComponent(e).normalize("NFD").replaceAll(/[\u0300-\u036f]/g,"")),bt=/^pickup-in-point-(.+)$/;function yn(e){if(!e)return{};try{const t=te.parse(e).vtex_segment;if(!t)return{};const r=Buffer.from(t,"base64").toString("utf-8");return JSON.parse(r)}catch{return{}}}function wt(e){const n={},t=[];for(const r of e.split(";")){const i=r.indexOf("=");if(i<0)continue;const o=r.slice(0,i),a=r.slice(i+1);!o||!a||(Ot.has(o)?n[o]=a:t.push({key:o,value:a}))}return{shipping:n,extraFacets:t}}function Dt(e){const n=typeof e.facets=="string"?e.facets:"",{shipping:t,extraFacets:r}=wt(n);return{segmentParams:{sc:e.channel,regionId:e.regionId,country:e.countryCode??t.country,locale:e.cultureInfo,"zip-code":t["zip-code"],coordinates:t.coordinates,pickupPoint:t.pickupPoint,deliveryZonesHash:t.deliveryZonesHash,pickupPointHash:t.pickupPointsHash,utmSource:e.utm_source??void 0,utmCampaign:e.utm_campaign??void 0,utmiCampaign:e.utmi_campaign??void 0,campaigns:typeof e.campaigns=="string"?e.campaigns:void 0,priceTables:e.priceTables??void 0},extraFacets:r}}function In(e,n){const t=[["sc",n.sc],["regionId",n.regionId],["country",n.country],["locale",n.locale],["zip-code",n["zip-code"]],["coordinates",n.coordinates],["pickupPoint",n.pickupPoint],["deliveryZonesHash",n.deliveryZonesHash],["pickupPointHash",n.pickupPointHash],["utmSource",n.utmSource],["utmCampaign",n.utmCampaign],["utmiCampaign",n.utmiCampaign],["campaigns",n.campaigns],["priceTables",n.priceTables]];for(const[r,i]of t)i!=null&&i!==""&&e.append(r,String(i))}function vn(e){return bt.exec(e)?.[1]}function At(e){const n=e.find(r=>r.key==="shipping"),t=n?vn(n.value):void 0;if(t!==void 0)try{return decodeURIComponent(t)}catch{return t}}function Pt(e,n){const t=At(n);return t===void 0?e:{...e,pickupPoint:t}}function Et(e){return e.map(n=>n.key!=="shipping"||vn(n.value)===void 0?n:{...n,value:"pickup-in-point"})}function Tt(e,n){let t=[...e];const r=t.some(i=>i.key==="shipping");for(const i of n)(!r||i.key!=="shipping")&&t.push(i);return t.some(i=>i.key==="shipping"&&i.value==="ignore")&&(t=t.filter(i=>i.key!=="shipping")),Et(t)}function kt(e){return e.reduce((n,t)=>{let{key:r,value:i}=t;return r==="priceRange"&&(r="price",i=i.replace(" TO ",":")),r==="ft"?n:`${n}${Fe(r)}/${Ct(Fe(i)).replaceAll(/ |%20/g,"-")}/`},"")}const Ut=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),_t=e=>e.key==="operator"&&(e.value==="and"||e.value==="or");function Rt(e,n){const{segmentParams:t,extraFacets:r}=Dt(e??{}),i=n?.salesChannel??t.sc,o=n?.regionId??t.regionId,a=n?.locale??t.locale??"";return{segmentParams:{...t,...i?{sc:i}:{},...o?{regionId:o}:{},locale:a},extraFacets:r}}function Ft(e,n){const t=e.filter(({key:c})=>!vt.has(c)),r=e.find(({key:c,value:l})=>c===_e&&l!=="all-delivery-methods")??null,i=e.find(({key:c,value:l})=>c===Re&&l!=="all-delivery-options")??null,o=[...t],a=o.some(({key:c})=>c===_e),s=o.some(({key:c})=>c===Re);return r!==null&&!a&&o.push(r),i!==null&&!s&&o.push(i),Tt(o,n)}function Nt(e,n){const t=e.find(({key:o})=>o===he)??null,r=e.find(({key:o})=>o===fe)??null,i=e.find(({key:o})=>o===Se)??null;t&&Ut(t)&&n.append(he,t.value),r&&_t(r)&&n.append(fe,r.value),i&&n.append(Se,i.value)}function Ne(e,n,t,r){const{query:i="",page:o,count:a,sort:s,selectedFacets:c=[],showInvisibleItems:l,sponsoredCount:g,hideUnavailableItems:u,allowRedirect:h=!1}=e,f=new URLSearchParams;if(r.includePagination&&o!==void 0&&a!==void 0){const p=o*a,m=a===0?p:p+a-1;f.append("from",p.toString()),f.append("to",m.toString())}i&&f.append("query",i),r.includeSort&&s&&f.append("sort",s);const v=Pt(t.segmentParams,c);if(In(f,v??t.segmentParams),Nt(c,f),l&&f.append("show-invisible-items","true"),n?.hideUnavailableItems!==void 0){const p=c.find(({key:y})=>y===St),m=p?p.value:u?.toString()??n.hideUnavailableItems.toString();f.append("hideUnavailableItems",m)}n?.simulationBehavior!==void 0&&f.append("simulationBehavior",n.simulationBehavior.toString()),n?.showSponsored!==void 0&&f.append("showSponsored",n.showSponsored.toString()),g!==void 0&&f.append("sponsoredCount",g.toString()),h!==void 0&&f.append("allowRedirect",h.toString());const d=kt(Ft(c,t.extraFacets));return{params:f,path:d}}function Lt(e,n){const{field:t,value:r,hideUnavailableItems:i,showInvisibleItems:o}=e,a=new URLSearchParams({field:t??"",value:r??""});return In(a,n),i&&a.append("hideUnavailableItems","true"),o&&a.append("show-invisible-items","true"),a}function Y(e,n){return{path:e,params:n,toString(){const t=n.toString();return e?t?`${e}?${t}`:e:t?`?${t}`:""}}}function J(e){const{endpoint:n,segment:t,defaults:r,args:i={}}=e,o=Rt(t,r);switch(n){case"product-search":case"facets":{const{params:a,path:s}=Ne(i,r,o,{includePagination:!0,includeSort:!0});return Y(s,a)}case"catalog-count":{const{params:a,path:s}=Ne(i,r,o,{includePagination:!1,includeSort:!1});return Y(s,a)}case"products":{const a=Lt(i,o.segmentParams);return Y("",a)}case"search-suggestions":{const a=new URLSearchParams({query:i.query?.toString()??"",locale:r?.locale??o.segmentParams.locale??""});return Y("",a)}case"top-searches":{const a=new URLSearchParams({locale:r?.locale??o.segmentParams.locale??""});return Y("",a)}default:{const a=n;throw new Error(`Unknown intelligent-search endpoint: ${a}`)}}}const Bt=10;function $t(e){const{regionId:n,seller:t}=e.storage.channel;return(t?Buffer.from(`SW#${t}`).toString("base64"):void 0)??(n||void 0)}function Mt(e){const t=yn(e.headers?.cookie).cultureInfo||"";return ne(e)?e.storage.locale||t:t||e.storage.locale||""}const zt=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:o},a)=>{const s=`https://${e}.${n}.com.br`,c=Sn(a),l=yn(a.headers?.cookie),g=()=>({salesChannel:a.storage.channel.salesChannel,regionId:$t(a),locale:Mt(a),hideUnavailableItems:t,simulationBehavior:r,showSponsored:i}),u=new Headers(a.headers).get("x-forwarded-host")??a.headers?.host??"",h=o&&o.map(S=>S+".").find(S=>u.includes(S))||"",f=u.replace(h,""),v=c({"content-type":"application/json","X-FORWARDED-HOST":f}),d=({type:S,...D})=>{const A=S==="facets"?"facets":"product-search",T=J({endpoint:A,segment:l,defaults:g(),args:D});return I(`${s}/api/intelligent-search/v1/${A}/${T.path}?${T.params.toString()}`,{headers:v})},p=S=>d({...S,type:"product_search"}),m=({field:S,value:D,hideUnavailableItems:A,showInvisibleItems:T})=>{const b=J({endpoint:"products",segment:l,defaults:g(),args:{field:S,value:D,hideUnavailableItems:A,showInvisibleItems:T}});return I(`${s}/api/intelligent-search/v1/products?${b.params.toString()}`,{headers:v})};return{facets:S=>d({...S,type:"facets"}),products:p,fetchProduct:m,productsByIdentifier:async({field:S,values:D,showInvisibleItems:A,hideUnavailableItems:T})=>{const b=Ae(Bt);return(await Promise.all(D.map(U=>b(async()=>{try{return await m({field:S,value:U,hideUnavailableItems:T,showInvisibleItems:A})}catch{return null}})))).filter(U=>U!==null)},suggestedTerms:S=>{const D=J({endpoint:"search-suggestions",segment:l,defaults:g(),args:{query:S.query}});return I(`${s}/api/intelligent-search/v1/search-suggestions?${D.params.toString()}`,{headers:v})},topSearches:()=>{const S=J({endpoint:"top-searches",segment:l,defaults:g()});return I(`${s}/api/intelligent-search/v1/top-searches?${S.params.toString()}`,{headers:v})},productCount:S=>{const D=J({endpoint:"catalog-count",segment:l,defaults:g(),args:S});return I(`${s}/api/intelligent-search/v1/catalog-count/${D.path}?${D.params.toString()}`,{headers:v})}}},qt=(e,n)=>{const t=zt(e,n),r=mt(e,n),i=tt(e);return{search:t,commerce:r,catalog:i}},Vt=20,xt=e=>e.entityType==="category",ye=e=>e.entityType==="brand",Le=e=>e.entityType==="collection",jt=(e,n)=>{const t=Ae(Vt),r=async i=>Promise.all(i.map(o=>t(async()=>{const a=o.slug.toLowerCase(),s=o.locale,c=await n.commerce.catalog.byLinkId.category(a,s);if(c)return{...c,entityType:"category",slug:a};const l=await n.commerce.catalog.byLinkId.brand(a,s);if(l)return{...l,entityType:"brand"};const g=await n.commerce.catalog.byLinkId.collection(a,s);if(g)return{...g,entityType:"collection"};throw new L(`No catalog entity found for slug: ${o.slug}. Cascade exhausted (category → brand → collection).`)})));return new ue(r,{batch:!1,cacheKeyFn:({slug:i,locale:o})=>`${i.toLowerCase()}::${o??""}`})},Wt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new ue(t)},Gt=1,Ht=(e,n)=>{const t=Ae(Gt),r=async o=>{const a=o.reduce((u,{items:h})=>[...u,h],[]),s=[...a.flat()],c=await n.commerce.checkout.simulation({country:o[0].country,postalCode:o[0].postalCode,items:s}),l=c.items.reduce((u,h)=>{const f=h.requestIndex;return typeof f=="number"&&f<u.length&&(u[f]=h),u},Array(s.length).fill(null)),g=a.reduce((u,h)=>[...u,h.length+u[u.length-1]],[0]);return a.map((u,h)=>({...c,items:l.slice(g[h],g[h+1]).filter(f=>!!f)}))},i=async o=>t(r,o);return new ue(i,{maxBatchSize:50})},Xt=(e,n)=>Vn(e,n);function Yt(e){return{...e,description:e.description?Xt(e.description):e.description}}const N=(e,n)=>({...e,isVariantOf:Yt(n)}),Jt=({flags:e},n)=>{const t=async r=>{const i=r.map(g=>g.split("-")[0]),o=r.some(g=>g.split("-")[1]==="invisibleItems"),s=(await n.search.productsByIdentifier({field:"sku",values:i,showInvisibleItems:o,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}})).reduce((g,u)=>{for(const h of u.items)g[h.itemId]=N(h,u);return g},{}),c=i.map(g=>s[g]),l=i.filter(g=>!s[g]);if(l.length>0)throw new L(`Search API did not found the following skus: ${l.join(",")}`);return c};return new ue(t,{maxBatchSize:99})},Kt=(e,n)=>{const{clients:t}=n,r=Jt(e,t),i=Ht(e,t),o=jt(e,t),a=Wt(e,t);return{skuLoader:r,simulationLoader:i,collectionLoader:o,salesChannelLoader:a}},$=e=>e.AvailableQuantity>0,j=e=>e.spotPrice??0,Qt=e=>e.Price??0,Be=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",On=(e,n)=>$(e)&&!$(n)?-1:!$(e)&&$(n)?1:j(e)-j(n),Zt=e=>e==="available",M=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},er=(e,n={includeTaxes:!1})=>{const t=e.filter($),r=t[t.length-1],i=r?j(r):0;return n.includeTaxes?M(i,r?.Tax,r?.product?.unitMultiplier):i},$e=(e,n={includeTaxes:!1})=>{const[t]=e.filter($),r=t?j(t):0;return n.includeTaxes?M(r,t?.Tax,t?.product?.unitMultiplier):r},nr={highPrice:e=>er(e),lowPrice:e=>$e(e),lowPriceWithTaxes:e=>$e(e,{includeTaxes:!0}),offerCount:e=>e.length,priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:e=>e},tr={ratingValue:()=>5,reviewCount:()=>0},Me="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",rr="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",ir=e=>{let n=e.slice(0);for(let t=0;t<Me.length;t++)n=n.replace(new RegExp(Me.charAt(t),"g"),rr.charAt(t));return n},or=e=>e.replace(/[·/_,:]/,"-");function se(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return or(ir(t)).toLowerCase()}const K=e=>xt(e)?e.slug:ye(e)?e.linkId:e.linkId??se(e.name),Cn={id:({id:e})=>e.toString(),slug:e=>K(e),seo:e=>({title:e.title??e.name,description:e.metaTagDescription??e.description}),type:e=>ye(e)?"Brand":Le(e)?"Collection":e.fatherCategoryId===null?"Department":"Category",meta:async(e,n,t)=>{const r=K(e);if(ye(e))return{selectedFacets:[{key:"brand",value:r}]};if(Le(e))return{selectedFacets:[{key:"productclusterids",value:e.id}]};const{defaultLocale:i}=ee(t),o=r.split("/").filter(Boolean),a=o.map((l,g)=>o.slice(0,g+1).join("/")),{loaders:{collectionLoader:s}}=t;return{selectedFacets:(await Promise.all(a.map(l=>s.load({slug:l,locale:ie(t)})))).map((l,g)=>({key:`category-${g+1}`,value:i&&l.availableLinkIds?.[i]||l.linkId}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,o=K(e).split("/").filter(Boolean),a=o.map((c,l)=>o.slice(0,l+1).join("/")),s=await Promise.all(a.map(c=>r.load({slug:c,locale:ie(t)})));return{itemListElement:s.map((c,l)=>({item:`/${K(c)}`,name:c.name,position:l+1})),numberOfItems:s.length}},otherLocales:async(e,n,t)=>{const r=ee(t);if(!r.enabled)return null;const i=Object.keys(r.locales??{});if(i.length===0)return null;const o=t.storage.locale,a=K(e),s=a.split("/").filter(Boolean);if(s.length===0)return null;const{loaders:{collectionLoader:c}}=t,l=s.map((u,h)=>s.slice(0,h+1).join("/"));let g;try{g=await Promise.all(l.map(u=>c.load({slug:u,locale:ie(t)})))}catch(u){return console.warn("[otherLocales] failed to load collection entities:",u),null}return i.map(u=>{if(u===o)return{locale:u,slug:a};const h=[];for(const f of g){const v=f.availableLinkIds?.[u];if(!v)return null;h.push(v)}return h.length>0?{locale:u,slug:h.join("/")}:null}).filter(u=>u!==null)}},bn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},ze=({key:e,value:n})=>{switch(e){case"price":return{key:e,value:n.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:e,value:n}}},qe=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},ar=e=>typeof bn[e]=="string",sr=e=>{const n=e?.filter(t=>ar(t.key));if(Array.isArray(n)&&n.length>1)throw new E(`You passed ${n.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${n.map(t=>t.key).join(",")}`);return n?.[0]??null},cr=e=>e?.find(n=>n.key==="slug")?.value??null,lr=e=>e?.find(n=>n.key==="id")?.value??null,Ve=e=>e?.find(n=>n.key==="locale")?.value??null,xe=e=>e?.find(n=>n.key==="channel")?.value??null,Ie=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},dr={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},ur={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},pr={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=qe(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Ie(e,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??a,absolute:a}},max:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=qe(r?.selectedFacets?.find(s=>s.key===n)?.value??""),a=Ie(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??a,absolute:a}}},gr={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},mr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new E("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function wn(e){if(!e||e.status!=="pending")return null;for(const n of e.dimensionStatus){if(n.status!=="pending")continue;const t=n.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:e.id,dimensionId:n.id}}return null}function hr(e){if(!e||e.status!=="pending")return!1;const n=e.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return n.length===0?!1:n.every(t=>!t.isUserNextAuthorizer)}const fr=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=wn(r);return{isPendingForOtherAuthorizer:!i&&hr(r),ruleForAuthorization:i}},Sr=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new E("Missing objectKey");const r=n.orderFormId||(await t.orderEntry.createOrderForm()).orderFormId;return t.orderEntry.startOperation({objectKey:n.objectKey,orderFormId:r,sessionToken:n.sessionToken??void 0})},yr=async(e,n,t)=>{if(!(await t.clients.commerce.recommendation.startRecommendationSession())?.recommendationsUserId)throw new Error("Failed to start recommendation session: no session data returned");return!0},Ir=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),vr=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:o}=n;if(!r||!i||!o)throw new E("Missing required fields: fileContent, fileName, mimeType");const a=r.replaceAll(/\s/g,""),s=5*1024*1024;if(Math.floor(a.length*3/4)>s)throw new E("File exceeds maximum allowed size of 5MB");if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(a))throw new E("Invalid Base64 fileContent");const g=Buffer.from(a,"base64");return await t.orderEntry.uploadFile({fileBuffer:g,fileName:i,mimeType:o})};class ce{static parse(n){try{const t=JSON.parse(n);return{seller:t.seller??"",regionId:t.regionId??"",salesChannel:t.salesChannel??"",hasOnlyDefaultSalesChannel:t.hasOnlyDefaultSalesChannel??!0}}catch(t){throw console.error(t),new Error("Malformed channel string")}}static stringify(n){return JSON.stringify(n)}}const ve=(e,n)=>{e.storage.channel=ce.parse(n)},Oe=(e,n)=>{e.storage.locale=n},Dn=e=>xn.createHash("md5").update(e).digest("hex"),re={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function An(e){return{name:e.name,value:e.content,valueReference:re.attachment}}function Or(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:re.attribute,visible:e.visible}}}function Pn(e){return Dn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const Cr=e=>{const n=e.postalCode,t=e.geoCoordinates,r={addressType:e.addressType||null,postalCode:n||null,city:null,state:null,country:e.country||null,street:null,number:null,neighborhood:null,complement:null,reference:null,geoCoordinates:[]};if(t){const i=typeof t=="object"&&"latitude"in t?t.latitude:null,o=typeof t=="object"&&"longitude"in t?t.longitude:null;r.geoCoordinates=i!==null&&o!==null?[o,i]:[]}return[r]},br=(e,n,t)=>{const r=n.postalCode,i=n.geoCoordinates,o=e?.shippingData?.availableAddresses??[],a=e?.shippingData?.selectedAddresses??[];if(!t&&a.length>0)return[a[0]];if(t&&o.length>0)for(const s of o){if(r&&i&&(s.postalCode===r||s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude))return[s];if(r&&!i&&s.postalCode===r)return[s];if(i&&!r&&s.geoCoordinates[0]===i.longitude&&s.geoCoordinates[1]===i.latitude)return[s]}return null},En=(e,n)=>{if(!wr(n))return{updateShipping:!1,addressChanged:!1};if(!Er(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(Dr(t,n.postalCode)||Ar(t,n.geoCoordinates)||Pr(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return Tr(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},wr=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,Dr=(e,n)=>typeof n=="string"&&e?.postalCode!==n,Ar=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Pr=(e,n)=>typeof n=="string"&&e?.addressType!==n,Er=e=>e.items.length!==0,Tr=(e,n)=>{const t=n?.deliveryMode?.deliveryChannel,r=n?.deliveryMode?.deliveryMethod,{startDate:i,endDate:o}=n?.deliveryMode?.deliveryWindow||{};return e.some(({selectedDeliveryChannel:a,selectedSla:s,slas:c})=>{const l=t&&a!==t,g=r&&s!==r;return c?.some(u=>l&&u.deliveryChannel===t||g&&u.id===r?!0:i&&o&&u.deliveryChannel===t&&u.id===r&&(!u?.deliveryWindow||u?.deliveryWindow?.startDateUtc!==i||u?.deliveryWindow?.endDateUtc!==o)&&u.availableDeliveryWindows?.some(h=>h?.startDateUtc===i&&h?.endDateUtc===o))})},Tn=e=>e.valueReference===re.attachment,Ce=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(Tn).map(Pn).join("-")].filter(Boolean).join("::"),le=(e,n)=>({listPrice:e.listPrice/100,price:e.sellingPrice/100,quantity:e.quantity,seller:{identifier:e.seller},itemOffered:{sku:e.id,image:[],name:e.name,additionalProperty:e.attachments.map(An)},index:n}),kr=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(Tn)??[]).map(n=>({name:n.name,content:n.value})),...e.priceToken?{priceToken:e.priceToken}:{}}),je=e=>e.reduce((n,t)=>{const r=Ce(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),Ur=(e,n)=>{const t=({priceToken:s,...c},l)=>({...c,itemOffered:{sku:c.itemOffered.sku},index:l}),r=n.items.map(le).map(t),i=e.acceptedOffer.map(t),o=e.orderNumber===n.orderFormId,a=Pe(r,i);return o&&a};function kn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function Un(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const We=e=>{const n=e.items.reduce((t,r,i)=>{const o=Un(e.items,r.id)||kn(e.items,r.id)?`${Ce(le(r))}::${i}`:Ce(le(r));return t[o]||(t[o]=[]),t[o].push(r),t},{});return{...e,items:Object.values(n).map(t=>{const[r]=t,i=t.reduce((a,s)=>a+s.quantity,0),o=t.reduce((a,s)=>a+(s?.priceDefinition?.total??(s?.quantity??0)*(s?.sellingPrice??0)),0);return{...r,quantity:i,sellingPrice:o/i}})}},Ge=async(e,n,t)=>({order:{orderNumber:e.orderFormId,acceptedOffer:e.items.map(async r=>({...r,product:await n.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:e.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),_n=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return Dn(JSON.stringify({sessionId:n?.id??"",items:t}))},He=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:_n(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
|
|
3
5
|
Make sure to add the following custom app to the orderForm:
|
|
4
6
|
{"fields":["cartEtag"],"id":"faststore","major":1}.
|
|
5
|
-
More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},
|
|
6
|
-
`),r}}const
|
|
7
|
-
`)}let U;o.seller&&(s||g)&&(U=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:g,country:c,salesChannel:f}))?.[0]?.sellers.find(pe=>o.seller===pe.id));const G={...n,currency:{code:D?.currencyCode?.value??n.currency.code,symbol:D?.currencySymbol?.value??n.currency.symbol},country:D?.countryCode?.value??c,channel:ce.stringify({salesChannel:D?.channel?.value??o.salesChannel,regionId:k?.regionId?.value??o.regionId,seller:U?.id,hasOnlyDefaultSalesChannel:!D?.channel?.value}),b2b:y?{isRepresentative:y??!1,customerId:P?.customerId?.value??O??"",unitName:P?.unitName?.value??"",unitId:P?.unitId?.value??w??"",firstName:typeof S?.firstName?.value=="string"?S.firstName.value:"",lastName:typeof S?.lastName?.value=="string"?S.lastName.value:"",userName:`${typeof S?.firstName?.value=="string"?S.firstName.value:""} ${typeof S?.lastName?.value=="string"?S.lastName.value:""}`.trim(),userEmail:P?.storeUserEmail.value??"",savedPostalCode:C?.postalCode?.value??"",contractName:_n(E,A),organizationManager:S?.organizationManager?.value??!1}:null,marketingData:d,person:A?.id?{id:A.id?.value??"",email:A.email?.value??"",givenName:A.firstName?.value??"",familyName:A.lastName?.value??""}:null,geoCoordinates:g?.latitude&&g?.longitude&&g||null,city:l};return ke(n,G)?null:G},qr={validateCart:Rr,validateSession:zr,subscribeToNewsletter:Sr,cancelOrder:pr,processOrderAuthorization:mr,uploadFileToOrderEntry:yr,startOrderEntryOperation:hr,startRecommendationSession:fr};var De;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(De||(De={}));const Vr=e=>typeof e=="string"?Rn(e):null;function Rn(e){try{return JSON.parse(e)}catch{return e}}const xr=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,jr=new oe.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:Vr,serialize:xr,parseLiteral(e){return e.kind===De.STRING?Rn(e.value):null}}),R=e=>"Price"in e&&"seller"in e&&"product"in e,F=e=>"skuName"in e,Wr={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>R(e)?e.PriceValidUntil??"":F(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>R(e)?$e($(e)):F(e)?$e(Kt(e.availability)):null,seller:(e,n,t)=>R(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:F(e)?{identifier:e.seller}:null,price:e=>R(e)?j(e):F(e)?e.sellingPrice/100:null,priceWithTaxes:e=>R(e)?M(j(e),e?.Tax,e.product.unitMultiplier):F(e)?M(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>R(e)?Jt(e):F(e)?e.sellingPrice/100:null,listPrice:e=>R(e)?e.ListPrice??0:F(e)?e.listPrice/100:null,listPriceWithTaxes:e=>R(e)?M(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):F(e)?M(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>R(e)?e.product:F(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>R(e)?e.AvailableQuantity??0:F(e)?e.quantity:null,isGift:e=>F(e)?e.isGift??!1:null,priceToken:e=>R(e)?e.PriceToken??null:null},Gr=({linkText:e})=>`/${e}/p`,Hr=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),Xr={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},ae=(e,n)=>`${e}-${n}`,Ke=(e,n)=>`/${ae(e,n)}/p`,Yr=e=>Array.isArray(e)&&e.length>0?e:null;function Pe(e){return e.replace(/^\/+|\/+$/g,"")}async function Ae(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,a=i.get(r);if(a)return a;const o=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch{return null}})();return i.set(r,o),o}const Jr=(e,n)=>{const t=e.findIndex(r=>Pe(r).split("/").at(-1)===n);return t<0?0:t},Kr={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>ae(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:Gr(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:a,categoryId:o,categoriesIds:s,productId:c},itemId:l}=e,g=Jr(s,o),u=r[g],h=Pe(u).split("/"),f=t.storage.locale;if(ne(t)&&f){const v=await Ae(t,c,f);if(v){const d=new Set(Pe(s[g]).split("/").filter(Boolean)),p=v.categories.filter(y=>d.has(y.id.toString())).sort((y,O)=>y.fullPath.split("/").length-O.fullPath.split("/").length);if(p.length===h.length)return{itemListElement:[...p.map((y,O)=>({name:y.name,item:`/${y.fullPathUriName}/`,position:O+1})),{name:i,item:Ke(v.linkId,l),position:h.length+1}],numberOfItems:h.length}}}return{itemListElement:[...h.map((v,d)=>{const p=`/${h.slice(0,d+1).map(se).join("/")}/`;return{name:v,item:p,position:d+1}}),{name:i,item:Ke(a,l),position:h.length+1}],numberOfItems:h.length}},image:({images:e},n)=>{const t=(Yr(e)??[Xr]).map(({imageUrl:s,imageText:c,imageLabel:l})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:l}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const a=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let o=a?t.filter(({keywords:s})=>s===r):t;return o=o.length===0?t:o,o.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>Hr({offer:n.commertialOffer,seller:n,product:e})).sort(vn),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:o,values:s})=>s.map(c=>({name:o,value:c,valueReference:re.specification}))),i=n.map(Dn),a=t.map(Ir);return[...r,...i,...a]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!ne(t))return null;const r=gt(t);if(r.length===0)return null;const i=e.isVariantOf.productId,a=e.itemId,o=t.storage.locale,s=mt(t),c=await Ae(t,i,o);if(!c?.availableLinkIds)return null;const{availableLinkIds:l}=c,{linkText:g}=e.isVariantOf;return r.map(u=>{if(u===s)return{locale:u,slug:ae(g,a)};const h=l[u];return h?{locale:u,slug:ae(h,a)}:null}).filter(u=>u!==null)}},Qr=new Set(["allSpecifications"]),Zr={hasVariant:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!Qr.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},ei={propertyID:e=>e.propertyID||Pn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},de=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Oe(n,({offer:r},{offer:i})=>vn(r,i));return t?t.sku:e[0]},Fn=e=>e!==""&&!Number.isNaN(Number(e)),ni=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,ti=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:a}}=i,{salesChannel:o}=i.storage.channel,s=n?.trim();if(!s||!ni.test(s))throw new T(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new T("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(f=>!f?.trim())))throw new T("Invalid products: must be an array of non-empty strings");const l=await a.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:o??void 0,locale:i.storage.locale}),{campaign:g,correlationId:u}=l;return{products:(l.products??[]).map(f=>{const v=de(f.items);return v?N(v,f):null}).filter(f=>!!f),correlationId:u,campaign:g}},Qe={price_desc:"price:desc",price_asc:"price:asc",orders_desc:"orders:desc",name_desc:"name:desc",name_asc:"name:asc",release_desc:"release:desc",discount_desc:"discount:desc",score_desc:""},ri=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing operationId");return t.orderEntry.getOperation({operationId:n})},ii=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new T("Missing orderFormId");const{items:r}=await t.orderEntry.getOrderFormItems({orderFormId:n});return(r??[]).map(i=>({id:i.id,name:i.name,price:i.price,listPrice:i.listPrice,quantity:i.quantity,imageUrl:i.imageUrl??null,availability:i.availability,seller:i.seller,unitMultiplier:i.unitMultiplier??1}))};async function ai(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await Ae(e,t,r))?.linkId===i}const Nn="Invalid SkuId",Ln="Slug was set but the fetched sku does not satisfy the slug condition.",oi=e=>q(e)||e instanceof Error&&(e.message===Nn||e.message.startsWith(Ln));async function si(e,n,t,r){const{linkText:i,productId:a}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||ne(e)&&r&&Fn(t.split("-").pop()??"")&&await ai(e,t,a,r)))throw new Error(`${Ln} slug: ${t}, linkText: ${i}`)}async function ci(e,n){if(n==null)throw new T("Missing slug or id");const{clients:{commerce:t,search:r}}=e,i=await t.catalog.portal.pagetype(`${n}/p`);if(i.pageType!=="Product"||!i.id)throw new B(`No product found for slug ${n}`);const a=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!a)throw new B(`No product found for id ${i.id}`);return N(de(a.items),a)}const li={product:async(e,{locator:n},t)=>{const r=je(n),i=xe(n),a=sr(n),o=or(n);r&&be(t,r),i&&Ce(t,i);const{loaders:{skuLoader:s}}=t;try{const c=a??o?.split("-").pop()??"";if(!Fn(c))throw new Error(Nn);const l=await s.load(c);return await si(t,l,o,i),l}catch(c){if(!oi(c))throw c;return ci(t,o)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:ie(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=je(a),l=xe(a),g=ar(a);c&&be(s,c),l&&Ce(s,l);const u=t?Number(t):0,h={page:Math.ceil(u/n)||0,count:n,query:i??void 0,sort:Qe[r??"score_desc"]??Qe.score_desc,selectedFacets:a?.flatMap(qe)??[],sponsoredCount:o??void 0};if(g){const d=(await s.clients.commerce.catalog.products.crossselling({type:bn[g.key],productId:g.value})).map(m=>m.productId).slice(0,n),p=s.clients.search.productsByIdentifier({field:"id",values:d}).then(m=>({products:m,recordsFiltered:m.length,pagination:{count:m.length,current:{index:0,proxyURL:""},before:[],after:[],perPage:n,next:{index:0,proxyURL:""},previous:{index:0,proxyURL:""},first:{index:0,proxyURL:""},last:{index:0,proxyURL:""}},sampling:!1,options:{sorts:[],counts:[]},translated:!1,locale:"",query:"",operator:"and",fuzzy:"0",searchId:""}));return{searchArgs:h,productSearchPromise:p}}const f=s.clients.search.products(h);return{searchArgs:h,productSearchPromise:f}},allProducts:async(e,{first:n,after:t},r)=>{const{clients:{search:i}}=r,a=t?Number(t):0,o=await i.products({page:Math.ceil(a/n),count:n}),s=o.products.flatMap(c=>c.items.map(l=>N(l,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:o.pagination.after.length>0,hasPreviousPage:o.pagination.before.length>0,startCursor:"0",endCursor:o.recordsFiltered.toString(),totalCount:o.recordsFiltered},edges:s.map((c,l)=>({node:c,cursor:(a+l).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(a=>a.items.map(o=>N(o,a))).filter(a=>n.includes(a.itemId)&&a.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,a=t?Number(t):0,[o,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],l=(f,v)=>{c.push({id:f.id,name:f.name,fatherCategoryId:v,linkId:se(f.name),title:f.Title,description:null,metaTagDescription:f.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(f.url).pathname.slice(1).toLowerCase()});for(const d of f.children)l(d,f.id)};for(const f of s)l(f,null);const h=[...o.filter(f=>f.isActive).map(f=>({id:f.id,name:f.name,linkId:se(f.name),title:f.title,description:null,metaTagDescription:f.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(f=>!!On.slug(f,null,r,null));return{pageInfo:{hasNextPage:h.length-a>n,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(n,h.length-a)-1).toString(),totalCount:h.length},edges:h.slice(a,a+n).map((f,v)=>({node:f,cursor:(a+v).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:a},clients:{commerce:o}}=i,[s,c]=await Promise.all([a.load({country:n,items:t,postalCode:r}),o.checkout.address({postalCode:r,country:n})]);return{...s,address:c}},redirect:async(e,{term:n,selectedFacets:t},r)=>{if(!n&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:n??void 0,selectedFacets:t?.flatMap(qe)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},a)=>{const{clients:{commerce:o}}=a,c=(await o.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:l,sellers:g}=c;return{id:l,sellers:g}},profile:async(e,{id:n},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(n);function a(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:a(i)}},productCount:async(e,{term:n},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:n??void 0})},userOrder:async(e,{orderId:n},t)=>{try{if(!n)throw new T("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new B(`No order found for id ${n}`);let a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});a=Cn(c)}catch{}const s=(await r.masterData.getShopperById({userId:i.purchaseAgentData?.purchaseAgents?.[0]?.userId??""})??[])[0]??{};return{orderId:i.orderId,creationDate:i.creationDate,totals:i.totals,items:i.items,shippingData:i.shippingData,paymentData:i.paymentData,customData:i.customData,status:i.status,statusDescription:i.statusDescription,allowCancellation:i.allowCancellation,storePreferencesData:i.storePreferencesData,clientProfileData:i.clientProfileData,canProcessOrderAuthorization:(i.status==="waiting-for-confirmation"||i.status==="waiting-for-authorization")&&!!a,ruleForAuthorization:a,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let a={};try{const s=JSON.parse(i);a=s.error||s}catch{a={message:i}}const o=a?.message||i;throw q(r)?new B(`No order found for id ${n}. ${o}.`):mn(r)?new x(`You are forbidden to interact with order with id ${n}. ${o}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(a=>({orderId:a.orderId,creationDate:a.creationDate,clientName:a.clientName,items:a.items,totalValue:a.totalValue,status:a.status,statusDescription:a.statusDescription,ShippingEstimatedDate:a.ShippingEstimatedDate,customFields:a.customFields,currencyCode:a.currencyCode})),paging:i.paging}},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),a=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],o=new Map;return await Promise.all(a.map(async c=>{try{const[l]=await r.masterData.getShopperById({userId:c});if(l){const g=[l.firstName,l.lastName].filter(Boolean).join(" ");g&&o.set(c,g)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?o.get(c.createdBy)??c.createdBy:null})),paging:{total:i.totalItems,currentPage:i.pageNumber,perPage:i.pageSize}}},validateUser:async(e,n,t)=>({isValid:!0}),isOrganizationMember:async(e,n,t)=>{const{clients:{commerce:r}}=t;return!!(await r.session("").catch(()=>null))?.namespaces.authentication?.unitId?.value},userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=Z(V(i?.cookie??"",r))?.userId??"",[c,l,g]=await Promise.all([a.session("").catch(()=>null),s?a.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?a.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),u=l?.[0],h=c?.namespaces.authentication??null,f=`${(u?.firstName??"").trim()} ${(u?.lastName??"").trim()}`.trim();return{username:h?.storeUserEmail?.value??"",name:f,email:h?.storeUserEmail?.value??"",phone:u?.phone??"",role:g?.Roles?.map(v=>v.Name)??[],orgUnit:h?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=Z(V(i?.cookie??"",r));if(!o?.userId)return null;if(o?.isRepresentative){const c=await a.session("").catch(()=>null);if(!c)return null;const l=c.namespaces.profile??null,g=c.namespaces.shopper??null,u=c.namespaces.authentication??null,h=Je(c)||o?.customerId?.trim()||"";let f=null;if(h)try{f=await a.masterData.getContractById({contractId:h})}catch(p){console.error(`Error while getting contract data for contract ID (${h}).`,p)}const v=`${(g?.firstName?.value??"").trim()} ${(g?.lastName?.value??"").trim()}`.trim();return{name:_n(f,l)||v||"",email:l?.email?.value||u?.storeUserEmail?.value||"",id:l?.id?.value||u?.customerId?.value||o?.customerId?.trim()||""}}const s=await a.licenseManager.getUserById({userId:o?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},availableContracts:async(e,{orgUnitId:n},t)=>{if(!n)throw new T("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:a}}=t,o=await a.session("").catch(()=>null),s=V(i?.cookie??"",r);let c=null;try{c=s?Z(s):null}catch{c=null}const l=o?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!l||l!==n)throw new x("You are not allowed to list contracts for this organization unit");const g=Lr(o?.namespaces.shopper),u=Je(o)||c?.customerId?.trim()||"";return $r(g,u)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:ri,orderFormItems:ii,recommendations:ti},di={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},ui=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,pi={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(u=>({value:u.term,count:u.count})),products:[]};const{productSearchPromise:a}=e,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(g=>{const u=de(g.items);return u&&N(u,g)}).filter(g=>!!g),{searches:l}=o;return{terms:l.map(g=>({value:g.term,count:g.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=de(r.items);return i&&N(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),a=!e.query,o=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(l=>!a||!ui(l,o,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},gi={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},mi=["bd","d","h","m"],hi=e=>mi.includes(e),fi={bd:{0:"Today",1:"In 1 business day",other:"Up to # business days"},d:{0:"Today",1:"In 1 day",other:"Up to # days"},h:{0:"Now",1:"In 1 hour",other:"Up to # hours"},m:{0:"Now",1:"In 1 minute",other:"Up to # minutes"}},Bn=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=hi(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return fi[t][a].replace("#",n)??""},Si={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?Bn(e.shippingEstimate):""},Ze="skuvariation";function en(e,n){const t=`${Ze}${n}`.toLowerCase(),r=e.find(a=>a.imageLabel===t);if(r)return r;const i=e.find(a=>a.imageLabel===Ze);return i||e[0]}function yi(e,n,t){const r={};return e.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${n}-${a.find(c=>c.name===n)?.values[0]??""}`,s=a.reduce((c,l)=>l.name===n?c:c+`-${l.name}-${l.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function nn(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function Ii(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function vi(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Oi(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>vi(i.value,a.value));return n}function bi(e,n,t){const r={},i=new Set;return e.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===n);if(!(o?.values[0]===t)){const c=`${n}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const l=en(a.images,n),g={src:l.imageUrl,alt:l.imageLabel??"",label:`${n}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(g):r[o.name]=[g];return}a.variations.forEach(c=>{const l=`${c.name}-${c.values[0]}`;if(i.has(l))return;i.add(l);const g=en(a.images,c.name),u={src:g.imageUrl,alt:g.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(u):r[c.name]=[u]})}),Oi(r)}const Ci={activeVariations:e=>nn(e.variations),allVariantsByName:e=>Ii(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>yi(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=nn(e.variations)[t];return bi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf))},wi={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Di={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],a=r.reduce((l,g)=>{const u=g?.selectedSla||"",h=g?.selectedDeliveryChannel||g?.deliveryChannel||"",f=g?.deliveryCompany||"",v=g?.deliveryWindow,d=g?.pickupStoreInfo,p=g?.shippingEstimate||"",m=g?.shippingEstimate?Bn(g?.shippingEstimate):"",y=g?.shippingEstimateDate||"",O=g?.addressId||"",w=g?.itemIndex??0,b=t?.[w],A=b?.seller||"",S=`${u}|${h}|${f}|${A}|${p}|${y}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(U=>U?.addressId===O),P=`${wi[h]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:k,taxPriceTags:C}=Pi(b?.priceTags??[]),E=(b?.sellingPrice??0)*(b?.quantity??0)+(b?.tax??0)+(k??0);return l[S]||(l[S]={selectedSla:u,deliveryChannel:h,deliveryCompany:f,deliveryWindow:v,shippingEstimate:p,shippingEstimateDate:y,seller:A,friendlyShippingEstimate:m,friendlyDeliveryOptionName:P,address:D,pickupStoreInfo:d,quantityOfDifferentItems:0,total:0,items:[]}),l[S]&&(l[S].items?.push({id:b?.id||"",uniqueId:b?.uniqueId||"",name:b?.name||"",quantity:b?.quantity||0,price:b?.price||0,sellingPrice:b?.sellingPrice||0,imageUrl:b?.imageUrl||"",taxPriceTags:C??[],taxPriceTagsTotal:k??0,tax:b?.tax||0,total:E}),l[S].quantityOfDifferentItems=(l[S].quantityOfDifferentItems??0)+1,l[S].total=(l[S].total??0)+E),l},{}),o=Object.values(a),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||o?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:o,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",a=r?.linkedEntity?.id||"",o=`${i}|${a||""}`;return t[o]||(t[o]={type:i,id:a,fields:[]}),t[o].fields.push(...r?.fields||[]),t},{}))||[]}};function Pi(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,a)=>i+(a.rawValue?a.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const Ai={StoreCollection:On,StoreAggregateOffer:Zt,StoreProduct:Kr,StoreSeo:gi,StoreFacet:cr,StoreFacetBoolean:lr,StoreFacetRange:dr,StoreFacetValueBoolean:ur,StoreOffer:Wr,StoreAggregateRating:er,StoreReview:di,StoreProductGroup:Zr,StoreSearchResult:pi,StorePropertyValue:ei,SkuVariants:Ci,ShippingSLA:Si,UserOrderResult:Di,ObjectOrString:jr,Query:li,Mutation:qr},Ti=()=>Ai,ki=`"""
|
|
7
|
+
More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},_r=(e,n)=>{const r=e.customData?.customApps.find(o=>o.id==="faststore")?.fields?.cartEtag;return r==null?!0:_n(e,n)!==r},Rr=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),Xe=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=En(e,n);if(r){const o=br(e,n,i),s=o||Cr(n);return!!n.deliveryMode?.deliveryWindow&&await t.checkout.shippingData({id:e.orderFormId,index:e.items.length,deliveryMode:n.deliveryMode,selectedAddresses:s},!1),t.checkout.shippingData({id:e.orderFormId,index:e.items.length,deliveryMode:n.deliveryMode,selectedAddresses:s},!0)}return e},Fr=(e,n)=>{if(!e)return"";const r=te.parse(e)[n];return r?r.split("=")[1]:""},Nr=async(e,{cart:{order:n},session:t},r)=>{const i=Fr(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:o},loaders:{skuLoader:a}}=r,s=t?.channel,c=t?.locale;s&&ve(r,s),c&&Oe(r,c);const l=await o.checkout.orderForm({id:i||void 0,channel:r.storage.channel}),g=l.orderFormId;l.messages.length!==0&&await Rr(g,r);const u=te.parse(r?.headers?.cookie??"")?.vtex_session,h=Z(u),{acceptedOffer:f,shouldSplitItem:v}=n;if(_r(l,h)){const b=await He(l,o,h).then(We);if(g)return Ge(b,a,v)}const p=je(f),m=je(l.items.map(le)),y=Array.from(m.entries()),O=Array.from(p.entries()),{itemsToAdd:w,itemsToUpdate:C}=O.reduce((b,[k,U])=>{const G=m.get(k);if(!G)return U.forEach(H=>b.itemsToAdd.push(H)),b;const[_,...Ee]=G;if(Un(l.items,_.itemOffered.sku)||kn(l.items,_.itemOffered.sku))return b.itemsToUpdate.push(_),b;const pe=U.reduce((H,zn)=>H+zn.quantity,0);return b.itemsToUpdate.push({..._,quantity:pe}),Ee.forEach(H=>b.itemsToUpdate.push({...H,quantity:0})),b},{itemsToAdd:[],itemsToUpdate:[]}),P=y.filter(([b])=>!p.has(b)).flatMap(([,b])=>b.map(k=>({...k,quantity:0}))),S=[...w,...C,...P].map(kr),{updateShipping:D}=t?En(l,t):{updateShipping:!1};if(S.length===0&&!D)return null;let A;S.length>0?A=await o.checkout.updateOrderFormItems({id:l.orderFormId,orderItems:S,shouldSplitItem:v}).then(b=>Xe(b,t,r)):A=await Xe(l,t,r),A=await Promise.resolve(A).then(b=>{if(t?.marketingData){const k={...b.marketingData,...t.marketingData};return o.checkout.marketingData({id:l.orderFormId,marketingData:k})}return b}).then(b=>c&&b.clientPreferencesData?.locale!==c?o.checkout.clientPreferencesData({id:b.orderFormId,clientPreferencesData:{...b.clientPreferencesData,locale:c}}):b).then(b=>He(b,o,h)).then(We);const T=Pe(l.messages,A.messages);return Ur(n,A)&&T?null:Ge(A,a,v)},Lr=e=>{const n=(e?.corporateName??"").trim();return n||(e?.firstName??"").trim()},Br=e=>{if(!e||typeof e!="object")return!1;const n=e;return typeof n.customerId=="string"&&n.customerId.trim()!==""&&typeof n.contractName=="string"&&typeof n.isActive=="boolean"&&typeof n.isCurrent=="boolean"},$r=e=>{const n=e?.availableContracts?.value;return Array.isArray(n)?n.filter(Br):[]},Mr=e=>e?.customerId?!!((e.contractName??"").trim()&&e.isActive):!1,Ye=e=>e?.namespaces?.shopper?.activeContractId?.value?.trim()??e?.namespaces?.authentication?.customerId?.value?.trim()??e?.namespaces?.profile?.id?.value?.trim()??"",zr=(e,n="")=>{const t=n.trim();return e.filter(Mr).map(r=>({id:r.customerId,corporateName:r.contractName.trim(),isActive:t?r.customerId===t:r.isCurrent}))},Rn=(e,n)=>{const t=Lr(e);return t||(n?.firstName?.value??"").trim()};async function qr(e,n,t){try{const r=await e.commerce.checkout.address({postalCode:t,country:n}),i=r.geoCoordinates?{latitude:r.geoCoordinates[1],longitude:r.geoCoordinates[0]}:null;return{city:r.city,geoCoordinates:i}}catch(r){throw console.error(`Error while getting geo coordinates for the current postal code (${t}) and country (${n}).
|
|
8
|
+
`),r}}const Vr=async(e,{session:n,search:t},{clients:r,headers:i,account:o})=>{const a=ce.parse(n.channel??""),s=String(n.postalCode??""),c=n.country??"";let l=n.city??null,g=n.geoCoordinates??null;if((!l||!g)&&s!==""&&c!==""){const _=await qr(r,c,s);l=_.city,g=_.geoCoordinates}const h=new URLSearchParams(t);h.has("facets")&&h.delete("facets");const f=h.get("sc")??a.salesChannel;h.set("sc",f),s&&h.set("postalCode",s),c&&h.set("country",c),g&&h.set("geoCoordinates",`${g.longitude},${g.latitude}`),h.set("locale",n.locale);const{marketingData:v}=n,d={utmCampaign:h.get("utm_campaign")??v?.utmCampaign??"",utmMedium:h.get("utm_medium")??v?.utmMedium??"",utmSource:h.get("utm_source")??v?.utmSource??"",utmiCampaign:h.get("utmi_cp")??v?.utmiCampaign??"",utmiPage:h.get("utmi_p")??v?.utmiPage??"",utmiPart:h.get("utmi_pc")??v?.utmiPart??""},p=Z(V(i?.cookie??"",o));let m=!1;if(p)try{m=(await r.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(_){console.warn("JWT validation failed:",_),m=!1}const y=m?p?.isRepresentative:!1,O=m?p?.customerId:void 0,w=m?p?.unitId:void 0,C=await r.commerce.session(h.toString()).catch(()=>null),P=C?.namespaces.profile??null,S=C?.namespaces.shopper??null,D=C?.namespaces.store??null,A=C?.namespaces.authentication??null,T=C?.namespaces.checkout??null,b=C?.namespaces.public??null;let k=null;if(y&&P?.id?.value)try{k=await r.commerce.masterData.getContractById({contractId:P.id.value})}catch{console.error(`Error while getting contract data for profile ID (${P.id.value}).
|
|
9
|
+
`)}let U;a.seller&&(s||g)&&(U=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:g,country:c,salesChannel:f}))?.[0]?.sellers.find(pe=>a.seller===pe.id));const G={...n,currency:{code:D?.currencyCode?.value??n.currency.code,symbol:D?.currencySymbol?.value??n.currency.symbol},country:D?.countryCode?.value??c,channel:ce.stringify({salesChannel:D?.channel?.value??a.salesChannel,regionId:T?.regionId?.value??a.regionId,seller:U?.id,hasOnlyDefaultSalesChannel:!D?.channel?.value}),b2b:y?{isRepresentative:y??!1,customerId:A?.customerId?.value??O??"",unitName:A?.unitName?.value??"",unitId:A?.unitId?.value??w??"",firstName:typeof S?.firstName?.value=="string"?S.firstName.value:"",lastName:typeof S?.lastName?.value=="string"?S.lastName.value:"",userName:`${typeof S?.firstName?.value=="string"?S.firstName.value:""} ${typeof S?.lastName?.value=="string"?S.lastName.value:""}`.trim(),userEmail:A?.storeUserEmail.value??"",savedPostalCode:b?.postalCode?.value??"",contractName:Rn(k,P),organizationManager:S?.organizationManager?.value??!1}:null,marketingData:d,person:P?.id?{id:P.id?.value??"",email:P.email?.value??"",givenName:P.firstName?.value??"",familyName:P.lastName?.value??""}:null,geoCoordinates:g?.latitude&&g?.longitude&&g||null,city:l};return Pe(n,G)?null:G},xr={validateCart:Nr,validateSession:Vr,subscribeToNewsletter:Ir,cancelOrder:mr,processOrderAuthorization:fr,uploadFileToOrderEntry:vr,startOrderEntryOperation:Sr,startRecommendationSession:yr};var be;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(be||(be={}));const jr=e=>typeof e=="string"?Fn(e):null;function Fn(e){try{return JSON.parse(e)}catch{return e}}const Wr=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,Gr=new ae.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:jr,serialize:Wr,parseLiteral(e){return e.kind===be.STRING?Fn(e.value):null}}),R=e=>"Price"in e&&"seller"in e&&"product"in e,F=e=>"skuName"in e,Hr={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>R(e)?e.PriceValidUntil??"":F(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>R(e)?Be($(e)):F(e)?Be(Zt(e.availability)):null,seller:(e,n,t)=>R(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:F(e)?{identifier:e.seller}:null,price:e=>R(e)?j(e):F(e)?e.sellingPrice/100:null,priceWithTaxes:e=>R(e)?M(j(e),e?.Tax,e.product.unitMultiplier):F(e)?M(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>R(e)?Qt(e):F(e)?e.sellingPrice/100:null,listPrice:e=>R(e)?e.ListPrice??0:F(e)?e.listPrice/100:null,listPriceWithTaxes:e=>R(e)?M(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):F(e)?M(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>R(e)?e.product:F(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>R(e)?e.AvailableQuantity??0:F(e)?e.quantity:null,isGift:e=>F(e)?e.isGift??!1:null,priceToken:e=>R(e)?e.PriceToken??null:null},Xr=({linkText:e})=>`/${e}/p`,Yr=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),Jr={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},oe=(e,n)=>`${e}-${n}`,Je=(e,n)=>`/${oe(e,n)}/p`,Kr=e=>Array.isArray(e)&&e.length>0?e:null;function we(e){return e.replace(/^\/+|\/+$/g,"")}async function De(e,n,t){const r=`${n}:${t}`;e.storage.productTranslationsCache??=new Map;const i=e.storage.productTranslationsCache,o=i.get(r);if(o)return o;const a=(async()=>{try{const s=await e.clients.catalog.getLocalizedProduct(n,t);return{linkId:s.linkId,categories:s.categories??[],availableLinkIds:s.availableLinkIds??{}}}catch{return null}})();return i.set(r,a),a}const Qr=(e,n)=>{const t=e.findIndex(r=>we(r).split("/").at(-1)===n);return t<0?0:t},Zr={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>oe(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:Xr(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:async(e,n,t)=>{const{isVariantOf:{categories:r,productName:i,linkText:o,categoryId:a,categoriesIds:s,productId:c},itemId:l}=e,g=Qr(s,a),u=r[g],h=we(u).split("/"),f=t.storage.locale;if(ne(t)&&f){const v=await De(t,c,f);if(v){const d=new Set(we(s[g]).split("/").filter(Boolean)),p=v.categories.filter(y=>d.has(y.id.toString())).sort((y,O)=>y.fullPath.split("/").length-O.fullPath.split("/").length);if(p.length===h.length)return{itemListElement:[...p.map((y,O)=>({name:y.name,item:`/${y.fullPathUriName}/`,position:O+1})),{name:i,item:Je(v.linkId,l),position:h.length+1}],numberOfItems:h.length}}}return{itemListElement:[...h.map((v,d)=>{const p=`/${h.slice(0,d+1).map(se).join("/")}/`;return{name:v,item:p,position:d+1}}),{name:i,item:Je(o,l),position:h.length+1}],numberOfItems:h.length}},image:({images:e},n)=>{const t=(Kr(e)??[Jr]).map(({imageUrl:s,imageText:c,imageLabel:l})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:l}));if(typeof n!="object")return t;let{context:r,limit:i}=n;const o=r!=="generic";i=i||-1,i=i<=-1?void 0:i;let a=o?t.filter(({keywords:s})=>s===r):t;return a=a.length===0?t:a,a.slice(0,i)},sku:({itemId:e})=>e,gtin:({ean:e,referenceId:n})=>e||(n[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:e}})=>e??"",review:()=>[],aggregateRating:()=>({}),offers:e=>e.sellers.map(n=>Yr({offer:n.commertialOffer,seller:n,product:e})).sort(On),isVariantOf:e=>e,additionalProperty:({variations:e=[],attachmentsValues:n=[],attributes:t=[]})=>{const r=e.flatMap(({name:a,values:s})=>s.map(c=>({name:a,value:c,valueReference:re.specification}))),i=n.map(An),o=t.map(Or);return[...r,...i,...o]},hasSpecifications:({isVariantOf:e})=>!!e.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:e}})=>e??[],specificationGroups:({isVariantOf:{specificationGroups:e}})=>e,releaseDate:({isVariantOf:{releaseDate:e}})=>e??"",advertisement:({isVariantOf:{advertisement:e}})=>e,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:e}})=>e,otherLocales:async(e,n,t)=>{if(!ne(t))return null;const r=ht(t);if(r.length===0)return null;const i=e.isVariantOf.productId,o=e.itemId,a=t.storage.locale,s=ft(t),c=await De(t,i,a);if(!c?.availableLinkIds)return null;const{availableLinkIds:l}=c,{linkText:g}=e.isVariantOf;return r.map(u=>{if(u===s)return{locale:u,slug:oe(g,o)};const h=l[u];return h?{locale:u,slug:oe(h,o)}:null}).filter(u=>u!==null)}},ei=new Set(["allSpecifications"]),ni={hasVariant:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!ei.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:re.specification}))))},ti={propertyID:e=>e.propertyID||Pn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},de=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Ie(n,({offer:r},{offer:i})=>On(r,i));return t?t.sku:e[0]},Nn=e=>e!==""&&!Number.isNaN(Number(e)),ri=/^vrn:recommendations:[^:]+:[^:]+:[^:]+$/,ii=async(e,{campaignVrn:n,userId:t,products:r},i)=>{const{clients:{commerce:o}}=i,{salesChannel:a}=i.storage.channel,s=n?.trim();if(!s||!ri.test(s))throw new E(`Invalid campaignVrn: "${n}"`);const c=t?.trim();if(t!=null&&!c)throw new E("Invalid userId: must be a non-empty string");if(r!=null&&(!Array.isArray(r)||r.some(f=>!f?.trim())))throw new E("Invalid products: must be an array of non-empty strings");const l=await o.recommendation.recommendations({campaignVrn:s,userId:c||void 0,products:r??[],salesChannel:a??void 0,locale:i.storage.locale}),{campaign:g,correlationId:u}=l;return{products:(l.products??[]).map(f=>{const v=de(f.items);return v?N(v,f):null}).filter(f=>!!f),correlationId:u,campaign:g}},Ke={price_desc:"price:desc",price_asc:"price:asc",orders_desc:"orders:desc",name_desc:"name:desc",name_asc:"name:asc",release_desc:"release:desc",discount_desc:"discount:desc",score_desc:""},oi=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new E("Missing operationId");return t.orderEntry.getOperation({operationId:n})},ai=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new E("Missing orderFormId");const{items:r}=await t.orderEntry.getOrderFormItems({orderFormId:n});return(r??[]).map(i=>({id:i.id,name:i.name,price:i.price,listPrice:i.listPrice,quantity:i.quantity,imageUrl:i.imageUrl??null,availability:i.availability,seller:i.seller,unitMultiplier:i.unitMultiplier??1}))};async function si(e,n,t,r){const i=n.slice(0,n.lastIndexOf("-"));return(await De(e,t,r))?.linkId===i}const Ln="Invalid SkuId",Bn="Slug was set but the fetched sku does not satisfy the slug condition.",ci=e=>q(e)||e instanceof Error&&(e.message===Ln||e.message.startsWith(Bn));async function li(e,n,t,r){const{linkText:i,productId:o}=n.isVariantOf;if(!(!t||!i||t.startsWith(i)||ne(e)&&r&&Nn(t.split("-").pop()??"")&&await si(e,t,o,r)))throw new Error(`${Bn} slug: ${t}, linkText: ${i}`)}async function di(e,n){if(n==null)throw new E("Missing slug or id");const{clients:{commerce:t,search:r}}=e,i=await t.catalog.portal.pagetype(`${n}/p`);if(i.pageType!=="Product"||!i.id)throw new L(`No product found for slug ${n}`);const o=await r.fetchProduct({field:"id",value:String(i.id)}).catch(()=>null);if(!o)throw new L(`No product found for id ${i.id}`);return N(de(o.items),o)}const ui={product:async(e,{locator:n},t)=>{const r=xe(n),i=Ve(n),o=lr(n),a=cr(n);r&&ve(t,r),i&&Oe(t,i);const{loaders:{skuLoader:s}}=t;try{const c=o??a?.split("-").pop()??"";if(!Nn(c))throw new Error(Ln);const l=await s.load(c);return await li(t,l,a,i),l}catch(c){if(!ci(c))throw c;return di(t,a)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load({slug:n,locale:ie(t)})},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:o,sponsoredCount:a},s)=>{const c=xe(o),l=Ve(o),g=sr(o);c&&ve(s,c),l&&Oe(s,l);const u=t?Number(t):0,h={page:Math.ceil(u/n)||0,count:n,query:i??void 0,sort:Ke[r??"score_desc"]??Ke.score_desc,selectedFacets:o?.flatMap(ze)??[],sponsoredCount:a??void 0};if(g){const d=(await s.clients.commerce.catalog.products.crossselling({type:bn[g.key],productId:g.value})).map(m=>m.productId).slice(0,n),p=s.clients.search.productsByIdentifier({field:"id",values:d}).then(m=>({products:m,recordsFiltered:m.length,pagination:{count:m.length,current:{index:0,proxyURL:""},before:[],after:[],perPage:n,next:{index:0,proxyURL:""},previous:{index:0,proxyURL:""},first:{index:0,proxyURL:""},last:{index:0,proxyURL:""}},sampling:!1,options:{sorts:[],counts:[]},translated:!1,locale:"",query:"",operator:"and",fuzzy:"0",searchId:""}));return{searchArgs:h,productSearchPromise:p}}const f=s.clients.search.products(h);return{searchArgs:h,productSearchPromise:f}},allProducts:async(e,{first:n,after:t},r)=>{const{clients:{search:i}}=r,o=t?Number(t):0,a=await i.products({page:Math.ceil(o/n),count:n}),s=a.products.flatMap(c=>c.items.map(l=>N(l,c))).filter(c=>c.sellers.length>0);return{pageInfo:{hasNextPage:a.pagination.after.length>0,hasPreviousPage:a.pagination.before.length>0,startCursor:"0",endCursor:a.recordsFiltered.toString(),totalCount:a.recordsFiltered},edges:s.map((c,l)=>({node:c,cursor:(o+l).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;return n.length?(await r.productsByIdentifier({field:"id",values:n})).flatMap(o=>o.items.map(a=>N(a,o))).filter(o=>n.includes(o.itemId)&&o.sellers.length>0):[]},allCollections:async(e,{first:n,after:t},r)=>{const{clients:{commerce:i}}=r,o=t?Number(t):0,[a,s]=await Promise.all([i.catalog.brand.list(),i.catalog.category.tree()]),c=[],l=(f,v)=>{c.push({id:f.id,name:f.name,fatherCategoryId:v,linkId:se(f.name),title:f.Title,description:null,metaTagDescription:f.MetaTagDescription,availableLinkIds:null,entityType:"category",slug:new URL(f.url).pathname.slice(1).toLowerCase()});for(const d of f.children)l(d,f.id)};for(const f of s)l(f,null);const h=[...a.filter(f=>f.isActive).map(f=>({id:f.id,name:f.name,linkId:se(f.name),title:f.title,description:null,metaTagDescription:f.metaTagDescription,availableLinkIds:null,entityType:"brand"})),...c].filter(f=>!!Cn.slug(f,null,r,null));return{pageInfo:{hasNextPage:h.length-o>n,hasPreviousPage:o>0,startCursor:"0",endCursor:(Math.min(n,h.length-o)-1).toString(),totalCount:h.length},edges:h.slice(o,o+n).map((f,v)=>({node:f,cursor:(o+v).toString()}))}},shipping:async(e,{country:n,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:o},clients:{commerce:a}}=i,[s,c]=await Promise.all([o.load({country:n,items:t,postalCode:r}),a.checkout.address({postalCode:r,country:n})]);return{...s,address:c}},redirect:async(e,{term:n,selectedFacets:t},r)=>{if(!n&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:n??void 0,selectedFacets:t?.flatMap(ze)??[],allowRedirect:!0});return{url:i}},sellers:async(e,{postalCode:n,geoCoordinates:t,country:r,salesChannel:i},o)=>{const{clients:{commerce:a}}=o,c=(await a.checkout.region({postalCode:n,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:l,sellers:g}=c;return{id:l,sellers:g}},profile:async(e,{id:n},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(n);function o(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:o(i)}},productCount:async(e,{term:n},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:n??void 0})},userOrder:async(e,{orderId:n},t)=>{try{if(!n)throw new E("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:n});if(!i)throw new L(`No order found for id ${n}`);let o=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:n});o=wn(c)}catch{}const s=(await r.masterData.getShopperById({userId:i.purchaseAgentData?.purchaseAgents?.[0]?.userId??""})??[])[0]??{};return{orderId:i.orderId,creationDate:i.creationDate,totals:i.totals,items:i.items,shippingData:i.shippingData,paymentData:i.paymentData,customData:i.customData,status:i.status,statusDescription:i.statusDescription,allowCancellation:i.allowCancellation,storePreferencesData:i.storePreferencesData,clientProfileData:i.clientProfileData,canProcessOrderAuthorization:(i.status==="waiting-for-confirmation"||i.status==="waiting-for-authorization")&&!!o,ruleForAuthorization:o,shopper:{firstName:s?.firstName||"",lastName:s?.lastName||"",email:s?.email||"",phone:s?.phone||""},budgetData:i.budgetData??{budgets:[]}}}catch(r){const i=r.message;let o={};try{const s=JSON.parse(i);o=s.error||s}catch{o={message:i}}const a=o?.message||i;throw q(r)?new L(`No order found for id ${n}. ${a}.`):hn(r)?new x(`You are forbidden to interact with order with id ${n}. ${a}.`):r}},listUserOrders:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(n);return{list:i.list?.map(o=>({orderId:o.orderId,creationDate:o.creationDate,clientName:o.clientName,items:o.items,totalValue:o.totalValue,status:o.status,statusDescription:o.statusDescription,ShippingEstimatedDate:o.ShippingEstimatedDate,customFields:o.customFields,currencyCode:o.currencyCode})),paging:i.paging}},listUserQuotes:async(e,n,t)=>{const{clients:{commerce:r}}=t,i=await r.quotes.listUserQuotes(n),o=[...new Set(i.items.map(c=>c.createdBy).filter(Boolean))],a=new Map;return await Promise.all(o.map(async c=>{try{const[l]=await r.masterData.getShopperById({userId:c});if(l){const g=[l.firstName,l.lastName].filter(Boolean).join(" ");g&&a.set(c,g)}}catch{}})),{list:i.items.map(c=>({id:c.id,status:c.status,label:c.label??null,createdAt:c.createdAt,expiresAt:c.expiresAt,amount:c.amount,createdBy:c.createdBy?a.get(c.createdBy)??c.createdBy:null})),paging:{total:i.totalItems,currentPage:i.pageNumber,perPage:i.pageSize}}},validateUser:async(e,n,t)=>({isValid:!0}),isOrganizationMember:async(e,n,t)=>{const{clients:{commerce:r}}=t;return!!(await r.session("").catch(()=>null))?.namespaces.authentication?.unitId?.value},userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,s=Z(V(i?.cookie??"",r))?.userId??"",[c,l,g]=await Promise.all([o.session("").catch(()=>null),s?o.masterData.getShopperById({userId:s}).catch(()=>null):Promise.resolve(null),s?o.licenseManager.getUserRoles({userId:s}).catch(()=>null):Promise.resolve(null)]),u=l?.[0],h=c?.namespaces.authentication??null,f=`${(u?.firstName??"").trim()} ${(u?.lastName??"").trim()}`.trim();return{username:h?.storeUserEmail?.value??"",name:f,email:h?.storeUserEmail?.value??"",phone:u?.phone??"",role:g?.Roles?.map(v=>v.Name)??[],orgUnit:h?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:o}}=t,a=Z(V(i?.cookie??"",r));if(!a?.userId)return null;if(a?.isRepresentative){const c=await o.session("").catch(()=>null);if(!c)return null;const l=c.namespaces.profile??null,g=c.namespaces.shopper??null,u=c.namespaces.authentication??null,h=Ye(c)||a?.customerId?.trim()||"";let f=null;if(h)try{f=await o.masterData.getContractById({contractId:h})}catch(p){console.error(`Error while getting contract data for contract ID (${h}).`,p)}const v=`${(g?.firstName?.value??"").trim()} ${(g?.lastName?.value??"").trim()}`.trim();return{name:Rn(f,l)||v||"",email:l?.email?.value||u?.storeUserEmail?.value||"",id:l?.id?.value||u?.customerId?.value||a?.customerId?.trim()||""}}const s=await o.licenseManager.getUserById({userId:a?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},availableContracts:async(e,{orgUnitId:n},t)=>{if(!n)throw new E("Missing orgUnitId");const{account:r,headers:i,clients:{commerce:o}}=t,a=await o.session("").catch(()=>null),s=V(i?.cookie??"",r);let c=null;try{c=s?Z(s):null}catch{c=null}const l=a?.namespaces.authentication?.unitId?.value?.trim()??c?.unitId?.trim()??"";if(!l||l!==n)throw new x("You are not allowed to list contracts for this organization unit");const g=$r(a?.namespaces.shopper),u=Ye(a)||c?.customerId?.trim()||"";return zr(g,u)},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:oi,orderFormItems:ai,recommendations:ii},pi={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},gi=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,mi={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(u=>({value:u.term,count:u.count})),products:[]};const{productSearchPromise:o}=e,[a,s]=await Promise.all([r.suggestedTerms(i),o]),c=s.products.map(g=>{const u=de(g.items);return u&&N(u,g)}).filter(g=>!!g),{searches:l}=a;return{terms:l.map(g=>({value:g.term,count:g.count})),products:c}},products:async({productSearchPromise:e})=>{const n=await e,t=n.products.map(r=>{const i=de(r.items);return i&&N(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:n.pagination.after.length>0,hasPreviousPage:n.pagination.before.length>0,startCursor:"0",endCursor:n.recordsFiltered.toString(),totalCount:n.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:e},n,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=e;const{facets:i=[]}=await r.facets(e),o=!e.query,a=e.selectedFacets?.length?e.selectedFacets[0].key==="category-1":!1,s=e.selectedFacets?.length?e.selectedFacets[0].key==="brand":!1;return i.filter(l=>!o||!gi(l,a,s))},metadata:async({productSearchPromise:e})=>{const n=await e;return{isTermMisspelled:n.correction?.misspelled??!1,logicalOperator:n.operator,fuzzy:n.fuzzy}},searchId:async({productSearchPromise:e})=>(await e).searchId},hi={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},fi=["bd","d","h","m"],Si=e=>fi.includes(e),yi={bd:{0:"Today",1:"In 1 business day",other:"Up to # business days"},d:{0:"Today",1:"In 1 day",other:"Up to # days"},h:{0:"Now",1:"In 1 hour",other:"Up to # hours"},m:{0:"Now",1:"In 1 minute",other:"Up to # minutes"}},$n=e=>{const[n,t]=[e.split(/\D+/)[0],e.split(/[0-9]+/)[1]],r=n!==""&&!Number.isNaN(Number(n)),i=Si(t);if(!r||!i)return"";const o=Number(n)<2?Number(n):"other";return yi[t][o].replace("#",n)??""},Ii={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?$n(e.shippingEstimate):""},Qe="skuvariation";function Ze(e,n){const t=`${Qe}${n}`.toLowerCase(),r=e.find(o=>o.imageLabel===t);if(r)return r;const i=e.find(o=>o.imageLabel===Qe);return i||e[0]}function vi(e,n,t){const r={};return e.forEach(i=>{const o=i.variations;if(o.length===0)return;const a=`${n}-${o.find(c=>c.name===n)?.values[0]??""}`,s=o.reduce((c,l)=>l.name===n?c:c+`-${l.name}-${l.values[0]}`,a);r[s]=`${t}-${i.itemId}`}),r}function en(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function Oi(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function Ci(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function bi(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,o)=>Ci(i.value,o.value));return n}function wi(e,n,t){const r={},i=new Set;return e.forEach(o=>{if(o.variations.length===0)return;const a=o.variations.find(c=>c.name===n);if(!(a?.values[0]===t)){const c=`${n}-${a?.values[0]}`;if(!a||i.has(c))return;i.add(c);const l=Ze(o.images,n),g={src:l.imageUrl,alt:l.imageLabel??"",label:`${n}: ${a.values[0]}`,value:a.values[0]};r[a.name]?r[a.name].push(g):r[a.name]=[g];return}o.variations.forEach(c=>{const l=`${c.name}-${c.values[0]}`;if(i.has(l))return;i.add(l);const g=Ze(o.images,c.name),u={src:g.imageUrl,alt:g.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(u):r[c.name]=[u]})}),bi(r)}const Di={activeVariations:e=>en(e.variations),allVariantsByName:e=>Oi(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>vi(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=en(e.variations)[t];return wi(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>N(n,e.isVariantOf))},Ai={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Pi={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],o=r.reduce((l,g)=>{const u=g?.selectedSla||"",h=g?.selectedDeliveryChannel||g?.deliveryChannel||"",f=g?.deliveryCompany||"",v=g?.deliveryWindow,d=g?.pickupStoreInfo,p=g?.shippingEstimate||"",m=g?.shippingEstimate?$n(g?.shippingEstimate):"",y=g?.shippingEstimateDate||"",O=g?.addressId||"",w=g?.itemIndex??0,C=t?.[w],P=C?.seller||"",S=`${u}|${h}|${f}|${P}|${p}|${y}|${O}|${v?.startDateUtc}|${v?.endDateUtc}`,D=i?.find(U=>U?.addressId===O),A=`${Ai[h]||""} ${m} ${D?.neighborhood?`to ${D?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:T,taxPriceTags:b}=Ei(C?.priceTags??[]),k=(C?.sellingPrice??0)*(C?.quantity??0)+(C?.tax??0)+(T??0);return l[S]||(l[S]={selectedSla:u,deliveryChannel:h,deliveryCompany:f,deliveryWindow:v,shippingEstimate:p,shippingEstimateDate:y,seller:P,friendlyShippingEstimate:m,friendlyDeliveryOptionName:A,address:D,pickupStoreInfo:d,quantityOfDifferentItems:0,total:0,items:[]}),l[S]&&(l[S].items?.push({id:C?.id||"",uniqueId:C?.uniqueId||"",name:C?.name||"",quantity:C?.quantity||0,price:C?.price||0,sellingPrice:C?.sellingPrice||0,imageUrl:C?.imageUrl||"",taxPriceTags:b??[],taxPriceTagsTotal:T??0,tax:C?.tax||0,total:k}),l[S].quantityOfDifferentItems=(l[S].quantityOfDifferentItems??0)+1,l[S].total=(l[S].total??0)+k),l},{}),a=Object.values(o),s=n?.contactInformation?.[0],c={name:`${s?.firstName??""} ${s?.lastName??""}`.trim()||a?.[0]?.address?.receiverName||"",email:s?.email||"",phone:s?.phone||""};return{deliveryOptions:a,contact:c}},customFields:e=>{const n=e?.customData?.customFields||[];return Object.values(n.reduce((t,r)=>{const i=r?.linkedEntity?.type||"",o=r?.linkedEntity?.id||"",a=`${i}|${o||""}`;return t[a]||(t[a]={type:i,id:o,fields:[]}),t[a].fields.push(...r?.fields||[]),t},{}))||[]}};function Ei(e){const t=e.filter(i=>i?.name?.includes("TAX")),r=t.reduce((i,o)=>i+(o.rawValue?o.rawValue*100:0),0);return{taxPriceTags:t,taxPriceTagsTotal:r}}const Ti={StoreCollection:Cn,StoreAggregateOffer:nr,StoreProduct:Zr,StoreSeo:hi,StoreFacet:dr,StoreFacetBoolean:ur,StoreFacetRange:pr,StoreFacetValueBoolean:gr,StoreOffer:Hr,StoreAggregateRating:tr,StoreReview:pi,StoreProductGroup:ni,StoreSearchResult:mi,StorePropertyValue:ti,SkuVariants:Di,ShippingSLA:Ii,UserOrderResult:Pi,ObjectOrString:Gr,Query:ui,Mutation:xr},ki=()=>Ti,Ui=`"""
|
|
8
10
|
Address information.
|
|
9
11
|
"""
|
|
10
12
|
type Address {
|
|
@@ -49,7 +51,7 @@ type Address {
|
|
|
49
51
|
"""
|
|
50
52
|
geoCoordinates: [Float]
|
|
51
53
|
}
|
|
52
|
-
`,
|
|
54
|
+
`,_i=`"""
|
|
53
55
|
Advertisement information about a specific product in a campaign
|
|
54
56
|
"""
|
|
55
57
|
type Advertisement {
|
|
@@ -74,7 +76,7 @@ type Advertisement {
|
|
|
74
76
|
"""
|
|
75
77
|
adResponseId: String!
|
|
76
78
|
}
|
|
77
|
-
`,
|
|
79
|
+
`,Ri=`"""
|
|
78
80
|
Aggregate offer information, for a given SKU that is available to be fulfilled by multiple sellers.
|
|
79
81
|
"""
|
|
80
82
|
type StoreAggregateOffer {
|
|
@@ -103,7 +105,7 @@ type StoreAggregateOffer {
|
|
|
103
105
|
"""
|
|
104
106
|
offers: [StoreOffer!]!
|
|
105
107
|
}
|
|
106
|
-
`,
|
|
108
|
+
`,Fi=`"""
|
|
107
109
|
Average rating, based on multiple ratings or reviews.
|
|
108
110
|
"""
|
|
109
111
|
type StoreAggregateRating {
|
|
@@ -116,7 +118,7 @@ type StoreAggregateRating {
|
|
|
116
118
|
"""
|
|
117
119
|
reviewCount: Int!
|
|
118
120
|
}
|
|
119
|
-
`,
|
|
121
|
+
`,Ni=`"""
|
|
120
122
|
information about the author of a product review or rating.
|
|
121
123
|
"""
|
|
122
124
|
type StoreAuthor {
|
|
@@ -125,7 +127,7 @@ type StoreAuthor {
|
|
|
125
127
|
"""
|
|
126
128
|
name: String!
|
|
127
129
|
}
|
|
128
|
-
`,
|
|
130
|
+
`,Li=`"""
|
|
129
131
|
Brand of a given product.
|
|
130
132
|
"""
|
|
131
133
|
type StoreBrand {
|
|
@@ -134,7 +136,7 @@ type StoreBrand {
|
|
|
134
136
|
"""
|
|
135
137
|
name: String!
|
|
136
138
|
}
|
|
137
|
-
`,
|
|
139
|
+
`,Bi=`"""
|
|
138
140
|
Item of a list.
|
|
139
141
|
"""
|
|
140
142
|
type StoreListItem {
|
|
@@ -165,7 +167,7 @@ type StoreBreadcrumbList {
|
|
|
165
167
|
"""
|
|
166
168
|
numberOfItems: Int!
|
|
167
169
|
}
|
|
168
|
-
|
|
170
|
+
`,$i=`"""
|
|
169
171
|
Shopping cart message.
|
|
170
172
|
"""
|
|
171
173
|
type StoreCartMessage {
|
|
@@ -202,7 +204,7 @@ input IStoreCart {
|
|
|
202
204
|
"""
|
|
203
205
|
order: IStoreOrder!
|
|
204
206
|
}
|
|
205
|
-
`,
|
|
207
|
+
`,Mi=`"""
|
|
206
208
|
Product collection type. Possible values are \`Department\`, \`Category\`, \`Brand\` or \`Collection\`.
|
|
207
209
|
|
|
208
210
|
\`SubCategory\` and \`Cluster\` are still declared for backward compatibility but are
|
|
@@ -317,7 +319,7 @@ type StoreCollectionLocale {
|
|
|
317
319
|
"""
|
|
318
320
|
slug: String!
|
|
319
321
|
}
|
|
320
|
-
|
|
322
|
+
`,zi=`"""
|
|
321
323
|
Delivery Promise badge.
|
|
322
324
|
"""
|
|
323
325
|
type DeliveryPromiseBadge {
|
|
@@ -326,7 +328,7 @@ type DeliveryPromiseBadge {
|
|
|
326
328
|
"""
|
|
327
329
|
typeName: String
|
|
328
330
|
}
|
|
329
|
-
`,
|
|
331
|
+
`,qi=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
|
|
330
332
|
|
|
331
333
|
"""
|
|
332
334
|
Search facet range information.
|
|
@@ -403,7 +405,7 @@ type StoreFacetValueBoolean {
|
|
|
403
405
|
"""
|
|
404
406
|
quantity: Int
|
|
405
407
|
}
|
|
406
|
-
`,
|
|
408
|
+
`,Vi=`"""
|
|
407
409
|
Image.
|
|
408
410
|
"""
|
|
409
411
|
type StoreImage {
|
|
@@ -430,7 +432,7 @@ input IStoreImage {
|
|
|
430
432
|
"""
|
|
431
433
|
alternateName: String!
|
|
432
434
|
}
|
|
433
|
-
`,
|
|
435
|
+
`,xi=`type Mutation {
|
|
434
436
|
"""
|
|
435
437
|
Checks for changes between the cart presented in the UI and the cart stored in the ecommerce platform. If changes are detected, it returns the cart stored on the platform. Otherwise, it returns \`null\`.
|
|
436
438
|
"""
|
|
@@ -472,7 +474,7 @@ input IStoreImage {
|
|
|
472
474
|
"""
|
|
473
475
|
startRecommendationSession: Boolean!
|
|
474
476
|
}
|
|
475
|
-
`,
|
|
477
|
+
`,ji=`"""
|
|
476
478
|
Newsletter information.
|
|
477
479
|
"""
|
|
478
480
|
type PersonNewsletter {
|
|
@@ -495,8 +497,8 @@ input IPersonNewsletter {
|
|
|
495
497
|
"""
|
|
496
498
|
email: String!
|
|
497
499
|
}
|
|
498
|
-
`,
|
|
499
|
-
`,
|
|
500
|
+
`,Wi=`scalar ObjectOrString
|
|
501
|
+
`,Gi=`"""
|
|
500
502
|
Offer information.
|
|
501
503
|
"""
|
|
502
504
|
type StoreOffer {
|
|
@@ -589,7 +591,7 @@ input IStoreOffer {
|
|
|
589
591
|
"""
|
|
590
592
|
priceToken: String
|
|
591
593
|
}
|
|
592
|
-
`,
|
|
594
|
+
`,Hi=`"""
|
|
593
595
|
Information of a specific order.
|
|
594
596
|
"""
|
|
595
597
|
type StoreOrder {
|
|
@@ -624,7 +626,7 @@ input IStoreOrder {
|
|
|
624
626
|
"""
|
|
625
627
|
shouldSplitItem: Boolean
|
|
626
628
|
}
|
|
627
|
-
`,
|
|
629
|
+
`,Xi=`"""
|
|
628
630
|
Commercial Authorization response.
|
|
629
631
|
"""
|
|
630
632
|
type CommercialAuthorizationResponse {
|
|
@@ -1023,7 +1025,7 @@ type ProcessOrderAuthorizationRule {
|
|
|
1023
1025
|
"""
|
|
1024
1026
|
rule: CommercialAuthorizationRule!
|
|
1025
1027
|
}
|
|
1026
|
-
`,
|
|
1028
|
+
`,Yi=`"""
|
|
1027
1029
|
Input for uploading a file to the Order Entry Service.
|
|
1028
1030
|
The file is transmitted as a Base64-encoded string so it can travel
|
|
1029
1031
|
through the standard GraphQL JSON pipeline without multipart support.
|
|
@@ -1084,7 +1086,7 @@ type StoreOrderFormCartItem {
|
|
|
1084
1086
|
seller: String!
|
|
1085
1087
|
unitMultiplier: Float
|
|
1086
1088
|
}
|
|
1087
|
-
`,
|
|
1089
|
+
`,Ji=`"""
|
|
1088
1090
|
Organization.
|
|
1089
1091
|
"""
|
|
1090
1092
|
type StoreOrganization {
|
|
@@ -1121,7 +1123,7 @@ type StoreContract {
|
|
|
1121
1123
|
"""
|
|
1122
1124
|
isActive: Boolean!
|
|
1123
1125
|
}
|
|
1124
|
-
`,
|
|
1126
|
+
`,Ki=`"""
|
|
1125
1127
|
Whenever you make a query that allows for pagination, such as \`allProducts\` or \`allCollections\`, you can check \`StorePageInfo\` to learn more about the complete set of items and use it to paginate your queries.
|
|
1126
1128
|
"""
|
|
1127
1129
|
type StorePageInfo {
|
|
@@ -1146,7 +1148,7 @@ type StorePageInfo {
|
|
|
1146
1148
|
"""
|
|
1147
1149
|
totalCount: Int!
|
|
1148
1150
|
}
|
|
1149
|
-
`,
|
|
1151
|
+
`,Qi=`"""
|
|
1150
1152
|
Input type for setting a new password.
|
|
1151
1153
|
"""
|
|
1152
1154
|
input ISetPassword {
|
|
@@ -1189,7 +1191,7 @@ type SetPasswordResponse {
|
|
|
1189
1191
|
"""
|
|
1190
1192
|
message: String
|
|
1191
1193
|
}
|
|
1192
|
-
`,
|
|
1194
|
+
`,Zi=`"""
|
|
1193
1195
|
Client profile data.
|
|
1194
1196
|
"""
|
|
1195
1197
|
type StorePerson {
|
|
@@ -1232,7 +1234,7 @@ input IStorePerson {
|
|
|
1232
1234
|
"""
|
|
1233
1235
|
familyName: String!
|
|
1234
1236
|
}
|
|
1235
|
-
`,
|
|
1237
|
+
`,eo=`type PickupPointAddress {
|
|
1236
1238
|
"""
|
|
1237
1239
|
Address city.
|
|
1238
1240
|
"""
|
|
@@ -1311,7 +1313,7 @@ type PickupPoints {
|
|
|
1311
1313
|
"""
|
|
1312
1314
|
pickupPointsHash: String
|
|
1313
1315
|
}
|
|
1314
|
-
`,
|
|
1316
|
+
`,no=`"""
|
|
1315
1317
|
Product information. Products are variants within product groups, equivalent to VTEX [SKUs](https://help.vtex.com/en/tutorial/what-is-an-sku--1K75s4RXAQyOuGUYKMM68u#). For example, you may have a **Shirt** product group with associated products such as **Blue shirt size L**, **Green shirt size XL** and so on.
|
|
1316
1318
|
"""
|
|
1317
1319
|
type StoreProduct {
|
|
@@ -1479,7 +1481,7 @@ input IStoreProduct {
|
|
|
1479
1481
|
"""
|
|
1480
1482
|
additionalProperty: [IStorePropertyValue!]
|
|
1481
1483
|
}
|
|
1482
|
-
`,
|
|
1484
|
+
`,to=`"""
|
|
1483
1485
|
Product group information. Product groups are catalog entities that may contain variants. They are equivalent to VTEX [Products](https://help.vtex.com/en/tutorial/what-is-a-product--2zrB2gFCHyQokCKKE8kuAw#), whereas each variant is equivalent to a VTEX [SKU](https://help.vtex.com/en/tutorial/what-is-an-sku--1K75s4RXAQyOuGUYKMM68u#). For example, you may have a **Shirt** product group with associated products such as **Blue shirt size L**, **Green shirt size XL** and so on.
|
|
1484
1486
|
"""
|
|
1485
1487
|
type StoreProductGroup {
|
|
@@ -1506,7 +1508,7 @@ type StoreProductGroup {
|
|
|
1506
1508
|
"""
|
|
1507
1509
|
skuVariants: SkuVariants
|
|
1508
1510
|
}
|
|
1509
|
-
`,
|
|
1511
|
+
`,ro=`type Profile {
|
|
1510
1512
|
"""
|
|
1511
1513
|
Collection of user's address
|
|
1512
1514
|
"""
|
|
@@ -1567,7 +1569,7 @@ type ProfileAddress {
|
|
|
1567
1569
|
"""
|
|
1568
1570
|
geoCoordinate: [Float]
|
|
1569
1571
|
}
|
|
1570
|
-
`,
|
|
1572
|
+
`,io=`"""
|
|
1571
1573
|
Properties that can be associated with products and products groups.
|
|
1572
1574
|
"""
|
|
1573
1575
|
type StorePropertyValue {
|
|
@@ -1607,7 +1609,7 @@ input IStorePropertyValue {
|
|
|
1607
1609
|
"""
|
|
1608
1610
|
valueReference: ObjectOrString!
|
|
1609
1611
|
}
|
|
1610
|
-
`,
|
|
1612
|
+
`,oo=`"""
|
|
1611
1613
|
Each product edge contains a \`node\`, with product information, and a \`cursor\`, that can be used as a reference for pagination.
|
|
1612
1614
|
"""
|
|
1613
1615
|
type StoreProductEdge {
|
|
@@ -2237,7 +2239,7 @@ type StoreAccountProfile {
|
|
|
2237
2239
|
email: String
|
|
2238
2240
|
id: String
|
|
2239
2241
|
}
|
|
2240
|
-
`,
|
|
2242
|
+
`,ao=`"""
|
|
2241
2243
|
Summary of a quote returned in list results.
|
|
2242
2244
|
"""
|
|
2243
2245
|
type UserQuoteSummary {
|
|
@@ -2302,7 +2304,7 @@ type UserQuoteListPaging {
|
|
|
2302
2304
|
"""
|
|
2303
2305
|
perPage: Int!
|
|
2304
2306
|
}
|
|
2305
|
-
`,
|
|
2307
|
+
`,so=`type RecommendationResponse {
|
|
2306
2308
|
products: [StoreProduct!]!
|
|
2307
2309
|
correlationId: String!
|
|
2308
2310
|
campaign: RecommendationCampaign!
|
|
@@ -2313,7 +2315,7 @@ type RecommendationCampaign {
|
|
|
2313
2315
|
title: String
|
|
2314
2316
|
type: String!
|
|
2315
2317
|
}
|
|
2316
|
-
`,
|
|
2318
|
+
`,co=`"""
|
|
2317
2319
|
Information of a given review rating.
|
|
2318
2320
|
"""
|
|
2319
2321
|
type StoreReviewRating {
|
|
@@ -2340,7 +2342,7 @@ type StoreReview {
|
|
|
2340
2342
|
"""
|
|
2341
2343
|
author: StoreAuthor!
|
|
2342
2344
|
}
|
|
2343
|
-
`,
|
|
2345
|
+
`,lo=`"""
|
|
2344
2346
|
Search Engine Optimization (SEO) tags data.
|
|
2345
2347
|
"""
|
|
2346
2348
|
type StoreSeo {
|
|
@@ -2361,7 +2363,7 @@ type StoreSeo {
|
|
|
2361
2363
|
"""
|
|
2362
2364
|
canonical: String!
|
|
2363
2365
|
}
|
|
2364
|
-
`,
|
|
2366
|
+
`,uo=`"""
|
|
2365
2367
|
Currency information.
|
|
2366
2368
|
"""
|
|
2367
2369
|
type StoreCurrency {
|
|
@@ -2636,7 +2638,7 @@ input IStoreSession {
|
|
|
2636
2638
|
"""
|
|
2637
2639
|
refreshAfter: String
|
|
2638
2640
|
}
|
|
2639
|
-
`,
|
|
2641
|
+
`,po=`"""
|
|
2640
2642
|
Shipping Simulation item input.
|
|
2641
2643
|
"""
|
|
2642
2644
|
input IShippingItem {
|
|
@@ -2967,7 +2969,7 @@ type MessageFields {
|
|
|
2967
2969
|
"""
|
|
2968
2970
|
skuName: String
|
|
2969
2971
|
}
|
|
2970
|
-
`,
|
|
2972
|
+
`,go=`type SkuVariants {
|
|
2971
2973
|
"""
|
|
2972
2974
|
SKU property values for the current SKU.
|
|
2973
2975
|
"""
|
|
@@ -3062,7 +3064,7 @@ Example:
|
|
|
3062
3064
|
\`\`\`
|
|
3063
3065
|
"""
|
|
3064
3066
|
scalar FormattedVariants
|
|
3065
|
-
`,
|
|
3067
|
+
`,mo=`"""
|
|
3066
3068
|
Status used to indicate a message type. For instance, a shopping cart informative or error message.
|
|
3067
3069
|
"""
|
|
3068
3070
|
enum StoreStatus {
|
|
@@ -3070,7 +3072,7 @@ enum StoreStatus {
|
|
|
3070
3072
|
WARNING
|
|
3071
3073
|
ERROR
|
|
3072
3074
|
}
|
|
3073
|
-
`,
|
|
3075
|
+
`,ho=`scalar JSONObject
|
|
3074
3076
|
|
|
3075
3077
|
type UserOrder {
|
|
3076
3078
|
orderId: String
|
|
@@ -3894,4 +3896,4 @@ type UserOrderBudgetAllocationLinkedEntity {
|
|
|
3894
3896
|
type: String
|
|
3895
3897
|
id: String
|
|
3896
3898
|
}
|
|
3897
|
-
`,
|
|
3899
|
+
`,fo=Object.assign({"./address.graphql":Ui,"./advertisement.graphql":_i,"./aggregateOffer.graphql":Ri,"./aggregateRating.graphql":Fi,"./author.graphql":Ni,"./brand.graphql":Li,"./breadcrumb.graphql":Bi,"./cart.graphql":$i,"./collection.graphql":Mi,"./deliveryPromisesBadge.graphql":zi,"./facet.graphql":qi,"./image.graphql":Vi,"./mutation.graphql":xi,"./newsletter.graphql":ji,"./objectOrString.graphql":Wi,"./offer.graphql":Gi,"./order.graphql":Hi,"./orderCommercialAuthorizaton.graphql":Xi,"./orderEntry.graphql":Yi,"./organization.graphql":Ji,"./pageInfo.graphql":Ki,"./password.graphql":Qi,"./person.graphql":Zi,"./pickupPoints.graphql":eo,"./product.graphql":no,"./productGroup.graphql":to,"./profile.graphql":ro,"./propertyValue.graphql":io,"./query.graphql":oo,"./quote.graphql":ao,"./recommendation.graphql":so,"./review.graphql":co,"./seo.graphql":lo,"./session.graphql":uo,"./shipping.graphql":po,"./skuVariants.graphql":go,"./status.graphql":mo,"./userOrder.graphql":ho}),So=ae.print(Object.values(fo).map(e=>ae.parse(e)).reduce((e,n)=>nn.mergeTypeDefs([e,n],{sort:!0}))),Mn=So,yo=async e=>n=>(n.storage={channel:ce.parse(e.channel),flags:e.flags??{},locale:e.locale,cookies:new Map},n.account=e.account,n.OTEL_ENABLED=e.OTEL_ENABLED,n.discoveryConfig=e.discoveryConfig,n.clients=qt(e,n),n.loaders=Kt(e,n),n);function Io(){const e=ki(),n={};for(const[t,r]of Object.entries(e))n[t]=Object.fromEntries(Object.entries(r).map(([i,o])=>typeof o!="function"?[i,o]:[i,Kn(o,`${t}(${i})`)]));return n}function vo(e){const t=pn([un,dn])(Io(),Mn);return e&&ae.isSchema(e)?tn.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=dn;exports.BadRequestError=E;exports.CacheControlDirective=un;exports.CommercialAuthorizationStatus=rn;exports.FastStoreError=W;exports.ForbiddenError=x;exports.GraphqlVtexContextFactory=yo;exports.GraphqlVtexSchema=vo;exports.NotFoundError=L;exports.StoreCollectionType=on;exports.StoreFacetType=an;exports.StoreSort=sn;exports.StoreStatus=cn;exports.UnauthorizedError=Q;exports.UserOrderInvoiceType=ln;exports.isBadRequestError=Zn;exports.isFastStoreError=Qn;exports.isForbiddenError=hn;exports.isNotFoundError=q;exports.isUnauthorizedError=et;exports.stringifyCacheControl=Xn;exports.typeDefs=Mn;exports.withDirectives=pn;
|