@kachingappz/bundles-js 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,6 +35,7 @@ npm install @kachingappz/bundles-js
35
35
  | `selected-variant-id` | No | Currently selected variant ID (plain ID or full GID) |
36
36
  | `country` | No | Country code for localization (e.g. `US`) |
37
37
  | `language` | No | Language code for localization (e.g. `EN`) |
38
+ | `deal-bars-only` | No | Show only deal bars, hiding title, timer, gifts, upsells, etc. |
38
39
  | `demo` | No | Render with placeholder data (no credentials needed) |
39
40
 
40
41
  ## Events
@@ -200,4 +200,4 @@
200
200
  }
201
201
  }
202
202
  }
203
- `,{variables:{productGID:e.id,cursor:p,reverse:s,...l}}),{nodes:n,pageInfo:u}=m.product.variants;for(const r of n){if(a.has(r.id)){d=!1;break}a.add(r.id),s?o.push(r):i.push(r)}u.hasNextPage||(d=!1),p=u.endCursor}};return await Promise.all([c(!1),c(!0)]),e.variants.nodes=[...i,...o.reverse()],e},U=t=>{var c,s,d,p,m,n;const e=t.variants.nodes.map(({unitPriceMeasurement:u,...r})=>{var f,g;return{id:Number(r.id.split("/").pop()),availableForSale:r.availableForSale,price:Math.round(Number(r.price.amount)*100),compareAtPrice:r.compareAtPrice?Math.round(Number(r.compareAtPrice.amount)*100):null,options:r.selectedOptions.map(h=>h.value),imageId:r.image?Number(r.image.id.split("/").pop()):null,image:((f=r.image)==null?void 0:f.url)||null,sellingPlans:((g=r.sellingPlanAllocations)==null?void 0:g.nodes.map(h=>({id:Number(h.sellingPlan.id.split("/").pop()),price:h.priceAdjustments.length>0?Math.round(Number(h.priceAdjustments[0].price.amount)*100):Math.round(Number(r.price.amount)*100)})))||[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:r.quantityAvailable??null,unitPriceMeasurement:u!=null&&u.quantityUnit&&(u!=null&&u.referenceUnit)?{quantityValue:u.quantityValue,quantityUnit:u.quantityUnit.toLowerCase(),referenceValue:u.referenceValue,referenceUnit:u.referenceUnit.toLowerCase()}:null}}),l=t.options.map((u,r)=>{const f=u.optionValues.map(g=>{var h,b,y,I;return{id:Number(g.id.split("/").pop()),defaultName:g.name,name:g.name,swatch:{color:((h=g.swatch)==null?void 0:h.color)||null,image:((I=(y=(b=g.swatch)==null?void 0:b.image)==null?void 0:y.previewImage)==null?void 0:I.url)||null}}});return{defaultName:u.name,name:u.name,position:r+1,optionValues:V(f,r,e)}}),a=u=>{const r=u.priceAdjustments[0];if(!r)return null;const f=r.adjustmentValue;switch(f.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:f.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"fixed_amount",value:Number(f.adjustmentAmount.amount)*100};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:Number(f.price.amount)*100};default:throw new Error(`Unknown price adjustment type: ${f.__typename}`)}},i=((c=t.sellingPlanGroups)==null?void 0:c.nodes.flatMap(u=>u.sellingPlans.nodes.map(r=>({id:Number(r.id.split("/").pop()),name:r.name,priceAdjustment:a(r)}))))||[],o=t.variants.nodes.some(u=>u.requiresComponents);return{id:Number(t.id.split("/").pop()),handle:t.handle,url:t.onlineStoreUrl,availableForSale:t.availableForSale,createdAt:t.createdAt,title:t.title,image:((s=t.featuredImage)==null?void 0:s.url)||null,collectionIds:t.collections.nodes.map(u=>Number(u.id.split("/").pop())),options:l,selectedVariantId:Number(t.variants.nodes[0].id.split("/").pop()),variants:e,requiresSellingPlan:t.requiresSellingPlan,sellingPlans:i,isNativeBundle:o,metafields:{text:((d=t.metafield)==null?void 0:d.value)||null,text2:((p=t.metafield2)==null?void 0:p.value)||null,text3:((m=t.metafield3)==null?void 0:m.value)||null,text4:((n=t.metafield4)==null?void 0:n.value)||null}}},V=(t,e,l)=>t.filter(a=>l.filter(i=>i.options[e]===a.name).length>0),F=(t,e)=>{const l=[],a=t.filter(s=>s.blockVisibility==="selected-products");for(const s of a)s.selectedProductIds.map(Number).includes(e.id)&&l.push(s);const i=t.filter(s=>s.blockVisibility==="selected-collections");for(const s of i)e.collectionIds.some(d=>s.selectedCollectionIds.map(Number).includes(d))&&l.push(s);const o=t.filter(s=>s.blockVisibility==="excluded-products");for(const s of o)!s.excludedProductIds.map(Number).includes(e.id)&&!(s.excludedCollectionIds||[]).some(d=>e.collectionIds.includes(d))&&l.push(s);const c=t.filter(s=>s.blockVisibility==="all-products");for(const s of c)l.push(s);return l},j=t=>[...z(t),...R(t),...H(t),...J(t),...Q(t),...X(t),...W(t),...K(t),...Y(t),...Z(t)].filter(e=>e!=null&&!e.includes("placeholder")),z=t=>t.dealBars.flatMap(e=>[e.mediaImageGID,e.badgeImageGID]).filter(e=>e!=null),R=t=>t.dealBars.map(({freeGifts:e})=>(e||[]).map(l=>l.mediaImageGID)).reduce((e,l)=>e.concat(l),[]).filter(e=>e!=null),H=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>(e||[]).map(l=>l.mediaImageGID)).filter(e=>e!=null),J=t=>t.dealBars.map(({upsells:e})=>(e||[]).map(l=>l.mediaImageGID)).reduce((e,l)=>e.concat(l),[]).filter(e=>e!=null),Q=t=>t.swatchOptions?t.swatchOptions.reduce((e,l)=>{const a=l.images.map(i=>i.mediaImageGID).filter(i=>i!=null);return[...e,...a]},[]):[],X=t=>{if(!t.collectionBreaksEnabled||!t.collectionBreaks)return[];const e=t.collectionBreaks.mediaImageGID;return e?[e]:[]},W=t=>{var e,l,a;return t.progressiveGifts?[...((e=t.progressiveGifts.gifts)==null?void 0:e.map(i=>i.mediaImageGID))||[],(l=t.progressiveGifts.style)==null?void 0:l.lockedMediaImageGID,(a=t.progressiveGifts.dealBarStyle)==null?void 0:a.lockedMediaImageGID].filter(i=>i!=null):[]},K=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.mediaImageGID).filter(e=>e!=null),Y=t=>t.dealBars.map(e=>{var l;return(l=e.productPersonalisation)==null?void 0:l.mediaImageGID}).filter(e=>e!=null),Z=t=>t.dealBars.map(e=>{var l;return(l=e.highlights)==null?void 0:l.customIconGID}).filter(e=>e!=null),ee=t=>{const e=[...te(t),...le(t),...se(t),...ae(t),...ne(t),...ie(t),...re(t)];return Array.from(new Set(e.filter(l=>l!=null)))},te=t=>t.dealBars.flatMap(({freeGifts:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null),le=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>e?e.flatMap(l=>l.products?l.products.map(a=>a.id):[]):[]).filter(e=>e!=null),se=t=>{var e;return t.progressiveGiftsEnabled?((e=t.progressiveGifts)==null?void 0:e.gifts.map(l=>l.productGID).filter(l=>l!=null))||[]:[]},ae=t=>t.dealBars.flatMap(({upsells:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null),ne=t=>t.dealBars.filter(e=>e.dealBarType==="bundle").flatMap(({bundleProducts:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null).filter(e=>e!=="default"),ie=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.productGID).filter(e=>e!=null),re=t=>t.dealBars.filter(e=>e.dealBarType==="sku").flatMap(({productGID:e})=>e?[e]:[]);class w{constructor(e,l){this.storefrontApiVersion="2025-10",this.storefrontAccessToken=l,this.shopifyDomain=e}async query(e,l){var s;const a=(l==null?void 0:l.variables)??{};let i=`https://${this.shopifyDomain}/api/${this.storefrontApiVersion}/graphql.json`;const o=(s=e.match(/query\s+(\w+)/))==null?void 0:s[1];o&&(i+=`?operation_name=${o}`);const c=await(await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefrontAccessToken},body:JSON.stringify({query:e,variables:a})})).text();if(!c)throw new Error("Empty graphql response");return JSON.parse(c).data}}const oe=async(t,e,{country:l,language:a})=>{const i=e.collectionBreaks;if(!e.collectionBreaksEnabled||!i)return;let o;i.visibility==="deal-products"?o=await E(t,{country:l,language:a,blockVisibility:e.blockVisibility,excludedProductGIDs:(e.excludedProductIds||[]).map(s=>`gid://shopify/Product/${s}`),selectedProductGIDs:(e.selectedProductIds||[]).map(s=>`gid://shopify/Product/${s}`),selectedCollectionGIDs:(e.selectedCollectionIds||[]).map(s=>`gid://shopify/Collection/${s}`)}):o=await E(t,{country:l,language:a,blockVisibility:i.visibility,excludedProductGIDs:(i.excludedProducts||[]).map(({id:s})=>s),selectedProductGIDs:(i.selectedProducts||[]).map(({id:s})=>s),selectedCollectionGIDs:(i.selectedCollections||[]).map(({id:s})=>s)}),o=o.slice(0,250);let c=await P(t,{country:l,language:a,productIds:o.map(s=>Number(s.split("/").pop())),useExternalMetafieldNamespace:!0});return c=c.filter(s=>s.availableForSale),c},ce=()=>({"system.out_of_stock":"There's not enough items in our stock, please select smaller bundle.","system.invalid_variant":"Sorry, this is not currently available.","system.unavailable_option_value":"Unavailable","system.confirm":"Confirm","system.cancel":"Cancel","system.free":"FREE","system.search":"Search","system.sort_by":"Sort by","system.sort_relevance":"Relevance","system.sort_newest_first":"Newest first","system.sort_price_low_to_high":"Price: Low → High","system.sort_price_high_to_low":"Price: High → Low","system.no_results_found":"No results found","system.no_results_description":"We can't find any item matching your search.","system.clear_search":"Clear search","system.no_products_available":"No products available"}),ue=async(t,{productId:e,dealBlockId:l,country:a,language:i})=>{try{const o=[Number(e.split("/").pop())],c=new w(t.shopifyDomain,t.storefrontAccessToken),s=await q(c,{language:i,country:a,useExternalMetafieldNamespace:!0}),d=s.storefrontAccessToken?new w(s.shopifyDomain,s.storefrontAccessToken):c,[p,m]=await Promise.all([P(d,{country:a,language:i,productIds:o,useExternalMetafieldNamespace:!0}),x(d,{useExternalMetafieldNamespace:!0,useMetaobjects:s.featureFlags.storefront_metaobjects})]),n=p[0];if(!n)return null;const u=F(m,n);let r;if(l?(r=u.find($=>$.id===l||$.nanoId===l),r||(r=u[0])):r=u[0],!r)return null;const f=j(r),g=ee(r),[h,b,y,I]=await Promise.all([P(d,{country:a,language:i,productIds:g,useExternalMetafieldNamespace:!0}),L(d,f,300),oe(d,r,{country:a,language:i}),ce()]);return{product:n,dealBlock:r,config:s,otherProducts:h,mediaImages:b,collectionBreaksProducts:y??[],translations:I}}catch(o){return console.error(o),null}},_="kaching-bundles-block",D=1e4,de="https://bundles-integrations-dev.kachingappz.dev/kaching-bundles-block.js",me="https://bundles-integrations.kachingappz.app/kaching-bundles-block.js",k=new WeakSet,C=async t=>{const e=t.document;if(!t.customElements.get(_)){if(k.has(e))return G(t,_);k.add(e);try{await ge(t)}catch(l){throw k.delete(e),l}}},pe=()=>typeof window<"u"&&typeof window.__KACHING_DEV__<"u",fe=()=>pe()?de:me,ge=t=>{const e=t.document;return new Promise((l,a)=>{const i=fe();if(e.querySelector(`script[src="${i}"]`)){l();return}const c=e.createElement("script");c.src=i,c.onload=()=>G(t,_).then(l).catch(a),c.onerror=()=>a(new Error("Failed to load script")),e.head.appendChild(c)})},G=(t,e)=>new Promise((l,a)=>{if(t.customElements.get(e)){l();return}Promise.race([t.customElements.whenDefined(e),new Promise((i,o)=>setTimeout(()=>o(new Error(`Custom element "${e}" failed to register within ${D}ms`)),D))]).then(()=>l()).catch(a)});class he extends HTMLElement{constructor(){super(...arguments),this.innerElement=null,this.handleItemsChanged=null,this.initializeId=0}static get observedAttributes(){return["selected-variant-id","product-id"]}async connectedCallback(){await this.initialize()}async initialize(){var c,s;const e=++this.initializeId;if(this.cleanup(),this.hasAttribute("demo")){if(await C(window),e!==this.initializeId)return;this.renderInnerElement(N);return}const l=this.getAttribute("shop-domain"),a=this.getAttribute("storefront-token"),i=this.getAttribute("product-id");if(!l||!a||!i)return;const[o]=await Promise.all([ue({shopifyDomain:l,storefrontAccessToken:a},{productId:i,dealBlockId:this.getAttribute("deal-block-id")??void 0,country:((c=this.getAttribute("country"))==null?void 0:c.toUpperCase())??void 0,language:((s=this.getAttribute("language"))==null?void 0:s.toUpperCase())??void 0}),C(window)]);!o||e!==this.initializeId||this.renderInnerElement(o)}renderInnerElement(e){const{config:l,dealBlock:a,product:i,otherProducts:o,mediaImages:c,collectionBreaksProducts:s,translations:d}=e;this.innerElement=document.createElement("kaching-bundles-block"),this.innerElement.setAttribute("deal-block-id",a.id),this.innerElement.setAttribute("config",JSON.stringify(l)),this.innerElement.setAttribute("deal-block",JSON.stringify(a)),this.innerElement.setAttribute("media-images",JSON.stringify(c??[])),this.innerElement.setAttribute("product",JSON.stringify(i)),this.innerElement.setAttribute("other-products",JSON.stringify(o??[])),this.innerElement.setAttribute("collection-breaks-products",JSON.stringify(s??[])),this.innerElement.setAttribute("translations",JSON.stringify(d??{}));const p=this.getAttribute("selected-variant-id");this.innerElement.setAttribute("current-variant-id",String(p?p.split("/").pop():i.variants[0].id)),this.appendChild(this.innerElement);const m=()=>{const n=this.innerElement.items();n&&this.dispatchEvent(new CustomEvent("items-changed",{detail:{items:n},bubbles:!0}))};this.handleItemsChanged=n=>{n.stopPropagation(),m()},this.innerElement.addEventListener("kaching-bundles-block-loaded",()=>{this.innerElement.addEventListener("items-changed",this.handleItemsChanged),m(),this.dispatchEvent(new CustomEvent("loaded",{bubbles:!0}))},{once:!0})}cleanup(){this.handleItemsChanged&&this.innerElement&&(this.innerElement.removeEventListener("items-changed",this.handleItemsChanged),this.handleItemsChanged=null),this.innerElement&&(this.innerElement.remove(),this.innerElement=null)}attributeChangedCallback(e,l,a){l!==a&&(e==="product-id"?this.initialize():e==="selected-variant-id"&&this.innerElement&&a&&this.innerElement.setAttribute("current-variant-id",a.includes("/")?String(a.split("/").pop()):a))}items(){return this.innerElement?this.innerElement.items():[]}disconnectedCallback(){this.cleanup(),this.initializeId++}}customElements.define("kaching-bundle-component",he)})();
203
+ `,{variables:{productGID:e.id,cursor:p,reverse:s,...l}}),{nodes:n,pageInfo:u}=m.product.variants;for(const r of n){if(a.has(r.id)){d=!1;break}a.add(r.id),s?o.push(r):i.push(r)}u.hasNextPage||(d=!1),p=u.endCursor}};return await Promise.all([c(!1),c(!0)]),e.variants.nodes=[...i,...o.reverse()],e},U=t=>{var c,s,d,p,m,n;const e=t.variants.nodes.map(({unitPriceMeasurement:u,...r})=>{var f,g;return{id:Number(r.id.split("/").pop()),availableForSale:r.availableForSale,price:Math.round(Number(r.price.amount)*100),compareAtPrice:r.compareAtPrice?Math.round(Number(r.compareAtPrice.amount)*100):null,options:r.selectedOptions.map(h=>h.value),imageId:r.image?Number(r.image.id.split("/").pop()):null,image:((f=r.image)==null?void 0:f.url)||null,sellingPlans:((g=r.sellingPlanAllocations)==null?void 0:g.nodes.map(h=>({id:Number(h.sellingPlan.id.split("/").pop()),price:h.priceAdjustments.length>0?Math.round(Number(h.priceAdjustments[0].price.amount)*100):Math.round(Number(r.price.amount)*100)})))||[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:r.quantityAvailable??null,unitPriceMeasurement:u!=null&&u.quantityUnit&&(u!=null&&u.referenceUnit)?{quantityValue:u.quantityValue,quantityUnit:u.quantityUnit.toLowerCase(),referenceValue:u.referenceValue,referenceUnit:u.referenceUnit.toLowerCase()}:null}}),l=t.options.map((u,r)=>{const f=u.optionValues.map(g=>{var h,b,y,I;return{id:Number(g.id.split("/").pop()),defaultName:g.name,name:g.name,swatch:{color:((h=g.swatch)==null?void 0:h.color)||null,image:((I=(y=(b=g.swatch)==null?void 0:b.image)==null?void 0:y.previewImage)==null?void 0:I.url)||null}}});return{defaultName:u.name,name:u.name,position:r+1,optionValues:V(f,r,e)}}),a=u=>{const r=u.priceAdjustments[0];if(!r)return null;const f=r.adjustmentValue;switch(f.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:f.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"fixed_amount",value:Number(f.adjustmentAmount.amount)*100};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:Number(f.price.amount)*100};default:throw new Error(`Unknown price adjustment type: ${f.__typename}`)}},i=((c=t.sellingPlanGroups)==null?void 0:c.nodes.flatMap(u=>u.sellingPlans.nodes.map(r=>({id:Number(r.id.split("/").pop()),name:r.name,priceAdjustment:a(r)}))))||[],o=t.variants.nodes.some(u=>u.requiresComponents);return{id:Number(t.id.split("/").pop()),handle:t.handle,url:t.onlineStoreUrl,availableForSale:t.availableForSale,createdAt:t.createdAt,title:t.title,image:((s=t.featuredImage)==null?void 0:s.url)||null,collectionIds:t.collections.nodes.map(u=>Number(u.id.split("/").pop())),options:l,selectedVariantId:Number(t.variants.nodes[0].id.split("/").pop()),variants:e,requiresSellingPlan:t.requiresSellingPlan,sellingPlans:i,isNativeBundle:o,metafields:{text:((d=t.metafield)==null?void 0:d.value)||null,text2:((p=t.metafield2)==null?void 0:p.value)||null,text3:((m=t.metafield3)==null?void 0:m.value)||null,text4:((n=t.metafield4)==null?void 0:n.value)||null}}},V=(t,e,l)=>t.filter(a=>l.filter(i=>i.options[e]===a.name).length>0),F=(t,e)=>{const l=[],a=t.filter(s=>s.blockVisibility==="selected-products");for(const s of a)s.selectedProductIds.map(Number).includes(e.id)&&l.push(s);const i=t.filter(s=>s.blockVisibility==="selected-collections");for(const s of i)e.collectionIds.some(d=>s.selectedCollectionIds.map(Number).includes(d))&&l.push(s);const o=t.filter(s=>s.blockVisibility==="excluded-products");for(const s of o)!s.excludedProductIds.map(Number).includes(e.id)&&!(s.excludedCollectionIds||[]).some(d=>e.collectionIds.includes(d))&&l.push(s);const c=t.filter(s=>s.blockVisibility==="all-products");for(const s of c)l.push(s);return l},j=t=>[...z(t),...R(t),...H(t),...J(t),...Q(t),...X(t),...W(t),...K(t),...Y(t),...Z(t)].filter(e=>e!=null&&!e.includes("placeholder")),z=t=>t.dealBars.flatMap(e=>[e.mediaImageGID,e.badgeImageGID]).filter(e=>e!=null),R=t=>t.dealBars.map(({freeGifts:e})=>(e||[]).map(l=>l.mediaImageGID)).reduce((e,l)=>e.concat(l),[]).filter(e=>e!=null),H=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>(e||[]).map(l=>l.mediaImageGID)).filter(e=>e!=null),J=t=>t.dealBars.map(({upsells:e})=>(e||[]).map(l=>l.mediaImageGID)).reduce((e,l)=>e.concat(l),[]).filter(e=>e!=null),Q=t=>t.swatchOptions?t.swatchOptions.reduce((e,l)=>{const a=l.images.map(i=>i.mediaImageGID).filter(i=>i!=null);return[...e,...a]},[]):[],X=t=>{if(!t.collectionBreaksEnabled||!t.collectionBreaks)return[];const e=t.collectionBreaks.mediaImageGID;return e?[e]:[]},W=t=>{var e,l,a;return t.progressiveGifts?[...((e=t.progressiveGifts.gifts)==null?void 0:e.map(i=>i.mediaImageGID))||[],(l=t.progressiveGifts.style)==null?void 0:l.lockedMediaImageGID,(a=t.progressiveGifts.dealBarStyle)==null?void 0:a.lockedMediaImageGID].filter(i=>i!=null):[]},K=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.mediaImageGID).filter(e=>e!=null),Y=t=>t.dealBars.map(e=>{var l;return(l=e.productPersonalisation)==null?void 0:l.mediaImageGID}).filter(e=>e!=null),Z=t=>t.dealBars.map(e=>{var l;return(l=e.highlights)==null?void 0:l.customIconGID}).filter(e=>e!=null),ee=t=>{const e=[...te(t),...le(t),...se(t),...ae(t),...ne(t),...ie(t),...re(t)];return Array.from(new Set(e.filter(l=>l!=null)))},te=t=>t.dealBars.flatMap(({freeGifts:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null),le=t=>t.dealBars.flatMap(({multipleGiftsSelectors:e})=>e?e.flatMap(l=>l.products?l.products.map(a=>a.id):[]):[]).filter(e=>e!=null),se=t=>{var e;return t.progressiveGiftsEnabled?((e=t.progressiveGifts)==null?void 0:e.gifts.map(l=>l.productGID).filter(l=>l!=null))||[]:[]},ae=t=>t.dealBars.flatMap(({upsells:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null),ne=t=>t.dealBars.filter(e=>e.dealBarType==="bundle").flatMap(({bundleProducts:e})=>e?e.map(l=>l.productGID):[]).filter(e=>e!=null).filter(e=>e!=="default"),ie=t=>!t.checkboxUpsellsEnabled||!t.checkboxUpsells?[]:t.checkboxUpsells.upsells.map(e=>e.productGID).filter(e=>e!=null),re=t=>t.dealBars.filter(e=>e.dealBarType==="sku").flatMap(({productGID:e})=>e?[e]:[]);class w{constructor(e,l){this.storefrontApiVersion="2025-10",this.storefrontAccessToken=l,this.shopifyDomain=e}async query(e,l){var s;const a=(l==null?void 0:l.variables)??{};let i=`https://${this.shopifyDomain}/api/${this.storefrontApiVersion}/graphql.json`;const o=(s=e.match(/query\s+(\w+)/))==null?void 0:s[1];o&&(i+=`?operation_name=${o}`);const c=await(await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefrontAccessToken},body:JSON.stringify({query:e,variables:a})})).text();if(!c)throw new Error("Empty graphql response");return JSON.parse(c).data}}const oe=async(t,e,{country:l,language:a})=>{const i=e.collectionBreaks;if(!e.collectionBreaksEnabled||!i)return;let o;i.visibility==="deal-products"?o=await E(t,{country:l,language:a,blockVisibility:e.blockVisibility,excludedProductGIDs:(e.excludedProductIds||[]).map(s=>`gid://shopify/Product/${s}`),selectedProductGIDs:(e.selectedProductIds||[]).map(s=>`gid://shopify/Product/${s}`),selectedCollectionGIDs:(e.selectedCollectionIds||[]).map(s=>`gid://shopify/Collection/${s}`)}):o=await E(t,{country:l,language:a,blockVisibility:i.visibility,excludedProductGIDs:(i.excludedProducts||[]).map(({id:s})=>s),selectedProductGIDs:(i.selectedProducts||[]).map(({id:s})=>s),selectedCollectionGIDs:(i.selectedCollections||[]).map(({id:s})=>s)}),o=o.slice(0,250);let c=await P(t,{country:l,language:a,productIds:o.map(s=>Number(s.split("/").pop())),useExternalMetafieldNamespace:!0});return c=c.filter(s=>s.availableForSale),c},ce=()=>({"system.out_of_stock":"There's not enough items in our stock, please select smaller bundle.","system.invalid_variant":"Sorry, this is not currently available.","system.unavailable_option_value":"Unavailable","system.confirm":"Confirm","system.cancel":"Cancel","system.free":"FREE","system.search":"Search","system.sort_by":"Sort by","system.sort_relevance":"Relevance","system.sort_newest_first":"Newest first","system.sort_price_low_to_high":"Price: Low → High","system.sort_price_high_to_low":"Price: High → Low","system.no_results_found":"No results found","system.no_results_description":"We can't find any item matching your search.","system.clear_search":"Clear search","system.no_products_available":"No products available"}),ue=async(t,{productId:e,dealBlockId:l,country:a,language:i})=>{try{const o=[Number(e.split("/").pop())],c=new w(t.shopifyDomain,t.storefrontAccessToken),s=await q(c,{language:i,country:a,useExternalMetafieldNamespace:!0}),d=s.storefrontAccessToken?new w(s.shopifyDomain,s.storefrontAccessToken):c,[p,m]=await Promise.all([P(d,{country:a,language:i,productIds:o,useExternalMetafieldNamespace:!0}),x(d,{useExternalMetafieldNamespace:!0,useMetaobjects:s.featureFlags.storefront_metaobjects})]),n=p[0];if(!n)return null;const u=F(m,n);let r;if(l?(r=u.find($=>$.id===l||$.nanoId===l),r||(r=u[0])):r=u[0],!r)return null;const f=j(r),g=ee(r),[h,b,y,I]=await Promise.all([P(d,{country:a,language:i,productIds:g,useExternalMetafieldNamespace:!0}),L(d,f,300),oe(d,r,{country:a,language:i}),ce()]);return{product:n,dealBlock:r,config:s,otherProducts:h,mediaImages:b,collectionBreaksProducts:y??[],translations:I}}catch(o){return console.error(o),null}},_="kaching-bundles-block",D=1e4,de="https://bundles-integrations-dev.kachingappz.dev/kaching-bundles-block.js",me="https://bundles-integrations.kachingappz.app/kaching-bundles-block.js",k=new WeakSet,C=async t=>{const e=t.document;if(!t.customElements.get(_)){if(k.has(e))return G(t,_);k.add(e);try{await ge(t)}catch(l){throw k.delete(e),l}}},pe=()=>typeof window<"u"&&typeof window.__KACHING_DEV__<"u",fe=()=>pe()?de:me,ge=t=>{const e=t.document;return new Promise((l,a)=>{const i=fe();if(e.querySelector(`script[src="${i}"]`)){l();return}const c=e.createElement("script");c.src=i,c.onload=()=>G(t,_).then(l).catch(a),c.onerror=()=>a(new Error("Failed to load script")),e.head.appendChild(c)})},G=(t,e)=>new Promise((l,a)=>{if(t.customElements.get(e)){l();return}Promise.race([t.customElements.whenDefined(e),new Promise((i,o)=>setTimeout(()=>o(new Error(`Custom element "${e}" failed to register within ${D}ms`)),D))]).then(()=>l()).catch(a)});class he extends HTMLElement{constructor(){super(...arguments),this.innerElement=null,this.handleItemsChanged=null,this.initializeId=0}static get observedAttributes(){return["selected-variant-id","product-id"]}async connectedCallback(){await this.initialize()}async initialize(){var c,s;const e=++this.initializeId;if(this.cleanup(),this.hasAttribute("demo")){if(await C(window),e!==this.initializeId)return;this.renderInnerElement(N);return}const l=this.getAttribute("shop-domain"),a=this.getAttribute("storefront-token"),i=this.getAttribute("product-id");if(!l||!a||!i)return;const[o]=await Promise.all([ue({shopifyDomain:l,storefrontAccessToken:a},{productId:i,dealBlockId:this.getAttribute("deal-block-id")??void 0,country:((c=this.getAttribute("country"))==null?void 0:c.toUpperCase())??void 0,language:((s=this.getAttribute("language"))==null?void 0:s.toUpperCase())??void 0}),C(window)]);!o||e!==this.initializeId||this.renderInnerElement(o)}renderInnerElement(e){const{config:l,dealBlock:a,product:i,otherProducts:o,mediaImages:c,collectionBreaksProducts:s,translations:d}=e;this.innerElement=document.createElement("kaching-bundles-block"),this.innerElement.setAttribute("deal-block-id",a.id),this.innerElement.setAttribute("config",JSON.stringify(l)),this.innerElement.setAttribute("deal-block",JSON.stringify(a)),this.innerElement.setAttribute("media-images",JSON.stringify(c??[])),this.innerElement.setAttribute("product",JSON.stringify(i)),this.innerElement.setAttribute("other-products",JSON.stringify(o??[])),this.innerElement.setAttribute("collection-breaks-products",JSON.stringify(s??[])),this.innerElement.setAttribute("translations",JSON.stringify(d??{}));const p=this.getAttribute("selected-variant-id");this.innerElement.setAttribute("current-variant-id",String(p?p.split("/").pop():i.variants[0].id)),this.hasAttribute("deal-bars-only")&&this.innerElement.setAttribute("deal-bars-only",""),this.appendChild(this.innerElement);const m=()=>{const n=this.innerElement.items();n&&this.dispatchEvent(new CustomEvent("items-changed",{detail:{items:n},bubbles:!0}))};this.handleItemsChanged=n=>{n.stopPropagation(),m()},this.innerElement.addEventListener("kaching-bundles-block-loaded",()=>{this.innerElement.addEventListener("items-changed",this.handleItemsChanged),m(),this.dispatchEvent(new CustomEvent("loaded",{bubbles:!0}))},{once:!0})}cleanup(){this.handleItemsChanged&&this.innerElement&&(this.innerElement.removeEventListener("items-changed",this.handleItemsChanged),this.handleItemsChanged=null),this.innerElement&&(this.innerElement.remove(),this.innerElement=null)}attributeChangedCallback(e,l,a){l!==a&&(e==="product-id"?this.initialize():e==="selected-variant-id"&&this.innerElement&&a&&this.innerElement.setAttribute("current-variant-id",a.includes("/")?String(a.split("/").pop()):a))}items(){return this.innerElement?this.innerElement.items():[]}disconnectedCallback(){this.cleanup(),this.initializeId++}}customElements.define("kaching-bundle-component",he)})();
@@ -426,7 +426,7 @@ const N = {
426
426
  )).nodes.filter(Boolean).map((a) => ({
427
427
  gid: a.id,
428
428
  url: a.image.url
429
- }))), w = async (t, {
429
+ }))), A = async (t, {
430
430
  country: e,
431
431
  language: l,
432
432
  blockVisibility: a,
@@ -881,7 +881,7 @@ const N = {
881
881
  }, re = (t) => t.dealBars.flatMap(({ upsells: e }) => e ? e.map((l) => l.productGID) : []).filter((e) => e != null), oe = (t) => t.dealBars.filter((e) => e.dealBarType === "bundle").flatMap(
882
882
  ({ bundleProducts: e }) => e ? e.map((l) => l.productGID) : []
883
883
  ).filter((e) => e != null).filter((e) => e !== "default"), ce = (t) => !t.checkboxUpsellsEnabled || !t.checkboxUpsells ? [] : t.checkboxUpsells.upsells.map((e) => e.productGID).filter((e) => e != null), ue = (t) => t.dealBars.filter((e) => e.dealBarType === "sku").flatMap(({ productGID: e }) => e ? [e] : []);
884
- class A {
884
+ class w {
885
885
  constructor(e, l) {
886
886
  this.storefrontApiVersion = "2025-10", this.storefrontAccessToken = l, this.shopifyDomain = e;
887
887
  }
@@ -911,7 +911,7 @@ const de = async (t, e, { country: l, language: a }) => {
911
911
  const i = e.collectionBreaks;
912
912
  if (!e.collectionBreaksEnabled || !i) return;
913
913
  let o;
914
- i.visibility === "deal-products" ? o = await w(t, {
914
+ i.visibility === "deal-products" ? o = await A(t, {
915
915
  country: l,
916
916
  language: a,
917
917
  blockVisibility: e.blockVisibility,
@@ -924,7 +924,7 @@ const de = async (t, e, { country: l, language: a }) => {
924
924
  selectedCollectionGIDs: (e.selectedCollectionIds || []).map(
925
925
  (s) => `gid://shopify/Collection/${s}`
926
926
  )
927
- }) : o = await w(t, {
927
+ }) : o = await A(t, {
928
928
  country: l,
929
929
  language: a,
930
930
  blockVisibility: i.visibility,
@@ -971,14 +971,14 @@ const de = async (t, e, { country: l, language: a }) => {
971
971
  language: i
972
972
  }) => {
973
973
  try {
974
- const o = [Number(e.split("/").pop())], c = new A(
974
+ const o = [Number(e.split("/").pop())], c = new w(
975
975
  t.shopifyDomain,
976
976
  t.storefrontAccessToken
977
977
  ), s = await L(c, {
978
978
  language: i,
979
979
  country: a,
980
980
  useExternalMetafieldNamespace: !0
981
- }), d = s.storefrontAccessToken ? new A(
981
+ }), d = s.storefrontAccessToken ? new w(
982
982
  s.shopifyDomain,
983
983
  s.storefrontAccessToken
984
984
  ) : c, [p, m] = await Promise.all([
@@ -1137,7 +1137,7 @@ class Ie extends HTMLElement {
1137
1137
  this.innerElement.setAttribute(
1138
1138
  "current-variant-id",
1139
1139
  String(p ? p.split("/").pop() : i.variants[0].id)
1140
- ), this.appendChild(this.innerElement);
1140
+ ), this.hasAttribute("deal-bars-only") && this.innerElement.setAttribute("deal-bars-only", ""), this.appendChild(this.innerElement);
1141
1141
  const m = () => {
1142
1142
  const n = this.innerElement.items();
1143
1143
  n && this.dispatchEvent(
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kachingappz/bundles-js",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "type": "module",
5
5
  "main": "./dist/bundles-js.js",
6
6
  "module": "./dist/bundles-js.js",