@kachingappz/bundles-js 0.3.7 → 1.0.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.
@@ -0,0 +1,228 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const U=require("react/jsx-runtime"),S=require("react"),F=(e,t)=>{const a=[],n=e.filter(l=>l.blockVisibility==="selected-products");for(const l of n)l.selectedProductIds.map(Number).includes(t.id)&&a.push(l);const r=e.filter(l=>l.blockVisibility==="selected-collections");for(const l of r)t.collectionIds.some(m=>l.selectedCollectionIds.map(Number).includes(m))&&a.push(l);const i=e.filter(l=>l.blockVisibility==="excluded-products");for(const l of i)!l.excludedProductIds.map(Number).includes(t.id)&&!(l.excludedCollectionIds||[]).some(m=>t.collectionIds.includes(m))&&a.push(l);const o=e.filter(l=>l.blockVisibility==="all-products");for(const l of o)a.push(l);return a},R=(e,{language:t,country:a})=>{var f,g;const n=L(t,a),r=new Intl.NumberFormat(n,{style:"currency",currency:e,currencyDisplay:"narrowSymbol"}).formatToParts(123456789e-2),i=(f=r.find(y=>y.type==="decimal"))==null?void 0:f.value,o=J((g=r.find(y=>y.type==="group"))==null?void 0:g.value),l=r.some(y=>y.type==="fraction"),m=z(o,i,l),d=r.findIndex(E),c=r.findLastIndex(E);return[...r.slice(0,d).map(G),m,...r.slice(c+1).map(G)].join("")},G=e=>O(e.value),O=e=>e.replace(/\s/g," "),E=e=>e.type==="integer"||e.type==="group"||e.type==="decimal"||e.type==="fraction",L=(e,t)=>e&&t?`${e}-${t.toUpperCase()}`:e||(t?t.toUpperCase():"en"),J=e=>e===void 0?void 0:O(e).replace(/’/g,"'"),z=(e,t,a)=>t===","&&e==="."?a?"{{amount_with_comma_separator}}":"{{amount_no_decimals_with_comma_separator}}":t===","&&e===" "?a?"{{amount_with_space_separator}}":"{{amount_no_decimals_with_space_separator}}":t==="."&&e===" "?"{{amount_with_period_and_space_separator}}":t==="."&&e==="'"?"{{amount_with_apostrophe_separator}}":a?"{{amount}}":"{{amount_no_decimals}}",$=({country:e,language:t})=>{const a=[];return e&&a.push(`country: ${e}`),t&&a.push(`language: ${t}`),a.length>0?`@inContext(${a.join(", ")})`:""},Q=async(e,{useExternalMetafieldNamespace:t,useMetaobjects:a})=>a?K(e):H(e),H=async(e,t)=>{var n;const a=(n=(await e.query(`
2
+ query FetchDealBlocks($metafieldNamespace: String!) {
3
+ shop {
4
+ metafield(namespace: $metafieldNamespace, key: "deal_blocks") {
5
+ value
6
+ }
7
+ }
8
+ }
9
+ `,{variables:{metafieldNamespace:"app--2935586817--kaching_bundles"}})).shop.metafield)==null?void 0:n.value;return a?JSON.parse(a):[]},K=async(e,t)=>{const a="app--2935586817--deal_block",n=[];let r=null;for(;;){const i=await e.query(`
10
+ query FetchDealBlockMetaobjects($type: String!, $cursor: String) {
11
+ metaobjects(type: $type, first: 250, after: $cursor) {
12
+ nodes {
13
+ fields {
14
+ key
15
+ value
16
+ }
17
+ }
18
+ pageInfo {
19
+ hasNextPage
20
+ endCursor
21
+ }
22
+ }
23
+ }
24
+ `,{variables:{type:a,cursor:r}});for(const o of i.metaobjects.nodes){const l=o.fields.find(m=>m.key==="settings");l!=null&&l.value&&n.push(JSON.parse(l.value))}if(!i.metaobjects.pageInfo.hasNextPage)break;r=i.metaobjects.pageInfo.endCursor}return n},C=async(e,{country:t,language:a,blockVisibility:n,excludedProductGIDs:r,selectedProductGIDs:i,selectedCollectionGIDs:o,limit:l=1e3})=>{switch(n){case"selected-products":return i.slice(0,l);case"all-products":case"excluded-products":{const m=$({country:t,language:a});let d=[],c=null;for(;d.length<l;){const f=Math.min(l-d.length,250),g=await e.query(`
25
+ query FetchProductGIDs($limit: Int!, $cursor: String) ${m} {
26
+ products(first: $limit, after: $cursor) {
27
+ nodes {
28
+ id
29
+ }
30
+ pageInfo {
31
+ hasNextPage
32
+ endCursor
33
+ }
34
+ }
35
+ }
36
+ `,{variables:{limit:f,cursor:c}});if(d.push(...g.products.nodes.map(y=>y.id)),!g.products.pageInfo.hasNextPage)break;c=g.products.pageInfo.endCursor}if(n==="excluded-products"){const f=new Set(r);d=d.filter(g=>!f.has(g))}return d}case"selected-collections":{const m=$({country:t,language:a}),d=(await e.query(`
37
+ query FetchCollectionProductGIDs($collectionGIDs: [ID!]!, $limit: Int!) ${m} {
38
+ nodes(ids: $collectionGIDs) {
39
+ ... on Collection {
40
+ products(first: $limit) {
41
+ nodes {
42
+ id
43
+ }
44
+ }
45
+ }
46
+ }
47
+ }
48
+ `,{variables:{collectionGIDs:o,limit:Math.min(l,250)}})).nodes.filter(c=>c!==null).flatMap(c=>c.products.nodes.map(f=>f.id));return Array.from(new Set(d)).slice(0,l)}}},V=`
49
+ id
50
+ availableForSale
51
+ price {
52
+ amount
53
+ }
54
+ compareAtPrice {
55
+ amount
56
+ }
57
+ selectedOptions {
58
+ name
59
+ value
60
+ }
61
+ image {
62
+ id
63
+ url(transform: { maxWidth: 200, maxHeight: 200 })
64
+ }
65
+ unitPriceMeasurement {
66
+ quantityUnit
67
+ quantityValue
68
+ referenceUnit
69
+ referenceValue
70
+ }
71
+ requiresComponents
72
+ sellingPlanAllocations(first: 100) @include(if: $includeSellingPlans) {
73
+ nodes {
74
+ sellingPlan {
75
+ id
76
+ }
77
+ priceAdjustments {
78
+ price {
79
+ amount
80
+ }
81
+ compareAtPrice {
82
+ amount
83
+ }
84
+ perDeliveryPrice {
85
+ amount
86
+ }
87
+ }
88
+ }
89
+ }
90
+ quantityAvailable @include(if: $includeAvailableQuantity)
91
+ `,A=async(e,{country:t,language:a,productIds:n,includeSellingPlans:r=!0,includeAvailableQuantity:i=!0,useExternalMetafieldNamespace:o=!1,batchSize:l=250,onBatchError:m})=>{if(!n.length)return[];const d=n.map(u=>typeof u=="string"&&u.startsWith("gid://")?u:`gid://shopify/Product/${u}`),c=$({country:t,language:a}),f=`
92
+ query FetchProducts($productGIDs: [ID!]!, $includeSellingPlans: Boolean!, $includeAvailableQuantity: Boolean!, $metafieldNamespace: String!) ${c} {
93
+ shop {
94
+ currencyRateConstant: metafield(namespace: $metafieldNamespace, key: "currency_rate_constant") {
95
+ value
96
+ }
97
+ }
98
+ nodes(ids: $productGIDs) {
99
+ ... on Product {
100
+ id
101
+ handle
102
+ onlineStoreUrl
103
+ availableForSale
104
+ createdAt
105
+ title
106
+ featuredImage {
107
+ url
108
+ }
109
+ options {
110
+ name
111
+ optionValues {
112
+ id
113
+ name
114
+ swatch {
115
+ color
116
+ image {
117
+ previewImage {
118
+ url(transform: { maxWidth: 200, maxHeight: 200 })
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }
124
+ variants(first: 250) {
125
+ nodes {
126
+ ${V}
127
+ }
128
+ }
129
+ collections(first: 50) {
130
+ nodes {
131
+ id
132
+ }
133
+ }
134
+ metafield: metafield(namespace: $metafieldNamespace, key: "text") {
135
+ value
136
+ }
137
+ metafield2: metafield(namespace: $metafieldNamespace, key: "text2") {
138
+ value
139
+ }
140
+ metafield3: metafield(namespace: $metafieldNamespace, key: "text3") {
141
+ value
142
+ }
143
+ metafield4: metafield(namespace: $metafieldNamespace, key: "text4") {
144
+ value
145
+ }
146
+ requiresSellingPlan
147
+ sellingPlanGroups(first: 100) @include(if: $includeSellingPlans) {
148
+ nodes {
149
+ sellingPlans(first: 100) {
150
+ nodes {
151
+ id
152
+ name
153
+ priceAdjustments {
154
+ adjustmentValue {
155
+ __typename
156
+ ... on SellingPlanPercentagePriceAdjustment {
157
+ adjustmentPercentage
158
+ }
159
+ ... on SellingPlanFixedAmountPriceAdjustment {
160
+ adjustmentAmount {
161
+ amount
162
+ }
163
+ }
164
+ ... on SellingPlanFixedPriceAdjustment {
165
+ price {
166
+ amount
167
+ }
168
+ }
169
+ }
170
+ }
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
177
+ }
178
+ `,g=o?"app--2935586817--kaching_bundles":"$app:kaching_bundles",y=[],h=Math.min(l,250);for(let u=0;u<d.length;u+=h)y.push(d.slice(u,u+h));let s=1;const p=async u=>{const v=await e.query(f,{variables:{productGIDs:u,includeSellingPlans:r,includeAvailableQuantity:i,metafieldNamespace:g}});return v.shop.currencyRateConstant&&(s=JSON.parse(v.shop.currencyRateConstant.value).amount/1e6),v};let b;if(m){const u=await Promise.allSettled(y.map(p));for(const v of u)v.status==="rejected"&&m(v.reason instanceof Error?v.reason:new Error(String(v.reason)));b=u.filter(v=>v.status==="fulfilled").flatMap(v=>v.value.nodes)}else b=(await Promise.all(y.map(p))).flatMap(u=>u.nodes);const _=b.filter(u=>u!=null);if(m){const u=await Promise.allSettled(_.map(async I=>{const P=await M(e,I,{includeSellingPlans:r,includeAvailableQuantity:i},c);return T(P,e.shopifyDomain,s)})),v=[];for(const I of u)I.status==="fulfilled"?v.push(I.value):m(I.reason instanceof Error?I.reason:new Error(String(I.reason)));return v}return(await Promise.all(_.map(u=>M(e,u,{includeSellingPlans:r,includeAvailableQuantity:i},c)))).map(u=>T(u,e.shopifyDomain,s))},M=async(e,t,a,n="")=>{if(t.variants.nodes.length<250)return t;const r=new Set,i=[],o=[],l=async m=>{let d=!0,c=null;for(;d;){const f=await e.query(`
179
+ query($productGID: ID!, $cursor: String, $reverse: Boolean, $includeSellingPlans: Boolean!, $includeAvailableQuantity: Boolean!) ${n} {
180
+ product(id: $productGID) {
181
+ variants(first: 250, after: $cursor, reverse: $reverse) {
182
+ nodes {
183
+ ${V}
184
+ }
185
+ pageInfo {
186
+ endCursor
187
+ hasNextPage
188
+ }
189
+ }
190
+ }
191
+ }
192
+ `,{variables:{productGID:t.id,cursor:c,reverse:m,...a}}),{nodes:g,pageInfo:y}=f.product.variants;for(const h of g){if(r.has(h.id)){d=!1;break}r.add(h.id),m?o.push(h):i.push(h)}y.hasNextPage||(d=!1),c=y.endCursor}};return await Promise.all([l(!1),l(!0)]),t.variants.nodes=[...i,...o.reverse()],t},T=(e,t,a)=>{var d,c,f,g,y,h;const n=e.variants.nodes.map(({unitPriceMeasurement:s,...p})=>{var b,_;return{id:Number(p.id.split("/").pop()),availableForSale:p.availableForSale,price:Math.round(Number(p.price.amount)*100),compareAtPrice:p.compareAtPrice?Math.round(Number(p.compareAtPrice.amount)*100):null,options:p.selectedOptions.map(u=>u.value),imageId:p.image?Number(p.image.id.split("/").pop()):null,image:((b=p.image)==null?void 0:b.url)||null,sellingPlans:((_=p.sellingPlanAllocations)==null?void 0:_.nodes.map(u=>({id:Number(u.sellingPlan.id.split("/").pop()),price:u.priceAdjustments.length>0?Math.round(Number(u.priceAdjustments[0].price.amount)*100):Math.round(Number(p.price.amount)*100),compareAtPrice:u.priceAdjustments.length>0?Math.round(Number(u.priceAdjustments[0].compareAtPrice.amount)*100):Math.round(Number(p.price.amount)*100),perDeliveryPrice:u.priceAdjustments.length>0?Math.round(Number(u.priceAdjustments[0].perDeliveryPrice.amount)*100):Math.round(Number(p.price.amount)*100)})))||[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:p.quantityAvailable??null,unitPriceMeasurement:s!=null&&s.quantityUnit&&(s!=null&&s.referenceUnit)?{quantityValue:s.quantityValue,quantityUnit:s.quantityUnit.toLowerCase(),referenceValue:s.referenceValue,referenceUnit:s.referenceUnit.toLowerCase()}:null}}),r=e.options.map((s,p)=>{const b=s.optionValues.map(_=>{var u,v,I,P;return{id:Number(_.id.split("/").pop()),defaultName:_.name,name:_.name,swatch:{color:((u=_.swatch)==null?void 0:u.color)||null,image:((P=(I=(v=_.swatch)==null?void 0:v.image)==null?void 0:I.previewImage)==null?void 0:P.url)||null}}});return{defaultName:s.name,name:s.name,position:p+1,optionValues:W(b,p,n)}}),i=s=>{const p=s.priceAdjustments[0];if(!p)return null;const b=p.adjustmentValue;switch(b.__typename){case"SellingPlanPercentagePriceAdjustment":return{type:"percentage",value:b.adjustmentPercentage};case"SellingPlanFixedAmountPriceAdjustment":return{type:"fixed_amount",value:o(b.adjustmentAmount.amount)};case"SellingPlanFixedPriceAdjustment":return{type:"price",value:o(b.price.amount)};default:throw new Error(`Unknown price adjustment type: ${b.__typename}`)}},o=s=>a===1?Number(s)*100:Math.round(Number(s)*100*a),l=((d=e.sellingPlanGroups)==null?void 0:d.nodes.flatMap(s=>s.sellingPlans.nodes.map(p=>({id:Number(p.id.split("/").pop()),name:p.name,priceAdjustment:i(p)}))))||[],m=e.variants.nodes.some(s=>s.requiresComponents);return{id:Number(e.id.split("/").pop()),handle:e.handle,url:e.onlineStoreUrl||`https://${t}/products/${e.handle}`,availableForSale:e.availableForSale,createdAt:e.createdAt,title:e.title,image:((c=e.featuredImage)==null?void 0:c.url)||null,collectionIds:e.collections.nodes.map(s=>Number(s.id.split("/").pop())),options:r,selectedVariantId:Number(e.variants.nodes[0].id.split("/").pop()),variants:n,requiresSellingPlan:e.requiresSellingPlan,sellingPlans:l,isNativeBundle:m,metafields:{text:((f=e.metafield)==null?void 0:f.value)||null,text2:((g=e.metafield2)==null?void 0:g.value)||null,text3:((y=e.metafield3)==null?void 0:y.value)||null,text4:((h=e.metafield4)==null?void 0:h.value)||null}}},W=(e,t,a)=>e.filter(n=>a.filter(r=>r.options[t]===n.name).length>0),q="app--2935586817",X=async(e,{language:t,country:a,useExternalMetafieldNamespace:n})=>{const r=`${q}--kaching_bundles`,i=q,o=$({country:a}),{localization:{country:{currency:{isoCode:l}}},shop:{moneyFormat:m,paymentSettings:{currencyCode:d},currencyRateConstant:c,primaryDomain:f,settingsMetafield:g}}=await e.query(`
193
+ query config($metafieldNamespace: String!, $settingsNamespace: String!) ${o} {
194
+ localization {
195
+ country {
196
+ currency {
197
+ isoCode
198
+ }
199
+ }
200
+ }
201
+ shop {
202
+ moneyFormat
203
+ paymentSettings {
204
+ currencyCode
205
+ }
206
+ primaryDomain {
207
+ host
208
+ }
209
+ currencyRateConstant: metafield(namespace: $metafieldNamespace, key: "currency_rate_constant") {
210
+ value
211
+ }
212
+ settingsMetafield: metafield(namespace: $settingsNamespace, key: "config") {
213
+ value
214
+ }
215
+ }
216
+ }
217
+ `,{variables:{metafieldNamespace:r,settingsNamespace:i}}),y=l===d?m:R(l,{language:t,country:a}),h=c?Y(c.value):1,s=g?JSON.parse(g.value):null,p=(s==null?void 0:s.feature_flags)??{},b=(s==null?void 0:s.custom_selectors)??{};return{shopifyDomain:f.host,moneyFormat:y,locale:(t==null?void 0:t.toLowerCase())||"en",liquidLocale:(t==null?void 0:t.toLowerCase())||"en",country:a??"US",currencyRate:h,marketId:0,productId:null,storefrontAccessToken:(s==null?void 0:s.storefront_access_token)??null,includeSellingPlans:(s==null?void 0:s.include_selling_plans)??!1,includeAvailableQuantity:(s==null?void 0:s.include_available_quantity)??!1,customApiHost:(s==null?void 0:s.custom_api_host)??null,keepQuantityInput:(s==null?void 0:s.keep_quantity_input)??!1,ignoreDeselect:(s==null?void 0:s.ignore_deselect)??!1,ignoreUnitPrice:(s==null?void 0:s.ignore_unit_price)??!1,requireCustomerLogin:(s==null?void 0:s.require_customer_login)??!1,abTestsRunning:(s==null?void 0:s.ab_tests_running)??!1,webPixel:(s==null?void 0:s.web_pixel)??!1,b2bCustomer:!1,isLoggedIn:!1,preview:!1,previewAlerts:!1,previewScratchOff:!1,defaultTranslations:{"system.out_of_stock":"Out of stock","system.invalid_variant":"Invalid variant","system.unavailable_option_value":"Unavailable option value","system.confirm":"Confirm","system.cancel":"Cancel","system.free":"FREE","system.search":"Search","system.quantity":"Quantity","system.subscription_plan":"Subscription plan","system.remove":"Remove","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","system.original_price":"Original price:","system.price":"Price:","system.letters_only":"Only letters are allowed.","system.numbers_only":"Only numbers are allowed."},customSelectors:{quantity:b.quantity??null,addToCartButton:b.add_to_cart_button??null,variantPicker:b.variant_picker??null,price:b.price??null,priceCompare:b.price_compare??null},shopCustomStyles:(s==null?void 0:s.shop_custom_styles)??"",featureFlags:p,brandColors:(s==null?void 0:s.brand_colors)??null}},Y=e=>JSON.parse(e).amount/1e6,Z=async(e,t,a=200)=>(t=t.filter(Boolean).filter(n=>!n.startsWith("placeholder")),t.length===0?[]:(await e.query(`
218
+ query FetchMediaImages($mediaImageIds: [ID!]!, $size: Int!) {
219
+ nodes(ids: $mediaImageIds) {
220
+ ... on MediaImage {
221
+ id
222
+ image {
223
+ url(transform: { maxWidth: $size, maxHeight: $size })
224
+ }
225
+ }
226
+ }
227
+ }
228
+ `,{variables:{mediaImageIds:t,size:a}})).nodes.filter(Boolean).map(n=>({gid:n.id,url:n.image.url})));var w=(e=>(e.QuantityBreak="quantity-break",e.Bxgy="bxgy",e.Bundle="bundle",e.MixAndMatch="mix-and-match",e.Sku="sku",e))(w||{});const ee=e=>[...te(e),...ae(e),...se(e),...ne(e),...le(e),...re(e),...ie(e),...oe(e),...ce(e),...ue(e),...de(e),...me(e),...pe(e)].filter(t=>t!=null&&!t.includes("placeholder")),te=e=>e.dealBars.flatMap(t=>[t.mediaImageGID,t.badgeImageGID]).filter(t=>t!=null),ae=e=>e.dealBars.flatMap(t=>t.dealBarType===w.Bundle?t.bundleProducts.map(a=>a.mediaImageGID):[]).filter(t=>t!=null),se=e=>e.dealBars.map(({freeGifts:t})=>(t||[]).map(a=>a.mediaImageGID)).reduce((t,a)=>t.concat(a),[]).filter(t=>t!=null),ne=e=>e.dealBars.flatMap(({multipleGiftsSelectors:t})=>(t||[]).map(a=>a.mediaImageGID)).filter(t=>t!=null),le=e=>e.dealBars.map(({upsells:t})=>(t||[]).map(a=>a.mediaImageGID)).reduce((t,a)=>t.concat(a),[]).filter(t=>t!=null),re=e=>e.swatchOptions?e.swatchOptions.reduce((t,a)=>{const n=a.images.map(r=>r.mediaImageGID).filter(r=>r!=null);return[...t,...n]},[]):[],ie=e=>{if(!e.collectionBreaksEnabled||!e.collectionBreaks)return[];const t=e.collectionBreaks.mediaImageGID;return t?[t]:[]},oe=e=>{var t,a,n;return e.progressiveGifts?[...((t=e.progressiveGifts.gifts)==null?void 0:t.map(r=>r.mediaImageGID))||[],(a=e.progressiveGifts.style)==null?void 0:a.lockedMediaImageGID,(n=e.progressiveGifts.dealBarStyle)==null?void 0:n.lockedMediaImageGID].filter(r=>r!=null):[]},ce=e=>!e.checkboxUpsellsEnabled||!e.checkboxUpsells?[]:e.checkboxUpsells.upsells.flatMap(t=>[t.mediaImageGID,t.badgeImageGID]).filter(t=>t!=null),ue=e=>e.dealBars.map(t=>{var a;return(a=t.productPersonalisation)==null?void 0:a.mediaImageGID}).filter(t=>t!=null),de=e=>{var n,r;const t=e.dealBars.map(i=>{var o;return(o=i.highlights)==null?void 0:o.customIconGID}).filter(i=>i!=null),a=(r=(n=e.subscriptions)==null?void 0:n.highlights)==null?void 0:r.customIconGID;return a?[...t,a]:t},me=e=>(e.badges||[]).flatMap(t=>t.badgeType==="custom"&&t.imageGID?[t.imageGID]:[]),pe=e=>!e.savingsSummaryEnabled||!e.savingsSummary?[]:e.savingsSummary.customIconGID?[e.savingsSummary.customIconGID]:[],fe=e=>{const t=[...ye(e),...ge(e),...he(e),...be(e),...ve(e),..._e(e),...Ie(e),...Pe(e)];return Array.from(new Set(t.filter(a=>a!=null)))},ye=e=>e.dealBars.flatMap(({freeGifts:t})=>t?t.map(a=>a.productGID):[]).filter(t=>t!=null),ge=e=>e.dealBars.flatMap(({multipleGiftsSelectors:t})=>t?t.flatMap(a=>a.products?a.products.map(n=>n.id):[]):[]).filter(t=>t!=null),he=e=>{var t;return e.progressiveGiftsEnabled?((t=e.progressiveGifts)==null?void 0:t.gifts.map(a=>a.productGID).filter(a=>a!=null))||[]:[]},be=e=>e.dealBars.flatMap(({upsells:t})=>t?t.map(a=>a.productGID):[]).filter(t=>t!=null),ve=e=>e.dealBars.filter(t=>t.dealBarType===w.Bundle).flatMap(({bundleProducts:t})=>t?t.map(a=>a.productGID):[]).filter(t=>t!=null).filter(t=>t!=="default"),_e=e=>e.dealBars.filter(t=>t.dealBarType===w.MixAndMatch).flatMap(({bundleProducts:t})=>t?t.flatMap(a=>{var n;return[a.productGID,...((n=a.selectedProducts)==null?void 0:n.map(r=>r.id))??[]]}):[]).filter(t=>t!=null).filter(t=>t!=="default"),Ie=e=>!e.checkboxUpsellsEnabled||!e.checkboxUpsells?[]:e.checkboxUpsells.upsells.map(t=>t.productGID).filter(t=>t!=null),Pe=e=>e.dealBars.filter(t=>t.dealBarType===w.Sku).flatMap(({productGID:t})=>t?[t]:[]);class Se{constructor(t,a){this.storefrontApiVersion="2026-07",this.storefrontAccessToken=a,this.shopifyDomain=t}async query(t,a){var l;const n=(a==null?void 0:a.variables)??{};let r=`https://${this.shopifyDomain}/api/${this.storefrontApiVersion}/graphql.json`;const i=(l=t.match(/query\s+(\w+)/))==null?void 0:l[1];i&&(r+=`?operation_name=${i}`);const o=await(await fetch(r,{method:"POST",headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefrontAccessToken},body:JSON.stringify({query:t,variables:n})})).text();if(!o)throw new Error("Empty graphql response");return JSON.parse(o).data}}const ke=async(e,t,{country:a,language:n})=>{const r=t.collectionBreaks;if(!t.collectionBreaksEnabled||!r)return;let i;r.visibility==="deal-products"?i=await C(e,{country:a,language:n,blockVisibility:t.blockVisibility,excludedProductGIDs:(t.excludedProductIds||[]).map(l=>`gid://shopify/Product/${l}`),selectedProductGIDs:(t.selectedProductIds||[]).map(l=>`gid://shopify/Product/${l}`),selectedCollectionGIDs:(t.selectedCollectionIds||[]).map(l=>`gid://shopify/Collection/${l}`)}):i=await C(e,{country:a,language:n,blockVisibility:r.visibility,excludedProductGIDs:(r.excludedProducts||[]).map(({id:l})=>l),selectedProductGIDs:(r.selectedProducts||[]).map(({id:l})=>l),selectedCollectionGIDs:(r.selectedCollections||[]).map(({id:l})=>l)});let o=await A(e,{country:a,language:n,productIds:i.map(l=>Number(l.split("/").pop())),useExternalMetafieldNamespace:!0});return o=o.filter(l=>l.availableForSale),o},we=()=>({"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.quantity":"Quantity","system.subscription_plan":"Subscription plan","system.remove":"Remove","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","system.original_price":"Original price:","system.price":"Price:","system.letters_only":"Only letters are allowed.","system.numbers_only":"Only numbers are allowed.","system.personalisation_required_alert":"Please add personalisation for every item to continue."}),$e="2026-07",De=async(e,{productId:t,dealBlockId:a,country:n=void 0,language:r=void 0})=>{var i,o;try{const l=[Number(t.split("/").pop())],m=new Ne(e);n=n||((i=m.i18n)==null?void 0:i.country),r=r||((o=m.i18n)==null?void 0:o.language);const d=await X(m,{language:r,country:n,useExternalMetafieldNamespace:!0});m.shopifyDomain=d.shopifyDomain;const c=d.storefrontAccessToken?new Se(d.shopifyDomain,d.storefrontAccessToken):m,[f,g]=await Promise.all([A(c,{country:n,language:r,productIds:l,useExternalMetafieldNamespace:!0}),Q(c,{useExternalMetafieldNamespace:!0,useMetaobjects:d.featureFlags.storefront_metaobjects})]),y=f[0];if(!y)return null;const h=F(g,y);let s;if(a?(s=h.find(P=>P.id===a||P.nanoId===a),s||(s=h[0])):s=h[0],!s)return null;const p=ee(s),b=fe(s),[_,u,v,I]=await Promise.all([A(c,{country:n,language:r,productIds:b,useExternalMetafieldNamespace:!0}),Z(c,p,300),ke(c,s,{country:n,language:r}),we()]);return{product:y,dealBlock:s,config:d,otherProducts:_,mediaImages:u,collectionBreaksProducts:v??[],translations:I}}catch(l){return console.error(l),null}};class Ne{constructor(t){this.storefront=t,this.shopifyDomain=""}async query(t,a){if("query"in this.storefront&&"i18n"in this.storefront)return await this.storefront.query(t,a);if("request"in this.storefront)return(await this.storefront.request(t,a)).data;if("shopifyDomain"in this.storefront&&"storefrontAccessToken"in this.storefront){const n=await fetch(`https://${this.storefront.shopifyDomain}/api/${$e}/graphql.json`,{body:JSON.stringify({query:t,variables:a==null?void 0:a.variables}),headers:{"Content-Type":"application/json","X-Shopify-Storefront-Access-Token":this.storefront.storefrontAccessToken},method:"POST"});if(!n.ok)throw new Error(n.statusText);return(await n.json()).data}else{const n=await fetch(this.storefront.getStorefrontApiUrl(),{body:JSON.stringify({query:t,variables:a==null?void 0:a.variables}),headers:this.storefront.getPublicTokenHeaders(),method:"POST"});if(!n.ok)throw new Error(n.statusText);return(await n.json()).data}}get i18n(){if("i18n"in this.storefront)return this.storefront.i18n}}const Ae=De,D="kaching-bundles-block",j=1e4,xe="https://bundles-integrations-dev.kachingappz.dev/kaching-bundles-block.js",Be="https://bundles-integrations.kachingappz.app/kaching-bundles-block.js",N=new WeakSet,Ge=async e=>{const t=e.document;if(!e.customElements.get(D)){if(N.has(t))return x(e,D);N.add(t);try{await Me(e)}catch(a){throw N.delete(t),a}}},Ee=()=>typeof window<"u"&&typeof window.__KACHING_DEV__<"u",Ce=()=>Ee()?xe:Be,Me=e=>{const t=e.document;return new Promise((a,n)=>{const r=Ce();if(t.querySelector(`script[src="${r}"]`)){x(e,D).then(a).catch(n);return}const o=t.createElement("script");o.src=r,o.onload=()=>x(e,D).then(a).catch(n),o.onerror=()=>n(new Error("Failed to load script")),t.head.appendChild(o)})},x=(e,t)=>new Promise((a,n)=>{if(e.customElements.get(t)){a();return}Promise.race([e.customElements.whenDefined(t),new Promise((r,i)=>setTimeout(()=>i(new Error(`Custom element "${t}" failed to register within ${j}ms`)),j))]).then(()=>a()).catch(n)});var B=(e=>(e.QuantityBreak="quantity-break",e.Bxgy="bxgy",e.Bundle="bundle",e.MixAndMatch="mix-and-match",e.Sku="sku",e))(B||{});const k="a-f\\d",Te=`#?[${k}]{3}[${k}]?`,qe=`#?[${k}]{6}([${k}]{2})?`,je=new RegExp(`[^#${k}]`,"gi"),Oe=new RegExp(`^${Te}$|^${qe}$`,"i");function Ve(e,t={}){if(typeof e!="string"||je.test(e)||!Oe.test(e))throw new TypeError("Expected a valid hex string");e=e.replace(/^#/,"");let a=1;e.length===8&&(a=Number.parseInt(e.slice(6,8),16)/255,e=e.slice(0,6)),e.length===4&&(a=Number.parseInt(e.slice(3,4).repeat(2),16)/255,e=e.slice(0,3)),e.length===3&&(e=e[0]+e[0]+e[1]+e[1]+e[2]+e[2]);const n=Number.parseInt(e,16),r=n>>16,i=n>>8&255,o=n&255,l=typeof t.alpha=="number"?t.alpha:a;if(t.format==="array")return[r,i,o,l];if(t.format==="css"){const m=l===1?"":` / ${Number((l*100).toFixed(2))}%`;return`rgb(${r} ${i} ${o}${m})`}return{red:r,green:i,blue:o,alpha:l}}const Ue=({price:e})=>({id:123,handle:"123",url:null,availableForSale:!0,requiresSellingPlan:!1,title:"",image:null,selectedVariantId:456,collectionIds:[],options:[],sellingPlans:[],variants:[{id:456,availableForSale:!0,price:Math.round((e??10)*100),compareAtPrice:null,options:[],imageId:null,image:null,sellingPlans:[],inventoryManagement:null,inventoryPolicy:null,inventoryQuantity:50,unitPriceMeasurement:null}],metafields:{text:null,text2:null,text3:null,text4:null},isNativeBundle:!1}),Fe=()=>({shopifyDomain:"",moneyFormat:"${{amount_with_comma_separator}}",locale:"en",liquidLocale:"en",country:"US",marketId:0,productId:null,storefrontAccessToken:null,includeSellingPlans:!1,includeAvailableQuantity:!1,customApiHost:null,keepQuantityInput:!1,ignoreDeselect:!1,ignoreUnitPrice:!1,requireCustomerLogin:!1,abTestsRunning:!1,webPixel:!1,b2bCustomer:!1,isLoggedIn:!1,preview:!1,previewAlerts:!1,previewScratchOff:!1,currencyRate:1,defaultTranslations:{"system.out_of_stock":"","system.invalid_variant":"","system.unavailable_option_value":"","system.confirm":"","system.cancel":"","system.free":"","system.search":"","system.quantity":"","system.subscription_plan":"","system.remove":"","system.sort_by":"","system.sort_relevance":"","system.sort_newest_first":"","system.sort_price_low_to_high":"","system.sort_price_high_to_low":"","system.no_results_found":"","system.no_results_description":"","system.clear_search":"","system.no_products_available":"","system.original_price":"","system.price":"","system.letters_only":"","system.numbers_only":""},customSelectors:{quantity:null,addToCartButton:null,variantPicker:null},shopCustomStyles:"",featureFlags:{}}),Re=({color:e,cornerRadius:t})=>{const a={id:"123",nanoId:"123",blockName:"Bundle",discountName:"",blockTitle:"BUNDLE & SAVE",blockLayout:"vertical",blockVisibility:"all-products",marketId:null,currency:null,excludedProductIds:[],excludedCollectionIds:[],selectedProductIds:[],selectedCollectionIds:[],excludeB2bCustomers:!1,excludePos:!1,startTimestamp:175811496e4,endTimestamp:null,differentVariantsEnabled:!0,hideVariantPicker:!1,showPricesPerItem:!1,showBothPrices:!1,useProductCompareAtPrice:!0,showPricesWithoutDecimals:!1,priceRounding:!1,priceRoundingPrecision:".00",updateNativePrice:!1,updateNativePriceType:"item",skipCart:!1,showVariantsForSingleQuantity:!0,preselectedDealBarId:"1f-9",defaultVariantsV2:[],collectionBreaksEnabled:!1,collectionBreaks:null,chooseProductModal:null,timerEnabled:!1,timer:null,subscriptionsEnabled:!1,subscriptions:null,stickyAtcEnabled:!1,stickyAtc:null,progressiveGiftsEnabled:!1,progressiveGifts:null,checkboxUpsellsEnabled:!1,checkboxUpsells:null,lowStockAlertEnabled:!1,lowStockAlert:null,dealBars:[{id:"PfFU",dealBarType:B.QuantityBreak,title:"1 pack",subtitle:"Standard price",label:"",quantity:1,discountType:"default",discountValue:"",badgeStyle:"simple",badgeText:"",badgeImageGID:null,mediaImageGID:null,freeGifts:[],multipleGiftsSelectors:[],upsells:[],showAsSoldOutEnabled:!1,showAsSoldOut:null,productPersonalisation:null},{id:"1f-9",dealBarType:B.QuantityBreak,title:"2 pack",subtitle:"You save {{saved_percentage}}",label:"SAVE {{saved_total}}",quantity:2,discountType:"percentage",discountValue:"15",badgeStyle:"most-popular",badgeText:"",badgeImageGID:null,mediaImageGID:null,freeGifts:[],multipleGiftsSelectors:[],upsells:[],showAsSoldOutEnabled:!1,showAsSoldOut:null,productPersonalisation:null}],badgesEnabled:!0,badges:[{id:"bdg1",attachedTo:{type:"dealBar",dealBarId:"1f-9"},text:"MOST POPULAR",colors:null,badgeType:"most-popular",size:90}],cornerRadius:t??8,spacing:1,colors:{background:{red:255,green:255,blue:255,alpha:1},selectedBackground:{red:255,green:255,blue:255,alpha:1},border:{red:0,green:0,blue:0,alpha:1},blockTitle:{red:0,green:0,blue:0,alpha:1},title:{red:0,green:0,blue:0,alpha:1},subtitle:{red:85,green:85,blue:85,alpha:1},price:{red:0,green:0,blue:0,alpha:1},fullPrice:{red:85,green:85,blue:85,alpha:1},labelBackground:{red:238,green:238,blue:238,alpha:1},label:{red:0,green:0,blue:0,alpha:1},badgeBackground:{red:255,green:17,blue:17,alpha:1},badgeText:{red:255,green:255,blue:255,alpha:1},freeGiftBackground:{red:0,green:0,blue:0,alpha:.3},freeGiftText:{red:0,green:0,blue:0,alpha:1},freeGiftSelectedBackground:{red:0,green:0,blue:0,alpha:1},freeGiftSelectedText:{red:255,green:255,blue:255,alpha:1},upsellBackground:{red:0,green:0,blue:0,alpha:.2},upsellText:{red:0,green:0,blue:0,alpha:1},upsellSelectedBackground:{red:0,green:0,blue:0,alpha:.2},upsellSelectedText:{red:0,green:0,blue:0,alpha:1}},fonts:{blockTitle:{size:"14",style:"bold"},title:{size:"20",style:"bold"},subtitle:{size:"14",style:"regular"},label:{size:"12",style:"regular"},freeGift:{size:"13",style:"bold"},upsell:{size:"13",style:"bold"},unitLabel:{size:"14",style:"regular"}},swatchOptions:[],swatchSize:18,swatchShape:"circle",imageSize:48,imageCornerRadius:6};return e!==void 0&&(a.colors.border={...Ve(e),alpha:1}),a},Le=({data:e,selectedVariantId:t,preview:a,onLinesChange:n,targetWindow:r})=>{const i=S.useRef(null),[o,l]=S.useState(!1),m=S.useRef(!1);S.useEffect(()=>{if(!i.current||o)return;(async()=>{await Ge(r??window),l(!0)})()},[o,r]),S.useEffect(()=>{const c=i.current;if(!o||!c)return;const f=()=>{const y=c.items().map(h=>({merchandiseId:`gid://shopify/ProductVariant/${h.id}`,quantity:h.quantity,attributes:Object.entries(h.properties).map(([s,p])=>({key:s,value:String(p)})),sellingPlanId:h.selling_plan?`gid://shopify/SellingPlan/${h.selling_plan}`:void 0}));n==null||n(y)};return m.current||(typeof c.items=="function"?f():c.addEventListener("kaching-bundles-block-loaded",f),m.current=!0),c.addEventListener("variants-changed",f),()=>{c.removeEventListener("kaching-bundles-block-loaded",f),c.removeEventListener("variants-changed",f)}},[o,n]);const d=e?ze(e,t):a?Qe(a):null;return Je(()=>{const c=i.current;if(!(!c||!d))for(const[f,g]of Object.entries(d.jsonAttributes))c.getAttribute(f)!==g&&c.setAttribute(f,g)}),d?U.jsx("kaching-bundles-block",{ref:i,"deal-block-id":d.dealBlockId,...d.jsonAttributes,"current-variant-id":d.currentVariantId}):null},Je=typeof window>"u"?S.useEffect:S.useLayoutEffect,ze=({config:e,dealBlock:t,product:a,otherProducts:n,mediaImages:r,collectionBreaksProducts:i,translations:o},l)=>({dealBlockId:t.id,currentVariantId:l?l.split("/").pop():String(a.variants[0].id),jsonAttributes:{config:JSON.stringify(e),"deal-block":JSON.stringify(t),"media-images":JSON.stringify(r),product:JSON.stringify(a),"other-products":JSON.stringify(n),"collection-breaks-products":JSON.stringify(i),translations:JSON.stringify(o)}}),Qe=({cornerRadius:e,color:t,price:a})=>{const n=Ue({price:a}),r=Fe(),i=Re({color:t,cornerRadius:e});return{dealBlockId:i.id,currentVariantId:String(n.variants[0].id),jsonAttributes:{config:JSON.stringify(r),"deal-block":JSON.stringify(i),"media-images":JSON.stringify([]),product:JSON.stringify(n),"other-products":JSON.stringify([]),"collection-breaks-products":JSON.stringify([]),translations:JSON.stringify({})}}};exports.KachingBundle=Le;exports.fetchKachingBundlesData=Ae;