@zappie/sdk 0.30.1 → 0.30.4

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @zappie/sdk
2
2
 
3
+ ## 0.30.4
4
+
5
+ ### Patch Changes
6
+
7
+ - 49f5132: `useCart().actions` no longer takes back a line when the quote that refuses it is for another order type or branch than the change was made in. A shopper who added a Pickup-only item and switched to Delivery before the add's quote came back lost the line with a "no longer on the menu" notice, instead of seeing the line flagged with its Remove fix. A change is now judged only by a quote for the branch and order type it was made in. A quote for another one leaves the line in the bag with the cart's issue and its fixes.
8
+
9
+ ## 0.30.3
10
+
11
+ ### Patch Changes
12
+
13
+ - d46a615: `cachedApiFetch` sends the store's data version in `x-zappie-data-version` on the reads it keeps, both when it fetches one it doesn't have and when it refreshes a stale one, so the API can keep a read under the current version for an hour instead of a minute. It is sent only when the SDK knows the version (the `dataVersion` option or the one `rememberDataVersion` kept), and one the caller supplied is never passed on. It now also keeps one menu (`GET /menus/{id}`) and one item (`GET /items/{id}`), keyed like the store and the menus by store, URL and data version.
14
+
15
+ ## 0.30.2
16
+
17
+ ### Patch Changes
18
+
19
+ - 8630fc6: A line's choice in an option group the item doesn't have now shows as one cart issue, not two. The cart's own check reports it as `option_unavailable` and the quote as `option_limit` ("does not belong"), so the bag showed both for every such group, such as a delivery line on Pickup where the item's groups differ by order type. The quote's issue now goes with the cart's, as other problems both report already do.
20
+
3
21
  ## 0.30.1
4
22
 
5
23
  ### Patch Changes
