PageSourceSearch

https://onceuponafarmorganics.com/cdn/shop/t/1115/assets/bundle-bu…?v=51478446699973513391789484047

js onceuponafarmorganics.com collected 2026-09-24 21:59:24 UTC 20,778 bytes, 2 lines download raw bytes

1import{getTierVariant,getProduct,getOneTimeBaseVariant,getItemsToMaximum,getSellingPlanIdForSubscription,createSubscriptionBaseline,createAddonsBaseline,hasAddonChanges,getAddonVariantId,isProductFullySoldOut,isProductQuantityIncreaseLocked,hasOnetimeProperty,getSubscriptionFrequencyFromSubscription,isRechargeFrequencyUpdateNotAllowedError}from"@theme/bundle-builder-store-getters";import{bundleStore}from"@theme/bundle-builder-store";import{getActiveThreshold,getDiscountPercentForThreshold}from"@theme/bundle-builder-tier-config";import{clearBundleEditSnapshot}from"@theme/bundle-builder-edit-session";import{parseLocalDate,toISODate}from"@theme/bundle-editor-subscription-dates";import{listOnetimes,createOnetime,deleteOnetime,updateOnetime,skipSubscriptionCharge,updateSubscription,listSubscriptions,listCharges,skipCharge}from"@theme/bundle-builder-sdk";import{ADDON_PARENT_SUBSCRIPTION_ID_PROPERTY,ADDON_PARENT_ADDRESS_ID_PROPERTY,ADDON_SOURCE_PROPERTY,ADDON_SOURCE_VALUE}from"@theme/bundle-builder-constants";const LOCAL_ADDON_ID_PREFIX="local:",ADDON_MISSING_CHARGE_DATE_MESSAGE="Unable to add new add-ons until the next delivery date is available. Please refresh and try again.";function isLocalAddonId(id){return String(id).startsWith(LOCAL_ADDON_ID_PREFIX)}function isPersistableBundleItem(item){const quantity=Number(item.quantity);return Number.isFinite(item.productId)&&Number.isFinite(quantity)&&quantity>0&&Number.isFinite(item.variantId)&&Number.isFinite(item.collectionId)&&Number.isFinite(item.price)&&Number.isFinite(item.basePrice)}export const patchBundleItem=item=>{const preserveWhenUnpatchable=!!bundleStore.getState().activeSubscription,preserveSubscriptionItem=()=>{if(preserveWhenUnpatchable&&isPersistableBundleItem(item))return item};if(getProduct(item.productId)?.available===!1)return preserveSubscriptionItem();const variant=getTierVariant(item.productId);if(!variant){const preserved=preserveSubscriptionItem();return preserved||console.error("No variant found for product"),preserved}if(variant.available===!1)return preserveSubscriptionItem();const collectionId=getProduct(item.productId)?.collectionId;if(!collectionId){const preserved=preserveSubscriptionItem();return preserved||console.error("No collection found for product"),preserved}const discountPercent=getDiscountPercentForThreshold(getActiveThreshold());return{...item,variantId:variant.id,collectionId,price:variant.price,basePrice:getOneTimeBaseVariant(item.productId)?.price??variant.price,discountPercent}},addItemToBundle=item=>{if(getItemsToMaximum()===0||isProductFullySoldOut(item.productId))return;const patchedItem=patchBundleItem(item);patchedItem&&bundleStore.update({items:[...bundleStore.getState().items,patchedItem],activeCartStarterId:null})},removeItemFromBundle=productId=>{bundleStore.update({items:bundleStore.getState().items.filter(i=>i.productId!==productId),activeCartStarterId:null})},setItemQuantity=(productId,quantity)=>{const maxQuantityPerVariant=bundleStore.getState().bundleSettings?.max_quantity_per_variant;if(maxQuantityPerVariant&&quantity>maxQuantityPerVariant&&(quantity=maxQuantityPerVariant),quantity<1){removeItemFromBundle(productId);return}let computedQuantity=quantity;const itemQuantity=bundleStore.getState().items.find(i=>i.productId===productId)?.quantity??0;if(quantity>itemQuantity&&isProductQuantityIncreaseLocked(productId))return;const increaseInQuantity=computedQuantity-itemQuantity;increaseInQuantity>0&&increaseInQuantity>getItemsToMaximum()&&(computedQuantity=itemQuantity+getItemsToMaximum()),bundleStore.update({items:bundleStore.getState().items.map(i=>i.productId===productId?{...i,quantity:computedQuantity}:i),activeCartStarterId:null})},clearBundle=()=>{clearBundleEditSnapshot(),invalidateAddonFetch(),bundleStore.update({items:[],purchaseType:"subscribe",sellingPlanId:null,activeCartStarterId:null,isEditing:!1,editBundleKey:null,editCartLineKeys:[],activeSubscription:null,subscriptionBaseline:null,subscriptionJustUpdated:!1,addons:[],addonsBaseline:null,addonSyncing:!1})},hydrateFromEdit=snapshot=>{const patchedItems=snapshot.items.map(item=>patchBundleItem(item)).filter(item=>item!=null);bundleStore.update({items:patchedItems,purchaseType:snapshot.purchaseType,sellingPlanId:snapshot.sellingPlanId,isEditing:!0,editBundleKey:snapshot.bundleKey,editCartLineKeys:snapshot.cartLineKeys,activeCartStarterId:null})},applyCartStarter=(items,starterId)=>{const patchedItems=items.map(item=>patchBundleItem(item)).filter(item=>item!=null);bundleStore.update({items:patchedItems,activeCartStarterId:starterId})},throwError=reason=>{let message;if(reason instanceof Error)message=reason.message;
1else if(typeof reason=="string")message=reason;else if(reason!=null&&typeof reason=="object"){const maybeMsg=Reflect.get(reason,"message");message=typeof maybeMsg=="string"?maybeMsg:String(reason)}else message=String(reason??"Unknown error");bundleStore.update({errorMessage:message})},clearError=()=>{bundleStore.update({errorMessage:null})};function getBundleItemsFromSubscription(subscription){return(subscription.include?.bundle_selections??[]).flatMap(bundleSelection=>bundleSelection.items??[]).map(item=>item?{productId:Number(item.external_product_id),quantity:item.quantity,variantId:Number(item.external_variant_id),collectionId:Number(item.collection_id),price:Number(item.price),basePrice:Number(item.price),discountPercent:0}:null).filter(Boolean)}function resolveSubscriptionBundleItems(subscription,bundleItems,{saved=!1}={}){if(bundleItems.length>0)return bundleItems;const{activeSubscription,items}=bundleStore.getState();return!saved||items.length===0?bundleItems:activeSubscription?.id!=null&&Number(activeSubscription.id)===Number(subscription.id)?items:bundleItems}export const loadSubscription=(subscription,{saved=!1}={})=>{const bundleItems=resolveSubscriptionBundleItems(subscription,getBundleItemsFromSubscription(subscription),{saved}),sellingPlanId=getSellingPlanIdForSubscription(subscription);clearBundle(),bundleStore.update({activeSubscription:subscription,items:bundleItems,purchaseType:"subscribe",...sellingPlanId?{sellingPlanId}:{}});const captureSubscriptionBaseline=()=>{const currentState=bundleStore.getState();bundleStore.update({subscriptionBaseline:createSubscriptionBaseline(currentState),subscriptionJustUpdated:saved})};if(!sellingPlanId){requestAnimationFrame(()=>{const resolvedPlanId=getSellingPlanIdForSubscription(subscription);resolvedPlanId&&bundleStore.getState().sellingPlanId!==resolvedPlanId&&bundleStore.update({sellingPlanId:resolvedPlanId}),captureSubscriptionBaseline()});return}captureSubscriptionBaseline()},markSubscriptionSaved=()=>{const currentState=bundleStore.getState();currentState.activeSubscription&&bundleStore.update({subscriptionBaseline:createSubscriptionBaseline(currentState),addonsBaseline:createAddonsBaseline(currentState.addons),subscriptionJustUpdated:!0})};function buildAddonProperties({subscriptionId,addressId}){return[{name:ADDON_PARENT_SUBSCRIPTION_ID_PROPERTY,value:String(subscriptionId)},{name:ADDON_PARENT_ADDRESS_ID_PROPERTY,value:String(addressId)},{name:ADDON_SOURCE_PROPERTY,value:ADDON_SOURCE_VALUE},{name:"_isAddon",value:"true"},{name:"_isOneTime",value:"true"}]}let addonFetchEpoch=0,loadAddonsInFlight=null,addonSyncedOnLoad=!1;function bumpAddonFetchEpoch(){addonFetchEpoch+=1}
1function invalidateAddonFetch(){bumpAddonFetchEpoch(),loadAddonsInFlight=null,addonSyncedOnLoad=!1}function mergeOnetimeUpdate(previous,updated){return{...previous,...updated,quantity:updated.quantity??previous.quantity}}export async function syncAddonsOnLoad(session,subscription,linkedAddons){if(linkedAddons.length===0)return linkedAddons;if(subscription.status==="cancelled")return await Promise.all(linkedAddons.map(addon=>deleteOnetime(session,addon.id))),[];const targetDate=subscription.next_charge_scheduled_at;return targetDate?Promise.all(linkedAddons.map(async addon=>{if(addon.next_charge_scheduled_at===targetDate)return addon;const updated=await updateOnetime(session,addon.id,{next_charge_scheduled_at:targetDate});return mergeOnetimeUpdate(addon,updated)})):linkedAddons}export const loadAddons=async session=>{const{activeSubscription}=bundleStore.getState();if(!activeSubscription?.address_id)return!0;if(loadAddonsInFlight)return loadAddonsInFlight;const addressId=activeSubscription.address_id,subscriptionId=String(activeSubscription.id),epochAtStart=++addonFetchEpoch,inflight=(async()=>{bundleStore.update({addonSyncing:!0});try{const{onetimes}=await listOnetimes(session,{address_id:addressId});if(epochAtStart!==addonFetchEpoch)return!0;const linkedAddons=(onetimes??[]).filter(onetime=>hasOnetimeProperty(onetime,ADDON_PARENT_SUBSCRIPTION_ID_PROPERTY,subscriptionId)),reconciled=addonSyncedOnLoad?linkedAddons:await syncAddonsOnLoad(session,activeSubscription,linkedAddons);if(addonSyncedOnLoad=!0,epochAtStart!==addonFetchEpoch)return!0;const filtered=reconciled.filter(onetime=>(onetime?.quantity??0)>0);return epochAtStart!==addonFetchEpoch||(bundleStore.update({addons:filtered,addonsBaseline:createAddonsBaseline(filtered)}),clearError()),!0}catch(reason){return throwError(reason),!1}finally{epochAtStart===addonFetchEpoch&&bundleStore.update({addonSyncing:!1})}})();return loadAddonsInFlight=inflight,inflight.finally(()=>{loadAddonsInFlight===inflight&&(loadAddonsInFlight=null)}),inflight},addAddon=({variantId,quantity=1})=>{const qty=Number(quantity);if(!Number.isFinite(qty)||qty<=0){removeAddonByVariantId(variantId);return}const{activeSubscription,addons}=bundleStore.getState();if(!activeSubscription?.address_id)return;const target=String(variantId),existing=addons.find(addon=>getAddonVariantId(addon)===target);if(!existing&&!activeSubscription.next_charge_scheduled_at){throwError(ADDON_MISSING_CHARGE_DATE_MESSAGE);return}if(bumpAddonFetchEpoch(),existing){bundleStore.update({addons:addons.map(addon=>getAddonVariantId(addon)===target?{...addon,quantity:qty}:addon)});return}const localAddon={id:`${LOCAL_ADDON_ID_PREFIX}${target}`,quantity:qty,external_variant_id:{ecommerce:target},next_charge_scheduled_at:activeSubscription.next_charge_scheduled_at,address_id:activeSubscription.address_id,properties:buildAddonProperties({subscriptionId:activeSubscription.id,addressId:activeSubscription.address_id})};bundleStore.update({addons:[...addons,localAddon]})},removeAddon=addonId=>{bumpAddonFetchEpoch(),bundleStore.update({addons:bundleStore.getState().addons.filter(addon=>String(addon.id)!==String(addonId))})};function removeAddonByVariantId(variantId){const target=String(variantId);bumpAddonFetchEpoch(),bundleStore.update({addons:bundleStore.getState().addons.filter(addon=>getAddonVariantId(addon)!==target)})}export const setAddonQuantity=(addonId,quantity)=>{if(quantity<=0){removeAddon(addonId);return}bumpAddonFetchEpoch(),bundleStore.update({addons:bundleStore.getState().addons.map(addon=>String(addon.id)===String(addonId)?{...addon,quantity}:addon)})},commitAddonChanges=async session=>{const{activeSubscription,addonsBaseline}=bundleStore.getState();if(!activeSubscription?.address_id||!hasAddonChanges())return!0;const addressId=activeSubscription.address_id,subscriptionId=String(activeSubscription.id),nextChargeDate=activeSubscription.next_charge_scheduled_at,allowDeletes=addonsBaseline!=null;try{const{onetimes}=await listOnetimes(session,{address_id:addressId}),serverAddons=(onetimes??[]).filter(onetime=>hasOnetimeProperty(onetime,ADDON_PARENT_SUBSCRIPTION_ID_PROPERTY,subscriptionId)),desired=new Map;for(const addon of bundleStore.getState().addons){const variantId=getAddonVariantId(addon),quantity=Number(addon?.quantity)||0;!variantId||quantity<=0||desired.set(variantId,quantity)}const serverVariantIds=new Set;for(const serverAddon of serverAddons){const variantId=getAddonVariantId(serverAddon);variantId&&serverVariantIds.add(variantId)}for(const variantId of desired.keys())if(!serverVariantIds.has(variantId)&&!nextChargeDate)return throwError(ADDON_MISSING_CHARGE_DATE_MESSAGE),!1;const nextAddons=[];for(const serverAddon of serverAddons){const variantId=getAddonVariantId(serverAddon);if(!variantId)continue;const desiredQty=desired.get(variantId)??0;if(desired.delete(variantId),desiredQty<=0){allowDeletes?await deleteOnetime(session,serverAddon.id):nextAddons.push(serverAddon);continue}const patch={};if((serverAddon.quantity??0)!==desiredQty&&(patch.quantity=desiredQty),nextChargeDate&&serverAddon.next_charge_scheduled_at!==nextChargeDate&&(patch.next_charge_scheduled_at=nextChargeDate),Object.keys(patch).length>0){const updated=await updateOnetime(session,serverAddon.id,patch);nextAddons.push(mergeOnetimeUpdate(serverAddon,updated))}else nextAddons.push(serverAddon)}for(const[variantId,quantity]of desired){const created=await createOnetime(session,{address_id:addressId,external_variant_id:{ecommerce:variantId},quantity,next_charge_scheduled_at:nextChargeDate,properties:buildAddonProperties({subscriptionId:activeSubscription.id,addressId})});nextAddons.push(created)}const filtered=nextAddons.filter(onetime=>(onetime?.quantity??0)>0);return bumpAddonFetchEpoch(),bundleStore.update({addons:filtered}),!0}catch(reason){return throwError(reason),!1}},setAddonSyncing=syncing=>{bundleStore.update({addonSyncing:!!syncing})},syncAddonsToDate=async(session,nextChargeDate)=>{const{addons,activeSubscription}=bundleStore.getState();if(!activeSubscription?.address_id)return!0;const pendingChanges=hasAddonChanges();if(!pendingChanges&&addons.length===0)return!0;bundleStore.update({addonSyncing:!0});const updatedById=new Map,mergeUpdatedAddons=()=>bundleStore.update({addons:bundleStore.getState().addons.map(addon=>updatedById.get(String(addon.id))??addon)});try{for(const addon of addons)isLocalAddonId(addon.id)&&updatedById.set(String(addon.id),{...addon,next_charge_scheduled_at:nextChargeDate});let serverAddons;if(pendingChanges){const{onetimes}=await listOnetimes(session,{address_id:activeSubscription.address_id}),subscriptionId=String(activeSubscription.id);serverAddons=(onetimes??[]).filter(onetime=>hasOnetimeProperty(onetime,ADDON_PARENT_SUBSCRIPTION_ID_PROPERTY,subscriptionId))}else serverAddons=addons.filter(addon=>!isLocalAddonId(addon.id));for(const serverAddon of serverAddons){if(isLocalAddonId(serverAddon.id))continue;
1if(serverAddon.next_charge_scheduled_at===nextChargeDate){updatedById.set(String(serverAddon.id),serverAddon);continue}const result=await updateOnetime(session,serverAddon.id,{next_charge_scheduled_at:nextChargeDate});updatedById.set(String(serverAddon.id),mergeOnetimeUpdate(serverAddon,result))}return bumpAddonFetchEpoch(),mergeUpdatedAddons(),!0}catch(reason){return mergeUpdatedAddons(),throwError(reason),!1}finally{bundleStore.update({addonSyncing:!1})}};export function computeNextChargeAfterSkip(subscription){const base=parseLocalDate(subscription.next_charge_scheduled_at),frequency=getSubscriptionFrequencyFromSubscription(subscription);if(!base||!frequency)return null;const{charge_interval_frequency,order_interval_unit}=frequency;switch(order_interval_unit){case"day":base.setDate(base.getDate()+charge_interval_frequency);break;case"week":base.setDate(base.getDate()+charge_interval_frequency*7);break;case"month":{const day=base.getDate(),y=base.getFullYear(),m=base.getMonth()+charge_interval_frequency,daysInTargetMonth=new Date(y,m+1,0).getDate();return toISODate(new Date(y,m,Math.min(day,daysInTargetMonth)))}default:return null}return toISODate(base)}function rechargeErrorText(reason){const parts=[];if(reason instanceof Error?parts.push(reason.message):typeof reason=="string"&&parts.push(reason),reason&&typeof reason=="object")try{parts.push(JSON.stringify(reason))}catch{}return parts.join(" ")}function isTransientRechargeError(reason){return/being regenerated|try again in a few|too many requests|rate limit/i.test(rechargeErrorText(reason))}const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));async function withTransientRetry(fn,{attempts=3,delayMs=2500}={}){let lastReason;for(let attempt=0;attempt<attempts;attempt+=1)try{return await fn()}catch(reason){if(lastReason=reason,!isTransientRechargeError(reason)||attempt===attempts-1)throw reason;await sleep(delayMs)}throw lastReason}async function findQueuedSubscriptionCharge(session,subscriptionId){const response=await listCharges(session,{purchase_item_id:subscriptionId,status:["queued"],sort_by:"scheduled_at-desc",limit:25});return(Array.isArray(response?.charges)?response.charges:[]).filter(charge=>String(charge?.status??"").toLowerCase()==="queued").sort((left,right)=>String(left?.scheduled_at??"").localeCompare(String(right?.scheduled_at??"")))[0]??null}async function fetchSubscriptionNextChargeDate(session,subscriptionId,{staleDate=null,attempts=3,delayMs=2e3}={}){const datePart=value=>String(value).split("T")[0];for(let attempt=0;attempt<attempts;attempt+=1){attempt>0&&await sleep(delayMs);try{const response=await listSubscriptions(session,{hydrateBundles:!1}),date=(Array.isArray(response?.subscriptions)?response.subscriptions:[]).find(subscription=>String(subscription?.id)===String(subscriptionId))?.next_charge_scheduled_at;if(typeof date!="string"||date.length===0)continue;if(!staleDate||datePart(date)!==datePart(staleDate))return date}catch{}}return null}const ADDON_PARTIAL_SYNC_MESSAGE="Your delivery was updated, but your add-ons may still show the previous date. They will be realigned automatically \u2014 no action needed.";async function syncAddonsToDateWithRetry(session,nextChargeDate,partialSyncMessage=ADDON_PARTIAL_SYNC_MESSAGE){if(!hasAddonChanges()){let loaded=await loadAddons(session);if(loaded||(clearError(),await sleep(2500),loaded=await loadAddons(session)),!loaded){throwError(partialSyncMessage);return}}await syncAddonsToDate(session,nextChargeDate)||(clearError(),await sleep(2500),!await syncAddonsToDate(session,nextChargeDate)&&throwError(partialSyncMessage))}function requireActionableSubscription(){const{activeSubscription}=bundleStore.getState();if(!activeSubscription?.id||!activeSubscription.next_charge_scheduled_at){const reason="Subscription is missing. Please refresh and try again.";throw throwError(reason),new Error(reason)}return activeSubscription}export const skipSubscription=async(session,{partialSyncMessage=ADDON_PARTIAL_SYNC_MESSAGE}={})=>{const activeSubscription=requireActionableSubscription();try{const queuedCharge=await findQueuedSubscriptionCharge(session,activeSubscription.id);if(queuedCharge)await withTransientRetry(()=>skipCharge(session,queuedCharge.id,[activeSubscription.id]));else try{await withTransientRetry(()=>skipSubscriptionCharge(session,activeSubscription.id,activeSubscription.next_charge_scheduled_at))}catch(reason){if(!/charge already exists/i.test(rechargeErrorText(reason)))throw reason;
1const racedCharge=await findQueuedSubscriptionCharge(session,activeSubscription.id);if(!racedCharge)throw reason;await withTransientRetry(()=>skipCharge(session,racedCharge.id,[activeSubscription.id]))}}catch(reason){throw throwError(reason),reason}const fetched=await fetchSubscriptionNextChargeDate(session,activeSubscription.id,{staleDate:activeSubscription.next_charge_scheduled_at}),current=bundleStore.getState().activeSubscription,newDate=fetched??computeNextChargeAfterSkip(current??activeSubscription);if(!newDate){current&&String(current.id)===String(activeSubscription.id)&&bundleStore.update({activeSubscription:{...current,next_charge_scheduled_at:null}}),throwError(partialSyncMessage);return}current&&String(current.id)===String(activeSubscription.id)&&bundleStore.update({activeSubscription:{...current,next_charge_scheduled_at:newDate}}),await syncAddonsToDateWithRetry(session,newDate,partialSyncMessage)},rescheduleSubscription=async(session,newDate,{partialSyncMessage=ADDON_PARTIAL_SYNC_MESSAGE,frequencyErrorMessage="Rescheduling is temporarily unavailable. Please try again later or contact support."}={})=>{const activeSubscription=requireActionableSubscription();try{await withTransientRetry(()=>updateSubscription(session,activeSubscription.id,{next_charge_scheduled_at:newDate}))}catch(reason){throw isRechargeFrequencyUpdateNotAllowedError(reason)||/customer_adjust_frequency_rule/i.test(rechargeErrorText(reason))?(throwError(frequencyErrorMessage),new Error(frequencyErrorMessage)):(throwError(reason),reason)}const current=bundleStore.getState().activeSubscription;current&&String(current.id)===String(activeSubscription.id)&&bundleStore.update({activeSubscription:{...current,next_charge_scheduled_at:newDate}}),await syncAddonsToDateWithRetry(session,newDate,partialSyncMessage)},setAddonProducts=products=>{bundleStore.update({addonProducts:products})};
2//# sourceMappingURL=/cdn/shop/t/1115/assets/bundle-builder-store-mutations.js.map?v=51478446699973513391789484047

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.