@faststore/api 4.3.0-dev.1 → 4.3.0-dev.3
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 +124 -39
- package/dist/cjs/index.js.map +1 -1
- package/dist/es/index.mjs +832 -595
- package/dist/es/index.mjs.map +1 -1
- package/dist/src/__generated__/schema.d.ts +79 -0
- package/dist/src/__generated__/schema.d.ts.map +1 -1
- package/dist/src/platforms/vtex/clients/commerce/index.d.ts +36 -0
- package/dist/src/platforms/vtex/clients/commerce/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/clients/index.d.ts +36 -0
- package/dist/src/platforms/vtex/clients/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/index.d.ts +27 -0
- package/dist/src/platforms/vtex/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/getOrderEntryOperation.d.ts +13 -0
- package/dist/src/platforms/vtex/resolvers/getOrderEntryOperation.d.ts.map +1 -0
- package/dist/src/platforms/vtex/resolvers/getOrderFormItems.d.ts +14 -0
- package/dist/src/platforms/vtex/resolvers/getOrderFormItems.d.ts.map +1 -0
- package/dist/src/platforms/vtex/resolvers/index.d.ts +27 -0
- package/dist/src/platforms/vtex/resolvers/index.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/mutation.d.ts +6 -0
- package/dist/src/platforms/vtex/resolvers/mutation.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/query.d.ts +21 -0
- package/dist/src/platforms/vtex/resolvers/query.d.ts.map +1 -1
- package/dist/src/platforms/vtex/resolvers/startOrderEntryOperation.d.ts +6 -0
- package/dist/src/platforms/vtex/resolvers/startOrderEntryOperation.d.ts.map +1 -0
- package/dist/src/platforms/vtex/resolvers/uploadFileToOrderEntry.d.ts +6 -0
- package/dist/src/platforms/vtex/resolvers/uploadFileToOrderEntry.d.ts.map +1 -0
- package/package.json +3 -3
- package/src/__generated__/schema.ts +94 -0
- package/src/platforms/vtex/clients/commerce/index.ts +153 -0
- package/src/platforms/vtex/resolvers/getOrderEntryOperation.ts +15 -0
- package/src/platforms/vtex/resolvers/getOrderFormItems.ts +26 -0
- package/src/platforms/vtex/resolvers/mutation.ts +4 -0
- package/src/platforms/vtex/resolvers/query.ts +4 -0
- package/src/platforms/vtex/resolvers/startOrderEntryOperation.ts +23 -0
- package/src/platforms/vtex/resolvers/uploadFileToOrderEntry.ts +45 -0
- package/src/platforms/vtex/typeDefs/mutation.graphql +14 -0
- package/src/platforms/vtex/typeDefs/orderEntry.graphql +61 -0
- package/src/platforms/vtex/typeDefs/query.graphql +9 -0
package/dist/cjs/index.js
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const xn=require("@graphql-tools/merge"),jn=require("@graphql-tools/schema"),j=require("@graphql-tools/utils"),L=require("@faststore/diagnostics"),nn=require("graphql"),on=require("cookie"),Ae=require("isomorphic-unfetch"),sn=require("dataloader"),Wn=require("p-limit"),Pe=require("sanitize-html"),Dn=require("fast-deep-equal"),Ue=require("node:crypto");var Gn=(n=>(n.Accepted="accepted",n.Denied="denied",n.Pending="pending",n))(Gn||{}),Hn=(n=>(n.Brand="Brand",n.Category="Category",n.Cluster="Cluster",n.Collection="Collection",n.Department="Department",n.SubCategory="SubCategory",n))(Hn||{}),Xn=(n=>(n.Boolean="BOOLEAN",n.Range="RANGE",n))(Xn||{}),Yn=(n=>(n.DiscountDesc="discount_desc",n.NameAsc="name_asc",n.NameDesc="name_desc",n.OrdersDesc="orders_desc",n.PriceAsc="price_asc",n.PriceDesc="price_desc",n.ReleaseDesc="release_desc",n.ScoreDesc="score_desc",n))(Yn||{}),Jn=(n=>(n.Error="ERROR",n.Info="INFO",n.Warning="WARNING",n))(Jn||{}),Kn=(n=>(n.Input="Input",n.Output="Output",n))(Kn||{});const ke=()=>function(e={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new K("No authentication AppKey and AppToken passed.");return{...e,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},Te=async n=>{const{clients:{commerce:e}}=n;try{if((await e.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new J("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new J("Authentication required"):r===403?new K("You are not allowed to access this resource"):new J("Authentication required")}},_e="auth",Qn={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:n=>j.mapSchema(n,{[j.MapperKind.OBJECT_FIELD]:e=>{if(j.getDirective(n,e,_e)?.[0]){const r=e.resolve;e.resolve=async(i,a,o,s)=>(await Te(o),r?.(i,a,o,s))}return e}})},Ee="cacheControl",Ne=(n,e)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=n;return`${e?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},An=(n,e)=>typeof n=="number"&&typeof e=="number"?n>e?e:n:typeof n=="number"?n:e,Fe=(n,e)=>typeof n=="string"&&typeof e=="string"?n==="public"&&e==="public"?"public":"private":n||e,Zn={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:n=>j.mapSchema(n,{[j.MapperKind.OBJECT_FIELD]:e=>{const t=j.getDirective(n,e,Ee)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=e.resolve;e.resolve=(s,c,d,p)=>(d.cacheControl={sMaxAge:An(d.cacheControl?.sMaxAge,r),staleWhileRevalidate:An(d.cacheControl?.staleWhileRevalidate,i),scope:Fe(d.cacheControl?.scope,a)},o?.(s,c,d,p))}return e}})},ne=n=>(e,t)=>{const r=xn.mergeTypeDefs([...(n??[]).map(({typeDefs:i})=>i),t]);return(n??[]).reduce((i,{transformer:a})=>a?.(i)??i,jn.makeExecutableSchema({typeDefs:r,resolvers:e}))},dn="@faststore/api",un="4.3.0-dev.0",Pn={name:dn,version:un},Re=(n,e)=>(t,r,i,a)=>{if((i?.OTEL?.enabled??!1)===!1)return n(t,r,i,a);const o=L.OTELAPI.trace.getTracer(dn,un),s=L.OTELAPI.propagation.extract(L.OTELAPI.context.active(),i.OTEL);return L.OTELAPI.context.with(s,()=>{const c=o.startSpan(e??"Unknown Graphql Resolver",{startTime:Date.now(),kind:L.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":un,"@faststore_package_name":dn,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!c)return n(t,r,i,a);try{const d=n(t,r,i,a);return d instanceof Promise?d.then(p=>(c.end(),p)):(c.end(),d)}catch(d){throw c.end(),console.error(`Error when executing resolver: ${e}`,d),d}})};class H extends Error{constructor(e,t){super(t),this.extensions=e,this.name="FastStoreError"}}class $ extends H{constructor(e){super({status:400,type:"BadRequestError"},e)}}class J extends H{constructor(e){super({status:401,type:"UnauthorizedError"},e)}}class K extends H{constructor(e){super({status:403,type:"ForbiddenError"},e)}}class B extends H{constructor(e){super({status:404,type:"NotFoundError"},e)}}const Le=n=>n?.name==="FastStoreError",Be=n=>n?.extensions?.type==="BadRequestError",Me=n=>n?.extensions?.type==="UnauthorizedError",ee=n=>n?.extensions?.type==="ForbiddenError",te=n=>n?.extensions?.type==="NotFoundError",$e=`${Pn.name}@${Pn.version}`,I=async(n,e,t)=>{const r=await Ae(n,{...e,headers:{...e?.headers??{},"User-Agent":$e}});if(r.ok)return t?.storeCookies&&t.storeCookies(r.headers),r.status!==204?r.json():void 0;console.error(n,e,r);const i=await r.text();if(typeof r?.status=="number")switch(r.status){case 400:throw new $(i);case 401:throw new J(i);case 403:throw new K(i);case 404:throw new B(i);default:throw new H({status:r.status,type:"UnknownError"},i)}throw new Error(i)},re=n=>{if(!n)return n;const e=new Map,t=n.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);e.has(s)||r.push(s),e.set(s,c)}}}),r.map(i=>`${i}=${e.get(i)}`).join("; ")},ze=/^([^=]+)=([^;]*)/,Ve=(n,e)=>{const t=e.match(ze);if(t){const r=t[1],i=t[2];n.storage.cookies.set(r,{value:i,setCookie:e})}},qe=(n,e)=>{e.getSetCookie().forEach(t=>Ve(n,t))},xe=n=>e=>qe(n,e),je=n=>{if(!n.headers?.cookie)return null;const e=re(n.headers.cookie),t=Array.from(n.storage.cookies.entries());return t.length===0?e:t.reduce((r,[i,{value:a}])=>Ge(r,i,a),e)},wn=n=>function(t){const r=je(n);return r?{...t,cookie:r}:t},en=(n,e)=>{const t=re(n);return on.parse(t)[`VtexIdclientAutCookie_${e}`]||""},We=n=>{const e=wn(n);return function(r,i){const a=e({"content-type":"application/json","X-FORWARDED-HOST":r}),o=en(n?.headers?.cookie??"",i);return a.VtexIdclientAutCookie=o,a}},Ge=(n,e,t)=>{const r=new RegExp(`(${e})=([^;]*)`),i=n.match(r);return i?n.replace(i[0],`${i[1]}=${t}`):`${n};${e}=${t}`};function tn(n){return n?JSON.parse(Buffer.from(n.split(".")[1],"base64").toString()):null}const Y={method:"POST",headers:{"content-type":"application/json"}},He=({account:n,environment:e,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${n}.${e}.com.br`,o=xe(i),s=wn(i),c=We(i),d=ke(),p=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",m=r&&r.map(l=>l+".").find(l=>p.includes(l))||"",u=p.replace(m,"");return{catalog:{salesChannel:l=>I(`${a}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:o}),brand:{list:()=>I(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(l=3)=>I(`${a}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:o})},portal:{pagetype:l=>I(`${a}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:o})},products:{crossselling:({type:l,productId:g,groupByProduct:f=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:f.toString()});return I(`${a}/api/catalog_system/pub/products/crossselling/${l}/${g}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(l,{salesChannel:g}=i.storage.channel)=>{const f=new URLSearchParams({sc:g}),S=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForms/simulation?${f.toString()}`,{...Y,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:g,deliveryMode:f,selectedAddresses:S},O)=>{const D=O?{startDateUtc:f?.deliveryWindow?.startDate,endDateUtc:f?.deliveryWindow?.endDate}:null,A={logisticsInfo:Array.from({length:g},(v,U)=>({itemIndex:U,selectedDeliveryChannel:f?.deliveryChannel||null,selectedSla:f?.deliveryMethod||null,deliveryWindow:D})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},_=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...Y,headers:_,body:JSON.stringify(A)},{storeCookies:o})},marketingData:({id:l,marketingData:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:f,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:l,clientPreferencesData:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:f,body:JSON.stringify(g),method:"POST"},{storeCookies:o})},orderForm:({id:l,refreshOutdatedData:g=!0,channel:f=i.storage.channel})=>{const{salesChannel:S}=f,O=s({"content-type":"application/json","X-FORWARDED-HOST":u}),D=new URLSearchParams({sc:S});l&&D.set("refreshOutdatedData",g.toString());const A=`${a}/api/checkout/pub/orderForm${l?`/${l}`:""}?${D.toString()}`;return I(A,{...Y,headers:O,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...Y,headers:g,body:"{}"})},updateOrderFormItems:({id:l,orderItems:g,allowOutdatedData:f="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:O=!0})=>{const D=new URLSearchParams({allowOutdatedData:f,sc:S}),A=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/items?${D}`,{headers:A,body:JSON.stringify({orderItems:g,noSplitItem:!O}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:g,key:f,value:S})=>{const O=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orderForm/${l}/customData/${g}/${f}`,{headers:O,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:g,country:f,salesChannel:S})=>{const O=new URLSearchParams({country:f,sc:S??""});l?O.append("postalCode",l):O.append("geoCoordinates",`${g?.longitude};${g?.latitude}`);const D=`${a}/api/checkout/pub/regions/?${O.toString()}`,A=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(D,{headers:A},{storeCookies:o})},address:async({postalCode:l,country:g})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/postal-code/${g}/${l}`,{headers:f},{storeCookies:o})},cancelOrder:({orderId:l,customerEmail:g,reason:f})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:g,reason:f})},{})},pickupPoints:({geoCoordinates:l})=>{if(!l)throw new Error("Missing required parameter for listing pickup points.");const g=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:g,body:JSON.stringify({coordinate:l})},{storeCookies:o})}},session:l=>{const g=new URLSearchParams(l);g.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,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 f=s({"content-type":"application/json"}),S=on.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${a}/api/sessions?${g.toString()}`,{method:S?"PATCH":"POST",headers:f,body:"{}"},{storeCookies:o})},subscribeToNewsletter:l=>I(`${a}/api/dataentities/NL/documents/`,{...Y,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async l=>{const g=c(u,n);return I(`${a}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:g},{storeCookies:o})}},oms:{userOrder:({orderId:l})=>{const g=c(u,n);return I(`${a}/api/oms/user/orders/${l}`,{method:"GET",headers:g},{storeCookies:o})},listUserOrders:({page:l,status:g,dateInitial:f,dateFinal:S,text:O,clientEmail:D,perPage:A,pendingMyApproval:_})=>{const v=new URLSearchParams;if(f){const h=new Date(f).setHours(0,0,0,0);f=new Date(h).toISOString()}if(S){const h=new Date(S).setHours(23,59,59,999);S=new Date(h).toISOString()}O&&v.append("text",O),g&&g.length>0&&v.append("status",g.filter(Boolean).join(",")),f&&S?v.append("creation_date",`creationDate:[${f} TO ${S}]`):f?v.append("creation_date",`creationDate:[${f} TO *]`):S&&v.append("creation_date",`creationDate:[* TO ${S}]`),D&&v.append("clientEmail",D),l&&v.append("page",l.toString()),A&&v.append("per_page",A.toString()),_&&v.append("my_pending_approvals",String(!0));const U=s({"content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/oms/user/orders?${v.toString()}`,{method:"GET",headers:U},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const g=c(u,n);return I(`${a}/${n}/commercial-authorizations/order/${l}`,{method:"GET",headers:g},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:g,ruleId:f,approved:S})=>{const O=c(u,n),_={params:{ruleId:f,dimensionId:g,score:S?100:0}};return I(`${a}/${n}/commercial-authorizations/${l}/callback`,{method:"POST",headers:O,body:JSON.stringify(_)},{storeCookies:o})}},units:{getUnitByUserId:({userId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}/unit`,{method:"GET",headers:g},{})},getOrgUnitById:({orgUnitId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}`,{method:"GET",headers:g},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const g=c(u,n);return I(`${a}/api/units/v1/${l}/scopes`,{method:"GET",headers:g},{})}},licenseManager:{getUserById:({userId:l})=>{const g=c(u,n);return I(`${a}/api/license-manager/users/${l}`,{method:"GET",headers:g},{})},getUserByEmail:({email:l})=>{const g=c(u,n);return I(`${a}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:g},{})},getUserRoles:({userId:l})=>{const g=c(u,n);return I(`${a}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:g},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new $("Missing contractId to fetch CL fields.");const g=d({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u});return I(`${a}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:g},{})},getShopperById:({userId:l})=>{if(!l)throw new $("Missing userId to fetch shopper name.");const g=d({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":u}),f=l.replace(/-/g,"");return I(`${a}/api/dataentities/shopper/search?_where=(userId=${f} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:g},{})}},vtexid:{validate:()=>{const l=c(u,n);return I(`${a}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:l.VtexIdclientAutCookie}),method:"POST"},{storeCookies:o})}}}},pn="trade-policy",gn="region-id",mn="fuzzy",hn="operator",fn="pickupPoint",ie="shipping",ae="delivery-options",oe="in-stock",Xe=new Set([pn,gn,mn,hn,fn,ie,ae,oe]),Ye=n=>n.key==="fuzzy"&&(n.value==="0"||n.value==="1"||n.value==="auto"),Je=n=>n.key==="operator"&&(n.value==="and"||n.value==="or"),Ke=({account:n,environment:e,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${n}.${e}.com.br/api/io`,c=wn(o),d=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",p=a&&a.map(h=>h+".").find(h=>d.includes(h))||"",m=d.replace(p,""),u=c({"content-type":"application/json","X-FORWARDED-HOST":m}),l=()=>{const{salesChannel:h}=o.storage.channel;return h?{key:pn,value:h}:null},g=()=>{const{regionId:h,seller:C}=o.storage.channel,k=(C?Buffer.from(`SW#${C}`).toString("base64"):null)??h;return k?{key:gn,value:k}:null},f=h=>{const C=h.filter(({key:P})=>!Xe.has(P)),b=h.find(({key:P,value:E})=>P===ie&&E!=="all-delivery-methods")??null,k=h.find(({key:P,value:E})=>P===ae&&E!=="all-delivery-options")??null,y=h.find(({key:P})=>P===pn)??l(),w=h.find(({key:P})=>P===gn)??g();return b!==null&&C.push(b),k!==null&&C.push(k),y!==null&&C.push(y),w!==null&&C.push(w),C},S=(h,C)=>{const b=h.find(({key:w})=>w===mn)??null,k=h.find(({key:w})=>w===hn)??null,y=h.find(({key:w})=>w===fn)??null;b&&Ye(b)&&C.append(mn,b.value),k&&Je(k)&&C.append(hn,k.value),y&&C.append(fn,y.value)},O=({query:h="",page:C,count:b,sort:k="",selectedFacets:y=[],type:w,showInvisibleItems:P,sponsoredCount:E,hideUnavailableItems:T,allowRedirect:X=!1})=>{const N=new URLSearchParams({page:(C+1).toString(),count:b!==0?b.toString():"1",query:h,sort:k,locale:o.storage.locale});if(S(y,N),P&&N.append("show-invisible-items","true"),t!==void 0){const q=y.find(({key:we})=>we===oe),cn=q?q.value:T?.toString()??t.toString();N.append("hideUnavailableItems",cn)}r!==void 0&&N.append("simulationBehavior",r.toString()),i!==void 0&&N.append("showSponsored",i.toString()),E!==void 0&&N.append("sponsoredCount",E.toString()),X!==void 0&&N.append("allowRedirect",X.toString());const z=f(y).map(({key:q,value:cn})=>`${q}/${cn}`).join("/");return I(`${s}/_v/api/intelligent-search/${w}/${z}?${N.toString()}`,{headers:u})};return{facets:h=>O({...h,type:"facets"}),products:h=>O({...h,type:"product_search"}),suggestedTerms:h=>{const C=new URLSearchParams({query:h.query?.toString()??"",locale:o.storage.locale});return I(`${s}/_v/api/intelligent-search/search_suggestions?${C.toString()}`,{headers:u})},topSearches:()=>{const h=new URLSearchParams({locale:o.storage.locale});return I(`${s}/_v/api/intelligent-search/top_searches?${h.toString()}`,{headers:u})},productCount:h=>{const C=new URLSearchParams;return h?.query&&C.append("query",h.query.toString()),I(`${s}/_v/api/intelligent-search/catalog_count?${C.toString()}`,{headers:u})}}},Qe=(n,e)=>{const t=Ke(n,e),r=He(n,e);return{search:t,commerce:r}},Ze=20,nt=new Set(["brand","category","department","subcategory","collection","cluster"]),W=n=>typeof n.pageType=="string"&&nt.has(n.pageType.toLowerCase()),et=(n,e)=>{const t=Wn(Ze),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=await e.commerce.catalog.portal.pagetype(a);if(W(o))return o;throw new B(`Catalog returned ${o.pageType} for slug: ${a}. This usually happens when there is more than one category with the same name in the same category tree level.`)})));return new sn(r,{batch:!1})},tt=(n,e)=>{const t=async r=>Promise.all(r.map(i=>e.commerce.catalog.salesChannel(i)));return new sn(t)},rt=1,it=(n,e)=>{const t=Wn(rt),r=async a=>{const o=a.reduce((m,{items:u})=>[...m,u],[]),s=[...o.flat()],c=await e.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),d=c.items.reduce((m,u)=>{const l=u.requestIndex;return typeof l=="number"&&l<m.length&&(m[l]=u),m},Array(s.length).fill(null)),p=o.reduce((m,u)=>[...m,u.length+m[m.length-1]],[0]);return o.map((m,u)=>({...c,items:d.slice(p[u],p[u+1]).filter(l=>!!l)}))},i=async a=>t(r,a);return new sn(i,{maxBatchSize:50})},at=(n,e)=>Pe(n,e);function ot(n){return{...n,description:n.description?at(n.description):n.description}}const M=(n,e)=>({...n,isVariantOf:ot(e)}),st=({flags:n},e)=>{const t=async r=>{const i=r.map(p=>p.split("-")[0]),a=r.some(p=>p.split("-")[1]==="invisibleItems"),{products:o}=await e.search.products({query:`sku:${i.join(";")}`,page:0,count:i.length,showInvisibleItems:a,...n?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}}),s=o.reduce((p,m)=>{for(const u of m.items)p[u.itemId]=M(u,m);return p},{}),c=i.map(p=>s[p]),d=i.filter(p=>!s[p]);if(d.length>0)throw new B(`Search API did not found the following skus: ${d.join(",")}`);return c};return new sn(t,{maxBatchSize:99})},ct=(n,{clients:e})=>{const t=st(n,e),r=it(n,e),i=et(n,e),a=tt(n,e);return{skuLoader:t,simulationLoader:r,collectionLoader:i,salesChannelLoader:a}},V=n=>n.AvailableQuantity>0,G=n=>n.spotPrice??0,lt=n=>n.Price??0,Un=n=>n?"https://schema.org/InStock":"https://schema.org/OutOfStock",se=(n,e)=>V(n)&&!V(e)?-1:!V(n)&&V(e)?1:G(n)-G(e),dt=n=>n==="available",x=(n,e=0,t=1)=>{const r=e/t;return Math.round((n+r)*100)/100},ut=(n,e={includeTaxes:!1})=>{const t=n.filter(V),r=t[t.length-1],i=r?G(r):0;return e.includeTaxes?x(i,r?.Tax,r?.product?.unitMultiplier):i},kn=(n,e={includeTaxes:!1})=>{const[t]=n.filter(V),r=t?G(t):0;return e.includeTaxes?x(r,t?.Tax,t?.product?.unitMultiplier):r},pt={highPrice:n=>ut(n),lowPrice:n=>kn(n),lowPriceWithTaxes:n=>kn(n,{includeTaxes:!0}),offerCount:n=>n.length,priceCurrency:async(n,e,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},offers:n=>n},gt={ratingValue:()=>5,reviewCount:()=>0},Tn="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",mt="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",ht=n=>{let e=n.slice(0);for(let t=0;t<Tn.length;t++)e=e.replace(new RegExp(Tn.charAt(t),"g"),mt.charAt(t));return e},ft=n=>n.replace(/[·/_,:]/,"-");function ce(n){const t=n.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return ft(ht(t)).toLowerCase()}const Z=n=>n.type==="brand"||W(n)&&n.pageType.toLowerCase()==="brand",Sn=n=>W(n)&&n.pageType.toLowerCase()==="collection",ln=n=>Z(n)||Sn(n)?ce(n.name):W(n)?new URL(`https://${n.url}`).pathname.slice(1).toLowerCase():new URL(n.url).pathname.slice(1).toLowerCase(),le={id:({id:n})=>n.toString(),slug:n=>ln(n),seo:n=>Z(n)||W(n)?{title:n.title??n.name,description:n.metaTagDescription}:{title:n.Title,description:n.MetaTagDescription},type:n=>Z(n)?"Brand":W(n)?n.pageType:n.level===0?"Department":"Category",meta:n=>{const e=ln(n);return Z(n)?{selectedFacets:[{key:"brand",value:e}]}:Sn(n)?{selectedFacets:[{key:"productclusterids",value:n.id}]}:{selectedFacets:e.split("/").map((t,r)=>({key:`category-${r+1}`,value:t}))}},breadcrumbList:async(n,e,t)=>{const{loaders:{collectionLoader:r}}=t,a=ln(n).split("/").filter(c=>!!c),o=a.map((c,d)=>a.slice(0,d+1).join("/")),s=await Promise.all(o.map(async c=>{const d=await r.load(c);return{slug:c,...d}}));return{itemListElement:s.map((c,d)=>({item:Sn(c)?`/${c.slug}`:new URL(`https://${c.url}`).pathname.toLowerCase(),name:c.name,position:d+1})),numberOfItems:s.length}}},de={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},_n=({key:n,value:e})=>{switch(n){case"price":return{key:n,value:e.replace("-to-",":")};case"channel":case"locale":case"buy":case"view":case"similars":case"viewAndBought":case"accessories":case"suggestions":return[];default:return{key:n,value:e}}},En=n=>{const e=n.split(":").map(Number);return e.length!==2||Number.isNaN(e[0])||Number.isNaN(e[1])?null:e},St=n=>typeof de[n]=="string",yt=n=>{const e=n?.filter(t=>St(t.key));if(Array.isArray(e)&&e.length>1)throw new $(`You passed ${e.length} cross selling facets but only one is allowed. Please leave one of the following facet: ${e.map(t=>t.key).join(",")}`);return e?.[0]??null},It=n=>n?.find(e=>e.key==="slug")?.value??null,vt=n=>n?.find(e=>e.key==="id")?.value??null,Nn=n=>n?.find(e=>e.key==="locale")?.value??null,Fn=n=>n?.find(e=>e.key==="channel")?.value??null,yn=(n,e)=>{let t=0;for(let r=1;r<n.length;r++)e(n[t],n[r])>0&&(t=r);return n[t]},Ot={__resolveType:({type:n,values:e})=>n!=="TEXT"&&n!=="DELIVERY"?"StoreFacetRange":!e||e.length===0?"StoreFacetBoolean":e.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Ct={key:({key:n})=>n,label:({name:n})=>n,values:({values:n})=>n.sort((e,t)=>e.name.localeCompare(t.name))},bt={key:({key:n})=>n,label:({name:n})=>n,min:({values:n,key:e},t,{storage:{searchArgs:r}})=>{const i=En(r?.selectedFacets?.find(s=>s.key===e)?.value??""),o=yn(n,(s,c)=>s.range.from-c.range.from)?.range?.from??0;return{selected:i?.[0]??o,absolute:o}},max:({values:n,key:e},t,{storage:{searchArgs:r}})=>{const i=En(r?.selectedFacets?.find(s=>s.key===e)?.value??""),o=yn(n,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},Dt={value:({value:n})=>n,label:({name:n})=>n||"unknown",selected:({selected:n})=>n,quantity:({quantity:n})=>n},wt=async(n,{data:e},{clients:{commerce:t}})=>{if(!e?.orderId)throw new $("Missing orderId");return{data:(await t.checkout.cancelOrder(e))?.data}};function ue(n){if(!n||n.status!=="pending")return null;for(const e of n.dimensionStatus){if(e.status!=="pending")continue;const t=e.ruleCollection.find(r=>r.status==="pending"&&r.isUserNextAuthorizer);if(t)return{rule:t,orderAuthorizationId:n.id,dimensionId:e.id}}return null}function At(n){if(!n||n.status!=="pending")return!1;const e=n.dimensionStatus.filter(t=>t.status==="pending").flatMap(t=>t.ruleCollection).filter(t=>t.status==="pending");return e.length===0?!1:e.every(t=>!t.isUserNextAuthorizer)}const Pt=async(n,{data:e},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(e),i=ue(r);return{isPendingForOtherAuthorizer:!i&&At(r),ruleForAuthorization:i}},Ut=async(n,{data:e},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(e))?.Id});class rn{static parse(e){try{const t=JSON.parse(e);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(e){return JSON.stringify(e)}}const In=(n,e)=>{n.storage.channel=rn.parse(e)},vn=(n,e)=>{n.storage.locale=e},pe=n=>Ue.createHash("md5").update(n).digest("hex"),Q={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function ge(n){return{name:n.name,value:n.content,valueReference:Q.attachment}}function kt(n){return{propertyID:n.id,name:n.name,value:n.value,valueReference:{valueReference:Q.attribute,visible:n.visible}}}function me(n){return pe(`${n.name}:${JSON.stringify(n.value)}:${n.valueReference}`)}const Tt=n=>{const e=n.postalCode,t=n.geoCoordinates,r={addressType:n.addressType||null,postalCode:e||null,city:null,state:null,country:n.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]},_t=(n,e,t)=>{const r=e.postalCode,i=e.geoCoordinates,a=n?.shippingData?.availableAddresses??[],o=n?.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},he=(n,e)=>{if(!Et(e))return{updateShipping:!1,addressChanged:!1};if(!Lt(n))return{updateShipping:!1,addressChanged:!1};const[t]=n?.shippingData?.selectedAddresses??[];if(Nt(t,e.postalCode)||Ft(t,e.geoCoordinates)||Rt(t,e.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=n.shippingData;return Bt(r,e)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},Et=n=>!!n.postalCode||n.geoCoordinates?.latitude&&n.geoCoordinates?.longitude,Nt=(n,e)=>typeof e=="string"&&n?.postalCode!==e,Ft=(n,e)=>typeof e?.latitude=="number"&&typeof e?.longitude=="number"&&(n?.geoCoordinates[0]!==e?.longitude||n?.geoCoordinates[1]!==e?.latitude),Rt=(n,e)=>typeof e=="string"&&n?.addressType!==e,Lt=n=>n.items.length!==0,Bt=(n,e)=>{const t=e?.deliveryMode?.deliveryChannel,r=e?.deliveryMode?.deliveryMethod,{startDate:i,endDate:a}=e?.deliveryMode?.deliveryWindow||{};return n.some(({selectedDeliveryChannel:o,selectedSla:s,slas:c})=>{const d=t&&o!==t,p=r&&s!==r;return c?.some(m=>d&&m.deliveryChannel===t||p&&m.id===r?!0:i&&a&&m.deliveryChannel===t&&m.id===r&&(!m?.deliveryWindow||m?.deliveryWindow?.startDateUtc!==i||m?.deliveryWindow?.endDateUtc!==a)&&m.availableDeliveryWindows?.some(u=>u?.startDateUtc===i&&u?.endDateUtc===a))})},fe=n=>n.valueReference===Q.attachment,On=n=>[n.itemOffered.sku,n.seller.identifier,n.price<.01?"Gift":void 0,n.itemOffered.additionalProperty?.filter(fe).map(me).join("-")].filter(Boolean).join("::"),an=(n,e)=>({listPrice:n.listPrice/100,price:n.sellingPrice/100,quantity:n.quantity,seller:{identifier:n.seller},itemOffered:{sku:n.id,image:[],name:n.name,additionalProperty:n.attachments.map(ge)},index:e}),Mt=n=>({quantity:n.quantity,seller:n.seller.identifier,id:n.itemOffered.sku,index:n.index,attachments:(n.itemOffered.additionalProperty?.filter(fe)??[]).map(e=>({name:e.name,content:e.value}))}),Rn=n=>n.reduce((e,t)=>{const r=On(t);return e.has(r)||e.set(r,[]),e.get(r)?.push(t),e},new Map),$t=(n,e)=>{const t=(s,c)=>({...s,itemOffered:{sku:s.itemOffered.sku},index:c}),r=e.items.map(an).map(t),i=n.acceptedOffer.map(t),a=n.orderNumber===e.orderFormId,o=Dn(r,i);return a&&o};function Se(n,e){return n?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&n[t.parentItemIndex]?.id===e)}function ye(n,e){return n?.some(t=>t.id===e&&t.parentItemIndex!==null)}const Ln=n=>{const e=n.items.reduce((t,r,i)=>{const a=ye(n.items,r.id)||Se(n.items,r.id)?`${On(an(r))}::${i}`:On(an(r));return t[a]||(t[a]=[]),t[a].push(r),t},{});return{...n,items:Object.values(e).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}})}},Bn=async(n,e,t)=>({order:{orderNumber:n.orderFormId,acceptedOffer:n.items.map(async r=>({...r,product:await e.load(`${r.id}-invisibleItems`)})),shouldSplitItem:t},messages:n.messages.map(({text:r,status:i})=>({text:r,status:i.toUpperCase()}))}),Ie=({items:n},e)=>{const t=n.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return pe(JSON.stringify({sessionId:e?.id??"",items:t}))},Mn=async(n,e,t)=>{try{return await e.checkout.setCustomData({id:n.orderFormId,appId:"faststore",key:"cartEtag",value:Ie(n,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const qe=require("@graphql-tools/merge"),xe=require("@graphql-tools/schema"),j=require("@graphql-tools/utils"),M=require("@faststore/diagnostics"),ee=require("graphql"),ae=require("cookie"),An=require("isomorphic-unfetch"),oe=require("dataloader"),je=require("p-limit"),Pn=require("sanitize-html"),be=require("fast-deep-equal"),En=require("node:crypto");var We=(e=>(e.Accepted="accepted",e.Denied="denied",e.Pending="pending",e))(We||{}),Ge=(e=>(e.Brand="Brand",e.Category="Category",e.Cluster="Cluster",e.Collection="Collection",e.Department="Department",e.SubCategory="SubCategory",e))(Ge||{}),He=(e=>(e.Boolean="BOOLEAN",e.Range="RANGE",e))(He||{}),Xe=(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))(Xe||{}),Ye=(e=>(e.Error="ERROR",e.Info="INFO",e.Warning="WARNING",e))(Ye||{}),Je=(e=>(e.Input="Input",e.Output="Output",e))(Je||{});const Tn=()=>function(n={}){const t=process.env.FS_DISCOVERY_APP_KEY??"",r=process.env.FS_DISCOVERY_APP_TOKEN??"";if(!t||!r)throw new K("No authentication AppKey and AppToken passed.");return{...n,"X-VTEX-API-AppKey":t,"X-VTEX-API-AppToken":r}},_n=async e=>{const{clients:{commerce:n}}=e;try{if((await n.vtexid.validate())?.authStatus?.toLowerCase()!=="success")throw new J("Authentication required")}catch(t){const r=t.extensions?.status??t.status;throw r===401?new J("Authentication required"):r===403?new K("You are not allowed to access this resource"):new J("Authentication required")}},Un="auth",Ke={typeDefs:"directive @auth on FIELD_DEFINITION",transformer:e=>j.mapSchema(e,{[j.MapperKind.OBJECT_FIELD]:n=>{if(j.getDirective(e,n,Un)?.[0]){const r=n.resolve;n.resolve=async(i,a,o,s)=>(await _n(o),r?.(i,a,o,s))}return n}})},kn="cacheControl",Fn=(e,n)=>{const{scope:t="private",sMaxAge:r=0,staleWhileRevalidate:i=0}=e;return`${n?"private":t}, s-maxage=${r}, stale-while-revalidate=${i}`},De=(e,n)=>typeof e=="number"&&typeof n=="number"?e>n?n:e:typeof e=="number"?e:n,Nn=(e,n)=>typeof e=="string"&&typeof n=="string"?e==="public"&&n==="public"?"public":"private":e||n,Qe={typeDefs:"directive @cacheControl(sMaxAge: Int, staleWhileRevalidate: Int, scope: String) on FIELD_DEFINITION",transformer:e=>j.mapSchema(e,{[j.MapperKind.OBJECT_FIELD]:n=>{const t=j.getDirective(e,n,kn)?.[0];if(t){const{sMaxAge:r,staleWhileRevalidate:i,scope:a}=t,o=n.resolve;n.resolve=(s,c,u,g)=>(u.cacheControl={sMaxAge:De(u.cacheControl?.sMaxAge,r),staleWhileRevalidate:De(u.cacheControl?.staleWhileRevalidate,i),scope:Nn(u.cacheControl?.scope,a)},o?.(s,c,u,g))}return n}})},Ze=e=>(n,t)=>{const r=qe.mergeTypeDefs([...(e??[]).map(({typeDefs:i})=>i),t]);return(e??[]).reduce((i,{transformer:a})=>a?.(i)??i,xe.makeExecutableSchema({typeDefs:r,resolvers:n}))},le="@faststore/api",de="4.3.0-dev.2",Ae={name:le,version:de},Rn=(e,n)=>(t,r,i,a)=>{if((i?.OTEL?.enabled??!1)===!1)return e(t,r,i,a);const o=M.OTELAPI.trace.getTracer(le,de),s=M.OTELAPI.propagation.extract(M.OTELAPI.context.active(),i.OTEL);return M.OTELAPI.context.with(s,()=>{const c=o.startSpan(n??"Unknown Graphql Resolver",{startTime:Date.now(),kind:M.OTELAPI.SpanKind.INTERNAL,attributes:{timestamp:Date.now(),"@faststore_version":de,"@faststore_package_name":le,"@faststore_account_name":i.account,"@faststore_environment":process.env.NODE_ENV}});if(!c)return e(t,r,i,a);try{const u=e(t,r,i,a);return u instanceof Promise?u.then(g=>(c.end(),g)):(c.end(),u)}catch(u){throw c.end(),console.error(`Error when executing resolver: ${n}`,u),u}})};class H extends Error{constructor(n,t){super(t),this.extensions=n,this.name="FastStoreError"}}class k extends H{constructor(n){super({status:400,type:"BadRequestError"},n)}}class J extends H{constructor(n){super({status:401,type:"UnauthorizedError"},n)}}class K extends H{constructor(n){super({status:403,type:"ForbiddenError"},n)}}class B extends H{constructor(n){super({status:404,type:"NotFoundError"},n)}}const Ln=e=>e?.name==="FastStoreError",Mn=e=>e?.extensions?.type==="BadRequestError",Bn=e=>e?.extensions?.type==="UnauthorizedError",en=e=>e?.extensions?.type==="ForbiddenError",nn=e=>e?.extensions?.type==="NotFoundError",$n=`${Ae.name}@${Ae.version}`,I=async(e,n,t)=>{const r=await An(e,{...n,headers:{...n?.headers??{},"User-Agent":$n}});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 k(i);case 401:throw new J(i);case 403:throw new K(i);case 404:throw new B(i);default:throw new H({status:r.status,type:"UnknownError"},i)}throw new Error(i)},tn=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("; ")},zn=/^([^=]+)=([^;]*)/,Vn=(e,n)=>{const t=n.match(zn);if(t){const r=t[1],i=t[2];e.storage.cookies.set(r,{value:i,setCookie:n})}},qn=(e,n)=>{n.getSetCookie().forEach(t=>Vn(e,t))},xn=e=>n=>qn(e,n),jn=e=>{if(!e.headers?.cookie)return null;const n=tn(e.headers.cookie),t=Array.from(e.storage.cookies.entries());return t.length===0?n:t.reduce((r,[i,{value:a}])=>Gn(r,i,a),n)},we=e=>function(t){const r=jn(e);return r?{...t,cookie:r}:t},ne=(e,n)=>{const t=tn(e);return ae.parse(t)[`VtexIdclientAutCookie_${n}`]||""},Wn=e=>{const n=we(e);return function(r,i){const a=n({"content-type":"application/json","X-FORWARDED-HOST":r}),o=ne(e?.headers?.cookie??"",i);return a.VtexIdclientAutCookie=o,a}},Gn=(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 te(e){return e?JSON.parse(Buffer.from(e.split(".")[1],"base64").toString()):null}const Y={method:"POST",headers:{"content-type":"application/json"}},Hn=({account:e,environment:n,incrementAddress:t,subDomainPrefix:r},i)=>{const a=`https://${e}.${n}.com.br`,o=xn(i),s=we(i),c=Wn(i),u=Tn(),g=new Headers(i.headers).get("x-forwarded-host")??i.headers?.host??"",m=r&&r.map(l=>l+".").find(l=>g.includes(l))||"",d=g.replace(m,"");return{catalog:{salesChannel:l=>I(`${a}/api/catalog_system/pub/saleschannel/${l}`,void 0,{storeCookies:o}),brand:{list:()=>I(`${a}/api/catalog_system/pub/brand/list`,void 0,{storeCookies:o})},category:{tree:(l=3)=>I(`${a}/api/catalog_system/pub/category/tree/${l}`,void 0,{storeCookies:o})},portal:{pagetype:l=>I(`${a}/api/catalog_system/pub/portal/pagetype/${l}`,void 0,{storeCookies:o})},products:{crossselling:({type:l,productId:p,groupByProduct:f=!0})=>{const S=new URLSearchParams({sc:i.storage.channel.salesChannel,groupByProduct:f.toString()});return I(`${a}/api/catalog_system/pub/products/crossselling/${l}/${p}?${S}`,void 0,{storeCookies:o})}}},checkout:{simulation:(l,{salesChannel:p}=i.storage.channel)=>{const f=new URLSearchParams({sc:p}),S=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/orderForms/simulation?${f.toString()}`,{...Y,headers:S,body:JSON.stringify(l)},{storeCookies:o})},shippingData:({id:l,index:p,deliveryMode:f,selectedAddresses:S},v)=>{const w=v?{startDateUtc:f?.deliveryWindow?.startDate,endDateUtc:f?.deliveryWindow?.endDate}:null,P={logisticsInfo:Array.from({length:p},(O,E)=>({itemIndex:E,selectedDeliveryChannel:f?.deliveryChannel||null,selectedSla:f?.deliveryMethod||null,deliveryWindow:w})),selectedAddresses:S,clearAddressIfPostalCodeNotFound:t},_=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/shippingData`,{...Y,headers:_,body:JSON.stringify(P)},{storeCookies:o})},marketingData:({id:l,marketingData:p})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/marketingData`,{headers:f,body:JSON.stringify(p),method:"POST"},{storeCookies:o})},clientPreferencesData:({id:l,clientPreferencesData:p})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/orderForm/${l}/attachments/clientPreferencesData`,{headers:f,body:JSON.stringify(p),method:"POST"},{storeCookies:o})},orderForm:({id:l,refreshOutdatedData:p=!0,channel:f=i.storage.channel})=>{const{salesChannel:S}=f,v=s({"content-type":"application/json","X-FORWARDED-HOST":d}),w=new URLSearchParams({sc:S});l&&w.set("refreshOutdatedData",p.toString());const P=`${a}/api/checkout/pub/orderForm${l?`/${l}`:""}?${w.toString()}`;return I(P,{...Y,headers:v,...l?{}:{body:"{}"}},{storeCookies:o})},clearOrderFormMessages:({id:l})=>{const p=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/orderForm/${l}/messages/clear`,{...Y,headers:p,body:"{}"})},updateOrderFormItems:({id:l,orderItems:p,allowOutdatedData:f="paymentData",salesChannel:S=i.storage.channel.salesChannel,shouldSplitItem:v=!0})=>{const w=new URLSearchParams({allowOutdatedData:f,sc:S}),P=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/orderForm/${l}/items?${w}`,{headers:P,body:JSON.stringify({orderItems:p,noSplitItem:!v}),method:"PATCH"},{storeCookies:o})},setCustomData:({id:l,appId:p,key:f,value:S})=>{const v=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/orderForm/${l}/customData/${p}/${f}`,{headers:v,body:JSON.stringify({value:S}),method:"PUT"})},region:async({postalCode:l,geoCoordinates:p,country:f,salesChannel:S})=>{const v=new URLSearchParams({country:f,sc:S??""});l?v.append("postalCode",l):v.append("geoCoordinates",`${p?.longitude};${p?.latitude}`);const w=`${a}/api/checkout/pub/regions/?${v.toString()}`,P=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(w,{headers:P},{storeCookies:o})},address:async({postalCode:l,country:p})=>{const f=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/postal-code/${p}/${l}`,{headers:f},{storeCookies:o})},cancelOrder:({orderId:l,customerEmail:p,reason:f})=>{const S=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/checkout/pub/orders/${l}/user-cancel-request`,{method:"POST",headers:S,body:JSON.stringify({customerEmail:p,reason:f})},{})},pickupPoints:({geoCoordinates:l})=>{if(!l)throw new Error("Missing required parameter for listing pickup points.");const p=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/logistics-shipping/pickuppoints/_search`,{method:"POST",headers:p,body:JSON.stringify({coordinate:l})},{storeCookies:o})}},session:l=>{const p=new URLSearchParams(l);p.set("items","profile.id,profile.email,profile.firstName,profile.lastName,profile.phone,shopper.firstName,shopper.lastName,shopper.organizationManager,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 f=s({"content-type":"application/json"}),S=ae.parse(i?.headers?.cookie??"")?.vtex_session;return I(`${a}/api/sessions?${p.toString()}`,{method:S?"PATCH":"POST",headers:f,body:"{}"},{storeCookies:o})},subscribeToNewsletter:l=>I(`${a}/api/dataentities/NL/documents/`,{...Y,body:JSON.stringify({...l,isNewsletterOptIn:!0}),method:"PATCH"},{storeCookies:o}),profile:{addresses:async l=>{const p=c(d,e);return I(`${a}/api/profile-system/pvt/profiles/${l}/addresses`,{headers:p},{storeCookies:o})}},oms:{userOrder:({orderId:l})=>{const p=c(d,e);return I(`${a}/api/oms/user/orders/${l}`,{method:"GET",headers:p},{storeCookies:o})},listUserOrders:({page:l,status:p,dateInitial:f,dateFinal:S,text:v,clientEmail:w,perPage:P,pendingMyApproval:_})=>{const O=new URLSearchParams;if(f){const h=new Date(f).setHours(0,0,0,0);f=new Date(h).toISOString()}if(S){const h=new Date(S).setHours(23,59,59,999);S=new Date(h).toISOString()}v&&O.append("text",v),p&&p.length>0&&O.append("status",p.filter(Boolean).join(",")),f&&S?O.append("creation_date",`creationDate:[${f} TO ${S}]`):f?O.append("creation_date",`creationDate:[${f} TO *]`):S&&O.append("creation_date",`creationDate:[* TO ${S}]`),w&&O.append("clientEmail",w),l&&O.append("page",l.toString()),P&&O.append("per_page",P.toString()),_&&O.append("my_pending_approvals",String(!0));const E=s({"content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/oms/user/orders?${O.toString()}`,{method:"GET",headers:E},{storeCookies:o})},getCommercialAuthorizationsByOrderId:({orderId:l})=>{const p=c(d,e);return I(`${a}/${e}/commercial-authorizations/order/${l}`,{method:"GET",headers:p},{storeCookies:o})},processOrderAuthorization:async({orderAuthorizationId:l,dimensionId:p,ruleId:f,approved:S})=>{const v=c(d,e),_={params:{ruleId:f,dimensionId:p,score:S?100:0}};return I(`${a}/${e}/commercial-authorizations/${l}/callback`,{method:"POST",headers:v,body:JSON.stringify(_)},{storeCookies:o})}},units:{getUnitByUserId:({userId:l})=>{const p=c(d,e);return I(`${a}/api/units/v1/${l}/unit`,{method:"GET",headers:p},{})},getOrgUnitById:({orgUnitId:l})=>{const p=c(d,e);return I(`${a}/api/units/v1/${l}`,{method:"GET",headers:p},{})},getScopesByOrgUnit:({orgUnitId:l})=>{const p=c(d,e);return I(`${a}/api/units/v1/${l}/scopes`,{method:"GET",headers:p},{})}},licenseManager:{getUserById:({userId:l})=>{const p=c(d,e);return I(`${a}/api/license-manager/users/${l}`,{method:"GET",headers:p},{})},getUserByEmail:({email:l})=>{const p=c(d,e);return I(`${a}/api/license-manager/pvt/users/${l}`,{method:"GET",headers:p},{})},getUserRoles:({userId:l})=>{const p=c(d,e);return I(`${a}/api/license-manager/storefront/users/${l}/roles`,{method:"GET",headers:p},{})}},masterData:{getContractById:({contractId:l})=>{if(!l)throw new k("Missing contractId to fetch CL fields.");const p=u({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":d});return I(`${a}/api/dataentities/CL/documents/${l}?_fields=_all`,{method:"GET",headers:p},{})},getShopperById:({userId:l})=>{if(!l)throw new k("Missing userId to fetch shopper name.");const p=u({Accept:"application/json","content-type":"application/json","X-FORWARDED-HOST":d}),f=l.replace(/-/g,"");return I(`${a}/api/dataentities/shopper/search?_where=(userId=${f} OR userId=${l})&_fields=_all&_schema=v1`,{method:"GET",headers:p},{})}},vtexid:{validate:()=>{const l=c(d,e);return I(`${a}/api/vtexid/credential/validate`,{headers:l,body:JSON.stringify({token:l.VtexIdclientAutCookie}),method:"POST"},{storeCookies:o})}},orderEntry:{uploadFile:({fileBuffer:l,fileName:p,mimeType:f})=>{const S=c(d,e),v=`----FastStoreUploadBoundary${Date.now()}`,w=`\r
|
|
2
|
+
`,_=/^[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-.^_+]*$/.test(f)?f:"application/octet-stream",O=p.replaceAll(/[\r\n"]/g,"_"),E=[`--${v}`,`Content-Disposition: form-data; name="file"; filename="${O}"`,`Content-Type: ${_}`,"",""].join(w),h=`${w}--${v}--${w}`,C=Buffer.from(E),b=Buffer.from(h),D=new Uint8Array(C.byteLength+l.byteLength+b.byteLength);let y=0;return D.set(C,y),y+=C.byteLength,D.set(l,y),y+=l.byteLength,D.set(b,y),I(`${a}/api/order-entry/upload?an=${e}`,{method:"POST",headers:{...S,"content-type":`multipart/form-data; boundary=${v}`},body:D.buffer},{})},startOperation:({objectKey:l,orderFormId:p,sessionToken:f})=>{const S=c(d,e),v=JSON.stringify({objectKey:l,orderFormId:p,operation:"CreateCart",...f?{sessionToken:f}:{}});return I(`${a}/api/order-entry/operation?an=${e}`,{method:"POST",headers:{...S,"Content-Type":"application/json"},body:v},{})},getOperation:({operationId:l})=>{const p=c(d,e);return I(`${a}/api/order-entry/operation/${l}?an=${e}`,{method:"GET",headers:p},{})},createOrderForm:()=>{const l=c(d,e);return I(`${a}/api/checkout/pub/orderForm?sc=${i.storage.channel.salesChannel}`,{method:"POST",headers:{...l,"Content-Type":"application/json","X-FORWARDED-HOST":d},body:"{}"},{})},getOrderFormItems:({orderFormId:l})=>{const p=c(d,e);return I(`${a}/api/checkout/pub/orderForm/${l}`,{method:"GET",headers:{...p,"Content-Type":"application/json","X-FORWARDED-HOST":d}},{})}}}},ue="trade-policy",pe="region-id",ge="fuzzy",me="operator",he="pickupPoint",rn="shipping",an="delivery-options",on="in-stock",Xn=new Set([ue,pe,ge,me,he,rn,an,on]),Yn=e=>e.key==="fuzzy"&&(e.value==="0"||e.value==="1"||e.value==="auto"),Jn=e=>e.key==="operator"&&(e.value==="and"||e.value==="or"),Kn=({account:e,environment:n,hideUnavailableItems:t,simulationBehavior:r,showSponsored:i,subDomainPrefix:a},o)=>{const s=`https://${e}.${n}.com.br/api/io`,c=we(o),u=new Headers(o.headers).get("x-forwarded-host")??o.headers?.host??"",g=a&&a.map(h=>h+".").find(h=>u.includes(h))||"",m=u.replace(g,""),d=c({"content-type":"application/json","X-FORWARDED-HOST":m}),l=()=>{const{salesChannel:h}=o.storage.channel;return h?{key:ue,value:h}:null},p=()=>{const{regionId:h,seller:C}=o.storage.channel,D=(C?Buffer.from(`SW#${C}`).toString("base64"):null)??h;return D?{key:pe,value:D}:null},f=h=>{const C=h.filter(({key:T})=>!Xn.has(T)),b=h.find(({key:T,value:F})=>T===rn&&F!=="all-delivery-methods")??null,D=h.find(({key:T,value:F})=>T===an&&F!=="all-delivery-options")??null,y=h.find(({key:T})=>T===ue)??l(),A=h.find(({key:T})=>T===pe)??p();return b!==null&&C.push(b),D!==null&&C.push(D),y!==null&&C.push(y),A!==null&&C.push(A),C},S=(h,C)=>{const b=h.find(({key:A})=>A===ge)??null,D=h.find(({key:A})=>A===me)??null,y=h.find(({key:A})=>A===he)??null;b&&Yn(b)&&C.append(ge,b.value),D&&Jn(D)&&C.append(me,D.value),y&&C.append(he,y.value)},v=({query:h="",page:C,count:b,sort:D="",selectedFacets:y=[],type:A,showInvisibleItems:T,sponsoredCount:F,hideUnavailableItems:U,allowRedirect:X=!1})=>{const N=new URLSearchParams({page:(C+1).toString(),count:b!==0?b.toString():"1",query:h,sort:D,locale:o.storage.locale});if(S(y,N),T&&N.append("show-invisible-items","true"),t!==void 0){const q=y.find(({key:Dn})=>Dn===on),se=q?q.value:U?.toString()??t.toString();N.append("hideUnavailableItems",se)}r!==void 0&&N.append("simulationBehavior",r.toString()),i!==void 0&&N.append("showSponsored",i.toString()),F!==void 0&&N.append("sponsoredCount",F.toString()),X!==void 0&&N.append("allowRedirect",X.toString());const z=f(y).map(({key:q,value:se})=>`${q}/${se}`).join("/");return I(`${s}/_v/api/intelligent-search/${A}/${z}?${N.toString()}`,{headers:d})};return{facets:h=>v({...h,type:"facets"}),products:h=>v({...h,type:"product_search"}),suggestedTerms:h=>{const C=new URLSearchParams({query:h.query?.toString()??"",locale:o.storage.locale});return I(`${s}/_v/api/intelligent-search/search_suggestions?${C.toString()}`,{headers:d})},topSearches:()=>{const h=new URLSearchParams({locale:o.storage.locale});return I(`${s}/_v/api/intelligent-search/top_searches?${h.toString()}`,{headers:d})},productCount:h=>{const C=new URLSearchParams;return h?.query&&C.append("query",h.query.toString()),I(`${s}/_v/api/intelligent-search/catalog_count?${C.toString()}`,{headers:d})}}},Qn=(e,n)=>{const t=Kn(e,n),r=Hn(e,n);return{search:t,commerce:r}},Zn=20,et=new Set(["brand","category","department","subcategory","collection","cluster"]),W=e=>typeof e.pageType=="string"&&et.has(e.pageType.toLowerCase()),nt=(e,n)=>{const t=je(Zn),r=async i=>Promise.all(i.map(a=>t(async()=>{const o=await n.commerce.catalog.portal.pagetype(a);if(W(o))return o;throw new B(`Catalog returned ${o.pageType} for slug: ${a}. This usually happens when there is more than one category with the same name in the same category tree level.`)})));return new oe(r,{batch:!1})},tt=(e,n)=>{const t=async r=>Promise.all(r.map(i=>n.commerce.catalog.salesChannel(i)));return new oe(t)},rt=1,it=(e,n)=>{const t=je(rt),r=async a=>{const o=a.reduce((m,{items:d})=>[...m,d],[]),s=[...o.flat()],c=await n.commerce.checkout.simulation({country:a[0].country,postalCode:a[0].postalCode,items:s}),u=c.items.reduce((m,d)=>{const l=d.requestIndex;return typeof l=="number"&&l<m.length&&(m[l]=d),m},Array(s.length).fill(null)),g=o.reduce((m,d)=>[...m,d.length+m[m.length-1]],[0]);return o.map((m,d)=>({...c,items:u.slice(g[d],g[d+1]).filter(l=>!!l)}))},i=async a=>t(r,a);return new oe(i,{maxBatchSize:50})},at=(e,n)=>Pn(e,n);function ot(e){return{...e,description:e.description?at(e.description):e.description}}const $=(e,n)=>({...e,isVariantOf:ot(n)}),st=({flags:e},n)=>{const t=async r=>{const i=r.map(g=>g.split("-")[0]),a=r.some(g=>g.split("-")[1]==="invisibleItems"),{products:o}=await n.search.products({query:`sku:${i.join(";")}`,page:0,count:i.length,showInvisibleItems:a,...e?.enableUnavailableItemsOnCart&&{hideUnavailableItems:!1}}),s=o.reduce((g,m)=>{for(const d of m.items)g[d.itemId]=$(d,m);return g},{}),c=i.map(g=>s[g]),u=i.filter(g=>!s[g]);if(u.length>0)throw new B(`Search API did not found the following skus: ${u.join(",")}`);return c};return new oe(t,{maxBatchSize:99})},ct=(e,{clients:n})=>{const t=st(e,n),r=it(e,n),i=nt(e,n),a=tt(e,n);return{skuLoader:t,simulationLoader:r,collectionLoader:i,salesChannelLoader:a}},V=e=>e.AvailableQuantity>0,G=e=>e.spotPrice??0,lt=e=>e.Price??0,Pe=e=>e?"https://schema.org/InStock":"https://schema.org/OutOfStock",sn=(e,n)=>V(e)&&!V(n)?-1:!V(e)&&V(n)?1:G(e)-G(n),dt=e=>e==="available",x=(e,n=0,t=1)=>{const r=n/t;return Math.round((e+r)*100)/100},ut=(e,n={includeTaxes:!1})=>{const t=e.filter(V),r=t[t.length-1],i=r?G(r):0;return n.includeTaxes?x(i,r?.Tax,r?.product?.unitMultiplier):i},Ee=(e,n={includeTaxes:!1})=>{const[t]=e.filter(V),r=t?G(t):0;return n.includeTaxes?x(r,t?.Tax,t?.product?.unitMultiplier):r},pt={highPrice:e=>ut(e),lowPrice:e=>Ee(e),lowPriceWithTaxes:e=>Ee(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},gt={ratingValue:()=>5,reviewCount:()=>0},Te="ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆÍÌÎÏŇÑÓÖÒÔÕØŘŔŠŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇíìîïňñóöòôõøðřŕšťúůüùûýÿžþÞĐđ߯a",mt="AAAAAACCCDEEEEEEEEIIIINNOOOOOORRSTUUUUUYYZaaaaaacccdeeeeeeeeiiiinnooooooorrstuuuuuyyzbBDdBAa",ht=e=>{let n=e.slice(0);for(let t=0;t<Te.length;t++)n=n.replace(new RegExp(Te.charAt(t),"g"),mt.charAt(t));return n},ft=e=>e.replace(/[·/_,:]/,"-");function cn(e){const t=e.replace(/,/g,"").replace(/[*+~.()'"!:@&\[\]`/ %$#?{}><=_^]/g,"-");return ft(ht(t)).toLowerCase()}const Z=e=>e.type==="brand"||W(e)&&e.pageType.toLowerCase()==="brand",fe=e=>W(e)&&e.pageType.toLowerCase()==="collection",ce=e=>Z(e)||fe(e)?cn(e.name):W(e)?new URL(`https://${e.url}`).pathname.slice(1).toLowerCase():new URL(e.url).pathname.slice(1).toLowerCase(),ln={id:({id:e})=>e.toString(),slug:e=>ce(e),seo:e=>Z(e)||W(e)?{title:e.title??e.name,description:e.metaTagDescription}:{title:e.Title,description:e.MetaTagDescription},type:e=>Z(e)?"Brand":W(e)?e.pageType:e.level===0?"Department":"Category",meta:e=>{const n=ce(e);return Z(e)?{selectedFacets:[{key:"brand",value:n}]}:fe(e)?{selectedFacets:[{key:"productclusterids",value:e.id}]}:{selectedFacets:n.split("/").map((t,r)=>({key:`category-${r+1}`,value:t}))}},breadcrumbList:async(e,n,t)=>{const{loaders:{collectionLoader:r}}=t,a=ce(e).split("/").filter(c=>!!c),o=a.map((c,u)=>a.slice(0,u+1).join("/")),s=await Promise.all(o.map(async c=>{const u=await r.load(c);return{slug:c,...u}}));return{itemListElement:s.map((c,u)=>({item:fe(c)?`/${c.slug}`:new URL(`https://${c.url}`).pathname.toLowerCase(),name:c.name,position:u+1})),numberOfItems:s.length}}},dn={buy:"whoboughtalsobought",view:"whosawalsosaw",similars:"similars",viewAndBought:"whosawalsobought",accessories:"accessories",suggestions:"suggestions"},_e=({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}}},Ue=e=>{const n=e.split(":").map(Number);return n.length!==2||Number.isNaN(n[0])||Number.isNaN(n[1])?null:n},St=e=>typeof dn[e]=="string",yt=e=>{const n=e?.filter(t=>St(t.key));if(Array.isArray(n)&&n.length>1)throw new k(`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},It=e=>e?.find(n=>n.key==="slug")?.value??null,vt=e=>e?.find(n=>n.key==="id")?.value??null,ke=e=>e?.find(n=>n.key==="locale")?.value??null,Fe=e=>e?.find(n=>n.key==="channel")?.value??null,Se=(e,n)=>{let t=0;for(let r=1;r<e.length;r++)n(e[t],e[r])>0&&(t=r);return e[t]},Ot={__resolveType:({type:e,values:n})=>e!=="TEXT"&&e!=="DELIVERY"?"StoreFacetRange":!n||n.length===0?"StoreFacetBoolean":n.every(t=>t.range)?"StoreFacetRange":"StoreFacetBoolean"},Ct={key:({key:e})=>e,label:({name:e})=>e,values:({values:e})=>e.sort((n,t)=>n.name.localeCompare(t.name))},bt={key:({key:e})=>e,label:({name:e})=>e,min:({values:e,key:n},t,{storage:{searchArgs:r}})=>{const i=Ue(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Se(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=Ue(r?.selectedFacets?.find(s=>s.key===n)?.value??""),o=Se(e,(s,c)=>c.range.to-s.range.to)?.range?.to??0;return{selected:i?.[1]??o,absolute:o}}},wt={value:({value:e})=>e,label:({name:e})=>e||"unknown",selected:({selected:e})=>e,quantity:({quantity:e})=>e},Dt=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.orderId)throw new k("Missing orderId");return{data:(await t.checkout.cancelOrder(n))?.data}};function un(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 At(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 Pt=async(e,{data:n},{clients:{commerce:t}})=>{const r=await t.oms.processOrderAuthorization(n),i=un(r);return{isPendingForOtherAuthorizer:!i&&At(r),ruleForAuthorization:i}},Et=async(e,{data:n},{clients:{commerce:t}})=>{if(!n?.objectKey)throw new k("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})},Tt=async(e,{data:n},{clients:{commerce:t}})=>({id:(await t.subscribeToNewsletter(n))?.Id}),_t=async(e,{data:n},{clients:{commerce:t}})=>{const{fileContent:r,fileName:i,mimeType:a}=n;if(!r||!i||!a)throw new k("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 k("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 k("Invalid Base64 fileContent");const g=Buffer.from(o,"base64");return await t.orderEntry.uploadFile({fileBuffer:g,fileName:i,mimeType:a})};class re{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 ye=(e,n)=>{e.storage.channel=re.parse(n)},Ie=(e,n)=>{e.storage.locale=n},pn=e=>En.createHash("md5").update(e).digest("hex"),Q={attachment:"ATTACHMENT",specification:"SPECIFICATION",attribute:"ATTRIBUTE"};function gn(e){return{name:e.name,value:e.content,valueReference:Q.attachment}}function Ut(e){return{propertyID:e.id,name:e.name,value:e.value,valueReference:{valueReference:Q.attribute,visible:e.visible}}}function mn(e){return pn(`${e.name}:${JSON.stringify(e.value)}:${e.valueReference}`)}const kt=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]},Ft=(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},hn=(e,n)=>{if(!Nt(n))return{updateShipping:!1,addressChanged:!1};if(!Bt(e))return{updateShipping:!1,addressChanged:!1};const[t]=e?.shippingData?.selectedAddresses??[];if(Rt(t,n.postalCode)||Lt(t,n.geoCoordinates)||Mt(t,n.addressType))return{updateShipping:!0,addressChanged:!0};const{logisticsInfo:r}=e.shippingData;return $t(r,n)?{updateShipping:!0,addressChanged:!1}:{updateShipping:!1,addressChanged:!1}},Nt=e=>!!e.postalCode||e.geoCoordinates?.latitude&&e.geoCoordinates?.longitude,Rt=(e,n)=>typeof n=="string"&&e?.postalCode!==n,Lt=(e,n)=>typeof n?.latitude=="number"&&typeof n?.longitude=="number"&&(e?.geoCoordinates[0]!==n?.longitude||e?.geoCoordinates[1]!==n?.latitude),Mt=(e,n)=>typeof n=="string"&&e?.addressType!==n,Bt=e=>e.items.length!==0,$t=(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 u=t&&o!==t,g=r&&s!==r;return c?.some(m=>u&&m.deliveryChannel===t||g&&m.id===r?!0:i&&a&&m.deliveryChannel===t&&m.id===r&&(!m?.deliveryWindow||m?.deliveryWindow?.startDateUtc!==i||m?.deliveryWindow?.endDateUtc!==a)&&m.availableDeliveryWindows?.some(d=>d?.startDateUtc===i&&d?.endDateUtc===a))})},fn=e=>e.valueReference===Q.attachment,ve=e=>[e.itemOffered.sku,e.seller.identifier,e.price<.01?"Gift":void 0,e.itemOffered.additionalProperty?.filter(fn).map(mn).join("-")].filter(Boolean).join("::"),ie=(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(gn)},index:n}),zt=e=>({quantity:e.quantity,seller:e.seller.identifier,id:e.itemOffered.sku,index:e.index,attachments:(e.itemOffered.additionalProperty?.filter(fn)??[]).map(n=>({name:n.name,content:n.value}))}),Ne=e=>e.reduce((n,t)=>{const r=ve(t);return n.has(r)||n.set(r,[]),n.get(r)?.push(t),n},new Map),Vt=(e,n)=>{const t=(s,c)=>({...s,itemOffered:{sku:s.itemOffered.sku},index:c}),r=n.items.map(ie).map(t),i=e.acceptedOffer.map(t),a=e.orderNumber===n.orderFormId,o=be(r,i);return a&&o};function Sn(e,n){return e?.some(t=>t.parentItemIndex!==null&&t.parentItemIndex!==void 0&&e[t.parentItemIndex]?.id===n)}function yn(e,n){return e?.some(t=>t.id===n&&t.parentItemIndex!==null)}const Re=e=>{const n=e.items.reduce((t,r,i)=>{const a=yn(e.items,r.id)||Sn(e.items,r.id)?`${ve(ie(r))}::${i}`:ve(ie(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}})}},Le=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()}))}),In=({items:e},n)=>{const t=e.map(r=>({id:r.id,quantity:r.quantity,seller:r.seller,attachments:r.attachments}));return pn(JSON.stringify({sessionId:n?.id??"",items:t}))},Me=async(e,n,t)=>{try{return await n.checkout.setCustomData({id:e.orderFormId,appId:"faststore",key:"cartEtag",value:In(e,t)})}catch(r){throw console.error(`Error while setting custom data to orderForm.
|
|
2
3
|
Make sure to add the following custom app to the orderForm:
|
|
3
4
|
{"fields":["cartEtag"],"id":"faststore","major":1}.
|
|
4
|
-
More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},
|
|
5
|
-
`),r}}const
|
|
6
|
-
`)}let P;o.seller&&(s||p)&&(P=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:p,country:c,salesChannel:l}))?.[0]?.sellers.find(N=>o.seller===N.id));const E={...e,currency:{code:C?.currencyCode?.value??e.currency.code,symbol:C?.currencySymbol?.value??e.currency.symbol},country:C?.countryCode?.value??c,channel:rn.stringify({salesChannel:C?.channel?.value??o.salesChannel,regionId:k?.regionId?.value??o.regionId,seller:P?.id,hasOnlyDefaultSalesChannel:!C?.channel?.value}),b2b:D?{isRepresentative:D??!1,customerId:b?.customerId?.value??A??"",unitName:b?.unitName?.value??"",unitId:b?.unitId?.value??_??"",firstName:typeof h?.firstName?.value=="string"?h.firstName.value:"",lastName:typeof h?.lastName?.value=="string"?h.lastName.value:"",userName:`${typeof h?.firstName?.value=="string"?h.firstName.value:""} ${typeof h?.lastName?.value=="string"?h.lastName.value:""}`.trim(),userEmail:b?.storeUserEmail.value??"",savedPostalCode:y?.postalCode?.value??"",contractName:w?.corporateName??"",organizationManager:h?.organizationManager?.value??!1}:null,marketingData:f,person:U?.id?{id:U.id?.value??"",email:U.email?.value??"",givenName:U.firstName?.value??"",familyName:U.lastName?.value??""}:null,geoCoordinates:p?.latitude&&p?.longitude&&p||null,city:d};return Dn(e,E)?null:E},Gt={validateCart:xt,validateSession:Wt,subscribeToNewsletter:Ut,cancelOrder:wt,processOrderAuthorization:Pt};var Cn;(function(n){n.NAME="Name",n.DOCUMENT="Document",n.OPERATION_DEFINITION="OperationDefinition",n.VARIABLE_DEFINITION="VariableDefinition",n.SELECTION_SET="SelectionSet",n.FIELD="Field",n.ARGUMENT="Argument",n.FRAGMENT_SPREAD="FragmentSpread",n.INLINE_FRAGMENT="InlineFragment",n.FRAGMENT_DEFINITION="FragmentDefinition",n.VARIABLE="Variable",n.INT="IntValue",n.FLOAT="FloatValue",n.STRING="StringValue",n.BOOLEAN="BooleanValue",n.NULL="NullValue",n.ENUM="EnumValue",n.LIST="ListValue",n.OBJECT="ObjectValue",n.OBJECT_FIELD="ObjectField",n.DIRECTIVE="Directive",n.NAMED_TYPE="NamedType",n.LIST_TYPE="ListType",n.NON_NULL_TYPE="NonNullType",n.SCHEMA_DEFINITION="SchemaDefinition",n.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",n.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",n.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",n.FIELD_DEFINITION="FieldDefinition",n.INPUT_VALUE_DEFINITION="InputValueDefinition",n.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",n.UNION_TYPE_DEFINITION="UnionTypeDefinition",n.ENUM_TYPE_DEFINITION="EnumTypeDefinition",n.ENUM_VALUE_DEFINITION="EnumValueDefinition",n.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",n.DIRECTIVE_DEFINITION="DirectiveDefinition",n.SCHEMA_EXTENSION="SchemaExtension",n.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",n.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",n.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",n.UNION_TYPE_EXTENSION="UnionTypeExtension",n.ENUM_TYPE_EXTENSION="EnumTypeExtension",n.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(Cn||(Cn={}));const Ht=n=>typeof n=="string"?ve(n):null;function ve(n){try{return JSON.parse(n)}catch{return n}}const Xt=n=>typeof n=="object"?JSON.stringify(n):typeof n=="string"?n:null,Yt=new nn.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:Ht,serialize:Xt,parseLiteral(n){return n.kind===Cn.STRING?ve(n.value):null}}),R=n=>"Price"in n&&"seller"in n&&"product"in n,F=n=>"skuName"in n,Jt={priceCurrency:async(n,e,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:n=>R(n)?n.PriceValidUntil??"":F(n)?n.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async n=>R(n)?Un(V(n)):F(n)?Un(dt(n.availability)):null,seller:(n,e,t)=>R(n)?{identifier:t.storage.channel?.seller||n.seller.sellerId||""}:F(n)?{identifier:n.seller}:null,price:n=>R(n)?G(n):F(n)?n.sellingPrice/100:null,priceWithTaxes:n=>R(n)?x(G(n),n?.Tax,n.product.unitMultiplier):F(n)?x(n.sellingPrice/100,n.tax/100,n.unitMultiplier):null,sellingPrice:n=>R(n)?lt(n):F(n)?n.sellingPrice/100:null,listPrice:n=>R(n)?n.ListPrice??0:F(n)?n.listPrice/100:null,listPriceWithTaxes:n=>R(n)?x(n.ListPrice??0,n?.Tax,n.product.unitMultiplier):F(n)?x(n.listPrice/100,n.tax/100,n.unitMultiplier):null,itemOffered:n=>R(n)?n.product:F(n)?{...n.product,attachmentsValues:n.attachments}:null,quantity:n=>R(n)?n.AvailableQuantity??0:F(n)?n.quantity:null,isGift:n=>F(n)?n.isGift??!1:null},Kt=({linkText:n})=>`/${n}/p`,Qt=({offer:n,seller:e,product:t})=>({...n,product:t,seller:e}),Zt={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},Oe=(n,e)=>`${n}-${e}`,nr=(n,e)=>`/${Oe(n,e)}/p`,er=n=>Array.isArray(n)&&n.length>0?n:null;function Ce(n){return n.replace(/^\/+|\/+$/g,"")}const tr=(n,e)=>{const t=n.findIndex(r=>Ce(r).split("/").at(-1)===e);return t<0?0:t},rr={productID:({itemId:n})=>n,name:({isVariantOf:n,name:e})=>e??n.productName,slug:({isVariantOf:{linkText:n},itemId:e})=>Oe(n,e),description:({isVariantOf:{description:n}})=>n,seo:({isVariantOf:n})=>({title:n.productTitle||n.productName,description:n.metaTagDescription||n.description,canonical:Kt(n)}),brand:({isVariantOf:{brand:n}})=>({name:n}),unitMultiplier:({unitMultiplier:n})=>n,breadcrumbList:({isVariantOf:{categories:n,productName:e,linkText:t,categoryId:r,categoriesIds:i},itemId:a})=>{const o=tr(i,r),s=n[o],c=Ce(s).split("/");return{itemListElement:[...c.map((d,p)=>{const m=`/${c.slice(0,p+1).map(ce).join("/")}/`;return{name:d,item:m,position:p+1}}),{name:e,item:nr(t,a),position:c.length+1}],numberOfItems:c.length}},image:({images:n},e)=>{const t=(er(n)??[Zt]).map(({imageUrl:s,imageText:c,imageLabel:d})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:d}));if(typeof e!="object")return t;let{context:r,limit:i}=e;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:n})=>n,gtin:({ean:n,referenceId:e})=>n||(e[0]?.Value??""),mpn:({isVariantOf:{manufacturerCode:n}})=>n??"",review:()=>[],aggregateRating:()=>({}),offers:n=>n.sellers.map(e=>Qt({offer:e.commertialOffer,seller:e,product:n})).sort(se),isVariantOf:n=>n,additionalProperty:({variations:n=[],attachmentsValues:e=[],attributes:t=[]})=>{const r=n.flatMap(({name:o,values:s})=>s.map(c=>({name:o,value:c,valueReference:Q.specification}))),i=e.map(ge),a=t.map(kt);return[...r,...i,...a]},hasSpecifications:({isVariantOf:n})=>!!n.skuSpecifications?.length,skuSpecifications:({isVariantOf:{skuSpecifications:n}})=>n??[],specificationGroups:({isVariantOf:{specificationGroups:n}})=>n,releaseDate:({isVariantOf:{releaseDate:n}})=>n??"",advertisement:({isVariantOf:{advertisement:n}})=>n,deliveryPromiseBadges:({isVariantOf:{deliveryPromisesBadges:n}})=>n},ir=new Set(["allSpecifications"]),ar={hasVariant:n=>n.isVariantOf.items.map(e=>M(e,n.isVariantOf)),productGroupID:({isVariantOf:n})=>n.productId,name:n=>n.isVariantOf.productName,skuVariants:n=>n,additionalProperty:({isVariantOf:{specificationGroups:n}})=>n.filter(e=>!ir.has(e.name)).flatMap(({specifications:e})=>e.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:Q.specification}))))},or={propertyID:n=>n.propertyID||me(n),name:({name:n})=>n,value:({value:n})=>n,valueReference:({valueReference:n})=>n},bn=n=>{const e=n.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=yn(e,({offer:r},{offer:i})=>se(r,i));return t?t.sku:n[0]},sr=n=>n!==""&&!Number.isNaN(Number(n)),cr={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:""},lr={product:async(n,{locator:e},t)=>{const r=Fn(e),i=Nn(e),a=vt(e),o=It(e);r&&In(t,r),i&&vn(t,i);const{loaders:{skuLoader:s},clients:{commerce:c,search:d}}=t;try{const p=a??o?.split("-").pop()??"";if(!sr(p))throw new Error("Invalid SkuId");const m=await s.load(p);if(o&&m.isVariantOf.linkText&&!o.startsWith(m.isVariantOf.linkText))throw new Error(`Slug was set but the fetched sku does not satisfy the slug condition. slug: ${o}, linkText: ${m.isVariantOf.linkText}`);return m}catch{if(o==null)throw new $("Missing slug or id");const m=await c.catalog.portal.pagetype(`${o}/p`);if(m.pageType!=="Product"||!m.id)throw new B(`No product found for slug ${o}`);const{products:[u]}=await d.products({page:0,count:1,query:`product:${m.id}`,hideUnavailableItems:!1});if(!u)throw new B(`No product found for id ${m.id}`);const l=bn(u.items);return M(l,u)}},collection:(n,{slug:e},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load(e)},search:async(n,{first:e,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=Fn(a),d=Nn(a),p=yt(a);c&&In(s,c),d&&vn(s,d);let m=i;p&&(m=`product:${(await s.clients.commerce.catalog.products.crossselling({type:de[p.key],productId:p.value})).map(S=>S.productId).slice(0,e).join(";")}`);const u=t?Number(t):0,l={page:Math.ceil(u/e)||0,count:e,query:m??void 0,sort:cr[r??"score_desc"],selectedFacets:a?.flatMap(_n)??[],sponsoredCount:o??void 0},g=s.clients.search.products(l);return{searchArgs:l,productSearchPromise:g}},allProducts:async(n,{first:e,after:t},r)=>{const{clients:{search:i}}=r,a=t?Number(t):0,o=await i.products({page:Math.ceil(a/e),count:e}),s=o.products.flatMap(c=>c.items.map(d=>M(d,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,d)=>({node:c,cursor:(a+d).toString()}))}},products:async(n,{productIds:e},t)=>{const{clients:{search:r}}=t;if(!e.length)return[];const i=`id:${e.join(";")}`;return(await r.products({page:0,count:e.length,query:i})).products.flatMap(o=>o.items.map(s=>M(s,o))).filter(o=>e.includes(o.itemId)&&o.sellers.length>0)},allCollections:async(n,{first:e,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=[],d=(u,l)=>{c.push({...u,level:l});for(const g of u.children)d(g,l+1)};for(const u of s)d(u,0);const m=[...o.filter(u=>u.isActive).map(u=>({...u,type:"brand"})),...c].filter(u=>!!le.slug(u,null,r,null));return{pageInfo:{hasNextPage:m.length-a>e,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(e,m.length-a)-1).toString(),totalCount:m.length},edges:m.slice(a,a+e).map((u,l)=>({node:u,cursor:(a+l).toString()}))}},shipping:async(n,{country:e,items:t,postalCode:r},i)=>{const{loaders:{simulationLoader:a},clients:{commerce:o}}=i,[s,c]=await Promise.all([a.load({country:e,items:t,postalCode:r}),o.checkout.address({postalCode:r,country:e})]);return{...s,address:c}},redirect:async(n,{term:e,selectedFacets:t},r)=>{if(!e&&(!t||!t.length))return null;const{redirect:i}=await r.clients.search.products({page:1,count:1,query:e??void 0,selectedFacets:t?.flatMap(_n)??[],allowRedirect:!0});return{url:i}},sellers:async(n,{postalCode:e,geoCoordinates:t,country:r,salesChannel:i},a)=>{const{clients:{commerce:o}}=a,c=(await o.checkout.region({postalCode:e,geoCoordinates:t,country:r,salesChannel:i}))?.[0],{id:d,sellers:p}=c;return{id:d,sellers:p}},profile:async(n,{id:e},t)=>{const{clients:{commerce:r}}=t,i=await r.profile.addresses(e);function a(s){return!s||Object.keys(s).length===0?[]:Object.values(s).map(c=>JSON.parse(c))}return{addresses:a(i)}},productCount:async(n,{term:e},t)=>{const{clients:{search:r}}=t;return await r.productCount({query:e??void 0})},userOrder:async(n,{orderId:e},t)=>{try{if(!e)throw new $("Missing orderId");const{clients:{commerce:r}}=t,i=await r.oms.userOrder({orderId:e});if(!i)throw new B(`No order found for id ${e}`);let a=null;try{const c=await r.oms.getCommercialAuthorizationsByOrderId({orderId:e});a=ue(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 te(r)?new B(`No order found for id ${e}. ${o}.`):ee(r)?new K(`You are forbidden to interact with order with id ${e}. ${o}.`):r}},listUserOrders:async(n,e,t)=>{const{clients:{commerce:r}}=t,i=await r.oms.listUserOrders(e);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}},validateUser:async(n,e,t)=>({isValid:!0}),userDetails:async(n,e,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=tn(en(i?.cookie??"",r))?.userId??"",[c,d,p]=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)]),m=d?.[0],u=c?.namespaces.authentication??null,l=`${(m?.firstName??"").trim()} ${(m?.lastName??"").trim()}`.trim();return{username:u?.storeUserEmail?.value??"",name:l,email:u?.storeUserEmail?.value??"",phone:m?.phone??"",role:p?.Roles?.map(g=>g.Name)??[],orgUnit:u?.unitName?.value??""}},accountProfile:async(n,e,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=tn(en(i?.cookie??"",r));if(!o?.userId)return null;if(o?.isRepresentative){const c=await a.session("").catch(()=>null);if(!c)return null;const d=c.namespaces.profile??null;return{name:((await a.masterData.getContractById({contractId:d?.id?.value??""}))?.corporateName??`${(d?.firstName?.value??"").trim()} ${(d?.lastName?.value??"").trim()}`.trim())||"",email:d?.email?.value||"",id:d?.id?.value||""}}const s=await a.licenseManager.getUserById({userId:o?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},pickupPoints:async(n,{geoCoordinates:e},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:e})}},dr={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},ur=(n,e,t)=>e?n.key==="category-1":t?n.key==="brand":!1,pr={suggestions:async(n,e,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=n;if(!i.query)return{terms:(await r.topSearches()).searches.map(m=>({value:m.term,count:m.count})),products:[]};const{productSearchPromise:a}=n,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(p=>{const m=bn(p.items);return m&&M(m,p)}).filter(p=>!!p),{searches:d}=o;return{terms:d.map(p=>({value:p.term,count:p.count})),products:c}},products:async({productSearchPromise:n})=>{const e=await n,t=e.products.map(r=>{const i=bn(r.items);return i&&M(i,r)}).filter(r=>!!r);return{pageInfo:{hasNextPage:e.pagination.after.length>0,hasPreviousPage:e.pagination.before.length>0,startCursor:"0",endCursor:e.recordsFiltered.toString(),totalCount:e.recordsFiltered},edges:t.map((r,i)=>({node:r,cursor:i.toString()}))}},facets:async({searchArgs:n},e,t)=>{const{clients:{search:r}}=t;t.storage.searchArgs=n;const{facets:i=[]}=await r.facets(n),a=!n.query,o=n.selectedFacets?.length?n.selectedFacets[0].key==="category-1":!1,s=n.selectedFacets?.length?n.selectedFacets[0].key==="brand":!1;return i.filter(d=>!a||!ur(d,o,s))},metadata:async({productSearchPromise:n})=>{const e=await n;return{isTermMisspelled:e.correction?.misspelled??!1,logicalOperator:e.operator,fuzzy:e.fuzzy}},searchId:async({productSearchPromise:n})=>(await n).searchId},gr={title:({title:n})=>n??"",description:({description:n})=>n??"",canonical:({canonical:n})=>n??"",titleTemplate:()=>""},mr=["bd","d","h","m"],hr=n=>mr.includes(n),fr={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"}},be=n=>{const[e,t]=[n.split(/\D+/)[0],n.split(/[0-9]+/)[1]],r=e!==""&&!Number.isNaN(Number(e)),i=hr(t);if(!r||!i)return"";const a=Number(e)<2?Number(e):"other";return fr[t][a].replace("#",e)??""},Sr={carrier:n=>n?.friendlyName??n?.name??"",price:n=>n?.price?n.price/100:n?.price,localizedEstimates:n=>n?.shippingEstimate?be(n.shippingEstimate):""},zn="skuvariation";function Vn(n,e){const t=`${zn}${e}`.toLowerCase(),r=n.find(a=>a.imageLabel===t);if(r)return r;const i=n.find(a=>a.imageLabel===zn);return i||n[0]}function yr(n,e,t){const r={};return n.forEach(i=>{const a=i.variations;if(a.length===0)return;const o=`${e}-${a.find(c=>c.name===e)?.values[0]??""}`,s=a.reduce((c,d)=>d.name===e?c:c+`-${d.name}-${d.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function qn(n){const e={};return n.forEach(t=>{e[t.name]=t.values[0]}),e}function Ir(n){const e={};return n?.forEach(t=>{e[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),e}function vr(n,e){return Number.isNaN(Number(n)-Number(e))?n<e?-1:n>e?1:0:Number(n)-Number(e)}function Or(n){const e=n;for(const t in n)n[t].every(i=>!Number.isNaN(Number(i.value)))&&n[t].sort((i,a)=>vr(i.value,a.value));return e}function Cr(n,e,t){const r={},i=new Set;return n.forEach(a=>{if(a.variations.length===0)return;const o=a.variations.find(c=>c.name===e);if(!(o?.values[0]===t)){const c=`${e}-${o?.values[0]}`;if(!o||i.has(c))return;i.add(c);const d=Vn(a.images,e),p={src:d.imageUrl,alt:d.imageLabel??"",label:`${e}: ${o.values[0]}`,value:o.values[0]};r[o.name]?r[o.name].push(p):r[o.name]=[p];return}a.variations.forEach(c=>{const d=`${c.name}-${c.values[0]}`;if(i.has(d))return;i.add(d);const p=Vn(a.images,c.name),m={src:p.imageUrl,alt:p.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(m):r[c.name]=[m]})}),Or(r)}const br={activeVariations:n=>qn(n.variations),allVariantsByName:n=>Ir(n.isVariantOf.skuSpecifications),slugsMap:(n,e)=>yr(n.isVariantOf.items,e.dominantVariantName??n.variations[0]?.name,n.isVariantOf.linkText),availableVariations:(n,e)=>{const t=e.dominantVariantName??n.variations[0]?.name,i=qn(n.variations)[t];return Cr(n.isVariantOf.items,t,i)},allVariantProducts:n=>n.isVariantOf.items.map(e=>M(e,n.isVariantOf))},Dr={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},wr={deliveryOptionsData:n=>{const{shippingData:e,items:t}=n,r=e?.logisticsInfo||[],i=e?.selectedAddresses||e?.availableAddresses||[e?.address],a=r.reduce((d,p)=>{const m=p?.selectedSla||"",u=p?.selectedDeliveryChannel||p?.deliveryChannel||"",l=p?.deliveryCompany||"",g=p?.deliveryWindow,f=p?.pickupStoreInfo,S=p?.shippingEstimate||"",O=p?.shippingEstimate?be(p?.shippingEstimate):"",D=p?.shippingEstimateDate||"",A=p?.addressId||"",_=p?.itemIndex??0,v=t?.[_],U=v?.seller||"",h=`${m}|${u}|${l}|${U}|${S}|${D}|${A}|${g?.startDateUtc}|${g?.endDateUtc}`,C=i?.find(P=>P?.addressId===A),b=`${Dr[u]||""} ${O} ${C?.neighborhood?`to ${C?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:k,taxPriceTags:y}=Ar(v?.priceTags??[]),w=(v?.sellingPrice??0)*(v?.quantity??0)+(v?.tax??0)+(k??0);return d[h]||(d[h]={selectedSla:m,deliveryChannel:u,deliveryCompany:l,deliveryWindow:g,shippingEstimate:S,shippingEstimateDate:D,seller:U,friendlyShippingEstimate:O,friendlyDeliveryOptionName:b,address:C,pickupStoreInfo:f,quantityOfDifferentItems:0,total:0,items:[]}),d[h]&&(d[h].items?.push({id:v?.id||"",uniqueId:v?.uniqueId||"",name:v?.name||"",quantity:v?.quantity||0,price:v?.price||0,sellingPrice:v?.sellingPrice||0,imageUrl:v?.imageUrl||"",taxPriceTags:y??[],taxPriceTagsTotal:k??0,tax:v?.tax||0,total:w}),d[h].quantityOfDifferentItems=(d[h].quantityOfDifferentItems??0)+1,d[h].total=(d[h].total??0)+w),d},{}),o=Object.values(a),s=e?.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:n=>{const e=n?.customData?.customFields||[];return Object.values(e.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 Ar(n){const t=n.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 Pr={StoreCollection:le,StoreAggregateOffer:pt,StoreProduct:rr,StoreSeo:gr,StoreFacet:Ot,StoreFacetBoolean:Ct,StoreFacetRange:bt,StoreFacetValueBoolean:Dt,StoreOffer:Jt,StoreAggregateRating:gt,StoreReview:dr,StoreProductGroup:ar,StoreSearchResult:pr,StorePropertyValue:or,SkuVariants:br,ShippingSLA:Sr,UserOrderResult:wr,ObjectOrString:Yt,Query:lr,Mutation:Gt},Ur=()=>Pr,kr=`"""
|
|
5
|
+
More info at: https://developers.vtex.com/vtex-rest-api/docs/customizable-fields-with-checkout-api`),r}},qt=(e,n)=>{const r=e.customData?.customApps.find(a=>a.id==="faststore")?.fields?.cartEtag;return r==null?!0:In(e,n)!==r},xt=async(e,{clients:{commerce:n}})=>n.checkout.clearOrderFormMessages({id:e}),Be=async(e,n,{clients:{commerce:t}})=>{if(!n)return e;const{updateShipping:r,addressChanged:i}=hn(e,n);if(r){const a=Ft(e,n,i),s=a||kt(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},jt=(e,n)=>{if(!e)return"";const r=ae.parse(e)[n];return r?r.split("=")[1]:""},Wt=async(e,{cart:{order:n},session:t},r)=>{const i=jt(r.headers.cookie,"checkout.vtex.com"),{clients:{commerce:a},loaders:{skuLoader:o}}=r,s=t?.channel,c=t?.locale;s&&ye(r,s),c&&Ie(r,c);const u=await a.checkout.orderForm({id:i||void 0,channel:r.storage.channel}),g=u.orderFormId;u.messages.length!==0&&await xt(g,r);const m=ae.parse(r?.headers?.cookie??"")?.vtex_session,d=te(m),{acceptedOffer:l,shouldSplitItem:p}=n;if(qt(u,d)){const y=await Me(u,a,d).then(Re);if(g)return Le(y,o,p)}const S=Ne(l),v=Ne(u.items.map(ie)),w=Array.from(v.entries()),P=Array.from(S.entries()),{itemsToAdd:_,itemsToUpdate:O}=P.reduce((y,[A,T])=>{const F=v.get(A);if(!F)return T.forEach(z=>y.itemsToAdd.push(z)),y;const[U,...X]=F;if(yn(u.items,U.itemOffered.sku)||Sn(u.items,U.itemOffered.sku))return y.itemsToUpdate.push(U),y;const N=T.reduce((z,q)=>z+q.quantity,0);return y.itemsToUpdate.push({...U,quantity:N}),X.forEach(z=>y.itemsToUpdate.push({...z,quantity:0})),y},{itemsToAdd:[],itemsToUpdate:[]}),E=w.filter(([y])=>!S.has(y)).flatMap(([,y])=>y.map(A=>({...A,quantity:0}))),h=[..._,...O,...E].map(zt),{updateShipping:C}=t?hn(u,t):{updateShipping:!1};if(h.length===0&&!C)return null;let b;h.length>0?b=await a.checkout.updateOrderFormItems({id:u.orderFormId,orderItems:h,shouldSplitItem:p}).then(y=>Be(y,t,r)):b=await Be(u,t,r),b=await Promise.resolve(b).then(y=>{if(t?.marketingData){const A={...y.marketingData,...t.marketingData};return a.checkout.marketingData({id:u.orderFormId,marketingData:A})}return y}).then(y=>c&&y.clientPreferencesData?.locale!==c?a.checkout.clientPreferencesData({id:y.orderFormId,clientPreferencesData:{...y.clientPreferencesData,locale:c}}):y).then(y=>Me(y,a,d)).then(Re);const D=be(u.messages,b.messages);return Vt(n,b)&&D?null:Le(b,o,p)};async function Gt(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}).
|
|
6
|
+
`),r}}const Ht=async(e,{session:n,search:t},{clients:r,headers:i,account:a})=>{const o=re.parse(n.channel??""),s=String(n.postalCode??""),c=n.country??"";let u=n.city??null,g=n.geoCoordinates??null;if((!u||!g)&&s!==""&&c!==""){const U=await Gt(r,c,s);u=U.city,g=U.geoCoordinates}const d=new URLSearchParams(t);d.has("facets")&&d.delete("facets");const l=d.get("sc")??o.salesChannel;d.set("sc",l),s&&d.set("postalCode",s),c&&d.set("country",c),g&&d.set("geoCoordinates",`${g.longitude},${g.latitude}`),d.set("locale",n.locale);const{marketingData:p}=n,f={utmCampaign:d.get("utm_campaign")??p?.utmCampaign??"",utmMedium:d.get("utm_medium")??p?.utmMedium??"",utmSource:d.get("utm_source")??p?.utmSource??"",utmiCampaign:d.get("utmi_cp")??p?.utmiCampaign??"",utmiPage:d.get("utmi_p")??p?.utmiPage??"",utmiPart:d.get("utmi_pc")??p?.utmiPart??""},S=te(ne(i?.cookie??"",a));let v=!1;if(S)try{v=(await r.commerce.vtexid.validate())?.authStatus?.toLowerCase()==="success"}catch(U){console.warn("JWT validation failed:",U),v=!1}const w=v?S?.isRepresentative:!1,P=v?S?.customerId:void 0,_=v?S?.unitId:void 0,O=await r.commerce.session(d.toString()).catch(()=>null),E=O?.namespaces.profile??null,h=O?.namespaces.shopper??null,C=O?.namespaces.store??null,b=O?.namespaces.authentication??null,D=O?.namespaces.checkout??null,y=O?.namespaces.public??null;let A=null;if(w&&E?.id?.value)try{A=await r.commerce.masterData.getContractById({contractId:E.id.value})}catch{console.error(`Error while getting contract data for profile ID (${E.id.value}).
|
|
7
|
+
`)}let T;o.seller&&(s||g)&&(T=(await r.commerce.checkout.region({postalCode:s,geoCoordinates:g,country:c,salesChannel:l}))?.[0]?.sellers.find(N=>o.seller===N.id));const F={...n,currency:{code:C?.currencyCode?.value??n.currency.code,symbol:C?.currencySymbol?.value??n.currency.symbol},country:C?.countryCode?.value??c,channel:re.stringify({salesChannel:C?.channel?.value??o.salesChannel,regionId:D?.regionId?.value??o.regionId,seller:T?.id,hasOnlyDefaultSalesChannel:!C?.channel?.value}),b2b:w?{isRepresentative:w??!1,customerId:b?.customerId?.value??P??"",unitName:b?.unitName?.value??"",unitId:b?.unitId?.value??_??"",firstName:typeof h?.firstName?.value=="string"?h.firstName.value:"",lastName:typeof h?.lastName?.value=="string"?h.lastName.value:"",userName:`${typeof h?.firstName?.value=="string"?h.firstName.value:""} ${typeof h?.lastName?.value=="string"?h.lastName.value:""}`.trim(),userEmail:b?.storeUserEmail.value??"",savedPostalCode:y?.postalCode?.value??"",contractName:A?.corporateName??"",organizationManager:h?.organizationManager?.value??!1}:null,marketingData:f,person:E?.id?{id:E.id?.value??"",email:E.email?.value??"",givenName:E.firstName?.value??"",familyName:E.lastName?.value??""}:null,geoCoordinates:g?.latitude&&g?.longitude&&g||null,city:u};return be(n,F)?null:F},Xt={validateCart:Wt,validateSession:Ht,subscribeToNewsletter:Tt,cancelOrder:Dt,processOrderAuthorization:Pt,uploadFileToOrderEntry:_t,startOrderEntryOperation:Et};var Oe;(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"})(Oe||(Oe={}));const Yt=e=>typeof e=="string"?vn(e):null;function vn(e){try{return JSON.parse(e)}catch{return e}}const Jt=e=>typeof e=="object"?JSON.stringify(e):typeof e=="string"?e:null,Kt=new ee.GraphQLScalarType({name:"ObjectOrString",description:"A string or the string representation of an object (a stringified object).",parseValue:Yt,serialize:Jt,parseLiteral(e){return e.kind===Oe.STRING?vn(e.value):null}}),L=e=>"Price"in e&&"seller"in e&&"product"in e,R=e=>"skuName"in e,Qt={priceCurrency:async(e,n,t)=>{const{loaders:{salesChannelLoader:r},storage:{channel:i}}=t;return(await r.load(i.salesChannel)).CurrencyCode??""},priceValidUntil:e=>L(e)?e.PriceValidUntil??"":R(e)?e.priceValidUntil??"":null,itemCondition:()=>"https://schema.org/NewCondition",availability:async e=>L(e)?Pe(V(e)):R(e)?Pe(dt(e.availability)):null,seller:(e,n,t)=>L(e)?{identifier:t.storage.channel?.seller||e.seller.sellerId||""}:R(e)?{identifier:e.seller}:null,price:e=>L(e)?G(e):R(e)?e.sellingPrice/100:null,priceWithTaxes:e=>L(e)?x(G(e),e?.Tax,e.product.unitMultiplier):R(e)?x(e.sellingPrice/100,e.tax/100,e.unitMultiplier):null,sellingPrice:e=>L(e)?lt(e):R(e)?e.sellingPrice/100:null,listPrice:e=>L(e)?e.ListPrice??0:R(e)?e.listPrice/100:null,listPriceWithTaxes:e=>L(e)?x(e.ListPrice??0,e?.Tax,e.product.unitMultiplier):R(e)?x(e.listPrice/100,e.tax/100,e.unitMultiplier):null,itemOffered:e=>L(e)?e.product:R(e)?{...e.product,attachmentsValues:e.attachments}:null,quantity:e=>L(e)?e.AvailableQuantity??0:R(e)?e.quantity:null,isGift:e=>R(e)?e.isGift??!1:null},Zt=({linkText:e})=>`/${e}/p`,er=({offer:e,seller:n,product:t})=>({...e,product:t,seller:n}),nr={imageText:"image",imageUrl:"https://storecomponents.vtexassets.com/assets/faststore/images/image___117a6d3e229a96ad0e0d0876352566e2.svg",imageLabel:"label"},On=(e,n)=>`${e}-${n}`,tr=(e,n)=>`/${On(e,n)}/p`,rr=e=>Array.isArray(e)&&e.length>0?e:null;function Cn(e){return e.replace(/^\/+|\/+$/g,"")}const ir=(e,n)=>{const t=e.findIndex(r=>Cn(r).split("/").at(-1)===n);return t<0?0:t},ar={productID:({itemId:e})=>e,name:({isVariantOf:e,name:n})=>n??e.productName,slug:({isVariantOf:{linkText:e},itemId:n})=>On(e,n),description:({isVariantOf:{description:e}})=>e,seo:({isVariantOf:e})=>({title:e.productTitle||e.productName,description:e.metaTagDescription||e.description,canonical:Zt(e)}),brand:({isVariantOf:{brand:e}})=>({name:e}),unitMultiplier:({unitMultiplier:e})=>e,breadcrumbList:({isVariantOf:{categories:e,productName:n,linkText:t,categoryId:r,categoriesIds:i},itemId:a})=>{const o=ir(i,r),s=e[o],c=Cn(s).split("/");return{itemListElement:[...c.map((u,g)=>{const m=`/${c.slice(0,g+1).map(cn).join("/")}/`;return{name:u,item:m,position:g+1}}),{name:n,item:tr(t,a),position:c.length+1}],numberOfItems:c.length}},image:({images:e},n)=>{const t=(rr(e)??[nr]).map(({imageUrl:s,imageText:c,imageLabel:u})=>({alternateName:c??"",url:s.replace("vteximg.com.br","vtexassets.com"),keywords:u}));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=>er({offer:n.commertialOffer,seller:n,product:e})).sort(sn),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:Q.specification}))),i=n.map(gn),a=t.map(Ut);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},or=new Set(["allSpecifications"]),sr={hasVariant:e=>e.isVariantOf.items.map(n=>$(n,e.isVariantOf)),productGroupID:({isVariantOf:e})=>e.productId,name:e=>e.isVariantOf.productName,skuVariants:e=>e,additionalProperty:({isVariantOf:{specificationGroups:e}})=>e.filter(n=>!or.has(n.name)).flatMap(({specifications:n})=>n.flatMap(({name:t,values:r})=>r.map(i=>({name:t,value:i,valueReference:Q.specification}))))},cr={propertyID:e=>e.propertyID||mn(e),name:({name:e})=>e,value:({value:e})=>e,valueReference:({valueReference:e})=>e},lr=async(e,{operationId:n},{clients:{commerce:t}})=>{if(!n)throw new k("Missing operationId");return t.orderEntry.getOperation({operationId:n})},dr=async(e,{orderFormId:n},{clients:{commerce:t}})=>{if(!n)throw new k("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}))},Ce=e=>{const n=e.flatMap(r=>r.sellers.map(i=>({offer:i.commertialOffer,sku:r}))),t=Se(n,({offer:r},{offer:i})=>sn(r,i));return t?t.sku:e[0]},ur=e=>e!==""&&!Number.isNaN(Number(e)),pr={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:""},gr={product:async(e,{locator:n},t)=>{const r=Fe(n),i=ke(n),a=vt(n),o=It(n);r&&ye(t,r),i&&Ie(t,i);const{loaders:{skuLoader:s},clients:{commerce:c,search:u}}=t;try{const g=a??o?.split("-").pop()??"";if(!ur(g))throw new Error("Invalid SkuId");const m=await s.load(g);if(o&&m.isVariantOf.linkText&&!o.startsWith(m.isVariantOf.linkText))throw new Error(`Slug was set but the fetched sku does not satisfy the slug condition. slug: ${o}, linkText: ${m.isVariantOf.linkText}`);return m}catch{if(o==null)throw new k("Missing slug or id");const m=await c.catalog.portal.pagetype(`${o}/p`);if(m.pageType!=="Product"||!m.id)throw new B(`No product found for slug ${o}`);const{products:[d]}=await u.products({page:0,count:1,query:`product:${m.id}`,hideUnavailableItems:!1});if(!d)throw new B(`No product found for id ${m.id}`);const l=Ce(d.items);return $(l,d)}},collection:(e,{slug:n},t)=>{const{loaders:{collectionLoader:r}}=t;return r.load(n)},search:async(e,{first:n,after:t,sort:r,term:i,selectedFacets:a,sponsoredCount:o},s)=>{const c=Fe(a),u=ke(a),g=yt(a);c&&ye(s,c),u&&Ie(s,u);let m=i;g&&(m=`product:${(await s.clients.commerce.catalog.products.crossselling({type:dn[g.key],productId:g.value})).map(S=>S.productId).slice(0,n).join(";")}`);const d=t?Number(t):0,l={page:Math.ceil(d/n)||0,count:n,query:m??void 0,sort:pr[r??"score_desc"],selectedFacets:a?.flatMap(_e)??[],sponsoredCount:o??void 0},p=s.clients.search.products(l);return{searchArgs:l,productSearchPromise:p}},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(u=>$(u,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,u)=>({node:c,cursor:(a+u).toString()}))}},products:async(e,{productIds:n},t)=>{const{clients:{search:r}}=t;if(!n.length)return[];const i=`id:${n.join(";")}`;return(await r.products({page:0,count:n.length,query:i})).products.flatMap(o=>o.items.map(s=>$(s,o))).filter(o=>n.includes(o.itemId)&&o.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=[],u=(d,l)=>{c.push({...d,level:l});for(const p of d.children)u(p,l+1)};for(const d of s)u(d,0);const m=[...o.filter(d=>d.isActive).map(d=>({...d,type:"brand"})),...c].filter(d=>!!ln.slug(d,null,r,null));return{pageInfo:{hasNextPage:m.length-a>n,hasPreviousPage:a>0,startCursor:"0",endCursor:(Math.min(n,m.length-a)-1).toString(),totalCount:m.length},edges:m.slice(a,a+n).map((d,l)=>({node:d,cursor:(a+l).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(_e)??[],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:u,sellers:g}=c;return{id:u,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 k("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=un(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 nn(r)?new B(`No order found for id ${n}. ${o}.`):en(r)?new K(`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}},validateUser:async(e,n,t)=>({isValid:!0}),userDetails:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,s=te(ne(i?.cookie??"",r))?.userId??"",[c,u,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)]),m=u?.[0],d=c?.namespaces.authentication??null,l=`${(m?.firstName??"").trim()} ${(m?.lastName??"").trim()}`.trim();return{username:d?.storeUserEmail?.value??"",name:l,email:d?.storeUserEmail?.value??"",phone:m?.phone??"",role:g?.Roles?.map(p=>p.Name)??[],orgUnit:d?.unitName?.value??""}},accountProfile:async(e,n,t)=>{const{account:r,headers:i,clients:{commerce:a}}=t,o=te(ne(i?.cookie??"",r));if(!o?.userId)return null;if(o?.isRepresentative){const c=await a.session("").catch(()=>null);if(!c)return null;const u=c.namespaces.profile??null;return{name:((await a.masterData.getContractById({contractId:u?.id?.value??""}))?.corporateName??`${(u?.firstName?.value??"").trim()} ${(u?.lastName?.value??"").trim()}`.trim())||"",email:u?.email?.value||"",id:u?.id?.value||""}}const s=await a.licenseManager.getUserById({userId:o?.userId}).catch(()=>null);return{name:s?.name||"",email:s?.email||"",id:s?.id||""}},pickupPoints:async(e,{geoCoordinates:n},t)=>{const{clients:{commerce:r}}=t;return await r.checkout.pickupPoints({geoCoordinates:n})},orderEntryOperation:lr,orderFormItems:dr},mr={reviewRating:()=>({ratingValue:5,bestRating:5}),author:()=>({name:""})},hr=(e,n,t)=>n?e.key==="category-1":t?e.key==="brand":!1,fr={suggestions:async(e,n,t)=>{const{clients:{search:r}}=t,{searchArgs:i}=e;if(!i.query)return{terms:(await r.topSearches()).searches.map(m=>({value:m.term,count:m.count})),products:[]};const{productSearchPromise:a}=e,[o,s]=await Promise.all([r.suggestedTerms(i),a]),c=s.products.map(g=>{const m=Ce(g.items);return m&&$(m,g)}).filter(g=>!!g),{searches:u}=o;return{terms:u.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=Ce(r.items);return i&&$(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(u=>!a||!hr(u,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},Sr={title:({title:e})=>e??"",description:({description:e})=>e??"",canonical:({canonical:e})=>e??"",titleTemplate:()=>""},yr=["bd","d","h","m"],Ir=e=>yr.includes(e),vr={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=Ir(t);if(!r||!i)return"";const a=Number(n)<2?Number(n):"other";return vr[t][a].replace("#",n)??""},Or={carrier:e=>e?.friendlyName??e?.name??"",price:e=>e?.price?e.price/100:e?.price,localizedEstimates:e=>e?.shippingEstimate?bn(e.shippingEstimate):""},$e="skuvariation";function ze(e,n){const t=`${$e}${n}`.toLowerCase(),r=e.find(a=>a.imageLabel===t);if(r)return r;const i=e.find(a=>a.imageLabel===$e);return i||e[0]}function Cr(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,u)=>u.name===n?c:c+`-${u.name}-${u.values[0]}`,o);r[s]=`${t}-${i.itemId}`}),r}function Ve(e){const n={};return e.forEach(t=>{n[t.name]=t.values[0]}),n}function br(e){const n={};return e?.forEach(t=>{n[t.field.originalName??t.field.name]=t.values.map(r=>r.originalName??r.name)}),n}function wr(e,n){return Number.isNaN(Number(e)-Number(n))?e<n?-1:e>n?1:0:Number(e)-Number(n)}function Dr(e){const n=e;for(const t in e)e[t].every(i=>!Number.isNaN(Number(i.value)))&&e[t].sort((i,a)=>wr(i.value,a.value));return n}function Ar(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 u=ze(a.images,n),g={src:u.imageUrl,alt:u.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 u=`${c.name}-${c.values[0]}`;if(i.has(u))return;i.add(u);const g=ze(a.images,c.name),m={src:g.imageUrl,alt:g.imageText??"",label:`${c.name}: ${c.values[0]}`,value:c.values[0]};r[c.name]?r[c.name].push(m):r[c.name]=[m]})}),Dr(r)}const Pr={activeVariations:e=>Ve(e.variations),allVariantsByName:e=>br(e.isVariantOf.skuSpecifications),slugsMap:(e,n)=>Cr(e.isVariantOf.items,n.dominantVariantName??e.variations[0]?.name,e.isVariantOf.linkText),availableVariations:(e,n)=>{const t=n.dominantVariantName??e.variations[0]?.name,i=Ve(e.variations)[t];return Ar(e.isVariantOf.items,t,i)},allVariantProducts:e=>e.isVariantOf.items.map(n=>$(n,e.isVariantOf))},Er={"pickup-in-point":"Pickup",delivery:"Delivery",pickup:"Pickup","take-away":"Take away","":""},Tr={deliveryOptionsData:e=>{const{shippingData:n,items:t}=e,r=n?.logisticsInfo||[],i=n?.selectedAddresses||n?.availableAddresses||[n?.address],a=r.reduce((u,g)=>{const m=g?.selectedSla||"",d=g?.selectedDeliveryChannel||g?.deliveryChannel||"",l=g?.deliveryCompany||"",p=g?.deliveryWindow,f=g?.pickupStoreInfo,S=g?.shippingEstimate||"",v=g?.shippingEstimate?bn(g?.shippingEstimate):"",w=g?.shippingEstimateDate||"",P=g?.addressId||"",_=g?.itemIndex??0,O=t?.[_],E=O?.seller||"",h=`${m}|${d}|${l}|${E}|${S}|${w}|${P}|${p?.startDateUtc}|${p?.endDateUtc}`,C=i?.find(T=>T?.addressId===P),b=`${Er[d]||""} ${v} ${C?.neighborhood?`to ${C?.neighborhood}`:""}`.trim(),{taxPriceTagsTotal:D,taxPriceTags:y}=_r(O?.priceTags??[]),A=(O?.sellingPrice??0)*(O?.quantity??0)+(O?.tax??0)+(D??0);return u[h]||(u[h]={selectedSla:m,deliveryChannel:d,deliveryCompany:l,deliveryWindow:p,shippingEstimate:S,shippingEstimateDate:w,seller:E,friendlyShippingEstimate:v,friendlyDeliveryOptionName:b,address:C,pickupStoreInfo:f,quantityOfDifferentItems:0,total:0,items:[]}),u[h]&&(u[h].items?.push({id:O?.id||"",uniqueId:O?.uniqueId||"",name:O?.name||"",quantity:O?.quantity||0,price:O?.price||0,sellingPrice:O?.sellingPrice||0,imageUrl:O?.imageUrl||"",taxPriceTags:y??[],taxPriceTagsTotal:D??0,tax:O?.tax||0,total:A}),u[h].quantityOfDifferentItems=(u[h].quantityOfDifferentItems??0)+1,u[h].total=(u[h].total??0)+A),u},{}),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 _r(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 Ur={StoreCollection:ln,StoreAggregateOffer:pt,StoreProduct:ar,StoreSeo:Sr,StoreFacet:Ot,StoreFacetBoolean:Ct,StoreFacetRange:bt,StoreFacetValueBoolean:wt,StoreOffer:Qt,StoreAggregateRating:gt,StoreReview:mr,StoreProductGroup:sr,StoreSearchResult:fr,StorePropertyValue:cr,SkuVariants:Pr,ShippingSLA:Or,UserOrderResult:Tr,ObjectOrString:Kt,Query:gr,Mutation:Xt},kr=()=>Ur,Fr=`"""
|
|
7
8
|
Address information.
|
|
8
9
|
"""
|
|
9
10
|
type Address {
|
|
@@ -48,7 +49,7 @@ type Address {
|
|
|
48
49
|
"""
|
|
49
50
|
geoCoordinates: [Float]
|
|
50
51
|
}
|
|
51
|
-
`,
|
|
52
|
+
`,Nr=`"""
|
|
52
53
|
Advertisement information about a specific product in a campaign
|
|
53
54
|
"""
|
|
54
55
|
type Advertisement {
|
|
@@ -73,7 +74,7 @@ type Advertisement {
|
|
|
73
74
|
"""
|
|
74
75
|
adResponseId: String!
|
|
75
76
|
}
|
|
76
|
-
`,
|
|
77
|
+
`,Rr=`"""
|
|
77
78
|
Aggregate offer information, for a given SKU that is available to be fulfilled by multiple sellers.
|
|
78
79
|
"""
|
|
79
80
|
type StoreAggregateOffer {
|
|
@@ -102,7 +103,7 @@ type StoreAggregateOffer {
|
|
|
102
103
|
"""
|
|
103
104
|
offers: [StoreOffer!]!
|
|
104
105
|
}
|
|
105
|
-
`,
|
|
106
|
+
`,Lr=`"""
|
|
106
107
|
Average rating, based on multiple ratings or reviews.
|
|
107
108
|
"""
|
|
108
109
|
type StoreAggregateRating {
|
|
@@ -115,7 +116,7 @@ type StoreAggregateRating {
|
|
|
115
116
|
"""
|
|
116
117
|
reviewCount: Int!
|
|
117
118
|
}
|
|
118
|
-
`,
|
|
119
|
+
`,Mr=`"""
|
|
119
120
|
information about the author of a product review or rating.
|
|
120
121
|
"""
|
|
121
122
|
type StoreAuthor {
|
|
@@ -124,7 +125,7 @@ type StoreAuthor {
|
|
|
124
125
|
"""
|
|
125
126
|
name: String!
|
|
126
127
|
}
|
|
127
|
-
`,
|
|
128
|
+
`,Br=`"""
|
|
128
129
|
Brand of a given product.
|
|
129
130
|
"""
|
|
130
131
|
type StoreBrand {
|
|
@@ -133,7 +134,7 @@ type StoreBrand {
|
|
|
133
134
|
"""
|
|
134
135
|
name: String!
|
|
135
136
|
}
|
|
136
|
-
|
|
137
|
+
`,$r=`"""
|
|
137
138
|
Item of a list.
|
|
138
139
|
"""
|
|
139
140
|
type StoreListItem {
|
|
@@ -164,7 +165,7 @@ type StoreBreadcrumbList {
|
|
|
164
165
|
"""
|
|
165
166
|
numberOfItems: Int!
|
|
166
167
|
}
|
|
167
|
-
`,
|
|
168
|
+
`,zr=`"""
|
|
168
169
|
Shopping cart message.
|
|
169
170
|
"""
|
|
170
171
|
type StoreCartMessage {
|
|
@@ -201,7 +202,7 @@ input IStoreCart {
|
|
|
201
202
|
"""
|
|
202
203
|
order: IStoreOrder!
|
|
203
204
|
}
|
|
204
|
-
`,
|
|
205
|
+
`,Vr=`"""
|
|
205
206
|
Product collection type. Possible values are \`Department\`, \`Category\`, \`Brand\`, \`Cluster\`, \`SubCategory\` or \`Collection\`.
|
|
206
207
|
"""
|
|
207
208
|
enum StoreCollectionType {
|
|
@@ -284,7 +285,7 @@ type StoreCollection {
|
|
|
284
285
|
"""
|
|
285
286
|
type: StoreCollectionType!
|
|
286
287
|
}
|
|
287
|
-
`,
|
|
288
|
+
`,qr=`"""
|
|
288
289
|
Delivery Promise badge.
|
|
289
290
|
"""
|
|
290
291
|
type DeliveryPromiseBadge {
|
|
@@ -293,7 +294,7 @@ type DeliveryPromiseBadge {
|
|
|
293
294
|
"""
|
|
294
295
|
typeName: String
|
|
295
296
|
}
|
|
296
|
-
|
|
297
|
+
`,xr=`union StoreFacet = StoreFacetRange | StoreFacetBoolean
|
|
297
298
|
|
|
298
299
|
"""
|
|
299
300
|
Search facet range information.
|
|
@@ -370,7 +371,7 @@ type StoreFacetValueBoolean {
|
|
|
370
371
|
"""
|
|
371
372
|
quantity: Int
|
|
372
373
|
}
|
|
373
|
-
`,
|
|
374
|
+
`,jr=`"""
|
|
374
375
|
Image.
|
|
375
376
|
"""
|
|
376
377
|
type StoreImage {
|
|
@@ -397,7 +398,7 @@ input IStoreImage {
|
|
|
397
398
|
"""
|
|
398
399
|
alternateName: String!
|
|
399
400
|
}
|
|
400
|
-
`,
|
|
401
|
+
`,Wr=`type Mutation {
|
|
401
402
|
"""
|
|
402
403
|
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\`.
|
|
403
404
|
"""
|
|
@@ -420,8 +421,22 @@ input IStoreImage {
|
|
|
420
421
|
processOrderAuthorization(
|
|
421
422
|
data: IProcessOrderAuthorization!
|
|
422
423
|
): ProcessOrderAuthorizationResponse
|
|
424
|
+
"""
|
|
425
|
+
Uploads a file to the Order Entry Service and returns the S3 object key.
|
|
426
|
+
The file must be Base64-encoded and passed via the \`data\` input.
|
|
427
|
+
The returned \`objectKey\` is required to start an order entry operation.
|
|
428
|
+
"""
|
|
429
|
+
uploadFileToOrderEntry(data: IOrderEntryUpload!): StoreOrderEntryUploadResult
|
|
430
|
+
@auth
|
|
431
|
+
"""
|
|
432
|
+
Submits an uploaded file for bulk import into a VTEX cart via the Order Entry Service.
|
|
433
|
+
Returns an operationId to poll for the operation status.
|
|
434
|
+
"""
|
|
435
|
+
startOrderEntryOperation(
|
|
436
|
+
data: IOrderEntryOperation!
|
|
437
|
+
): StoreOrderEntryOperationResult @auth
|
|
423
438
|
}
|
|
424
|
-
`,
|
|
439
|
+
`,Gr=`"""
|
|
425
440
|
Newsletter information.
|
|
426
441
|
"""
|
|
427
442
|
type PersonNewsletter {
|
|
@@ -444,8 +459,8 @@ input IPersonNewsletter {
|
|
|
444
459
|
"""
|
|
445
460
|
email: String!
|
|
446
461
|
}
|
|
447
|
-
`,
|
|
448
|
-
`,
|
|
462
|
+
`,Hr=`scalar ObjectOrString
|
|
463
|
+
`,Xr=`"""
|
|
449
464
|
Offer information.
|
|
450
465
|
"""
|
|
451
466
|
type StoreOffer {
|
|
@@ -528,7 +543,7 @@ input IStoreOffer {
|
|
|
528
543
|
"""
|
|
529
544
|
quantity: Int!
|
|
530
545
|
}
|
|
531
|
-
`,
|
|
546
|
+
`,Yr=`"""
|
|
532
547
|
Information of a specific order.
|
|
533
548
|
"""
|
|
534
549
|
type StoreOrder {
|
|
@@ -563,7 +578,7 @@ input IStoreOrder {
|
|
|
563
578
|
"""
|
|
564
579
|
shouldSplitItem: Boolean
|
|
565
580
|
}
|
|
566
|
-
`,
|
|
581
|
+
`,Jr=`"""
|
|
567
582
|
Commercial Authorization response.
|
|
568
583
|
"""
|
|
569
584
|
type CommercialAuthorizationResponse {
|
|
@@ -962,7 +977,68 @@ type ProcessOrderAuthorizationRule {
|
|
|
962
977
|
"""
|
|
963
978
|
rule: CommercialAuthorizationRule!
|
|
964
979
|
}
|
|
965
|
-
`,
|
|
980
|
+
`,Kr=`"""
|
|
981
|
+
Input for uploading a file to the Order Entry Service.
|
|
982
|
+
The file is transmitted as a Base64-encoded string so it can travel
|
|
983
|
+
through the standard GraphQL JSON pipeline without multipart support.
|
|
984
|
+
"""
|
|
985
|
+
input IOrderEntryUpload {
|
|
986
|
+
"""
|
|
987
|
+
Base64-encoded file content.
|
|
988
|
+
"""
|
|
989
|
+
fileContent: String!
|
|
990
|
+
"""
|
|
991
|
+
Original file name (e.g. "order.csv").
|
|
992
|
+
"""
|
|
993
|
+
fileName: String!
|
|
994
|
+
"""
|
|
995
|
+
MIME type of the file (e.g. "text/csv", "image/png").
|
|
996
|
+
"""
|
|
997
|
+
mimeType: String!
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
"""
|
|
1001
|
+
Result returned after uploading a file to the Order Entry Service.
|
|
1002
|
+
"""
|
|
1003
|
+
type StoreOrderEntryUploadResult {
|
|
1004
|
+
objectKey: String!
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
input IOrderEntryOperation {
|
|
1008
|
+
objectKey: String!
|
|
1009
|
+
orderFormId: String
|
|
1010
|
+
sessionToken: String
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
type StoreOrderEntryOperationResult {
|
|
1014
|
+
operationId: String!
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
type StoreOrderEntryMissingItem {
|
|
1018
|
+
itemId: String!
|
|
1019
|
+
itemName: String
|
|
1020
|
+
reason: String!
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
type StoreOrderEntryOperationStatus {
|
|
1024
|
+
status: String!
|
|
1025
|
+
entityId: String
|
|
1026
|
+
message: String
|
|
1027
|
+
missingItems: [StoreOrderEntryMissingItem!]
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
type StoreOrderFormCartItem {
|
|
1031
|
+
id: String!
|
|
1032
|
+
name: String!
|
|
1033
|
+
price: Int!
|
|
1034
|
+
listPrice: Int!
|
|
1035
|
+
quantity: Int!
|
|
1036
|
+
imageUrl: String
|
|
1037
|
+
availability: String!
|
|
1038
|
+
seller: String!
|
|
1039
|
+
unitMultiplier: Float
|
|
1040
|
+
}
|
|
1041
|
+
`,Qr=`"""
|
|
966
1042
|
Organization.
|
|
967
1043
|
"""
|
|
968
1044
|
type StoreOrganization {
|
|
@@ -981,7 +1057,7 @@ input IStoreOrganization {
|
|
|
981
1057
|
"""
|
|
982
1058
|
identifier: String!
|
|
983
1059
|
}
|
|
984
|
-
`,
|
|
1060
|
+
`,Zr=`"""
|
|
985
1061
|
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.
|
|
986
1062
|
"""
|
|
987
1063
|
type StorePageInfo {
|
|
@@ -1006,7 +1082,7 @@ type StorePageInfo {
|
|
|
1006
1082
|
"""
|
|
1007
1083
|
totalCount: Int!
|
|
1008
1084
|
}
|
|
1009
|
-
`,
|
|
1085
|
+
`,ei=`"""
|
|
1010
1086
|
Input type for setting a new password.
|
|
1011
1087
|
"""
|
|
1012
1088
|
input ISetPassword {
|
|
@@ -1049,7 +1125,7 @@ type SetPasswordResponse {
|
|
|
1049
1125
|
"""
|
|
1050
1126
|
message: String
|
|
1051
1127
|
}
|
|
1052
|
-
`,
|
|
1128
|
+
`,ni=`"""
|
|
1053
1129
|
Client profile data.
|
|
1054
1130
|
"""
|
|
1055
1131
|
type StorePerson {
|
|
@@ -1092,7 +1168,7 @@ input IStorePerson {
|
|
|
1092
1168
|
"""
|
|
1093
1169
|
familyName: String!
|
|
1094
1170
|
}
|
|
1095
|
-
`,
|
|
1171
|
+
`,ti=`type PickupPointAddress {
|
|
1096
1172
|
"""
|
|
1097
1173
|
Address city.
|
|
1098
1174
|
"""
|
|
@@ -1171,7 +1247,7 @@ type PickupPoints {
|
|
|
1171
1247
|
"""
|
|
1172
1248
|
pickupPointsHash: String
|
|
1173
1249
|
}
|
|
1174
|
-
`,
|
|
1250
|
+
`,ri=`"""
|
|
1175
1251
|
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.
|
|
1176
1252
|
"""
|
|
1177
1253
|
type StoreProduct {
|
|
@@ -1320,7 +1396,7 @@ input IStoreProduct {
|
|
|
1320
1396
|
"""
|
|
1321
1397
|
additionalProperty: [IStorePropertyValue!]
|
|
1322
1398
|
}
|
|
1323
|
-
`,
|
|
1399
|
+
`,ii=`"""
|
|
1324
1400
|
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.
|
|
1325
1401
|
"""
|
|
1326
1402
|
type StoreProductGroup {
|
|
@@ -1347,7 +1423,7 @@ type StoreProductGroup {
|
|
|
1347
1423
|
"""
|
|
1348
1424
|
skuVariants: SkuVariants
|
|
1349
1425
|
}
|
|
1350
|
-
`,
|
|
1426
|
+
`,ai=`type Profile {
|
|
1351
1427
|
"""
|
|
1352
1428
|
Collection of user's address
|
|
1353
1429
|
"""
|
|
@@ -1408,7 +1484,7 @@ type ProfileAddress {
|
|
|
1408
1484
|
"""
|
|
1409
1485
|
geoCoordinate: [Float]
|
|
1410
1486
|
}
|
|
1411
|
-
`,
|
|
1487
|
+
`,oi=`"""
|
|
1412
1488
|
Properties that can be associated with products and products groups.
|
|
1413
1489
|
"""
|
|
1414
1490
|
type StorePropertyValue {
|
|
@@ -1448,7 +1524,7 @@ input IStorePropertyValue {
|
|
|
1448
1524
|
"""
|
|
1449
1525
|
valueReference: ObjectOrString!
|
|
1450
1526
|
}
|
|
1451
|
-
`,
|
|
1527
|
+
`,si=`"""
|
|
1452
1528
|
Each product edge contains a \`node\`, with product information, and a \`cursor\`, that can be used as a reference for pagination.
|
|
1453
1529
|
"""
|
|
1454
1530
|
type StoreProductEdge {
|
|
@@ -1911,6 +1987,15 @@ type Query {
|
|
|
1911
1987
|
geoCoordinates: IStoreGeoCoordinates
|
|
1912
1988
|
): PickupPoints
|
|
1913
1989
|
@cacheControl(scope: "public", sMaxAge: 300, staleWhileRevalidate: 3600)
|
|
1990
|
+
"""
|
|
1991
|
+
Returns the status of an Order Entry Service operation by its ID.
|
|
1992
|
+
"""
|
|
1993
|
+
orderEntryOperation(operationId: String!): StoreOrderEntryOperationStatus
|
|
1994
|
+
@auth
|
|
1995
|
+
"""
|
|
1996
|
+
Returns the items in an orderForm by its ID.
|
|
1997
|
+
"""
|
|
1998
|
+
orderFormItems(orderFormId: String!): [StoreOrderFormCartItem!]! @auth
|
|
1914
1999
|
}
|
|
1915
2000
|
|
|
1916
2001
|
type ValidateUserData {
|
|
@@ -2001,7 +2086,7 @@ type StoreAccountProfile {
|
|
|
2001
2086
|
email: String
|
|
2002
2087
|
id: String
|
|
2003
2088
|
}
|
|
2004
|
-
`,
|
|
2089
|
+
`,ci=`"""
|
|
2005
2090
|
Information of a given review rating.
|
|
2006
2091
|
"""
|
|
2007
2092
|
type StoreReviewRating {
|
|
@@ -2028,7 +2113,7 @@ type StoreReview {
|
|
|
2028
2113
|
"""
|
|
2029
2114
|
author: StoreAuthor!
|
|
2030
2115
|
}
|
|
2031
|
-
`,
|
|
2116
|
+
`,li=`"""
|
|
2032
2117
|
Search Engine Optimization (SEO) tags data.
|
|
2033
2118
|
"""
|
|
2034
2119
|
type StoreSeo {
|
|
@@ -2049,7 +2134,7 @@ type StoreSeo {
|
|
|
2049
2134
|
"""
|
|
2050
2135
|
canonical: String!
|
|
2051
2136
|
}
|
|
2052
|
-
`,
|
|
2137
|
+
`,di=`"""
|
|
2053
2138
|
Currency information.
|
|
2054
2139
|
"""
|
|
2055
2140
|
type StoreCurrency {
|
|
@@ -2324,7 +2409,7 @@ input IStoreSession {
|
|
|
2324
2409
|
"""
|
|
2325
2410
|
refreshAfter: String
|
|
2326
2411
|
}
|
|
2327
|
-
`,
|
|
2412
|
+
`,ui=`"""
|
|
2328
2413
|
Shipping Simulation item input.
|
|
2329
2414
|
"""
|
|
2330
2415
|
input IShippingItem {
|
|
@@ -2655,7 +2740,7 @@ type MessageFields {
|
|
|
2655
2740
|
"""
|
|
2656
2741
|
skuName: String
|
|
2657
2742
|
}
|
|
2658
|
-
`,
|
|
2743
|
+
`,pi=`type SkuVariants {
|
|
2659
2744
|
"""
|
|
2660
2745
|
SKU property values for the current SKU.
|
|
2661
2746
|
"""
|
|
@@ -2750,7 +2835,7 @@ Example:
|
|
|
2750
2835
|
\`\`\`
|
|
2751
2836
|
"""
|
|
2752
2837
|
scalar FormattedVariants
|
|
2753
|
-
`,
|
|
2838
|
+
`,gi=`"""
|
|
2754
2839
|
Status used to indicate a message type. For instance, a shopping cart informative or error message.
|
|
2755
2840
|
"""
|
|
2756
2841
|
enum StoreStatus {
|
|
@@ -2758,7 +2843,7 @@ enum StoreStatus {
|
|
|
2758
2843
|
WARNING
|
|
2759
2844
|
ERROR
|
|
2760
2845
|
}
|
|
2761
|
-
`,
|
|
2846
|
+
`,mi=`scalar JSONObject
|
|
2762
2847
|
|
|
2763
2848
|
type UserOrder {
|
|
2764
2849
|
orderId: String
|
|
@@ -3582,4 +3667,4 @@ type UserOrderBudgetAllocationLinkedEntity {
|
|
|
3582
3667
|
type: String
|
|
3583
3668
|
id: String
|
|
3584
3669
|
}
|
|
3585
|
-
`,
|
|
3670
|
+
`,hi=Object.assign({"./address.graphql":Fr,"./advertisement.graphql":Nr,"./aggregateOffer.graphql":Rr,"./aggregateRating.graphql":Lr,"./author.graphql":Mr,"./brand.graphql":Br,"./breadcrumb.graphql":$r,"./cart.graphql":zr,"./collection.graphql":Vr,"./deliveryPromisesBadge.graphql":qr,"./facet.graphql":xr,"./image.graphql":jr,"./mutation.graphql":Wr,"./newsletter.graphql":Gr,"./objectOrString.graphql":Hr,"./offer.graphql":Xr,"./order.graphql":Yr,"./orderCommercialAuthorizaton.graphql":Jr,"./orderEntry.graphql":Kr,"./organization.graphql":Qr,"./pageInfo.graphql":Zr,"./password.graphql":ei,"./person.graphql":ni,"./pickupPoints.graphql":ti,"./product.graphql":ri,"./productGroup.graphql":ii,"./profile.graphql":ai,"./propertyValue.graphql":oi,"./query.graphql":si,"./review.graphql":ci,"./seo.graphql":li,"./session.graphql":di,"./shipping.graphql":ui,"./skuVariants.graphql":pi,"./status.graphql":gi,"./userOrder.graphql":mi}),fi=ee.print(Object.values(hi).map(e=>ee.parse(e)).reduce((e,n)=>qe.mergeTypeDefs([e,n],{sort:!0}))),wn=fi,Si=async e=>M.OTELAPI.context.with(M.OTELAPI.propagation.extract(M.OTELAPI.context.active(),e.OTEL),()=>n=>(n.storage={channel:re.parse(e.channel),flags:e.flags??{},locale:e.locale,cookies:new Map},n.clients=Qn(e,n),n.loaders=ct(e,n),n.account=e.account,n.OTEL=e.OTEL,n.discoveryConfig=e.discoveryConfig,n));function yi(){const e=kr(),n={};for(const[t,r]of Object.entries(e))n[t]=Object.fromEntries(Object.entries(r).map(([i,a])=>typeof a!="function"?[i,a]:[i,Rn(a,`${t}(${i})`)]));return n}function Ii(e){const t=Ze([Qe,Ke])(yi(),wn);return e&&ee.isSchema(e)?xe.mergeSchemas({schemas:[t,e]}):t}exports.AuthDirective=Ke;exports.BadRequestError=k;exports.CacheControlDirective=Qe;exports.CommercialAuthorizationStatus=We;exports.FastStoreError=H;exports.ForbiddenError=K;exports.GraphqlVtexContextFactory=Si;exports.GraphqlVtexSchema=Ii;exports.NotFoundError=B;exports.StoreCollectionType=Ge;exports.StoreFacetType=He;exports.StoreSort=Xe;exports.StoreStatus=Ye;exports.UnauthorizedError=J;exports.UserOrderInvoiceType=Je;exports.isBadRequestError=Mn;exports.isFastStoreError=Ln;exports.isForbiddenError=en;exports.isNotFoundError=nn;exports.isUnauthorizedError=Bn;exports.stringifyCacheControl=Fn;exports.typeDefs=wn;exports.withDirectives=Ze;
|