@@ -1 +1 @@
1
- import{asError,ZappieError}from"../errors.js";import{multiplyMoney,sumMoney}from"../internal/money-math.js";import{money}from"../money.js";import{ZappieCartError}from"./errors.js";import{estimateUnitPrice}from"./price.js";import{freezeLine,lineInput,reconcile}from"./reconcile.js";import{withDefaultMenu}from"./source-menu.js";import{createCartStorage,parseCart,validFulfilment}from"./storage.js";import{issue,normalizeInput,resolveVariant,validateLine}from"./validate.js";import{wireFulfilment,wireLine}from"./wire.js";var typeOf=value=>value?.type.replace("_i","I");var EMPTY_CART=deepFreeze({branchId:void 0,lines:[],count:0,subtotal:null,fulfilment:null,promoCode:null,perks:[],state:{status:"ready"},issues:[],isHydrated:false});function deepFreeze(value){if(value&&typeof value==="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const child of Object.values(value)){deepFreeze(child)}}return value}function identity(input){return JSON.stringify([input.itemId,input.menuId,input.variantId,input.note??"",[...input.choices??[]].sort((a,b)=>a.groupId.localeCompare(b.groupId)||a.choiceId.localeCompare(b.choiceId)),Object.entries(input.inputs??{}).sort(([a],[b])=>a.localeCompare(b))])}function createCart(deps){const{config,menu:menus,store,events}=deps;const ttl=config.cart?.ttl??7*24*60*60*1e3;if(!Number.isFinite(ttl)||ttl<=0){throw new ZappieError("invalid_request","Cart ttl must be positive milliseconds")}let snapshot=EMPTY_CART;let menu;let branch;let selected=config.branch;let updatedAt=0;let timer;let revision=0;let quoteRevision=0;let moveSequence=0;let refreshSequence=0;let chased;let chasedAt=0;let mounted=0;let detach;let hydration;let lifecycle=0;let legacy;const listeners=new Set;const prefix=`zappie:cart:v1:${config.store}:`;const scope=config.cart?.storageScope;const keyFor=id=>`${prefix}${id}${scope?`:${scope}`:""}`;const key=()=>keyFor(branch.id);const storage=createCartStorage(config.storage,message=>events.emit("warning",{message}));const readSaved=id=>{let raw=storage.read(keyFor(id));if(raw===null&&scope){raw=storage.read(prefix+id);if(raw!==null){storage.remove(prefix+id);storage.write(keyFor(id),raw)}}return raw};let quotes;let loadingQuotes;const quoteClient=()=>loadingQuotes??(loadingQuotes=import("./quote-client.js").then(({createQuoteClient})=>quotes=createQuoteClient(deps.transport,deps.context,config),error=>{loadingQuotes=void 0;throw error}));const publish=patch=>{snapshot=deepFreeze({...snapshot,...patch,branchId:branch?.id});for(const fn of[...listeners]){try{fn()}catch(error){report(error)}}};const attention=(issues,quote)=>issues.some(i=>i.severity!=="info")?{status:"needs_attention",issues,...quote?{quote}:{}}:quote?{status:"quoted",quote}:{status:"ready"};const cancel=()=>{revision++;quoteRevision++;clearTimeout(timer);quotes?.cancel()};let customer=null;let planned=null;const mode=()=>menu?.fulfilment&&(typeOf(snapshot.fulfilment??planned)??menu.fulfilment);const wire=()=>({lines:snapshot.lines.map(wireLine),...customer?{customer}:{},...snapshot.promoCode?{promo_code:snapshot.promoCode}:{},...snapshot.perks.length&&snapshot.fulfilment?.type!="dine_in"?{perk_redemption_ids:snapshot.perks.map(p=>p.redemptionId)}:{},menu_version:menu.version});const persist=()=>{const value={v:1,lines:snapshot.lines.map(line=>({...lineInput(line),id:line.id,name:line.name,addedAt:line.addedAt,unitPrice:line.unitPrice})),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,perks:snapshot.perks,menuVersion:menu.version,updatedAt};storage.write(key(),JSON.stringify(value))};const schedule=()=>{clearTimeout(timer);if(snapshot.lines.length){timer=setTimeout(()=>{void cart.quote().catch(()=>{})},300)}};const resume=()=>{if(!("quote"in snapshot.state)){schedule()}};const recompute=(lines,pending=snapshot.issues.filter(i=>i.source==="local"),patch={})=>{const currency=store.peek().currency;const result=reconcile(lines,menu,branch,currency,pending);const subtotal=result.priced?sumMoney(result.lines.map(l=>l.lineSubtotal),money(0,currency)):null;publish({...patch,lines:result.lines,count:result.lines.reduce((n,l)=>n+l.quantity,0),subtotal,issues:result.issues,state:attention(result.issues)});for(const i of result.issues){events.emit("cart_issue",{code:i.code})}};const changed=(lines=snapshot.lines,patch={})=>{cancel();recompute(lines,void 0,patch);updatedAt=Date.now();persist();schedule();follow()};const adopt=value=>{menu=value;cancel();recompute(snapshot.lines);persist();schedule()};const report=error=>events.emit("error",{error:asError(error)});const follow=()=>{if(mode()!=menu?.fulfilment){refresh(void 0,true).catch(report)}};const choose=value=>{const found=store.peek()?.branches.find(b=>b.id===value.branchId);if(!found){throw new ZappieError("branch_not_found","Load the storefront branch before using its cart")}menu=value;branch=found;selected=found.id};const load=(raw,writeBack=true)=>{cancel();let saved;try{saved=raw?parseCart(raw):void 0;if(saved&&Date.now()-saved.updatedAt>ttl){saved=void 0;storage.remove(key());events.emit("cart_expired",{branchId:branch.id})}}catch{storage.remove(key());storage.warning("Invalid saved cart discarded")}updatedAt=saved?.updatedAt??Date.now();const idle=Date.now()-updatedAt;let fulfilment=saved?.fulfilment??null;if(fulfilment?.branchId!==branch.id||idle>864e5&&fulfilment.type==="delivery"){fulfilment=null}if(fulfilment&&"scheduledFor"in fulfilment&&fulfilment.scheduledFor&&Date.parse(fulfilment.scheduledFor)<Date.now()){fulfilment={...fulfilment};delete fulfilment.scheduledFor}const lines=(saved?.lines??[]).map(line=>({...line,...idle>864e5?{inputs:{}}:{}}));const result=reconcile(lines,menu,branch,store.peek().currency);recompute(result.lines,result.issues,{fulfilment,promoCode:saved?.promoCode??null,perks:saved?.perks??[],isHydrated:true});if(raw!==null&&writeBack){persist()}storage.sweep(prefix,key(),ttl);follow()};const pick=(branches=[])=>branches.find(b=>b.id===selected||b.slug===selected)??(selected?void 0:branches.find(b=>b.isDefault)??branches[0]);const ensure=()=>{if(snapshot.isHydrated){return}const id=branch?.id??pick(store.peek()?.branches)?.id;const loaded=menu??(id?deps.workingSet.peek(id,[]):void 0);if(!loaded||!store.peek()){throw new ZappieError("invalid_request","Load the store and menu before editing the cart")}choose(loaded);const raw=readSaved(branch.id);let migrated=[];if(raw===null&&legacy){try{migrated=legacy(storage.read)}catch{storage.warning("Invalid legacy cart discarded")}}load(raw);if(raw===null&&legacy){persist()}for(const input of migrated.slice(0,100)){try{cart.add(input.itemId,input)}catch{events.emit("cart_issue",{code:"item_unavailable"})}}};const refresh=async(target,switched)=>{const id=branch?.id;const seq=moveSequence;const request=++refreshSequence;const rev=revision;if(!id||!menu){return}if(!snapshot.lines.length){return}if(!switched&&menu.completeness!=="partial"){const version=await deps.transport.getMenuVersion({...deps.context(),branchId:id,fulfilment:mode()});if(version.version===menu.version){return}target=version.version}if(target&&target===chased&&Date.now()-chasedAt<3e4){return}chased=target;chasedAt=Date.now();const value=await deps.workingSet.read(id,snapshot.lines.map(l=>l.itemId),mode(),!switched);if(seq!==moveSequence||request!==refreshSequence||rev!==revision||JSON.stringify(value)===JSON.stringify(menu)){return}adopt(value)};const current=input=>{const{itemId}=input;const candidate=deps.workingSet.peek(branch.id,[...snapshot.lines.map(l=>l.itemId),itemId],mode());if(candidate.items[itemId]){if(candidate!=menu&&candidate.completeness!="partial"){queueMicrotask(()=>menu==candidate&&mode()==menu.fulfilment&&adopt(menu))}menu=candidate}return withDefaultMenu(menu,input)};const validated=(given,id,addedAt)=>{const raw=current(given);const item=Object.hasOwn(menu.items,raw.itemId)?menu.items[raw.itemId]:void 0;const problems=validateLine(item,raw,{menu,branch});if(problems.length||!item){throw new ZappieCartError(problems)}const input=normalizeInput(item,raw);const variant=resolveVariant(item,input);const{choices}=input;const unitPrice=estimateUnitPrice(item,{choices,variantId:variant.id});return freezeLine({id:id??`line_${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(10)),byte=>(byte%36).toString(36)).join("")}`,itemId:item.id,...input.menuId!==void 0?{menuId:input.menuId}:{},name:item.name,quantity:input.quantity,choices,inputs:input.inputs??{},variantId:variant.id,...input.note!==void 0?{note:input.note}:{},unitPrice,lineSubtotal:multiplyMoney(unitPrice,input.quantity),addedAt:addedAt??new Date().toISOString()})};const offMenu=events.on("menu:updated",({branchId,version})=>{if(branch?.id===branchId){const value=menus.peek(branchId,mode());if(value&&value.completeness!=="partial"&&value.version===version&&value.version!==menu?.version){refreshSequence++;adopt(value)}}});const cart={getSnapshot:()=>snapshot,subscribe(fn){listeners.add(fn);return()=>{listeners.delete(fn)}},async hydrate(){if(snapshot.isHydrated){resume();return refresh()}const life=lifecycle;hydration??(hydration=(async()=>{const value=await store.get();const target=pick(value.branches);if(!target){throw new ZappieError("branch_not_found","Cart branch is unavailable")}let inputs=snapshot.lines;let type;if(!snapshot.isHydrated){const raw=readSaved(target.id);try{const saved=raw?parseCart(raw):void 0;inputs=saved&&Date.now()-saved.updatedAt<=ttl?saved.lines:raw===null?legacy?.(storage.read)??[]:[];type=menus.peek(target.id)?.fulfilment&&typeOf(saved?.fulfilment)}catch{inputs=[]}}const loaded=await deps.workingSet.read(target.id,inputs.map(l=>l.itemId),type);if(life!==lifecycle){return}choose(loaded);ensure();resume();if(loaded.completeness!=="partial"){await refresh()}})().finally(()=>{hydration=void 0}));return hydration},mount(){mounted++;if(!detach&&typeof window!=="undefined"){const onStorage=event=>{if(branch&&event.key===key()&&storage.accepts(event.storageArea)){const raw=event.newValue;let saved;try{saved=raw?parseCart(raw):void 0}catch{load(raw,false);return}const ids=saved?.lines.map(l=>l.itemId)??[];const type=menu?.fulfilment&&typeOf(saved?.fulfilment);const cached=deps.workingSet.peek(branch.id,ids,type);if(cached.completeness!=="partial"||ids.every(id=>cached.items[id])){menu=cached;load(raw,false);schedule();return}const rev=revision;const request=++refreshSequence;const life=lifecycle;void deps.workingSet.read(branch.id,ids,type).then(value=>{if(life===lifecycle&&rev===revision&&request===refreshSequence){menu=value;load(raw,false);schedule()}}).catch(report)}};const onFocus=()=>{void refresh().catch(report)};window.addEventListener("storage",onStorage);window.addEventListener("focus",onFocus);detach=()=>{window.removeEventListener("storage",onStorage);window.removeEventListener("focus",onFocus)}}if(mounted===1){void cart.hydrate().catch(report)}let active=true;return()=>{if(active){active=false;mounted--;if(mounted===0){detach?.();detach=void 0;cancel()}}}},dispose(){lifecycle++;moveSequence++;offMenu();cancel();detach?.();detach=void 0;listeners.clear()},validate(input){ensure();const line=current(input);const problems=validateLine(Object.hasOwn(menu.items,line.itemId)?menu.items[line.itemId]:void 0,line,{menu,branch});return problems.length?{ok:false,issues:problems}:{ok:true}},add(item,input={}){ensure();let line=validated({...input,itemId:typeof item==="string"?item:item.id});const existing=snapshot.lines.find(l=>identity(lineInput(l))===identity(lineInput(line)));if(existing){line=validated({...lineInput(line),quantity:existing.quantity+line.quantity},existing.id,existing.addedAt)}else if(snapshot.lines.length>=100){throw new ZappieCartError([issue("quantity_limit","A cart can contain at most 100 lines")])}changed(existing?snapshot.lines.map(l=>l.id===existing.id?line:l):[...snapshot.lines,line]);events.emit("add_to_cart",{itemId:line.itemId,quantity:line.quantity-(existing?.quantity??0),value:multiplyMoney(line.unitPrice,line.quantity-(existing?.quantity??0))});return line},update(lineId,patch){ensure();const old=snapshot.lines.find(l=>l.id===lineId);if(!old){throw new ZappieCartError([issue("item_not_found","Cart line not found")])}const input={...lineInput(old),...patch};if(patch.choices&&!patch.variantId){delete input.variantId}let line=validated(input,old.id,old.addedAt);const duplicate=snapshot.lines.find(l=>l.id!==lineId&&identity(lineInput(l))===identity(lineInput(line)));if(duplicate){line=validated({...lineInput(line),quantity:line.quantity+duplicate.quantity},old.id,old.addedAt)}changed(snapshot.lines.filter(l=>l.id!==duplicate?.id).map(l=>l.id===lineId?line:l));events.emit("update_cart_line",{lineId,itemId:line.itemId,quantity:line.quantity});return line},remove(lineId){ensure();const line=snapshot.lines.find(l=>l.id===lineId);changed(snapshot.lines.filter(l=>l.id!==lineId));if(line){events.emit("remove_from_cart",{itemId:line.itemId,quantity:line.quantity,value:line.lineSubtotal})}},clear(){ensure();changed([],{fulfilment:null,promoCode:null,perks:[]})},setFulfilment(value){ensure();if(!validFulfilment(value)||value.branchId!==branch.id){throw new ZappieCartError([issue("fulfilment_unavailable","Select fulfilment for the cart's branch")])}changed(snapshot.lines,{fulfilment:structuredClone(value)})},setPromoCode(code){ensure();changed(snapshot.lines,{promoCode:code?.trim()||null})},setPerks(perks){ensure();changed(snapshot.lines,{perks:[...perks]})},setCustomer(next){if(JSON.stringify(next)!=JSON.stringify(customer)){customer=next;schedule()}},setPendingFulfilment(next){planned=next&&{type:next.type,...next.scheduledFor&&{scheduled_for:next.scheduledFor}};schedule();follow()},async moveTo(branchId){ensure();const seq=++moveSequence;cancel();publish({state:attention(snapshot.issues)});const value=await deps.workingSet.read(branchId,snapshot.lines.map(l=>l.itemId),mode());if(seq!==moveSequence){return}const oldKey=key();const oldLines=snapshot.lines;choose(value);const kept=oldLines.filter(line=>!validateLine(value.items[line.itemId],lineInput(line),{menu:value,branch}).length);changed(kept,{fulfilment:null,promoCode:null,perks:[]});const dropped=oldLines.filter(line=>!kept.includes(line)).map(line=>({...issue("item_unavailable",`${line.name} is unavailable at this branch`),severity:"warning",lineId:line.id}));const issues=[...snapshot.issues,...dropped];publish({issues,state:attention(issues)});if(oldKey!==key()){storage.remove(oldKey)}},async quote(opts={}){ensure();clearTimeout(timer);if(opts.force){events.emit("view_cart",{})}const body={branch_id:branch.id,...snapshot.fulfilment?{fulfilment:wireFulfilment(snapshot.fulfilment)}:planned&&{fulfilment:planned},...wire()};const failure=opts.force?void 0:quotes?.failure(body);if(failure!==void 0){throw asError(failure)}const seq=revision;const attempt=++quoteRevision;publish({state:{status:"quoting"}});try{const client=await quoteClient();return await client.get(body,opts.force??false,quote=>{if(seq!==revision){return}const local=snapshot.issues.filter(i=>i.source==="local");const remote=quote.issues.filter(q=>!local.some(l=>l.code===q.code&&l.lineId===q.lineId&&l.groupId===q.groupId));const issues=[...local,...remote];publish({issues,state:attention(issues,quote)});for(const i of remote){events.emit("cart_issue",{code:i.code})}if(quote.menuVersion!==menu.version||quote.issues.some(i=>i.code==="menu_version_stale")){void refresh(quote.menuVersion).catch(report)}})}catch(error){if(seq===revision&&attempt===quoteRevision){const local=snapshot.issues.filter(i=>i.source==="local");publish({issues:local,state:attention(local)});events.emit("quote_failed",{code:asError(error).code})}throw error instanceof Error&&error.name==="AbortError"?error:asError(error)}},applyFix(problem,fix=problem.fixes[0]){if(!snapshot.issues.includes(problem)||!fix||!problem.fixes.some(f=>JSON.stringify(f)===JSON.stringify(fix))){throw new ZappieError("invalid_request","Choose a current cart issue and one of its fixes")}switch(fix.action){case"remove_line":{if(problem.lineId){cart.remove(problem.lineId)}return}case"remove_promo":cart.setPromoCode(null);return;case"remove_perks":cart.setPerks([]);return;case"set_quantity":{if(problem.lineId){cart.update(problem.lineId,{quantity:fix.quantity})}return}case"accept_price":{quotes?.accept(problem);const issues=snapshot.issues.filter(i=>i!==problem);const quote="quote"in snapshot.state?snapshot.state.quote:void 0;const accepted=quote?{...quote,issues:quote.issues.filter(i=>!(i.code===problem.code&&i.lineId===problem.lineId))}:void 0;publish({issues,state:attention(issues,accepted)});return}case"choose_region":throw new ZappieError("invalid_request","Choose a delivery region and call setFulfilment with deliveryRegionId");default:throw new ZappieError("invalid_request",`${fix.action} needs the shopper's input`)}},toCheckoutPayload(){ensure();const blocking=snapshot.issues.filter(i=>i.severity==="blocking");if(!snapshot.lines.length||!snapshot.fulfilment){blocking.push(issue("fulfilment_unavailable","Add items and select fulfilment before checkout"))}if(blocking.length){throw new ZappieCartError(blocking)}return{fulfilment:structuredClone(snapshot.fulfilment),...wire()}}};for(const field of Object.keys(EMPTY_CART)){Object.defineProperty(cart,field,{get:()=>snapshot[field]})}return{cart:Object.freeze(cart),cartCatalogue:()=>menu,setLegacyReader(reader){legacy=reader}}}export{EMPTY_CART,createCart};
1
+ import{asError,ZappieError}from"../errors.js";import{multiplyMoney,sumMoney}from"../internal/money-math.js";import{money}from"../money.js";import{ZappieCartError}from"./errors.js";import{estimateUnitPrice}from"./price.js";import{freezeLine,lineInput,reconcile}from"./reconcile.js";import{withDefaultMenu}from"./source-menu.js";import{createCartStorage,parseCart,validFulfilment}from"./storage.js";import{issue,normalizeInput,resolveVariant,validateLine}from"./validate.js";import{wireFulfilment,wireLine}from"./wire.js";var typeOf=value=>value?.type.replace("_i","I");var EMPTY_CART=deepFreeze({branchId:void 0,lines:[],count:0,subtotal:null,fulfilment:null,promoCode:null,perks:[],state:{status:"ready"},issues:[],isHydrated:false});function deepFreeze(value){if(value&&typeof value==="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const child of Object.values(value)){deepFreeze(child)}}return value}function identity(input){return JSON.stringify([input.itemId,input.menuId,input.variantId,input.note??"",[...input.choices??[]].sort((a,b)=>a.groupId.localeCompare(b.groupId)||a.choiceId.localeCompare(b.choiceId)),Object.entries(input.inputs??{}).sort(([a],[b])=>a.localeCompare(b))])}function createCart(deps){const{config,menu:menus,store,events}=deps;const ttl=config.cart?.ttl??7*24*60*60*1e3;if(!Number.isFinite(ttl)||ttl<=0){throw new ZappieError("invalid_request","Cart ttl must be positive milliseconds")}let snapshot=EMPTY_CART;let menu;let branch;let selected=config.branch;let updatedAt=0;let timer;let revision=0;let quoteRevision=0;let moveSequence=0;let refreshSequence=0;let chased;let chasedAt=0;let mounted=0;let detach;let hydration;let lifecycle=0;let legacy;const listeners=new Set;const prefix=`zappie:cart:v1:${config.store}:`;const scope=config.cart?.storageScope;const keyFor=id=>`${prefix}${id}${scope?`:${scope}`:""}`;const key=()=>keyFor(branch.id);const storage=createCartStorage(config.storage,message=>events.emit("warning",{message}));const readSaved=id=>{let raw=storage.read(keyFor(id));if(raw===null&&scope){raw=storage.read(prefix+id);if(raw!==null){storage.remove(prefix+id);storage.write(keyFor(id),raw)}}return raw};let quotes;let loadingQuotes;const quoteClient=()=>loadingQuotes??(loadingQuotes=import("./quote-client.js").then(({createQuoteClient})=>quotes=createQuoteClient(deps.transport,deps.context,config),error=>{loadingQuotes=void 0;throw error}));const publish=patch=>{snapshot=deepFreeze({...snapshot,...patch,branchId:branch?.id});for(const fn of[...listeners]){try{fn()}catch(error){report(error)}}};const attention=(issues,quote)=>issues.some(i=>i.severity!=="info")?{status:"needs_attention",issues,...quote?{quote}:{}}:quote?{status:"quoted",quote}:{status:"ready"};const cancel=()=>{revision++;quoteRevision++;clearTimeout(timer);quotes?.cancel()};let customer=null;let planned=null;const mode=()=>menu?.fulfilment&&(typeOf(snapshot.fulfilment??planned)??menu.fulfilment);const wire=()=>({lines:snapshot.lines.map(wireLine),...customer?{customer}:{},...snapshot.promoCode?{promo_code:snapshot.promoCode}:{},...snapshot.perks.length&&snapshot.fulfilment?.type!="dine_in"?{perk_redemption_ids:snapshot.perks.map(p=>p.redemptionId)}:{},menu_version:menu.version});const persist=()=>{const value={v:1,lines:snapshot.lines.map(line=>({...lineInput(line),id:line.id,name:line.name,addedAt:line.addedAt,unitPrice:line.unitPrice})),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,perks:snapshot.perks,menuVersion:menu.version,updatedAt};storage.write(key(),JSON.stringify(value))};const schedule=()=>{clearTimeout(timer);if(snapshot.lines.length){timer=setTimeout(()=>{void cart.quote().catch(()=>{})},300)}};const resume=()=>{if(!("quote"in snapshot.state)){schedule()}};const recompute=(lines,pending=snapshot.issues.filter(i=>i.source==="local"),patch={})=>{const currency=store.peek().currency;const result=reconcile(lines,menu,branch,currency,pending);const subtotal=result.priced?sumMoney(result.lines.map(l=>l.lineSubtotal),money(0,currency)):null;publish({...patch,lines:result.lines,count:result.lines.reduce((n,l)=>n+l.quantity,0),subtotal,issues:result.issues,state:attention(result.issues)});for(const i of result.issues){events.emit("cart_issue",{code:i.code})}};const changed=(lines=snapshot.lines,patch={})=>{cancel();recompute(lines,void 0,patch);updatedAt=Date.now();persist();schedule();follow()};const adopt=value=>{menu=value;cancel();recompute(snapshot.lines);persist();schedule()};const report=error=>events.emit("error",{error:asError(error)});const follow=()=>{if(mode()!=menu?.fulfilment){refresh(void 0,true).catch(report)}};const choose=value=>{const found=store.peek()?.branches.find(b=>b.id===value.branchId);if(!found){throw new ZappieError("branch_not_found","Load the storefront branch before using its cart")}menu=value;branch=found;selected=found.id};const load=(raw,writeBack=true)=>{cancel();let saved;try{saved=raw?parseCart(raw):void 0;if(saved&&Date.now()-saved.updatedAt>ttl){saved=void 0;storage.remove(key());events.emit("cart_expired",{branchId:branch.id})}}catch{storage.remove(key());storage.warning("Invalid saved cart discarded")}updatedAt=saved?.updatedAt??Date.now();const idle=Date.now()-updatedAt;let fulfilment=saved?.fulfilment??null;if(fulfilment?.branchId!==branch.id||idle>864e5&&fulfilment.type==="delivery"){fulfilment=null}if(fulfilment&&"scheduledFor"in fulfilment&&fulfilment.scheduledFor&&Date.parse(fulfilment.scheduledFor)<Date.now()){fulfilment={...fulfilment};delete fulfilment.scheduledFor}const lines=(saved?.lines??[]).map(line=>({...line,...idle>864e5?{inputs:{}}:{}}));const result=reconcile(lines,menu,branch,store.peek().currency);recompute(result.lines,result.issues,{fulfilment,promoCode:saved?.promoCode??null,perks:saved?.perks??[],isHydrated:true});if(raw!==null&&writeBack){persist()}storage.sweep(prefix,key(),ttl);follow()};const pick=(branches=[])=>branches.find(b=>b.id===selected||b.slug===selected)??(selected?void 0:branches.find(b=>b.isDefault)??branches[0]);const ensure=()=>{if(snapshot.isHydrated){return}const id=branch?.id??pick(store.peek()?.branches)?.id;const loaded=menu??(id?deps.workingSet.peek(id,[]):void 0);if(!loaded||!store.peek()){throw new ZappieError("invalid_request","Load the store and menu before editing the cart")}choose(loaded);const raw=readSaved(branch.id);let migrated=[];if(raw===null&&legacy){try{migrated=legacy(storage.read)}catch{storage.warning("Invalid legacy cart discarded")}}load(raw);if(raw===null&&legacy){persist()}for(const input of migrated.slice(0,100)){try{cart.add(input.itemId,input)}catch{events.emit("cart_issue",{code:"item_unavailable"})}}};const refresh=async(target,switched)=>{const id=branch?.id;const seq=moveSequence;const request=++refreshSequence;const rev=revision;if(!id||!menu){return}if(!snapshot.lines.length){return}if(!switched&&menu.completeness!=="partial"){const version=await deps.transport.getMenuVersion({...deps.context(),branchId:id,fulfilment:mode()});if(version.version===menu.version){return}target=version.version}if(target&&target===chased&&Date.now()-chasedAt<3e4){return}chased=target;chasedAt=Date.now();const value=await deps.workingSet.read(id,snapshot.lines.map(l=>l.itemId),mode(),!switched);if(seq!==moveSequence||request!==refreshSequence||rev!==revision||JSON.stringify(value)===JSON.stringify(menu)){return}adopt(value)};const current=input=>{const{itemId}=input;const candidate=deps.workingSet.peek(branch.id,[...snapshot.lines.map(l=>l.itemId),itemId],mode());if(candidate.items[itemId]){if(candidate!=menu&&candidate.completeness!="partial"){queueMicrotask(()=>menu==candidate&&mode()==menu.fulfilment&&adopt(menu))}menu=candidate}return withDefaultMenu(menu,input)};const validated=(given,id,addedAt)=>{const raw=current(given);const item=Object.hasOwn(menu.items,raw.itemId)?menu.items[raw.itemId]:void 0;const problems=validateLine(item,raw,{menu,branch});if(problems.length||!item){throw new ZappieCartError(problems)}const input=normalizeInput(item,raw);const variant=resolveVariant(item,input);const{choices}=input;const unitPrice=estimateUnitPrice(item,{choices,variantId:variant.id});return freezeLine({id:id??`line_${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(10)),byte=>(byte%36).toString(36)).join("")}`,itemId:item.id,...input.menuId!==void 0?{menuId:input.menuId}:{},name:item.name,quantity:input.quantity,choices,inputs:input.inputs??{},variantId:variant.id,...input.note!==void 0?{note:input.note}:{},unitPrice,lineSubtotal:multiplyMoney(unitPrice,input.quantity),addedAt:addedAt??new Date().toISOString()})};const offMenu=events.on("menu:updated",({branchId,version})=>{if(branch?.id===branchId){const value=menus.peek(branchId,mode());if(value&&value.completeness!=="partial"&&value.version===version&&value.version!==menu?.version){refreshSequence++;adopt(value)}}});const cart={getSnapshot:()=>snapshot,subscribe(fn){listeners.add(fn);return()=>{listeners.delete(fn)}},async hydrate(){if(snapshot.isHydrated){resume();return refresh()}const life=lifecycle;hydration??(hydration=(async()=>{const value=await store.get();const target=pick(value.branches);if(!target){throw new ZappieError("branch_not_found","Cart branch is unavailable")}let inputs=snapshot.lines;let type;if(!snapshot.isHydrated){const raw=readSaved(target.id);try{const saved=raw?parseCart(raw):void 0;inputs=saved&&Date.now()-saved.updatedAt<=ttl?saved.lines:raw===null?legacy?.(storage.read)??[]:[];type=menus.peek(target.id)?.fulfilment&&typeOf(saved?.fulfilment)}catch{inputs=[]}}const loaded=await deps.workingSet.read(target.id,inputs.map(l=>l.itemId),type);if(life!==lifecycle){return}choose(loaded);ensure();resume();if(loaded.completeness!=="partial"){await refresh()}})().finally(()=>{hydration=void 0}));return hydration},mount(){mounted++;if(!detach&&typeof window!=="undefined"){const onStorage=event=>{if(branch&&event.key===key()&&storage.accepts(event.storageArea)){const raw=event.newValue;let saved;try{saved=raw?parseCart(raw):void 0}catch{load(raw,false);return}const ids=saved?.lines.map(l=>l.itemId)??[];const type=menu?.fulfilment&&typeOf(saved?.fulfilment);const cached=deps.workingSet.peek(branch.id,ids,type);if(cached.completeness!=="partial"||ids.every(id=>cached.items[id])){menu=cached;load(raw,false);schedule();return}const rev=revision;const request=++refreshSequence;const life=lifecycle;void deps.workingSet.read(branch.id,ids,type).then(value=>{if(life===lifecycle&&rev===revision&&request===refreshSequence){menu=value;load(raw,false);schedule()}}).catch(report)}};const onFocus=()=>{void refresh().catch(report)};window.addEventListener("storage",onStorage);window.addEventListener("focus",onFocus);detach=()=>{window.removeEventListener("storage",onStorage);window.removeEventListener("focus",onFocus)}}if(mounted===1){void cart.hydrate().catch(report)}let active=true;return()=>{if(active){active=false;mounted--;if(mounted===0){detach?.();detach=void 0;cancel()}}}},dispose(){lifecycle++;moveSequence++;offMenu();cancel();detach?.();detach=void 0;listeners.clear()},validate(input){ensure();const line=current(input);const problems=validateLine(Object.hasOwn(menu.items,line.itemId)?menu.items[line.itemId]:void 0,line,{menu,branch});return problems.length?{ok:false,issues:problems}:{ok:true}},add(item,input={}){ensure();let line=validated({...input,itemId:typeof item==="string"?item:item.id});const existing=snapshot.lines.find(l=>identity(lineInput(l))===identity(lineInput(line)));if(existing){line=validated({...lineInput(line),quantity:existing.quantity+line.quantity},existing.id,existing.addedAt)}else if(snapshot.lines.length>=100){throw new ZappieCartError([issue("quantity_limit","A cart can contain at most 100 lines")])}changed(existing?snapshot.lines.map(l=>l.id===existing.id?line:l):[...snapshot.lines,line]);events.emit("add_to_cart",{itemId:line.itemId,quantity:line.quantity-(existing?.quantity??0),value:multiplyMoney(line.unitPrice,line.quantity-(existing?.quantity??0))});return line},update(lineId,patch){ensure();const old=snapshot.lines.find(l=>l.id===lineId);if(!old){throw new ZappieCartError([issue("item_not_found","Cart line not found")])}const input={...lineInput(old),...patch};if(patch.choices&&!patch.variantId){delete input.variantId}let line=validated(input,old.id,old.addedAt);const duplicate=snapshot.lines.find(l=>l.id!==lineId&&identity(lineInput(l))===identity(lineInput(line)));if(duplicate){line=validated({...lineInput(line),quantity:line.quantity+duplicate.quantity},old.id,old.addedAt)}changed(snapshot.lines.filter(l=>l.id!==duplicate?.id).map(l=>l.id===lineId?line:l));events.emit("update_cart_line",{lineId,itemId:line.itemId,quantity:line.quantity});return line},remove(lineId){ensure();const line=snapshot.lines.find(l=>l.id===lineId);changed(snapshot.lines.filter(l=>l.id!==lineId));if(line){events.emit("remove_from_cart",{itemId:line.itemId,quantity:line.quantity,value:line.lineSubtotal})}},clear(){ensure();changed([],{fulfilment:null,promoCode:null,perks:[]})},setFulfilment(value){ensure();if(!validFulfilment(value)||value.branchId!==branch.id){throw new ZappieCartError([issue("fulfilment_unavailable","Select fulfilment for the cart's branch")])}changed(snapshot.lines,{fulfilment:structuredClone(value)})},setPromoCode(code){ensure();changed(snapshot.lines,{promoCode:code?.trim()||null})},setPerks(perks){ensure();changed(snapshot.lines,{perks:[...perks]})},setCustomer(next){if(JSON.stringify(next)!=JSON.stringify(customer)){customer=next;schedule()}},setPendingFulfilment(next){planned=next&&{type:next.type,...next.scheduledFor&&{scheduled_for:next.scheduledFor}};schedule();follow()},async moveTo(branchId){ensure();const seq=++moveSequence;cancel();publish({state:attention(snapshot.issues)});const value=await deps.workingSet.read(branchId,snapshot.lines.map(l=>l.itemId),mode());if(seq!==moveSequence){return}const oldKey=key();const oldLines=snapshot.lines;choose(value);const kept=oldLines.filter(line=>!validateLine(value.items[line.itemId],lineInput(line),{menu:value,branch}).length);changed(kept,{fulfilment:null,promoCode:null,perks:[]});const dropped=oldLines.filter(line=>!kept.includes(line)).map(line=>({...issue("item_unavailable",`${line.name} is unavailable at this branch`),severity:"warning",lineId:line.id}));const issues=[...snapshot.issues,...dropped];publish({issues,state:attention(issues)});if(oldKey!==key()){storage.remove(oldKey)}},async quote(opts={}){ensure();clearTimeout(timer);if(opts.force){events.emit("view_cart",{})}const body={branch_id:branch.id,...snapshot.fulfilment?{fulfilment:wireFulfilment(snapshot.fulfilment)}:planned&&{fulfilment:planned},...wire()};const failure=opts.force?void 0:quotes?.failure(body);if(failure!==void 0){throw asError(failure)}const seq=revision;const attempt=++quoteRevision;publish({state:{status:"quoting"}});try{const client=await quoteClient();return await client.get(body,opts.force??false,quote=>{if(seq!==revision){return}const local=snapshot.issues.filter(i=>i.source==="local");const remote=quote.issues.filter(q=>!local.some(l=>l.lineId===q.lineId&&l.groupId===q.groupId&&(l.code===q.code||l.code==="option_unavailable"&&q.code==="option_limit")));const issues=[...local,...remote];publish({issues,state:attention(issues,quote)});for(const i of remote){events.emit("cart_issue",{code:i.code})}if(quote.menuVersion!==menu.version||quote.issues.some(i=>i.code==="menu_version_stale")){void refresh(quote.menuVersion).catch(report)}})}catch(error){if(seq===revision&&attempt===quoteRevision){const local=snapshot.issues.filter(i=>i.source==="local");publish({issues:local,state:attention(local)});events.emit("quote_failed",{code:asError(error).code})}throw error instanceof Error&&error.name==="AbortError"?error:asError(error)}},applyFix(problem,fix=problem.fixes[0]){if(!snapshot.issues.includes(problem)||!fix||!problem.fixes.some(f=>JSON.stringify(f)===JSON.stringify(fix))){throw new ZappieError("invalid_request","Choose a current cart issue and one of its fixes")}switch(fix.action){case"remove_line":{if(problem.lineId){cart.remove(problem.lineId)}return}case"remove_promo":cart.setPromoCode(null);return;case"remove_perks":cart.setPerks([]);return;case"set_quantity":{if(problem.lineId){cart.update(problem.lineId,{quantity:fix.quantity})}return}case"accept_price":{quotes?.accept(problem);const issues=snapshot.issues.filter(i=>i!==problem);const quote="quote"in snapshot.state?snapshot.state.quote:void 0;const accepted=quote?{...quote,issues:quote.issues.filter(i=>!(i.code===problem.code&&i.lineId===problem.lineId))}:void 0;publish({issues,state:attention(issues,accepted)});return}case"choose_region":throw new ZappieError("invalid_request","Choose a delivery region and call setFulfilment with deliveryRegionId");default:throw new ZappieError("invalid_request",`${fix.action} needs the shopper's input`)}},toCheckoutPayload(){ensure();const blocking=snapshot.issues.filter(i=>i.severity==="blocking");if(!snapshot.lines.length||!snapshot.fulfilment){blocking.push(issue("fulfilment_unavailable","Add items and select fulfilment before checkout"))}if(blocking.length){throw new ZappieCartError(blocking)}return{fulfilment:structuredClone(snapshot.fulfilment),...wire()}}};for(const field of Object.keys(EMPTY_CART)){Object.defineProperty(cart,field,{get:()=>snapshot[field]})}return{cart:Object.freeze(cart),cartCatalogue:()=>menu,setLegacyReader(reader){legacy=reader}}}export{EMPTY_CART,createCart};
package/dist/debug.js CHANGED
@@ -1 +1 @@
1
- var VERSION=true?"0.30.1":"0.0.0-development";function installDebug(client){if(typeof window==="undefined"||client.mode!=="test"){return}const events=[];let quote;const emit=(name,detail)=>{const event={name,detail,at:new Date().toISOString()};events.push(event);window.dispatchEvent(new CustomEvent("zappie:event",{detail:event}))};globalThis.__zappieEmit=emit;window.__zappie={version:VERSION,store:client.config.store,async catalogue(){await client.cart.hydrate();const branch=(await client.store.get()).branches.find(value=>value.id===client.cart.getSnapshot().branchId);return{branch,menu:await client.menu.get({branch:branch.id})}},cart:Object.assign(()=>client.cart.getSnapshot(),{async inject(input){await client.cart.hydrate();if(input.lines.length>100||input.lines.some(line=>!Number.isInteger(line.quantity??1)||(line.quantity??1)<1||(line.quantity??1)>99)){throw new Error("Use up to 100 cart lines with whole quantities from 1 to 99.")}const snapshot=client.cart.getSnapshot();const value={v:1,menuVersion:client._internal.cartCatalogue().version,updatedAt:Date.now(),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,lines:input.lines.map((line,index)=>({...line,id:`debug_${index}`,name:line.itemId,quantity:line.quantity??1,choices:(line.choices??[]).map(choice=>({...choice,quantity:choice.quantity??1})),inputs:line.inputs??{},addedAt:new Date().toISOString()}))};const scope=client.config.cart?.storageScope;(client.config.storage??window.localStorage).setItem(`zappie:cart:v1:${client.config.store}:${snapshot.branchId}${scope?`:${scope}`:""}`,JSON.stringify(value))}}),quote:()=>quote,events};client.on("add_to_cart",detail=>emit("add_to_cart",detail));client.cart.subscribe(()=>{const state=client.cart.state;const next="quote"in state?state.quote:void 0;if(next&&next!==quote){quote=next;emit("quote",next)}})}export{installDebug};
1
+ var VERSION=true?"0.30.4":"0.0.0-development";function installDebug(client){if(typeof window==="undefined"||client.mode!=="test"){return}const events=[];let quote;const emit=(name,detail)=>{const event={name,detail,at:new Date().toISOString()};events.push(event);window.dispatchEvent(new CustomEvent("zappie:event",{detail:event}))};globalThis.__zappieEmit=emit;window.__zappie={version:VERSION,store:client.config.store,async catalogue(){await client.cart.hydrate();const branch=(await client.store.get()).branches.find(value=>value.id===client.cart.getSnapshot().branchId);return{branch,menu:await client.menu.get({branch:branch.id})}},cart:Object.assign(()=>client.cart.getSnapshot(),{async inject(input){await client.cart.hydrate();if(input.lines.length>100||input.lines.some(line=>!Number.isInteger(line.quantity??1)||(line.quantity??1)<1||(line.quantity??1)>99)){throw new Error("Use up to 100 cart lines with whole quantities from 1 to 99.")}const snapshot=client.cart.getSnapshot();const value={v:1,menuVersion:client._internal.cartCatalogue().version,updatedAt:Date.now(),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,lines:input.lines.map((line,index)=>({...line,id:`debug_${index}`,name:line.itemId,quantity:line.quantity??1,choices:(line.choices??[]).map(choice=>({...choice,quantity:choice.quantity??1})),inputs:line.inputs??{},addedAt:new Date().toISOString()}))};const scope=client.config.cart?.storageScope;(client.config.storage??window.localStorage).setItem(`zappie:cart:v1:${client.config.store}:${snapshot.branchId}${scope?`:${scope}`:""}`,JSON.stringify(value))}}),quote:()=>quote,events};client.on("add_to_cart",detail=>emit("add_to_cart",detail));client.cart.subscribe(()=>{const state=client.cart.state;const next="quote"in state?state.quote:void 0;if(next&&next!==quote){quote=next;emit("quote",next)}})}export{installDebug};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{ZappieCartError}from"./cart/errors.js";import{holdsForLater,isHeldQuote}from"./cart/held.js";import{previewItem}from"./cart/preview.js";import{estimateUnitPrice}from"./cart/price.js";import{resolveSourceMenu,withDefaultMenu}from"./cart/source-menu.js";import{validateLine}from"./cart/validate.js";import{createZappie}from"./client.js";import{API_VERSION}from"./config.js";import{ZappieError,isZappieError}from"./errors.js";export*from"./models.js";import{format,money}from"./money.js";import{RestTransport}from"./transport/rest.js";var VERSION=true?"0.30.1":"0.0.0-development";export{API_VERSION,RestTransport,VERSION,ZappieCartError,ZappieError,createZappie,estimateUnitPrice,format,holdsForLater,isHeldQuote,isZappieError,money,previewItem,resolveSourceMenu,validateLine,withDefaultMenu};
1
+ import{ZappieCartError}from"./cart/errors.js";import{holdsForLater,isHeldQuote}from"./cart/held.js";import{previewItem}from"./cart/preview.js";import{estimateUnitPrice}from"./cart/price.js";import{resolveSourceMenu,withDefaultMenu}from"./cart/source-menu.js";import{validateLine}from"./cart/validate.js";import{createZappie}from"./client.js";import{API_VERSION}from"./config.js";import{ZappieError,isZappieError}from"./errors.js";export*from"./models.js";import{format,money}from"./money.js";import{RestTransport}from"./transport/rest.js";var VERSION=true?"0.30.4":"0.0.0-development";export{API_VERSION,RestTransport,VERSION,ZappieCartError,ZappieError,createZappie,estimateUnitPrice,format,holdsForLater,isHeldQuote,isZappieError,money,previewItem,resolveSourceMenu,validateLine,withDefaultMenu};
@@ -1 +1 @@
1
- var trackers=new WeakMap;function cartActions(cart){let tracker=trackers.get(cart);if(tracker){return tracker}const confirmed=new Map;const keyed=new Map;const listeners=new Set;let notice=null;let watching=false;const emit=()=>{for(const fn of[...listeners]){fn()}};const find=lineId=>cart.lines.find(candidate=>candidate.id===lineId);const remember=(lineId,prior)=>{if(!confirmed.has(lineId)){confirmed.set(lineId,prior??null)}if(!watching){watching=true;void import("./rollback.js").then(({watch})=>watch(cart,confirmed,value=>{notice=value;emit()}))}};const actions=Object.freeze(Object.create(cart,{add:{value(item,input,{key}={}){const done=key?keyed.get(key):void 0;if(done){return find(done.id)??done}const before=cart.lines;const line=cart.add(item,input);remember(line.id,before.find(candidate=>candidate.id===line.id));if(key){keyed.set(key,line);if(keyed.size>100){keyed.delete(keyed.keys().next().value)}}return line}},update:{value(lineId,patch){const prior=find(lineId);const line=cart.update(lineId,patch);remember(lineId,prior);return line}},remove:{value(lineId){confirmed.delete(lineId);cart.remove(lineId)}}}));tracker={actions,notice:()=>notice,dismiss(){if(notice){notice=null;emit()}},subscribe(fn){listeners.add(fn);return()=>{listeners.delete(fn)}}};trackers.set(cart,tracker);return tracker}export{cartActions};
1
+ var orderOf=cart=>`${cart.branchId??""}:${cart.fulfilment?.type??""}`;var trackers=new WeakMap;function cartActions(cart){let tracker=trackers.get(cart);if(tracker){return tracker}const confirmed=new Map;const keyed=new Map;const listeners=new Set;let notice=null;let watching=false;const emit=()=>{for(const fn of[...listeners]){fn()}};const find=lineId=>cart.lines.find(candidate=>candidate.id===lineId);const remember=(lineId,prior)=>{const order=orderOf(cart);if(confirmed.get(lineId)?.order!==order){confirmed.set(lineId,{prior:prior??null,order})}if(!watching){watching=true;void import("./rollback.js").then(({watch})=>watch(cart,confirmed,value=>{notice=value;emit()},()=>orderOf(cart)))}};const actions=Object.freeze(Object.create(cart,{add:{value(item,input,{key}={}){const done=key?keyed.get(key):void 0;if(done){return find(done.id)??done}const before=cart.lines;const line=cart.add(item,input);remember(line.id,before.find(candidate=>candidate.id===line.id));if(key){keyed.set(key,line);if(keyed.size>100){keyed.delete(keyed.keys().next().value)}}return line}},update:{value(lineId,patch){const prior=find(lineId);const line=cart.update(lineId,patch);remember(lineId,prior);return line}},remove:{value(lineId){confirmed.delete(lineId);cart.remove(lineId)}}}));tracker={actions,notice:()=>notice,dismiss(){if(notice){notice=null;emit()}},subscribe(fn){listeners.add(fn);return()=>{listeners.delete(fn)}}};trackers.set(cart,tracker);return tracker}export{cartActions,orderOf};
@@ -1 +1 @@
1
- var refusals=/^(quantity_limit|item_unavailable|item_not_found|option_)/;var refuses=issue=>issue.severity==="blocking"&&refusals.test(issue.code)&&!issue.fixes.some(fix=>fix.action==="schedule");var region;function announce(message){if(typeof document==="undefined"){return}if(!region?.isConnected){region=document.createElement("div");region.setAttribute("role","status");region.setAttribute("aria-live","polite");region.setAttribute("data-zappie-announcer","");region.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)";document.body.appendChild(region)}const target=region;target.textContent="";setTimeout(()=>{target.textContent=message},50)}function watch(cart,confirmed,show){let seen;let sequence=0;const settle=()=>{const snapshot=cart.getSnapshot();const quote="quote"in snapshot.state?snapshot.state.quote:void 0;if(!quote||quote===seen){return}seen=quote;let first;let count=0;for(const[lineId,prior]of[...confirmed]){const line=snapshot.lines.find(candidate=>candidate.id===lineId);const quoted=quote.lines.find(candidate=>candidate.lineId===lineId)?.quantity;if(line&&quoted!==void 0&&quoted!==line.quantity){continue}confirmed.delete(lineId);const problem=quote.issues.find(issue=>issue.lineId===lineId&&refuses(issue));if(!line||!problem){continue}const fix=problem.fixes.find(candidate=>candidate.action==="set_quantity"&&candidate.quantity>(prior?.quantity??0)&&candidate.quantity<line.quantity);try{if(fix?.action==="set_quantity"){cart.update(lineId,{quantity:fix.quantity})}else if(prior){cart.update(lineId,{quantity:prior.quantity,choices:prior.choices,inputs:prior.inputs,variantId:prior.variantId,note:prior.note})}else{cart.remove(lineId)}first??(first=problem);count++}catch{}}if(first){announce(first.message);show({id:++sequence,code:first.code,message:first.message,...first.lineId?{lineId:first.lineId}:{},count})}};cart.subscribe(settle);settle()}export{watch};
1
+ var refusals=/^(quantity_limit|item_unavailable|item_not_found|option_)/;var refuses=issue=>issue.severity==="blocking"&&refusals.test(issue.code)&&!issue.fixes.some(fix=>fix.action==="schedule");var region;function announce(message){if(typeof document==="undefined"){return}if(!region?.isConnected){region=document.createElement("div");region.setAttribute("role","status");region.setAttribute("aria-live","polite");region.setAttribute("data-zappie-announcer","");region.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)";document.body.appendChild(region)}const target=region;target.textContent="";setTimeout(()=>{target.textContent=message},50)}function watch(cart,confirmed,show,orderOf){let seen;let sequence=0;const settle=()=>{const snapshot=cart.getSnapshot();const quote="quote"in snapshot.state?snapshot.state.quote:void 0;if(!quote||quote===seen){return}seen=quote;let first;let count=0;const order=orderOf();for(const[lineId,{prior,order:madeIn}]of[...confirmed]){if(madeIn!==order){confirmed.delete(lineId);continue}const line=snapshot.lines.find(candidate=>candidate.id===lineId);const quoted=quote.lines.find(candidate=>candidate.lineId===lineId)?.quantity;if(line&&quoted!==void 0&&quoted!==line.quantity){continue}confirmed.delete(lineId);const problem=quote.issues.find(issue=>issue.lineId===lineId&&refuses(issue));if(!line||!problem){continue}const fix=problem.fixes.find(candidate=>candidate.action==="set_quantity"&&candidate.quantity>(prior?.quantity??0)&&candidate.quantity<line.quantity);try{if(fix?.action==="set_quantity"){cart.update(lineId,{quantity:fix.quantity})}else if(prior){cart.update(lineId,{quantity:prior.quantity,choices:prior.choices,inputs:prior.inputs,variantId:prior.variantId,note:prior.note})}else{cart.remove(lineId)}first??(first=problem);count++}catch{}}if(first){announce(first.message);show({id:++sequence,code:first.code,message:first.message,...first.lineId?{lineId:first.lineId}:{},count})}};cart.subscribe(settle);settle()}export{watch};
@@ -1 +1 @@
1
- import{createSecurityNonce}from"./security.js";var EDGE_CACHE_HEADER="x-zappie-edge-cache";var DATA_VERSION_HEADER="x-zappie-data-version";var dataVersions=new WeakMap;function rememberDataVersion(request,ctx){const version=request.headers.get(DATA_VERSION_HEADER);if(ctx&&version){dataVersions.set(ctx,version)}}var STORED_AT="x-zappie-stored-at";var FRESH_FOR="x-zappie-fresh-for";var STALE_FOR="x-zappie-stale-for";var ORIGIN_CACHE_CONTROL="x-zappie-origin-cache-control";var CACHE_NAME="zappie";var opened;function openEdgeCache(){opened??(opened=(async()=>{try{return typeof caches==="undefined"?void 0:await caches.open(CACHE_NAME)}catch{return void 0}})());return opened}async function sha256(value){const digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(value));return[...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,"0")).join("")}function sharedFreshness(cacheControl){if(!cacheControl||/\b(?:private|no-store|no-cache)\b/i.test(cacheControl)){return void 0}const seconds=name=>{const match=new RegExp(`(?:^|[,\\s])${name}=(\\d+)`,"i").exec(cacheControl);return match?Number(match[1]):void 0};const fresh=seconds("s-maxage")??seconds("max-age")??0;if(fresh<=0){return void 0}return{fresh,stale:seconds("stale-while-revalidate")??0}}function storable(response,life,now){const headers=new Headers(response.headers);headers.delete("set-cookie");headers.delete(EDGE_CACHE_HEADER);const origin=response.headers.get("cache-control");if(origin){headers.set(ORIGIN_CACHE_CONTROL,origin)}headers.set(STORED_AT,String(now));headers.set(FRESH_FOR,String(life.fresh));headers.set(STALE_FOR,String(life.stale));headers.set("cache-control",`public, max-age=${life.fresh+life.stale}`);return new Response(response.body,{status:response.status,headers})}function served(cached,status,age){const headers=new Headers(cached.headers);const origin=headers.get(ORIGIN_CACHE_CONTROL);if(origin){headers.set("cache-control",origin)}else{headers.delete("cache-control")}for(const name of[STORED_AT,FRESH_FOR,STALE_FOR,ORIGIN_CACHE_CONTROL]){headers.delete(name)}headers.set("age",String(Math.max(0,Math.floor(age))));headers.set(EDGE_CACHE_HEADER,status);return new Response(cached.body,{status:cached.status,headers})}function discard(response){response.body?.cancel().catch(()=>{})}function marked(response,status){const out=new Response(response.body,response);out.headers.set(EDGE_CACHE_HEADER,status);return out}async function lookup(cache,key,now){const cached=await cache.match(key);if(!cached){return void 0}const storedAt=Number(cached.headers.get(STORED_AT));const life={fresh:Number(cached.headers.get(FRESH_FOR)),stale:Number(cached.headers.get(STALE_FOR))};if(!Number.isFinite(storedAt)||!Number.isFinite(life.fresh)||!Number.isFinite(life.stale)){discard(cached);return void 0}return{response:cached,age:(now-storedAt)/1e3,life}}var refreshing=new Map;function refreshOnce(ctx,key,refresh){if(refreshing.has(key.url)){return}const running=refresh().catch(()=>{}).finally(()=>refreshing.delete(key.url));refreshing.set(key.url,running);ctx.waitUntil(running)}var SHARED_READS=/\/(?:store|menus)$/;function apiCacheBypass(request){if(request.method!=="GET"){return"method"}if(!SHARED_READS.test(new URL(request.url).pathname)){return"path"}if(!/^Bearer pk_(?:test|live)_/.test(request.headers.get("authorization")??"")){return"credentials"}if(request.headers.has("cookie")){return"cookie"}if(request.headers.has("if-none-match")){return"conditional"}return void 0}async function apiCacheKey(request,dataVersion=""){const key=(request.headers.get("authorization")??"").replace(/^Bearer\s+/,"");const url=new URL(request.url);const parts=[key,request.headers.get("zappie-version")??""];const identity=await sha256(JSON.stringify(dataVersion?[...parts,dataVersion]:parts));return new Request(`https://zappie-api-cache.internal/${identity.slice(0,40)}/${url.host}${url.pathname}${url.search}`)}function cachedApiFetch(options={}){const upstream=options.fetch??((input,init)=>globalThis.fetch(input,init));const now=options.now??Date.now;const source=()=>options.cache??openEdgeCache();return async(input,init)=>{const request=new Request(input,init);if(apiCacheBypass(request)){return upstream(request)}let cache;let key;let hit;try{cache=await source();if(cache){key=await apiCacheKey(request,options.dataVersion??(options.ctx?dataVersions.get(options.ctx):void 0));hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache){return upstream(request)}const store=async response=>{const life=sharedFreshness(response.headers.get("cache-control"));if(response.status!==200||!life||response.headers.has("set-cookie")){return response}const copy=response.clone();const put=cache.put(key,storable(copy,life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return response};if(hit&&hit.age<hit.life.fresh){return served(hit.response,"HIT",hit.age)}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){const etag=hit.response.headers.get("etag");const kept=hit.response.clone();refreshOnce(options.ctx,key,async()=>{const headers=new Headers(request.headers);if(etag){headers.set("if-none-match",etag)}const response=await upstream(new Request(request.url,{method:"GET",headers,redirect:"manual"}));if(response.status===304){discard(response);const life2=sharedFreshness(response.headers.get("cache-control"))??hit.life;const restamped=served(kept,"HIT",0);restamped.headers.delete("age");restamped.headers.delete(EDGE_CACHE_HEADER);await cache.put(key,storable(restamped,life2,now()));return}const life=sharedFreshness(response.headers.get("cache-control"));if(response.status===200&&life&&!response.headers.has("set-cookie")){await cache.put(key,storable(response,life,now()))}else{discard(response)}});return served(hit.response,"STALE",hit.age)}if(hit){discard(hit.response)}return store(await upstream(request))}}var SESSION_COOKIE=/^(?:__Host-zappie_|__Host-zp_)|(?:^|[_-])(?:session|sess|sid|auth|token|jwt)(?:$|[_-])/i;function cookieNames(request){return(request.headers.get("cookie")??"").split(";").map(part=>part.slice(0,part.indexOf("=")>>>0).trim()).filter(Boolean)}function cookieValue(request,name){for(const part of(request.headers.get("cookie")??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name){return part.slice(index+1).trim()}}return""}function pageCacheBypass(request,options={}){if(request.method!=="GET"){return"method"}if(["x-zappie-draft","x-zappie-review","x-zappie-preview"].some(name=>request.headers.has(name))||new URL(request.url).searchParams.has("preview")){return"preview"}if(request.headers.has("x-zappie-site-state")){return"closed"}if(request.headers.has("authorization")){return"authorization"}if(request.headers.has("x-forwarded-host")||request.headers.has("forwarded")){return"forwarded"}const own=new Set(options.privateCookies??[]);if(cookieNames(request).some(name=>own.has(name)||SESSION_COOKIE.test(name))){return"session"}return void 0}async function pageCacheKey(request,options){const parts=[request.url,options.branchCookie?cookieValue(request,options.branchCookie):"",options.deployId,request.headers.get("x-zappie-site")??"",request.headers.get("x-zappie-key")??""];const version=request.headers.get(DATA_VERSION_HEADER);const identity=await sha256(JSON.stringify(version?[...parts,version]:parts));return new Request(`https://zappie-page-cache.internal/${identity}`)}function pageStoreBypass(response,fallback){if(response.status!==200){return"status"}if(response.headers.has("set-cookie")){return"set-cookie"}if(response.headers.has("x-zappie-closed-page")){return"closed"}if(/(?:^|,)\s*\*\s*(?:,|$)/.test(response.headers.get("vary")??"")){return"vary"}if(!sharedFreshness(response.headers.get("cache-control")??fallback??null)){return"cache-control"}return void 0}var NONCE=/'nonce-([A-Za-z0-9_+/=-]+)'/;var POLICY_HEADERS=["content-security-policy","content-security-policy-report-only"];async function rotatePageNonce(response,nonce=createSecurityNonce()){const old=POLICY_HEADERS.map(name=>NONCE.exec(response.headers.get(name)??"")?.[1]).find(Boolean);if(!old||!/^text\/html/i.test(response.headers.get("content-type")??"")){return response}const headers=new Headers(response.headers);for(const name of POLICY_HEADERS){const value=headers.get(name);if(value){headers.set(name,value.replaceAll(`'nonce-${old}'`,`'nonce-${nonce}'`))}}headers.delete("content-length");const body=(await response.text()).replaceAll(`nonce="${old}"`,`nonce="${nonce}"`).replaceAll(`nonce=${old}`,`nonce=${nonce}`);return new Response(body,{status:response.status,headers})}async function cachePage(request,render,options){rememberDataVersion(request,options.ctx);if(pageCacheBypass(request,options)){return marked(await render(request),"BYPASS")}const now=options.now??Date.now;let cache;let key;let hit;try{cache=await(options.cache??openEdgeCache());if(cache){key=await pageCacheKey(request,options);hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache||!key){return marked(await render(request),"BYPASS")}const fallback=()=>options.cacheControl?.(new URL(request.url));const keep=async response=>{const control=response.headers.get("cache-control")??fallback();if(pageStoreBypass(response,control)){return void 0}const life=sharedFreshness(control??null);const shared=new Response(response.body,response);if(control&&!shared.headers.has("cache-control")){shared.headers.set("cache-control",control)}return{shared,life}};if(hit&&hit.age<hit.life.fresh){return rotatePageNonce(served(hit.response,"HIT",hit.age))}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){refreshOnce(options.ctx,key,async()=>{const kept2=await keep(await render(new Request(request.url,{method:"GET",headers:request.headers})));if(kept2){await cache.put(key,storable(kept2.shared,kept2.life,now()))}else{await cache.delete(key)}});return rotatePageNonce(served(hit.response,"STALE",hit.age))}if(hit){discard(hit.response)}const rendered=await render(request);const kept=await keep(rendered);if(!kept){return marked(rendered,"MISS")}const put=cache.put(key,storable(kept.shared.clone(),kept.life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return marked(kept.shared,"MISS")}export{DATA_VERSION_HEADER,EDGE_CACHE_HEADER,apiCacheBypass,apiCacheKey,cachePage,cachedApiFetch,openEdgeCache,pageCacheBypass,pageCacheKey,pageStoreBypass,rememberDataVersion,rotatePageNonce,sharedFreshness};
1
+ import{createSecurityNonce}from"./security.js";var EDGE_CACHE_HEADER="x-zappie-edge-cache";var DATA_VERSION_HEADER="x-zappie-data-version";var dataVersions=new WeakMap;function rememberDataVersion(request,ctx){const version=request.headers.get(DATA_VERSION_HEADER);if(ctx&&version){dataVersions.set(ctx,version)}}var STORED_AT="x-zappie-stored-at";var FRESH_FOR="x-zappie-fresh-for";var STALE_FOR="x-zappie-stale-for";var ORIGIN_CACHE_CONTROL="x-zappie-origin-cache-control";var CACHE_NAME="zappie";var opened;function openEdgeCache(){opened??(opened=(async()=>{try{return typeof caches==="undefined"?void 0:await caches.open(CACHE_NAME)}catch{return void 0}})());return opened}async function sha256(value){const digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(value));return[...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,"0")).join("")}function sharedFreshness(cacheControl){if(!cacheControl||/\b(?:private|no-store|no-cache)\b/i.test(cacheControl)){return void 0}const seconds=name=>{const match=new RegExp(`(?:^|[,\\s])${name}=(\\d+)`,"i").exec(cacheControl);return match?Number(match[1]):void 0};const fresh=seconds("s-maxage")??seconds("max-age")??0;if(fresh<=0){return void 0}return{fresh,stale:seconds("stale-while-revalidate")??0}}function storable(response,life,now){const headers=new Headers(response.headers);headers.delete("set-cookie");headers.delete(EDGE_CACHE_HEADER);const origin=response.headers.get("cache-control");if(origin){headers.set(ORIGIN_CACHE_CONTROL,origin)}headers.set(STORED_AT,String(now));headers.set(FRESH_FOR,String(life.fresh));headers.set(STALE_FOR,String(life.stale));headers.set("cache-control",`public, max-age=${life.fresh+life.stale}`);return new Response(response.body,{status:response.status,headers})}function served(cached,status,age){const headers=new Headers(cached.headers);const origin=headers.get(ORIGIN_CACHE_CONTROL);if(origin){headers.set("cache-control",origin)}else{headers.delete("cache-control")}for(const name of[STORED_AT,FRESH_FOR,STALE_FOR,ORIGIN_CACHE_CONTROL]){headers.delete(name)}headers.set("age",String(Math.max(0,Math.floor(age))));headers.set(EDGE_CACHE_HEADER,status);return new Response(cached.body,{status:cached.status,headers})}function discard(response){response.body?.cancel().catch(()=>{})}function marked(response,status){const out=new Response(response.body,response);out.headers.set(EDGE_CACHE_HEADER,status);return out}async function lookup(cache,key,now){const cached=await cache.match(key);if(!cached){return void 0}const storedAt=Number(cached.headers.get(STORED_AT));const life={fresh:Number(cached.headers.get(FRESH_FOR)),stale:Number(cached.headers.get(STALE_FOR))};if(!Number.isFinite(storedAt)||!Number.isFinite(life.fresh)||!Number.isFinite(life.stale)){discard(cached);return void 0}return{response:cached,age:(now-storedAt)/1e3,life}}var refreshing=new Map;function refreshOnce(ctx,key,refresh){if(refreshing.has(key.url)){return}const running=refresh().catch(()=>{}).finally(()=>refreshing.delete(key.url));refreshing.set(key.url,running);ctx.waitUntil(running)}var SHARED_READS=/\/(?:store|menus|menus\/(?!version$)[^/]+|items\/(?!search$)[^/]+)$/;function apiCacheBypass(request){if(request.method!=="GET"){return"method"}if(!SHARED_READS.test(new URL(request.url).pathname)){return"path"}if(!/^Bearer pk_(?:test|live)_/.test(request.headers.get("authorization")??"")){return"credentials"}if(request.headers.has("cookie")){return"cookie"}if(request.headers.has("if-none-match")){return"conditional"}return void 0}async function apiCacheKey(request,dataVersion=""){const key=(request.headers.get("authorization")??"").replace(/^Bearer\s+/,"");const url=new URL(request.url);const parts=[key,request.headers.get("zappie-version")??""];const identity=await sha256(JSON.stringify(dataVersion?[...parts,dataVersion]:parts));return new Request(`https://zappie-api-cache.internal/${identity.slice(0,40)}/${url.host}${url.pathname}${url.search}`)}function cachedApiFetch(options={}){const upstream=options.fetch??((input,init)=>globalThis.fetch(input,init));const now=options.now??Date.now;const source=()=>options.cache??openEdgeCache();return async(input,init)=>{const request=new Request(input,init);request.headers.delete(DATA_VERSION_HEADER);if(apiCacheBypass(request)){return upstream(request)}const version=options.dataVersion??(options.ctx?dataVersions.get(options.ctx):void 0);if(version){request.headers.set(DATA_VERSION_HEADER,version)}let cache;let key;let hit;try{cache=await source();if(cache){key=await apiCacheKey(request,version);hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache){return upstream(request)}const store=async response=>{const life=sharedFreshness(response.headers.get("cache-control"));if(response.status!==200||!life||response.headers.has("set-cookie")){return response}const copy=response.clone();const put=cache.put(key,storable(copy,life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return response};if(hit&&hit.age<hit.life.fresh){return served(hit.response,"HIT",hit.age)}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){const etag=hit.response.headers.get("etag");const kept=hit.response.clone();refreshOnce(options.ctx,key,async()=>{const headers=new Headers(request.headers);if(etag){headers.set("if-none-match",etag)}const response=await upstream(new Request(request.url,{method:"GET",headers,redirect:"manual"}));if(response.status===304){discard(response);const life2=sharedFreshness(response.headers.get("cache-control"))??hit.life;const restamped=served(kept,"HIT",0);restamped.headers.delete("age");restamped.headers.delete(EDGE_CACHE_HEADER);await cache.put(key,storable(restamped,life2,now()));return}const life=sharedFreshness(response.headers.get("cache-control"));if(response.status===200&&life&&!response.headers.has("set-cookie")){await cache.put(key,storable(response,life,now()))}else{discard(response)}});return served(hit.response,"STALE",hit.age)}if(hit){discard(hit.response)}return store(await upstream(request))}}var SESSION_COOKIE=/^(?:__Host-zappie_|__Host-zp_)|(?:^|[_-])(?:session|sess|sid|auth|token|jwt)(?:$|[_-])/i;function cookieNames(request){return(request.headers.get("cookie")??"").split(";").map(part=>part.slice(0,part.indexOf("=")>>>0).trim()).filter(Boolean)}function cookieValue(request,name){for(const part of(request.headers.get("cookie")??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name){return part.slice(index+1).trim()}}return""}function pageCacheBypass(request,options={}){if(request.method!=="GET"){return"method"}if(["x-zappie-draft","x-zappie-review","x-zappie-preview"].some(name=>request.headers.has(name))||new URL(request.url).searchParams.has("preview")){return"preview"}if(request.headers.has("x-zappie-site-state")){return"closed"}if(request.headers.has("authorization")){return"authorization"}if(request.headers.has("x-forwarded-host")||request.headers.has("forwarded")){return"forwarded"}const own=new Set(options.privateCookies??[]);if(cookieNames(request).some(name=>own.has(name)||SESSION_COOKIE.test(name))){return"session"}return void 0}async function pageCacheKey(request,options){const parts=[request.url,options.branchCookie?cookieValue(request,options.branchCookie):"",options.deployId,request.headers.get("x-zappie-site")??"",request.headers.get("x-zappie-key")??""];const version=request.headers.get(DATA_VERSION_HEADER);const identity=await sha256(JSON.stringify(version?[...parts,version]:parts));return new Request(`https://zappie-page-cache.internal/${identity}`)}function pageStoreBypass(response,fallback){if(response.status!==200){return"status"}if(response.headers.has("set-cookie")){return"set-cookie"}if(response.headers.has("x-zappie-closed-page")){return"closed"}if(/(?:^|,)\s*\*\s*(?:,|$)/.test(response.headers.get("vary")??"")){return"vary"}if(!sharedFreshness(response.headers.get("cache-control")??fallback??null)){return"cache-control"}return void 0}var NONCE=/'nonce-([A-Za-z0-9_+/=-]+)'/;var POLICY_HEADERS=["content-security-policy","content-security-policy-report-only"];async function rotatePageNonce(response,nonce=createSecurityNonce()){const old=POLICY_HEADERS.map(name=>NONCE.exec(response.headers.get(name)??"")?.[1]).find(Boolean);if(!old||!/^text\/html/i.test(response.headers.get("content-type")??"")){return response}const headers=new Headers(response.headers);for(const name of POLICY_HEADERS){const value=headers.get(name);if(value){headers.set(name,value.replaceAll(`'nonce-${old}'`,`'nonce-${nonce}'`))}}headers.delete("content-length");const body=(await response.text()).replaceAll(`nonce="${old}"`,`nonce="${nonce}"`).replaceAll(`nonce=${old}`,`nonce=${nonce}`);return new Response(body,{status:response.status,headers})}async function cachePage(request,render,options){rememberDataVersion(request,options.ctx);if(pageCacheBypass(request,options)){return marked(await render(request),"BYPASS")}const now=options.now??Date.now;let cache;let key;let hit;try{cache=await(options.cache??openEdgeCache());if(cache){key=await pageCacheKey(request,options);hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache||!key){return marked(await render(request),"BYPASS")}const fallback=()=>options.cacheControl?.(new URL(request.url));const keep=async response=>{const control=response.headers.get("cache-control")??fallback();if(pageStoreBypass(response,control)){return void 0}const life=sharedFreshness(control??null);const shared=new Response(response.body,response);if(control&&!shared.headers.has("cache-control")){shared.headers.set("cache-control",control)}return{shared,life}};if(hit&&hit.age<hit.life.fresh){return rotatePageNonce(served(hit.response,"HIT",hit.age))}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){refreshOnce(options.ctx,key,async()=>{const kept2=await keep(await render(new Request(request.url,{method:"GET",headers:request.headers})));if(kept2){await cache.put(key,storable(kept2.shared,kept2.life,now()))}else{await cache.delete(key)}});return rotatePageNonce(served(hit.response,"STALE",hit.age))}if(hit){discard(hit.response)}const rendered=await render(request);const kept=await keep(rendered);if(!kept){return marked(rendered,"MISS")}const put=cache.put(key,storable(kept.shared.clone(),kept.life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return marked(kept.shared,"MISS")}export{DATA_VERSION_HEADER,EDGE_CACHE_HEADER,apiCacheBypass,apiCacheKey,cachePage,cachedApiFetch,openEdgeCache,pageCacheBypass,pageCacheKey,pageStoreBypass,rememberDataVersion,rotatePageNonce,sharedFreshness};
@@ -573,8 +573,8 @@ type CachedApiFetchOptions = {
573
573
  dataVersion?: string;
574
574
  };
575
575
  /**
576
- * Why an API request can't come from the shared cache, or `undefined` when it can. Only a `GET` of the store or a
577
- * menu, sent with a publishable key and no cookie, is shared. A customer's, cart's, order's or quote's call, or one
576
+ * Why an API request can't come from the shared cache, or `undefined` when it can. Only a `GET` of the store, the
577
+ * menus, a menu or an item, sent with a publishable key and no cookie, is shared. A customer's, cart's, order's or quote's call, or one
578
578
  * signed in as a shopper, is never cached.
579
579
  *
580
580
  * @param request - The request the SDK is about to send to the storefront API.
@@ -589,9 +589,10 @@ declare function apiCacheBypass(request: Request): string | undefined;
589
589
  */
590
590
  declare function apiCacheKey(request: Request, dataVersion?: string): Promise<Request>;
591
591
  /**
592
- * A fetch for `createZappie` on the server that keeps the storefront API's store and menu reads in the Worker's
593
- * cache, for as long as the API's own `Cache-Control` allows (`s-maxage`, then `stale-while-revalidate`). A stale
594
- * read answers at once and refreshes after the response through `ctx.waitUntil`, with the menu's ETag when it has
592
+ * A fetch for `createZappie` on the server that keeps the storefront API's store, menu and item reads in the Worker's
593
+ * cache, for as long as the API's own `Cache-Control` allows (`s-maxage`, then `stale-while-revalidate`). Each one
594
+ * carries the store's data version, when known, in `x-zappie-data-version`, so the API can let a read under the
595
+ * current version live long. A stale read answers at once and refreshes after the response through `ctx.waitUntil`, with the menu's ETag when it has
595
596
  * one. Every other call goes straight to the API. A cache that fails never fails the read.
596
597
  *
597
598
  * @example
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zappie/sdk",
3
- "version": "0.30.1",
3
+ "version": "0.30.4",
4
4
  "description": "Typed, framework-agnostic client for Zappie menus, carts, checkout, auth and events.",
5
5
  "type": "module",
6
6
  "sideEffects": [