@zappie/sdk 0.29.3 → 0.30.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/dist/cart/index.js +1 -1
- package/dist/cart/item.d.ts +1 -1
- package/dist/cart/quote-client.js +1 -1
- package/dist/cart/quote.d.ts +1 -1
- package/dist/cart/reconcile.js +1 -1
- package/dist/cart/working-set.js +1 -1
- package/dist/{client-CW_OWZ0l.d.ts → client-Co7NAvVq.d.ts} +19 -18
- package/dist/client.js +1 -1
- package/dist/debug.js +1 -1
- package/dist/index.d.ts +6 -6
- package/dist/index.js +1 -1
- package/dist/integrations/index.d.ts +2 -2
- package/dist/internal.d.ts +2 -2
- package/dist/{models-C77LjkK8.d.ts → models-BA7vWQIL.d.ts} +16 -2
- package/dist/persist/catalogue.d.ts +3 -3
- package/dist/react/hooks.js +1 -1
- package/dist/react/index.d.ts +23 -7
- package/dist/server/chosen-branch.js +1 -1
- package/dist/server/index.d.ts +21 -8
- package/dist/testing/index.d.ts +10 -3
- package/dist/testing/index.js +1 -1
- package/dist/transport/category-page.d.ts +21 -7
- package/dist/transport/category-page.js +1 -1
- package/dist/transport/mappers.js +1 -1
- package/dist/transport/menu-pages.js +1 -0
- package/dist/transport/rest.js +1 -1
- package/dist/transport/search.d.ts +1 -1
- package/dist/transport/selected-menu.d.ts +3 -3
- package/dist/{types-CuPaBf6k.d.ts → types-BB1F1Ita.d.ts} +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# @zappie/sdk
|
|
2
2
|
|
|
3
|
+
## 0.30.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- b159f99: A bag whose order type is not the branch's default is checked against that type's whole catalogue.
|
|
8
|
+
|
|
9
|
+
- An item read answers for the default order type, so a restored Pickup bag on a site that holds only the default catalogue's metadata was checked against delivery's copy of each item. A line could be flagged as off the menu or as missing an option that pickup does not ask for. The cart now reads the type's catalogue once, the same read the page makes, in place of a metadata-only read and the item reads. A line whose option groups the new type lacks is now flagged when the shopper switches type.
|
|
10
|
+
- A cart used before it restored its bag, such as by an item page checking its item, kept the issues it found against the default catalogue after it moved to the bag's order type's catalogue. It now checks the lines again when it moves to a newly held catalogue of its order type.
|
|
11
|
+
|
|
12
|
+
## 0.30.0
|
|
13
|
+
|
|
14
|
+
### Minor Changes
|
|
15
|
+
|
|
16
|
+
- ecb9878: Menus can differ by order type, and the SDK now reads, caches and checks them by type. A menu offered for pickup may not be offered for delivery.
|
|
17
|
+
|
|
18
|
+
- `Menu.fulfilment` names the order type the API read the catalogue for, such as the branch's default when the read named none.
|
|
19
|
+
- `loadStoreAndMenu` takes `fulfilment` and reads that type's menus, still alongside the store when the branch is known.
|
|
20
|
+
- `useMenu(branch, { fulfilment })` and `useItem(id, branch, { fulfilment })` read that type's catalogue and read again when it changes. Each type's catalogue is cached on its own. A catalogue hydrated from the server is used for its type without a request. `menu.peek` takes the type too.
|
|
21
|
+
- The cart checks lines against the catalogue of the bag's order type and names that type when it checks the catalogue's version. An item from a pickup-only menu stays in the bag on Pickup. When the shopper switches to Delivery, the line is flagged as off the menu with a remove fix, as the API's quote flags it.
|
|
22
|
+
- A restored bag, a bag changed in another tab and a branch move check the lines against the bag's order type's catalogue from the start. A held default catalogue stays the default and revalidates as the order type it holds.
|
|
23
|
+
- A line whose item is off the catalogue keeps its last price, so switching back shows no price change.
|
|
24
|
+
- `createMockZappie` takes `byFulfilment`, a branch's catalogue for each order type.
|
|
25
|
+
- A paged catalogue read reads and joins its later pages in modules loaded only when a server pages one.
|
|
26
|
+
- `Menu.fulfilment` is left out for any value other than delivery, pickup or dine-in.
|
|
27
|
+
|
|
28
|
+
Reads and `loadStoreAndMenu` without an order type are unchanged. The cart follows the shopper's chosen order type on every site once the API names the type a catalogue is for, so on Pickup a line from a delivery-only menu is flagged the same way.
|
|
29
|
+
|
|
3
30
|
## 0.29.3
|
|
4
31
|
|
|
5
32
|
### Patch Changes
|
package/dist/cart/index.js
CHANGED
|
@@ -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 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){events.emit("error",{error:asError(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 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()};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)};const ensure=()=>{const id=branch?.id??store.peek()?.branches.find(b=>b.id===selected||b.slug===selected||!selected&&b.isDefault)?.id??(!selected?store.peek()?.branches[0]?.id:void 0);if(snapshot.isHydrated){return}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=>{const id=branch?.id;const seq=moveSequence;const request=++refreshSequence;const rev=revision;if(!id||!menu){return}if(!snapshot.lines.length){return}if(menu.completeness!=="partial"){const version=await deps.transport.getMenuVersion({...deps.context(),branchId:id});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),true);if(seq!==moveSequence||request!==refreshSequence||rev!==revision||JSON.stringify(value)===JSON.stringify(menu)){return}menu=value;cancel();recompute(snapshot.lines);persist();schedule()};const current=input=>{const{itemId}=input;const candidate=deps.workingSet.peek(branch.id,[...snapshot.lines.map(l=>l.itemId),itemId]);if(candidate.items[itemId]){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.choices??[]).map(c=>({...c,quantity:c.quantity??1}));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);if(value&&value.completeness!=="partial"&&value.version===version&&value.version!==menu?.version){refreshSequence++;menu=value;cancel();recompute(snapshot.lines);persist();schedule()}}});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=value.branches.find(b=>b.id===selected||b.slug===selected)??(!selected?value.branches.find(b=>b.isDefault)??value.branches[0]:void 0);if(!target){throw new ZappieError("branch_not_found","Cart branch is unavailable")}let inputs=snapshot.lines;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)??[]:[]}catch{inputs=[]}}const loaded=await deps.workingSet.read(target.id,inputs.map(l=>l.itemId));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 ids;try{ids=raw?parseCart(raw).lines.map(l=>l.itemId):[]}catch{load(raw,false);return}const cached=deps.workingSet.peek(branch.id,ids);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).then(value=>{if(life===lifecycle&&rev===revision&&request===refreshSequence){menu=value;load(raw,false);schedule()}}).catch(error=>events.emit("error",{error:asError(error)}))}};const onFocus=()=>{void refresh().catch(error=>events.emit("error",{error:asError(error)}))};window.addEventListener("storage",onStorage);window.addEventListener("focus",onFocus);detach=()=>{window.removeEventListener("storage",onStorage);window.removeEventListener("focus",onFocus)}}if(mounted===1){void cart.hydrate().catch(error=>events.emit("error",{error:asError(error)}))}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()},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));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(error=>events.emit("error",{error:asError(error)}))}})}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.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};
|
package/dist/cart/item.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Zappie } from '../index.js';
|
|
2
2
|
import { Item } from '../index.js';
|
|
3
|
-
import '../types-
|
|
3
|
+
import '../types-BB1F1Ita.js';
|
|
4
4
|
|
|
5
5
|
/** Register an item already read by a partial/selected catalogue, without fetching it again. */
|
|
6
6
|
declare function prepareItem(client: Zappie, item: Item, options: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{wireError,ZappieError}from"../errors.js";import{requestWithRetry}from"../internal/customer-http.js";import{mapQuote}from"./quote-response.js";var FAILURE_WINDOW_MS=3e4;function createQuoteClient(transport,context,options={}){const customerBase=options.customerBase?.replace(/\/+$/,"");const signedQuote=async(body,signal)=>{const response=await requestWithRetry(options.fetch??globalThis.fetch,`${customerBase}/quote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((await import("../transport/quote-body.js")).quoteBody(body)),signal},"Could not reach the storefront quote service");if(!response.ok){throw wireError(await response.json().catch(()=>({})),response.status,response.headers.get("Zappie-Request-Id")??void 0)}return await response.json()};let controller;let sequence=0;let cached;let flight;let failed;const cancel=()=>{sequence++;controller?.abort();flight=void 0};return{cancel,failure(body){return failed?.key===JSON.stringify(body)&&Date.now()-failed.at<FAILURE_WINDOW_MS?failed.error:void 0},async get(body,force,apply){const key=JSON.stringify(body);if(!force&&cached?.key===key&&Date.parse(cached.quote.expiresAt)>Date.now()){apply(cached.quote);return cached.quote}if(!force&&flight?.key===key){return flight.promise}cancel();const seq=sequence;controller=new AbortController;const signal=controller.signal;const promise=(async()=>{const raw=customerBase?
|
|
1
|
+
import{wireError,ZappieError}from"../errors.js";import{requestWithRetry}from"../internal/customer-http.js";import{mapQuote}from"./quote-response.js";var FAILURE_WINDOW_MS=3e4;function createQuoteClient(transport,context,options={}){const customerBase=options.customerBase?.replace(/\/+$/,"");const signedQuote=async(body,signal)=>{const response=await requestWithRetry(options.fetch??globalThis.fetch,`${customerBase}/quote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((await import("../transport/quote-body.js")).quoteBody(body)),signal},"Could not reach the storefront quote service");if(!response.ok){throw wireError(await response.json().catch(()=>({})),response.status,response.headers.get("Zappie-Request-Id")??void 0)}return await response.json()};let controller;let sequence=0;let cached;let flight;let failed;const cancel=()=>{sequence++;controller?.abort();flight=void 0};return{cancel,failure(body){return failed?.key===JSON.stringify(body)&&Date.now()-failed.at<FAILURE_WINDOW_MS?failed.error:void 0},async get(body,force,apply){const key=JSON.stringify(body);if(!force&&cached?.key===key&&Date.parse(cached.quote.expiresAt)>Date.now()){apply(cached.quote);return cached.quote}if(!force&&flight?.key===key){return flight.promise}cancel();const seq=sequence;controller=new AbortController;const signal=controller.signal;const promise=(async()=>{const raw=await(customerBase?signedQuote(body,signal):transport.quote({...context(),signal},body));signal.throwIfAborted();const quote=mapQuote(raw,body.branch_id);const ids=new Set(quote.lines.map(line=>line.lineId));if(ids.size!==quote.lines.length||quote.lines.length!==body.lines.length||body.lines.some(line=>!ids.has(line.line_id))){throw new ZappieError("server_error","Quote line identities do not match the cart")}if(seq===sequence){cached={key,quote};failed=void 0;apply(quote)}return quote})();flight={key,promise};try{return await promise}catch(error){if(seq===sequence&&!(error instanceof Error&&error.name==="AbortError")){failed={key,error,at:Date.now()}}throw error}finally{if(seq===sequence){flight=void 0}}},accept(issue){if(cached){cached.quote={...cached.quote,issues:cached.quote.issues.filter(i=>!(i.code===issue.code&&i.lineId===issue.lineId))}}}}}export{createQuoteClient};
|
package/dist/cart/quote.d.ts
CHANGED
package/dist/cart/reconcile.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{multiplyMoney}from"../internal/money-math.js";import{format,money}from"../money.js";import{estimateUnitPrice}from"./price.js";import{withDefaultMenu}from"./source-menu.js";import{issue,normalizeInput,resolveVariant,validateLine}from"./validate.js";function lineInput(line){return{itemId:line.itemId,...line.menuId!==void 0?{menuId:line.menuId}:{},quantity:line.quantity,choices:line.choices.map(c=>({...c})),inputs:{...line.inputs},...line.variantId?{variantId:line.variantId}:{},...line.note!==void 0?{note:line.note}:{}}}function freezeLine(line){return Object.freeze({...line,choices:Object.freeze(line.choices.map(c=>Object.freeze({...c}))),inputs:Object.freeze({...line.inputs})})}function reconcile(lines,menu,branch,currency,previous=[]){const issues=[];let priced=true;const result=lines.map(old=>{const item=Object.hasOwn(menu.items,old.itemId)?menu.items[old.itemId]:void 0;const raw=withDefaultMenu(menu,{...old,choices:old.choices?.map(c=>({...c})),inputs:{...old.inputs}});const input=item?normalizeInput(item,raw):raw;issues.push(...validateLine(item,input,{menu,branch}).map(i=>({...i,lineId:old.id})));const variantId=input.variantId??(item?resolveVariant(item,input)?.id:void 0);let unitPrice=money(0,currency);let linePriced=true;try{if(!item){throw new Error("Missing item")}unitPrice=estimateUnitPrice(item,{choices
|
|
1
|
+
import{multiplyMoney}from"../internal/money-math.js";import{format,money}from"../money.js";import{estimateUnitPrice}from"./price.js";import{withDefaultMenu}from"./source-menu.js";import{issue,normalizeInput,resolveVariant,validateLine}from"./validate.js";function lineInput(line){return{itemId:line.itemId,...line.menuId!==void 0?{menuId:line.menuId}:{},quantity:line.quantity,choices:line.choices.map(c=>({...c})),inputs:{...line.inputs},...line.variantId?{variantId:line.variantId}:{},...line.note!==void 0?{note:line.note}:{}}}function freezeLine(line){return Object.freeze({...line,choices:Object.freeze(line.choices.map(c=>Object.freeze({...c}))),inputs:Object.freeze({...line.inputs})})}function reconcile(lines,menu,branch,currency,previous=[]){const issues=[];let priced=true;const result=lines.map(old=>{const item=Object.hasOwn(menu.items,old.itemId)?menu.items[old.itemId]:void 0;const raw=withDefaultMenu(menu,{...old,choices:old.choices?.map(c=>({...c})),inputs:{...old.inputs}});const input=item?normalizeInput(item,raw):raw;issues.push(...validateLine(item,input,{menu,branch}).map(i=>({...i,lineId:old.id})));const variantId=input.variantId??(item?resolveVariant(item,input)?.id:void 0);const choices=(input.choices??[]).map(c=>({...c,quantity:c.quantity??1}));let unitPrice=old.unitPrice??money(0,currency);let linePriced=true;try{if(!item){throw new Error("Missing item")}unitPrice=estimateUnitPrice(item,{choices,...variantId?{variantId}:{}})}catch{priced=false;linePriced=false}if(old.unitPrice&&old.unitPrice.amountMinor!==unitPrice.amountMinor&&item&&linePriced){issues.push({...issue("price_changed",`${item.name} is now ${format.money(unitPrice)}`,[{action:"accept_price"},{action:"remove_line"}]),severity:"warning",lineId:old.id,data:{previous:old.unitPrice,current:unitPrice}})}return freezeLine({id:old.id,itemId:old.itemId,...input.menuId!==void 0?{menuId:input.menuId}:{},name:item?.name??old.name,quantity:input.quantity??1,choices,inputs:input.inputs??{},...variantId?{variantId}:{},...input.note!==void 0?{note:input.note}:{},unitPrice,lineSubtotal:multiplyMoney(unitPrice,input.quantity??1),addedAt:old.addedAt})});for(const pending of previous){if(pending.code==="price_changed"&&result.some(l=>l.id===pending.lineId)&&!issues.some(i=>i.code===pending.code&&i.lineId===pending.lineId)){issues.push(pending)}}return{lines:Object.freeze(result),issues,priced}}export{freezeLine,lineInput,reconcile};
|
package/dist/cart/working-set.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ZappieError}from"../errors.js";function createWorkingSet(deps){const compose=(branchId,ids,metadata)=>{const source=metadata??deps.menu.peek(branchId);const items=Object.fromEntries([...new Set(ids)].flatMap(id=>{const item=deps.peekItem(id,branchId)??source?.items[id];return item?[[id,item]]:[]}));return{id:`branch:${branchId}`,name:"Cart working set",branchId,version:"",...source,kind:"working-set",completeness:"partial",items,categories:(source?.categories??[]).map(category=>({...category,itemIds:Object.values(items).filter(item=>item.placements?item.placements.some(p=>p.categoryId===category.id&&(source?.menus??[{id:source?.id,categoryIds:[category.id]}]).some(m=>m.id===p.menuId&&m.categoryIds.includes(category.id))):category.itemIds.includes(item.id)).map(item=>item.id)}))}};const peek=(branchId,ids)=>{const value=deps.menu.peek(branchId);return value&&value.completeness!=="partial"?value:compose(branchId,ids)};return{peek,async read(branchId,ids,fresh
|
|
1
|
+
import{ZappieError}from"../errors.js";function createWorkingSet(deps){const compose=(branchId,ids,mode,metadata)=>{const source=metadata??deps.menu.peek(branchId,mode);const items=Object.fromEntries([...new Set(ids)].flatMap(id=>{const item=deps.peekItem(id,branchId)??source?.items[id];return item?[[id,item]]:[]}));return{id:`branch:${branchId}`,name:"Cart working set",branchId,version:"",...mode&&{fulfilment:mode},...source,kind:"working-set",completeness:"partial",items,categories:(source?.categories??[]).map(category=>({...category,itemIds:Object.values(items).filter(item=>item.placements?item.placements.some(p=>p.categoryId===category.id&&(source?.menus??[{id:source?.id,categoryIds:[category.id]}]).some(m=>m.id===p.menuId&&m.categoryIds.includes(category.id))):category.itemIds.includes(item.id)).map(item=>item.id)}))}};const peek=(branchId,ids,mode)=>{const value=deps.menu.peek(branchId,mode);return value&&value.completeness!=="partial"?value:compose(branchId,ids,mode)};return{peek,async read(branchId,ids,mode,fresh){const cached=peek(branchId,ids,mode);if(!ids.length||!fresh&&cached.completeness!=="partial"){return cached}const whole=!!mode&&deps.menu.peek(branchId)?.fulfilment!=mode;const response=fresh?await deps.transport.getMenu({...deps.context(),branchId,metadataOnly:!whole,fulfilment:mode}):void 0;const fetched=response&&"menu"in response&&response.menu;const metadata=fetched||await deps.menu.get({branch:branchId,metadataOnly:!whole,fulfilment:mode});if(metadata.branchId!==branchId){throw new ZappieError("server_error","Cart metadata belongs to another branch")}if(fetched){deps.menu.hydrate(metadata)}if(metadata.completeness!=="partial"){return metadata}await Promise.all([...new Set(ids)].map(async id=>{try{await deps.readItem(id,branchId,fresh)}catch(error){if(error.code!=="item_not_found"){throw error}}}));return compose(branchId,ids,mode,metadata)}}}export{createWorkingSet};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as Menu, C as CategoryPage, S as Store, I as Item, M as Money, F as Formatters } from './models-
|
|
2
|
-
import { Q as QuoteRequest, i as WireQuote, e as CartIssueCode, d as CartModule, b as CartLineInput } from './types-
|
|
1
|
+
import { a as Menu, C as CategoryPage, S as Store, b as MenuFulfilment, I as Item, M as Money, F as Formatters } from './models-BA7vWQIL.js';
|
|
2
|
+
import { Q as QuoteRequest, i as WireQuote, e as CartIssueCode, d as CartModule, b as CartLineInput } from './types-BB1F1Ita.js';
|
|
3
3
|
|
|
4
4
|
/** Stable public error codes. */
|
|
5
5
|
type ZappieErrorCode =
|
|
@@ -465,14 +465,6 @@ type ZappieEvents = {
|
|
|
465
465
|
};
|
|
466
466
|
};
|
|
467
467
|
|
|
468
|
-
/** A catalogue fulfilment mode accepted by menu reads. */
|
|
469
|
-
type MenuFulfilment =
|
|
470
|
-
/** Orders delivered to the shopper. */
|
|
471
|
-
"delivery"
|
|
472
|
-
/** Orders the shopper collects from the branch. */
|
|
473
|
-
| "pickup"
|
|
474
|
-
/** Orders placed at a table in the branch. Sent to the API as `dine_in`. */
|
|
475
|
-
| "dineIn";
|
|
476
468
|
/** Optional branch selection and cancellation for resource reads. */
|
|
477
469
|
type ReadOptions = {
|
|
478
470
|
/** The branch to read, by id or slug. Defaults to the client's `branch`, then the store's default branch, then its first. */
|
|
@@ -482,7 +474,12 @@ type ReadOptions = {
|
|
|
482
474
|
};
|
|
483
475
|
/** Optional branch and fulfilment selection for catalogue reads. */
|
|
484
476
|
type MenuReadOptions = ReadOptions & {
|
|
485
|
-
|
|
477
|
+
/**
|
|
478
|
+
* The order type to read the menus for. Each type has its own menus, so a pickup-only menu is
|
|
479
|
+
* only in the pickup catalogue. Left out, the API reads the branch's default type, and the
|
|
480
|
+
* catalogue's `fulfilment` names it.
|
|
481
|
+
*/
|
|
482
|
+
fulfilment?: MenuFulfilment | undefined;
|
|
486
483
|
};
|
|
487
484
|
/** Read-only store resource. */
|
|
488
485
|
interface StoreResource {
|
|
@@ -511,7 +508,8 @@ interface MenuResource {
|
|
|
511
508
|
/**
|
|
512
509
|
* Read the branch's whole catalogue, every page of it. Reads are cached like the store's, and a
|
|
513
510
|
* changed version fires `menu:updated`. With `metadataOnly`, it reads the menus and categories
|
|
514
|
-
* without items, as a partial catalogue.
|
|
511
|
+
* without items, as a partial catalogue. With `fulfilment`, it reads that order type's menus,
|
|
512
|
+
* cached apart from other types', and a read for the type the default catalogue is for uses it.
|
|
515
513
|
*/
|
|
516
514
|
get(opts?: MenuReadOptions & {
|
|
517
515
|
metadataOnly?: boolean;
|
|
@@ -532,8 +530,9 @@ interface MenuResource {
|
|
|
532
530
|
* metadata-only read, and is undefined when neither is cached.
|
|
533
531
|
*
|
|
534
532
|
* @param branch - The branch, by id or slug. Defaults as `ReadOptions.branch` does.
|
|
533
|
+
* @param fulfilment - The order type, as `MenuReadOptions.fulfilment`. Left out, the default catalogue.
|
|
535
534
|
*/
|
|
536
|
-
peek(branch?: string): Menu | undefined;
|
|
535
|
+
peek(branch?: string, fulfilment?: MenuFulfilment): Menu | undefined;
|
|
537
536
|
/** Read the catalogue's current versions, to check for changes without reading the menus again. */
|
|
538
537
|
version(opts?: MenuReadOptions): Promise<MenuVersion>;
|
|
539
538
|
/**
|
|
@@ -545,7 +544,9 @@ interface MenuResource {
|
|
|
545
544
|
item(id: string, opts?: ReadOptions): Promise<Item>;
|
|
546
545
|
/**
|
|
547
546
|
* Put a catalogue read elsewhere, such as on the server, into this client's cache without a
|
|
548
|
-
* request. Fires `menu:updated` when it replaces a different version.
|
|
547
|
+
* request. Fires `menu:updated` when it replaces a different version. The branch's first
|
|
548
|
+
* catalogue becomes its default. Another order type's (`Menu.fulfilment`) is then kept for that
|
|
549
|
+
* type, for reads and `peek` that name it.
|
|
549
550
|
*
|
|
550
551
|
* @param menu - The catalogue to store under its `branchId`.
|
|
551
552
|
*/
|
|
@@ -582,7 +583,7 @@ declare function buildClient(input: ZappieConfig, secret?: boolean): Readonly<{
|
|
|
582
583
|
transport: Transport;
|
|
583
584
|
cache: Cache;
|
|
584
585
|
emit: <E extends keyof ZappieEvents>(event: E, payload: ZappieEvents[E]) => void;
|
|
585
|
-
menuKey: (requested?: string) => string;
|
|
586
|
+
menuKey: (requested?: string, mode?: MenuFulfilment) => string;
|
|
586
587
|
readMenu: (branchId: string, opts: MenuReadOptions & {
|
|
587
588
|
metadataOnly?: boolean;
|
|
588
589
|
}) => Promise<Menu>;
|
|
@@ -619,7 +620,7 @@ declare function createZappie(config: ZappieConfig): Readonly<{
|
|
|
619
620
|
transport: Transport;
|
|
620
621
|
cache: Cache;
|
|
621
622
|
emit: <E extends keyof ZappieEvents>(event: E, payload: ZappieEvents[E]) => void;
|
|
622
|
-
menuKey: (requested?: string) => string;
|
|
623
|
+
menuKey: (requested?: string, mode?: MenuFulfilment) => string;
|
|
623
624
|
readMenu: (branchId: string, opts: MenuReadOptions & {
|
|
624
625
|
metadataOnly?: boolean;
|
|
625
626
|
}) => Promise<Menu>;
|
|
@@ -627,5 +628,5 @@ declare function createZappie(config: ZappieConfig): Readonly<{
|
|
|
627
628
|
};
|
|
628
629
|
}>;
|
|
629
630
|
|
|
630
|
-
export { API_VERSION as A,
|
|
631
|
-
export type {
|
|
631
|
+
export { API_VERSION as A, createSelectedMenuReader as B, Cache as C, selectedMenu as D, selectedMenuKey as F, ZappieError as a, createZappie as n, isZappieError as o, CATALOGUE_MAX_AGE_MS as p, CATALOGUE_MAX_BYTES as q, catalogueDigest as t, catalogueKey as u, validateConfig as v, createCatalogueStorage as w, createSavedCatalogue as x };
|
|
632
|
+
export type { ErrorDetails as E, MenuResource as M, RequestCtx as R, StorageLike as S, Transport as T, Zappie as Z, ZappieConfig as b, StoreResource as c, ZappieEvents as d, MenuReadOptions as e, ZappieErrorCode as f, MenuResponse as g, SelectedMenuRequest as h, SelectedMenuResponse as i, SearchRequest as j, SearchPage as k, MenuVersion as l, ReadOptions as m, CatalogueScope as r, SavedCatalogue as s, SelectedMenu as y, SelectedMenuTransport as z };
|
package/dist/client.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createCart}from"./cart/index.js";import{createWorkingSet}from"./cart/working-set.js";import{API_VERSION,validateConfig}from"./config.js";import{ZappieError}from"./errors.js";import{Cache}from"./internal/cache.js";import{createEmitter}from"./internal/emitter.js";import{format}from"./money.js";import{RestTransport}from"./transport/rest.js";function buildClient(input,secret=false){const mode=validateConfig(input,secret);const config=Object.freeze({...input,version:input.version??API_VERSION,telemetry:input.telemetry??true});const transport=input.transport??new RestTransport({...input.baseUrl?{baseUrl:input.baseUrl}:{},...input.fetch?{fetch:input.fetch}:{}});const events=createEmitter();const cache=new Cache(error=>events.emit("error",{error}));const ctx=signal=>({key:config.key,version:config.version,...signal?{signal}:{}});const store={get:(opts={})=>cache.get("store",async signal=>({value:await transport.getStore(ctx(signal))}),opts.signal),peek:()=>cache.snapshot("store").value};const resolveBranch=(value,requested)=>{const selected=requested??config.branch;const branch=selected?value.branches.find(b=>b.id===selected||b.slug===selected):value.branches.find(b=>b.isDefault)??value.branches[0];if(!branch){throw new ZappieError("branch_not_found","No matching storefront branch",{param:"branch"})}return branch};let hydratedBranch;const branchKey=requested=>{const value=store.peek();if(value){return resolveBranch(value,requested).id}const selected=requested??config.branch;if(hydratedBranch&&(selected===void 0||selected===config.branch||selected===hydratedBranch)){return hydratedBranch}return selected??"default"};const
|
|
1
|
+
import{createCart}from"./cart/index.js";import{createWorkingSet}from"./cart/working-set.js";import{API_VERSION,validateConfig}from"./config.js";import{ZappieError}from"./errors.js";import{Cache}from"./internal/cache.js";import{createEmitter}from"./internal/emitter.js";import{format}from"./money.js";import{RestTransport}from"./transport/rest.js";function buildClient(input,secret=false){const mode=validateConfig(input,secret);const config=Object.freeze({...input,version:input.version??API_VERSION,telemetry:input.telemetry??true});const transport=input.transport??new RestTransport({...input.baseUrl?{baseUrl:input.baseUrl}:{},...input.fetch?{fetch:input.fetch}:{}});const events=createEmitter();const cache=new Cache(error=>events.emit("error",{error}));const ctx=signal=>({key:config.key,version:config.version,...signal?{signal}:{}});const store={get:(opts={})=>cache.get("store",async signal=>({value:await transport.getStore(ctx(signal))}),opts.signal),peek:()=>cache.snapshot("store").value};const resolveBranch=(value,requested)=>{const selected=requested??config.branch;const branch=selected?value.branches.find(b=>b.id===selected||b.slug===selected):value.branches.find(b=>b.isDefault)??value.branches[0];if(!branch){throw new ZappieError("branch_not_found","No matching storefront branch",{param:"branch"})}return branch};let hydratedBranch;const branchKey=requested=>{const value=store.peek();if(value){return resolveBranch(value,requested).id}const selected=requested??config.branch;if(hydratedBranch&&(selected===void 0||selected===config.branch||selected===hydratedBranch)){return hydratedBranch}return selected??"default"};const held=key=>cache.snapshot(key).value;const fallback=branchId=>held(`menu:${branchId}`)??held(`menu:${branchId}:partial`);const keyFor=(branchId,mode2)=>{const key=`menu:${branchId}`;return!mode2||fallback(branchId)?.fulfilment==mode2?key:`${key}:${mode2}`};const menuKey=(requested,mode2)=>keyFor(branchKey(requested),mode2);const readMenu=(branchId,opts)=>cache.get(`${keyFor(branchId,opts.fulfilment)}${opts.metadataOnly?":partial":""}`,async(signal,entry)=>{const response=await transport.getMenu({...ctx(signal),branchId,fulfilment:opts.fulfilment??entry.value?.fulfilment,...opts.metadataOnly?{metadataOnly:true}:{},...entry.etag?{ifNoneMatch:entry.etag}:{}});if("notModified"in response){if(!entry.value){throw new ZappieError("server_error","Received 304 without a cached menu")}return{value:entry.value,...response.etag??entry.etag?{etag:response.etag??entry.etag}:{}}}if(!opts.metadataOnly&&response.menu.completeness==="partial"){throw new ZappieError("server_error","Partial catalogue cannot satisfy a complete read")}if(response.menu.branchId!==branchId){throw new ZappieError("server_error","Menu belongs to a different branch")}return{value:response.menu,etag:response.etag??response.menu.version,onStored:()=>{if(entry.value&&entry.value.version!==response.menu.version){events.emit("menu:updated",{branchId,version:response.menu.version})}}}},opts.signal);const menu={async search(query,opts={}){if(!transport.search){throw new ZappieError("invalid_request","Transport does not support search")}const branch=resolveBranch(await store.get(opts),opts.branch);return transport.search({...ctx(opts.signal),branchId:branch.id,query,...opts.cursor?{cursor:opts.cursor}:{}})},async get(opts={}){return readMenu(resolveBranch(await store.get(opts),opts.branch).id,opts)},peek(branch,mode2){const key=menuKey(branch,mode2);return held(key)??held(`${key}:partial`)},async page(menuId,categoryId,opts={}){if(!transport.getCategoryPage){throw new ZappieError("invalid_request","Transport does not support category pages")}const branch=resolveBranch(await store.get(opts),opts.branch);return transport.getCategoryPage({...ctx(opts.signal),branchId:branch.id,menuId,categoryId,...opts.cursor?{cursor:opts.cursor}:{}})},async version(opts={}){const branch=resolveBranch(await store.get(opts),opts.branch);return transport.getMenuVersion({...ctx(opts.signal),branchId:branch.id,fulfilment:opts.fulfilment})},async item(id,opts={}){const branch=resolveBranch(await store.get(opts),opts.branch);const cached=menu.peek(branch.id);if(!cached||cached.completeness==="partial"){await menu.get({...opts,metadataOnly:true})}return readItem(id,branch.id,false,opts.signal)},hydrate(value){hydratedBranch??(hydratedBranch=value.branchId);const key=keyFor(value.branchId,fallback(value.branchId)&&value.fulfilment);const previous=held(key);cache.set(`${key}${value.completeness==="partial"?":partial":""}`,value,value.version);if(previous&&previous.version!==value.version){events.emit("menu:updated",{branchId:value.branchId,version:value.version})}}};const itemValues=new Map;const peekItem=(id,branch)=>itemValues.get(`${branch}:${id}`);const readItem=async(id,branch,fresh=false,signal)=>{const complete=held(`menu:${branch}`);const load=(requestSignal=signal)=>transport.getItem({...ctx(requestSignal),branchId:branch,itemId:id});try{const value=fresh?await load():complete&&Object.hasOwn(complete.items,id)?complete.items[id]:await cache.get(`item:${branch}:${id}`,async requestSignal=>({value:await load(requestSignal)}),signal);if(fresh){cache.set(`item:${branch}:${id}`,value)}itemValues.set(`${branch}:${id}`,value);return value}catch(error){if(error.code==="item_not_found"){itemValues.delete(`${branch}:${id}`);cache.set(`item:${branch}:${id}`,void 0)}throw error}};const workingSet=createWorkingSet({menu,store,transport,context:ctx,peekItem,readItem});const{cart,setLegacyReader,cartCatalogue}=createCart({workingSet,config,menu,store,transport,context:ctx,events});return Object.freeze({cart,config,mode,store,menu,format,on:events.on,_internal:{cartCatalogue,setLegacyReader,transport,cache,emit:events.emit,menuKey,readMenu,hydrateStore:value=>cache.set("store",value)}})}function createZappie(config){const client=buildClient(config);if(client.mode==="test"&&typeof window!=="undefined"){void import("./debug.js").then(({installDebug})=>installDebug(client))}return client}export{buildClient,createZappie};
|
package/dist/debug.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var VERSION=true?"0.
|
|
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};
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { a as ZappieError, T as Transport, R as RequestCtx, g as
|
|
1
|
+
import { a as ZappieError, T as Transport, R as RequestCtx, g as MenuResponse, j as SearchRequest, k as SearchPage, l as MenuVersion } from './client-Co7NAvVq.js';
|
|
2
2
|
import { SelectedMenuRequest, SelectedMenuResponse } from './transport/selected-menu.js';
|
|
3
|
-
export { A as API_VERSION, E as ErrorDetails, e as MenuReadOptions, M as MenuResource,
|
|
4
|
-
import { g as CartIssue, a as Quote, b as CartLineInput, C as CartLine, Q as QuoteRequest, i as WireQuote } from './types-
|
|
5
|
-
export { A as AppliedPerk, j as CartFix, c as CartFulfilment, e as CartIssueCode, d as CartModule, k as CartSnapshot, f as CartState, l as CartSyncAdapter, m as CartSyncDocument, n as CheckoutCustomer, D as DeliveryAddress, P as PendingFulfilment, o as WireFix, W as WireFulfilment, p as WireIssue, q as WireLine, h as WireMoney } from './types-
|
|
6
|
-
import { I as Item, O as OptionGroup, M as Money, a as Menu, B as Branch, S as Store, C as CategoryPage } from './models-
|
|
7
|
-
export {
|
|
3
|
+
export { A as API_VERSION, E as ErrorDetails, e as MenuReadOptions, M as MenuResource, m as ReadOptions, S as StorageLike, c as StoreResource, Z as Zappie, b as ZappieClientOptions, b as ZappieConfig, f as ZappieErrorCode, d as ZappieEvents, n as createZappie, o as isZappieError } from './client-Co7NAvVq.js';
|
|
4
|
+
import { g as CartIssue, a as Quote, b as CartLineInput, C as CartLine, Q as QuoteRequest, i as WireQuote } from './types-BB1F1Ita.js';
|
|
5
|
+
export { A as AppliedPerk, j as CartFix, c as CartFulfilment, e as CartIssueCode, d as CartModule, k as CartSnapshot, f as CartState, l as CartSyncAdapter, m as CartSyncDocument, n as CheckoutCustomer, D as DeliveryAddress, P as PendingFulfilment, o as WireFix, W as WireFulfilment, p as WireIssue, q as WireLine, h as WireMoney } from './types-BB1F1Ita.js';
|
|
6
|
+
import { I as Item, O as OptionGroup, M as Money, a as Menu, B as Branch, S as Store, b as MenuFulfilment, C as CategoryPage } from './models-BA7vWQIL.js';
|
|
7
|
+
export { c as BranchCategory, d as Category, e as CheckoutField, f as Choice, g as Currency, F as Formatters, h as Fulfilment, i as MenuSchedule, j as MenuSection, k as MoneyFormatOptions, l as OpeningTime, m as OptionCondition, P as PaymentMethodKind, n as SpecialHours, V as Variant, o as format, p as money } from './models-BA7vWQIL.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* The error a cart method throws when a line, a fulfilment or the checkout payload is invalid.
|
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.
|
|
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,6 +1,6 @@
|
|
|
1
1
|
import { RequestCtx } from '../index.js';
|
|
2
|
-
import '../models-
|
|
3
|
-
import '../types-
|
|
2
|
+
import '../models-BA7vWQIL.js';
|
|
3
|
+
import '../types-BB1F1Ita.js';
|
|
4
4
|
|
|
5
5
|
/** Public integration IDs and browser keys. Your app decides when to load scripts. */
|
|
6
6
|
type Integrations = {
|
package/dist/internal.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { CartFulfilment, WireFulfilment } from './index.js';
|
|
2
|
-
export { v as validateConfig } from './client-
|
|
3
|
-
import './models-
|
|
2
|
+
export { v as validateConfig } from './client-Co7NAvVq.js';
|
|
3
|
+
import './models-BA7vWQIL.js';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Convert a cart fulfilment selection to the API field names used by quotes and checkout.
|
|
@@ -292,6 +292,14 @@ type MenuSchedule = {
|
|
|
292
292
|
*/
|
|
293
293
|
preorderMaxDays?: number;
|
|
294
294
|
};
|
|
295
|
+
/** A catalogue fulfilment mode accepted by menu reads. */
|
|
296
|
+
type MenuFulfilment =
|
|
297
|
+
/** Orders delivered to the shopper. */
|
|
298
|
+
"delivery"
|
|
299
|
+
/** Orders the shopper collects from the branch. */
|
|
300
|
+
| "pickup"
|
|
301
|
+
/** Orders placed at a table in the branch. Sent to the API as `dine_in`. */
|
|
302
|
+
| "dineIn";
|
|
295
303
|
/** A source menu retained when the branch exposes several menus. */
|
|
296
304
|
type MenuSection = {
|
|
297
305
|
/** Fulfilment modes returned for this source menu. */
|
|
@@ -342,6 +350,12 @@ type Menu = {
|
|
|
342
350
|
items: Record<string, Item>;
|
|
343
351
|
/** The source menus the branch serves in this order type, in order. */
|
|
344
352
|
menus?: MenuSection[];
|
|
353
|
+
/**
|
|
354
|
+
* The order type the API read this catalogue for: the one asked for, or the branch's default when
|
|
355
|
+
* the read named none. Each order type has its own menus, so a pickup-only menu is only in the
|
|
356
|
+
* pickup catalogue. Left out when the API doesn't say.
|
|
357
|
+
*/
|
|
358
|
+
fulfilment?: MenuFulfilment;
|
|
345
359
|
/** The menu's schedule. Set only when the branch has one source menu with a schedule. */
|
|
346
360
|
schedule?: MenuSchedule;
|
|
347
361
|
};
|
|
@@ -536,5 +550,5 @@ type CategoryPage = {
|
|
|
536
550
|
nextCursor?: string;
|
|
537
551
|
};
|
|
538
552
|
|
|
539
|
-
export { format as
|
|
540
|
-
export type { Branch as B, CategoryPage as C, Formatters as F, Item as I, Money as M, OptionGroup as O, PaymentMethodKind as P, Store as S, Variant as V, Menu as a,
|
|
553
|
+
export { format as o, money as p };
|
|
554
|
+
export type { Branch as B, CategoryPage as C, Formatters as F, Item as I, Money as M, OptionGroup as O, PaymentMethodKind as P, Store as S, Variant as V, Menu as a, MenuFulfilment as b, BranchCategory as c, Category as d, CheckoutField as e, Choice as f, Currency as g, Fulfilment as h, MenuSchedule as i, MenuSection as j, MoneyFormatOptions as k, OpeningTime as l, OptionCondition as m, SpecialHours as n };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export {
|
|
2
|
-
import '../models-
|
|
3
|
-
import '../types-
|
|
1
|
+
export { p as CATALOGUE_MAX_AGE_MS, q as CATALOGUE_MAX_BYTES, r as CatalogueScope, s as SavedCatalogue, t as catalogueDigest, u as catalogueKey, w as createCatalogueStorage, x as createSavedCatalogue } from '../client-Co7NAvVq.js';
|
|
2
|
+
import '../models-BA7vWQIL.js';
|
|
3
|
+
import '../types-BB1F1Ita.js';
|
package/dist/react/hooks.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use client";import{useEffect,useMemo,useSyncExternalStore}from"react";import{ZappieError}from"../errors.js";import{useZappie}from"./provider.js";function useStore(){const client=useZappie();const cache=client._internal.cache;const snapshot=useSyncExternalStore(cache.subscribe,()=>cache.snapshot("store"),()=>cache.snapshot("store"));useEffect(()=>{const abort=new AbortController;void client.store.get({signal:abort.signal}).catch(()=>{});return()=>abort.abort()},[client]);return{data:snapshot.value,error:snapshot.error,isLoading:!snapshot.value&&!snapshot.error}}function useMenu(branch,options={}){const metadataOnly=options.metadataOnly===true;const client=useZappie();const store=useStore();const cache=client._internal.cache;let key;let branchError;try{key=client._internal.menuKey(branch);if(metadataOnly&&!cache.snapshot(key).value){key+=":partial"}}catch(error2){key="menu:invalid";branchError=error2}const snapshot=useSyncExternalStore(cache.subscribe,()=>cache.snapshot(key),()=>cache.snapshot(key));useEffect(()=>{if(!store.data||branchError){return}if(metadataOnly&&cache.snapshot(client._internal.menuKey(branch)).value){return}const abort=new AbortController;void client.menu.get({...branch?{branch}:{},...metadataOnly?{metadataOnly:true}:{},signal:abort.signal}).catch(()=>{});return()=>abort.abort()},[client,branch,store.data,branchError?.code,metadataOnly,cache]);const error=branchError??snapshot.error??store.error;return{data:snapshot.value,error,isLoading:!snapshot.value&&!error,isStale:cache.stale(key)}}function useItem(id,branch){const menu=useMenu(branch);const data=menu.data&&Object.prototype.hasOwnProperty.call(menu.data.items,id)?menu.data.items[id]:void 0;const missing=Boolean(menu.data)&&!data;const notFound=useMemo(()=>missing?new ZappieError("item_not_found","Item not found"):void 0,[missing,id]);return{data,error:menu.error??notFound,isLoading:menu.isLoading}}export{useItem,useMenu,useStore};
|
|
1
|
+
"use client";import{useEffect,useMemo,useSyncExternalStore}from"react";import{ZappieError}from"../errors.js";import{useZappie}from"./provider.js";function useStore(){const client=useZappie();const cache=client._internal.cache;const snapshot=useSyncExternalStore(cache.subscribe,()=>cache.snapshot("store"),()=>cache.snapshot("store"));useEffect(()=>{const abort=new AbortController;void client.store.get({signal:abort.signal}).catch(()=>{});return()=>abort.abort()},[client]);return{data:snapshot.value,error:snapshot.error,isLoading:!snapshot.value&&!snapshot.error}}function useMenu(branch,options={}){const metadataOnly=options.metadataOnly===true;const{fulfilment}=options;const client=useZappie();const store=useStore();const cache=client._internal.cache;let key;let branchError;try{key=client._internal.menuKey(branch,fulfilment);if(metadataOnly&&!cache.snapshot(key).value){key+=":partial"}}catch(error2){key="menu:invalid";branchError=error2}const snapshot=useSyncExternalStore(cache.subscribe,()=>cache.snapshot(key),()=>cache.snapshot(key));useEffect(()=>{if(!store.data||branchError){return}if(metadataOnly&&cache.snapshot(client._internal.menuKey(branch,fulfilment)).value){return}const abort=new AbortController;void client.menu.get({...branch?{branch}:{},...metadataOnly?{metadataOnly:true}:{},...fulfilment?{fulfilment}:{},signal:abort.signal}).catch(()=>{});return()=>abort.abort()},[client,branch,store.data,branchError?.code,metadataOnly,fulfilment,cache]);const error=branchError??snapshot.error??store.error;return{data:snapshot.value,error,isLoading:!snapshot.value&&!error,isStale:cache.stale(key)}}function useItem(id,branch,options={}){const menu=useMenu(branch,options);const data=menu.data&&Object.prototype.hasOwnProperty.call(menu.data.items,id)?menu.data.items[id]:void 0;const missing=Boolean(menu.data)&&!data;const notFound=useMemo(()=>missing?new ZappieError("item_not_found","Item not found"):void 0,[missing,id]);return{data,error:menu.error??notFound,isLoading:menu.isLoading}}export{useItem,useMenu,useStore};
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { VERSION } from '../index.js';
|
|
2
2
|
import { ZappieError, Zappie } from '../index.js';
|
|
3
|
-
import { Item, Menu, Store, Money } from '../index.js';
|
|
3
|
+
import { MenuFulfilment, Item, Menu, Store, Money } from '../index.js';
|
|
4
4
|
import * as react from 'react';
|
|
5
5
|
import { ReactNode } from 'react';
|
|
6
6
|
import { CartModule, CartLineInput, CartLine, CartIssueCode, CartFulfilment, AppliedPerk, CartState, CartIssue } from '../index.js';
|
|
@@ -11,17 +11,33 @@ declare function useStore(): {
|
|
|
11
11
|
error: ZappieError | undefined;
|
|
12
12
|
isLoading: boolean;
|
|
13
13
|
};
|
|
14
|
-
/**
|
|
15
|
-
|
|
14
|
+
/** Options for `useMenu`. */
|
|
15
|
+
type UseMenuOptions = {
|
|
16
|
+
/** Read the menus and categories without items, as a partial catalogue. A complete one already read is used instead. */
|
|
16
17
|
metadataOnly?: boolean;
|
|
17
|
-
|
|
18
|
+
/**
|
|
19
|
+
* The order type to show the menus for, such as the one the shopper chose. Each type has its
|
|
20
|
+
* own menus, so a pickup-only menu is only in the pickup catalogue. The hook reads again when
|
|
21
|
+
* it changes, and each type's catalogue is cached on its own. A catalogue hydrated from the
|
|
22
|
+
* server for the same type is used without a request. Left out, the branch's default type.
|
|
23
|
+
*/
|
|
24
|
+
fulfilment?: MenuFulfilment | undefined;
|
|
25
|
+
};
|
|
26
|
+
/** Subscribe to a branch catalogue and refresh stale data in the background. */
|
|
27
|
+
declare function useMenu(branch?: string, options?: UseMenuOptions): {
|
|
18
28
|
data: Menu | undefined;
|
|
19
29
|
error: ZappieError | undefined;
|
|
20
30
|
isLoading: boolean;
|
|
21
31
|
isStale: boolean;
|
|
22
32
|
};
|
|
23
|
-
/**
|
|
24
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Select one item from the branch catalogue without duplicating a request.
|
|
35
|
+
*
|
|
36
|
+
* @param id - The item id.
|
|
37
|
+
* @param branch - The branch, by id or slug. Defaults as `useMenu` does.
|
|
38
|
+
* @param options - The order type whose catalogue holds the item, as `useMenu` takes it.
|
|
39
|
+
*/
|
|
40
|
+
declare function useItem(id: string, branch?: string, options?: Pick<UseMenuOptions, "fulfilment">): {
|
|
25
41
|
data: Item | undefined;
|
|
26
42
|
error: ZappieError | undefined;
|
|
27
43
|
isLoading: boolean;
|
|
@@ -127,4 +143,4 @@ declare function useCartNotice(): {
|
|
|
127
143
|
};
|
|
128
144
|
|
|
129
145
|
export { ZappieProvider, useCart, useCartCatalogue, useCartLine, useCartNotice, useItem, useMenu, useStore, useZappie };
|
|
130
|
-
export type { CartActions, CartChangeOptions, CartNotice };
|
|
146
|
+
export type { CartActions, CartChangeOptions, CartNotice, UseMenuOptions };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var find=(store,wanted)=>wanted?store.branches.find(b=>b.id===wanted||b.slug===wanted):void 0;function readCookie(request,name){if(!name){return void 0}for(const part of(request.headers.get("cookie")??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name){try{return decodeURIComponent(part.slice(index+1).trim())}catch{return void 0}}}return void 0}function resolveBranch(store,request,{cookie,fallback,param="branch"}){const chosen=find(store,new URL(request.url).searchParams.get(param))??find(store,readCookie(request,cookie));const branch=chosen??find(store,fallback)??store.branches.find(b=>b.isDefault)??store.branches[0];return{branch,chosen:Boolean(chosen),mustChoose:!chosen&&store.branches.length>1}}function requestedBranch(request,{cookie,fallback,param="branch"}){return new URL(request.url).searchParams.get(param)||readCookie(request,cookie)||fallback||void 0}var ignore=()=>{};async function loadStoreAndMenu(client,request,options){const named=requestedBranch(request,options);const learned=slugs(client);const guess=named?.startsWith("br_")?named:named&&learned.get(named);const early=guess&&!client.store.peek()?client._internal.readMenu(guess,{}):void 0;early?.catch(ignore);const store=await client.store.get();for(const entry of store.branches){learned.set(entry.slug,entry.id)}const resolved=resolveBranch(store,request,options);const{branch}=resolved;if(!branch){return{store,...resolved,menu:void 0}}const menu=await(early&&branch.id===guess?early:client.menu.get({branch:branch.id}));return{store,...resolved,menu}}var learnedSlugs=new Map;function slugs(client){const{config}=client;const id=JSON.stringify([config.baseUrl??"",config.store,config.key]);let found=learnedSlugs.get(id);if(!found){if(learnedSlugs.size>=100){learnedSlugs.clear()}found=new Map;learnedSlugs.set(id,found)}return found}export{loadStoreAndMenu,requestedBranch,resolveBranch};
|
|
1
|
+
var find=(store,wanted)=>wanted?store.branches.find(b=>b.id===wanted||b.slug===wanted):void 0;function readCookie(request,name){if(!name){return void 0}for(const part of(request.headers.get("cookie")??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name){try{return decodeURIComponent(part.slice(index+1).trim())}catch{return void 0}}}return void 0}function resolveBranch(store,request,{cookie,fallback,param="branch"}){const chosen=find(store,new URL(request.url).searchParams.get(param))??find(store,readCookie(request,cookie));const branch=chosen??find(store,fallback)??store.branches.find(b=>b.isDefault)??store.branches[0];return{branch,chosen:Boolean(chosen),mustChoose:!chosen&&store.branches.length>1}}function requestedBranch(request,{cookie,fallback,param="branch"}){return new URL(request.url).searchParams.get(param)||readCookie(request,cookie)||fallback||void 0}var ignore=()=>{};async function loadStoreAndMenu(client,request,options){const{fulfilment}=options;const named=requestedBranch(request,options);const learned=slugs(client);const guess=named?.startsWith("br_")?named:named&&learned.get(named);const early=guess&&!client.store.peek()?client._internal.readMenu(guess,{fulfilment}):void 0;early?.catch(ignore);const store=await client.store.get();for(const entry of store.branches){learned.set(entry.slug,entry.id)}const resolved=resolveBranch(store,request,options);const{branch}=resolved;if(!branch){return{store,...resolved,menu:void 0}}const menu=await(early&&branch.id===guess?early:client.menu.get({branch:branch.id,fulfilment}));return{store,...resolved,menu}}var learnedSlugs=new Map;function slugs(client){const{config}=client;const id=JSON.stringify([config.baseUrl??"",config.store,config.key]);let found=learnedSlugs.get(id);if(!found){if(learnedSlugs.size>=100){learnedSlugs.clear()}found=new Map;learnedSlugs.set(id,found)}return found}export{loadStoreAndMenu,requestedBranch,resolveBranch};
|
package/dist/server/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Branch, Store, Menu, Item, Formatters } from '../index.js';
|
|
2
|
-
import { C as Cache } from '../client-
|
|
1
|
+
import { MenuFulfilment, Branch, Store, Menu, Item, Formatters } from '../index.js';
|
|
2
|
+
import { C as Cache } from '../client-Co7NAvVq.js';
|
|
3
3
|
import { ZappieError, Zappie, ZappieConfig, Transport, StorageLike, StoreResource, MenuResource, ZappieEvents, MenuReadOptions } from '../index.js';
|
|
4
4
|
export { VERSION } from '../index.js';
|
|
5
5
|
import { CartModule, CartLineInput } from '../index.js';
|
|
@@ -459,9 +459,18 @@ declare function requestedBranch(request: Request, { cookie, fallback, param }:
|
|
|
459
459
|
/** The store, the branch a request shows and that branch's menu. */
|
|
460
460
|
type StoreAndMenu = ResolvedBranch & {
|
|
461
461
|
store: Store;
|
|
462
|
-
/** The branch's menu. Absent when the store has no branches. */
|
|
462
|
+
/** The branch's menu for the order type asked for. Absent when the store has no branches. */
|
|
463
463
|
menu: Menu | undefined;
|
|
464
464
|
};
|
|
465
|
+
/** Where a site keeps the shopper's branch choice, and the order type to read the menu for. */
|
|
466
|
+
type LoadStoreAndMenuOptions = ResolveBranchOptions & {
|
|
467
|
+
/**
|
|
468
|
+
* The order type the page shows, such as the one the shopper chose. Each type has its own
|
|
469
|
+
* menus, so a pickup-only menu is only in the pickup catalogue. Left out, the API reads the
|
|
470
|
+
* branch's default type, and `menu.fulfilment` names it.
|
|
471
|
+
*/
|
|
472
|
+
fulfilment?: MenuFulfilment | undefined;
|
|
473
|
+
};
|
|
465
474
|
/**
|
|
466
475
|
* Read the store and the menu of the branch a request is for, as
|
|
467
476
|
* `resolveBranch` picks it. When the link, the cookie or the fallback names
|
|
@@ -471,20 +480,24 @@ type StoreAndMenu = ResolvedBranch & {
|
|
|
471
480
|
* same errors as `store.get` followed by `menu.get`. A branch named by slug
|
|
472
481
|
* starts early too once a store read in the same Worker isolate has given
|
|
473
482
|
* that slug's ID. The first such request, or one naming no branch, reads the
|
|
474
|
-
* menu after the store, because the API takes branch IDs only.
|
|
483
|
+
* menu after the store, because the API takes branch IDs only. With
|
|
484
|
+
* `fulfilment`, it reads that order type's menus. Hydrate the menu into the
|
|
485
|
+
* browser's client and a read there for the same type uses it.
|
|
475
486
|
*
|
|
476
487
|
* @example
|
|
477
488
|
* const { store, branch, chosen, mustChoose, menu } = await loadStoreAndMenu(client, request, {
|
|
478
489
|
* cookie: "site_branch",
|
|
479
490
|
* fallback: env.ZAPPIE_BRANCH,
|
|
491
|
+
* // The order type the shopper chose, kept here in a cookie of the site's own.
|
|
492
|
+
* fulfilment: request.headers.get("cookie")?.includes("site_mode=pickup") ? "pickup" : undefined,
|
|
480
493
|
* });
|
|
481
494
|
*
|
|
482
495
|
* @param client - A client created for the request.
|
|
483
496
|
* @param request - The incoming request.
|
|
484
|
-
* @param options - The site's branch cookie,
|
|
497
|
+
* @param options - The site's branch cookie, an optional fallback and query parameter, and the order type.
|
|
485
498
|
* @returns The store, the branch to show, whether the shopper chose it, whether to ask, and the branch's menu.
|
|
486
499
|
*/
|
|
487
|
-
declare function loadStoreAndMenu(client: Zappie, request: Request, options:
|
|
500
|
+
declare function loadStoreAndMenu(client: Zappie, request: Request, options: LoadStoreAndMenuOptions): Promise<StoreAndMenu>;
|
|
488
501
|
|
|
489
502
|
/** The part of a Worker's `ExecutionContext` the edge cache uses: work that may finish after the response. */
|
|
490
503
|
type EdgeContext = {
|
|
@@ -1445,7 +1458,7 @@ declare function createZappieServer({ secretKey, ...config }: ZappieServerConfig
|
|
|
1445
1458
|
transport: Transport;
|
|
1446
1459
|
cache: Cache;
|
|
1447
1460
|
emit: <E extends keyof ZappieEvents>(event: E, payload: ZappieEvents[E]) => void;
|
|
1448
|
-
menuKey: (requested?: string) => string;
|
|
1461
|
+
menuKey: (requested?: string, mode?: MenuFulfilment) => string;
|
|
1449
1462
|
readMenu: (branchId: string, opts: MenuReadOptions & {
|
|
1450
1463
|
metadataOnly?: boolean;
|
|
1451
1464
|
}) => Promise<Menu>;
|
|
@@ -1454,4 +1467,4 @@ declare function createZappieServer({ secretKey, ...config }: ZappieServerConfig
|
|
|
1454
1467
|
}>;
|
|
1455
1468
|
|
|
1456
1469
|
export { CLASSIC_QUERY_KEYS, DATA_VERSION_HEADER, EDGE_CACHE_HEADER, PAGE_CACHE_CONTROL, PREVIEW_HEADERS, PRIVATE_PAGES, ROBOTS_DISALLOW, STOREFRONT_QUERY_PARAMETERS, STOREFRONT_V1_QUERY_PARAMETERS, ZappieTokenError, ZappieWebhookSignatureError, allMenus, apiCacheBypass, apiCacheKey, applyAvailability, buildStorefrontUrl, cachePage, cachedApiFetch, canonicalJson, cookieSessionStore, createAvailabilityPatch, createMenuSnapshot, createPkce, createSecurityNonce, createStoreSnapshot, createTokenVerifier, createZappieServer, deferredDataFailed, inlineScriptHashes, isMenuSnapshot, legacyRedirects, loadStoreAndMenu, menuSnapshotFromPayload, openEdgeCache, openSealedValue, originFetch, pageCacheBypass, pageCacheKey, pageCacheRules, pageStoreBypass, parseStorefrontUrl, randomToken, rememberDataVersion, requestedBranch, resolveBranch, robotsResponse, robotsText, rotatePageNonce, sealValue, securityHeaders, sharedCacheControl, sharedFreshness, signInRedirect, siteWorker, sitemapResponse, sitemapUrls, sitemapXml, snapshotHash, snapshotKeys, storeRedirect, storefrontRedirect, verifyWebhook };
|
|
1457
|
-
export type { AllMenusOptions, AvailabilityPatch, AvailabilityPatchInput, CachedApiFetchOptions, CookieSessionStoreOptions, DocumentCacheInput, EdgeCache, EdgeCacheStatus, EdgeContext, EdgeSnapshotReader, Freshness, IdTokenChecks, IdTokenClaims, LegacyRedirects, LegacyRedirectsOptions, MenuSnapshot, MenuSnapshotInput, MenuSnapshotPayloadInput, PageCache, PageCacheOptions, PageCacheRules, PageCacheRulesOptions, PkcePair, ResolveBranchOptions, ResolvedBranch, RobotsResponseOptions, RobotsTextOptions, SealOptions, SealSecret, SecurityHeadersOptions, SessionData, SessionStore, SiteWorkerEnv, SiteWorkerOptions, SitemapOptions, SnapshotVersionRecord, StoreAndMenu, StoreSnapshot, StorefrontInstallation, StorefrontPageState, StorefrontQuery, StorefrontRoute, StorefrontUrlInput, StorefrontUrlOptions, TokenAlgorithm, TokenClaims, TokenErrorReason, TokenVerifier, TokenVerifierOptions, VerifyTokenChecks, VerifyWebhookOptions, WebhookEvent, WebhookEventType, ZappieServerConfig };
|
|
1470
|
+
export type { AllMenusOptions, AvailabilityPatch, AvailabilityPatchInput, CachedApiFetchOptions, CookieSessionStoreOptions, DocumentCacheInput, EdgeCache, EdgeCacheStatus, EdgeContext, EdgeSnapshotReader, Freshness, IdTokenChecks, IdTokenClaims, LegacyRedirects, LegacyRedirectsOptions, LoadStoreAndMenuOptions, MenuSnapshot, MenuSnapshotInput, MenuSnapshotPayloadInput, PageCache, PageCacheOptions, PageCacheRules, PageCacheRulesOptions, PkcePair, ResolveBranchOptions, ResolvedBranch, RobotsResponseOptions, RobotsTextOptions, SealOptions, SealSecret, SecurityHeadersOptions, SessionData, SessionStore, SiteWorkerEnv, SiteWorkerOptions, SitemapOptions, SnapshotVersionRecord, StoreAndMenu, StoreSnapshot, StorefrontInstallation, StorefrontPageState, StorefrontQuery, StorefrontRoute, StorefrontUrlInput, StorefrontUrlOptions, TokenAlgorithm, TokenClaims, TokenErrorReason, TokenVerifier, TokenVerifierOptions, VerifyTokenChecks, VerifyWebhookOptions, WebhookEvent, WebhookEventType, ZappieServerConfig };
|
package/dist/testing/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { C as Cache } from '../client-
|
|
1
|
+
import { C as Cache } from '../client-Co7NAvVq.js';
|
|
2
2
|
import { Transport, ZappieErrorCode, StorageLike, StoreResource, MenuResource, ZappieEvents, MenuReadOptions } from '../index.js';
|
|
3
|
-
import { Store, Menu, Formatters } from '../index.js';
|
|
3
|
+
import { Store, Menu, MenuFulfilment, Formatters } from '../index.js';
|
|
4
4
|
export { VERSION } from '../index.js';
|
|
5
5
|
import { WireMoney, CartModule, CartLineInput } from '../index.js';
|
|
6
6
|
|
|
@@ -121,6 +121,13 @@ type MockFixtures = {
|
|
|
121
121
|
store: Store;
|
|
122
122
|
/** Each branch's menu, keyed by branch ID. A branch with no entry fails with `branch_not_found`. */
|
|
123
123
|
menus: Record<string, Menu>;
|
|
124
|
+
/**
|
|
125
|
+
* A branch's menus for one order type, keyed by branch ID and then type, such as a pickup-only
|
|
126
|
+
* menu. A read, version check or quote for a type listed here gets that catalogue. Any other
|
|
127
|
+
* gets the branch's entry in `menus`, the default type's. An item read finds an item in any of
|
|
128
|
+
* them, as the API's does.
|
|
129
|
+
*/
|
|
130
|
+
byFulfilment?: Record<string, Partial<Record<MenuFulfilment, Menu>>>;
|
|
124
131
|
};
|
|
125
132
|
/** Mock timing and per-operation failures. */
|
|
126
133
|
type MockOptions = {
|
|
@@ -159,7 +166,7 @@ declare function createMockZappie(input: MockFixtures, opts?: MockOptions): Read
|
|
|
159
166
|
transport: Transport;
|
|
160
167
|
cache: Cache;
|
|
161
168
|
emit: <E extends keyof ZappieEvents>(event: E, payload: ZappieEvents[E]) => void;
|
|
162
|
-
menuKey: (requested?: string) => string;
|
|
169
|
+
menuKey: (requested?: string, mode?: MenuFulfilment) => string;
|
|
163
170
|
readMenu: (branchId: string, opts: MenuReadOptions & {
|
|
164
171
|
metadataOnly?: boolean;
|
|
165
172
|
}) => Promise<Menu>;
|
package/dist/testing/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{estimateUnitPrice}from"../cart/price.js";import{validateLine}from"../cart/validate.js";import{createZappie}from"../client.js";import{ZappieError}from"../errors.js";import{delay,throwIfAborted}from"../internal/abort.js";import{multiplyMoney}from"../internal/money-math.js";import{money}from"../money.js";import{VERSION}from"../index.js";import{createMockLoyalty}from"./loyalty.js";function createMockZappie(input,opts={}){const fixtures2=structuredClone(input);const before=async(method,ctx)=>{throwIfAborted(ctx.signal);if(opts.latencyMs){await delay(opts.latencyMs,ctx.signal)}const code=opts.failWith?.[method];if(code){throw new ZappieError(code,`Mock ${method} failure`)}};const menu2=id=>{const value=fixtures2.menus[id];if(!value){throw new ZappieError("branch_not_found","No fixture for this branch")}return structuredClone(value)};const transport={async quote(ctx,body){await before("quote",ctx);const value=menu2(body.branch_id);const branch=fixtures2.store.branches.find(b=>b.id===body.branch_id);const issues=[];const lines=body.lines.map(line=>{const item=value.items[line.item_id];const input2={itemId:line.item_id,...line.menu_id!==void 0?{menuId:line.menu_id}:{},quantity:line.quantity,choices:line.options.map(c=>({groupId:c.group_id,choiceId:c.choice_id,quantity:c.quantity})),inputs:line.inputs,...line.variant_id?{variantId:line.variant_id}:{}};const invalid=validateLine(item,input2,{menu:value,branch});issues.push(...invalid.map(i=>({code:i.code,severity:i.severity,message:i.message,line_id:line.line_id,...i.groupId?{data:{group_id:i.groupId}}:{},fixes:[]})));const price=item&&!invalid.length?estimateUnitPrice(item,input2):money(0,fixtures2.store.currency);return{line_id:line.line_id,unit_price:{amount_minor:price.amountMinor,currency:price.currency},line_total:{amount_minor:multiplyMoney(price,line.quantity).amountMinor,currency:price.currency}}});const subtotal={amount_minor:lines.reduce((n,l)=>n+l.line_total.amount_minor,0),currency:fixtures2.store.currency};return{branch_id:body.branch_id,lines,subtotal,total:subtotal,charges:[],discounts:[],issues,can_checkout:!issues.some(issue=>issue.severity==="blocking"),checkout:issues.some(issue=>issue.severity==="blocking")?{ready:false,reason:"issues"}:{ready:true},menu_version:value.version,expires_at:new Date(Date.now()+3e5).toISOString()}},async getStore(ctx){await before("getStore",ctx);return structuredClone(fixtures2.store)},async getMenu(ctx){await before("getMenu",ctx);const value=menu2(ctx.branchId);return ctx.ifNoneMatch===value.version?{notModified:true}:{menu:value,etag:value.version}},async getMenuVersion(ctx){await before("getMenuVersion",ctx);const value=menu2(ctx.branchId);return{version:value.version,availabilityHash:value.version}},async getItem(ctx){await before("getItem",ctx);const value=menu2(ctx.branchId).items[ctx.itemId];if(!value){throw new ZappieError("item_not_found","Item not found")}return value}};return createZappie({store:fixtures2.store.slug,key:"pk_test_fixture",transport})}var fulfilment={pickup:true,delivery:true,dineIn:false,scheduling:false};var store={id:"biz_fixture",slug:"default-store",name:"Default storefront",currency:"NGN",timezone:"Africa/Lagos",brand:{},fulfilment,paymentMethods:["card"],branches:[{id:"br_fixture",slug:"main",name:"Main",openingTimes:[{day:1,opens:"08:00",closes:"22:00"}],isOpen:true,fulfilment}]};var menu={id:"menu_fixture",branchId:"br_fixture",name:"Menu",version:"fixture-v1",categories:[{id:"cat_fixture",name:"Food",itemIds:["item_fixture"]}],items:{item_fixture:{id:"item_fixture",name:"Lunch",images:[],price:money(65e4,"NGN"),isAvailable:true,quantity:{min:1,step:1},variants:[{id:"variant_fixture",attributeChoices:{},images:[],price:money(65e4,"NGN"),isAvailable:true}],optionGroups:[],tags:[]}}};var ngn=amountMinor=>money(amountMinor,"NGN");var templateStore={id:"biz_template",slug:"default-template",name:"Default template",description:"A public storefront fixture for template authors.",templateSettings:{accent:"#175c3a",headerPhoto:"https://example.com/default-template-cover.png"},currency:"NGN",timezone:"Africa/Lagos",brand:{logoUrl:"https://example.com/default-template-logo.png",coverImageUrl:"https://example.com/default-template-cover.png"},fulfilment:{pickup:true,delivery:true,dineIn:true,scheduling:true},paymentMethods:["card","bank_transfer","wallet"],branches:[{id:"br_template_main",slug:"main",name:"Main",timezone:"Africa/Lagos",address:"1 Example Street, Lagos",phone:"+234 800 000 0000",pickupAddress:{placeId:"place_template_main",coordinates:{lat:6.5244,lng:3.3792}},socialLinks:[{type:"INSTAGRAM",url:"https://instagram.com/default-template"},{type:"WEBSITE",url:"https://example.com"}],openingTimes:[1,2,3,4,5].map(day=>({day,opens:"08:00",closes:"22:00"})),isOpen:true,isDefault:true,orderAheadDays:7,fulfilment:{pickup:true,delivery:true,dineIn:true,scheduling:true},minimumOrder:ngn(2e5)},{id:"br_template_island",slug:"island",name:"Island",timezone:"Africa/Lagos",openingTimes:[{day:6,opens:"10:00",closes:"18:00"}],specialHours:[{date:"2026-12-25",closed:true}],isOpen:false,closedUntil:"2026-12-26T10:00:00+01:00",orderAheadDays:0,fulfilment:{pickup:false,delivery:true,dineIn:false,scheduling:false}}]};var templateMenu={id:"menu_template",branchId:"br_template_main",name:"All day",version:"template-v1",categories:[{id:"cat_popular",name:"Popular",itemIds:["item_jollof","item_zobo"]},{id:"cat_mains",name:"Mains",itemIds:["item_jollof"]},{id:"cat_drinks",name:"Drinks and desserts",itemIds:["item_zobo","item_cake"]}],items:{item_jollof:{id:"item_jollof",name:"Jollof rice",description:"Smoky party jollof.",images:[],price:ngn(45e4),isAvailable:true,quantity:{min:1,max:10,step:1},variants:[{id:"variant_jollof",attributeChoices:{},images:[],price:ngn(45e4),isAvailable:true}],optionGroups:[{id:"grp_protein",name:"Protein",kind:"select",required:true,selection:{min:1,max:1},isAttribute:false,choices:[{id:"opt_chicken",name:"Chicken",price:ngn(0),isAvailable:true},{id:"opt_beef",name:"Beef",price:ngn(5e4),isAvailable:true},{id:"opt_fish",name:"Fish",price:ngn(8e4),isAvailable:false}]},{id:"grp_sauce",name:"Sauce",helpText:"Required with chicken.",kind:"select",required:false,selection:{min:0,max:1},isAttribute:false,choices:[{id:"opt_pepper",name:"Pepper sauce",price:ngn(0),isAvailable:true},{id:"opt_stew",name:"Stew",price:ngn(2e4),isAvailable:true}],conditions:[{groupId:"grp_protein",choiceIds:["opt_chicken"],match:"any",setRequired:true,setMin:1}]},{id:"grp_extras",name:"Extras",kind:"select",required:false,selection:{min:0,max:3},isAttribute:false,choices:[{id:"opt_plantain",name:"Plantain",price:ngn(3e4),isAvailable:true,quantity:{min:1,max:3}},{id:"opt_egg",name:"Boiled egg",price:ngn(15e3),isAvailable:true}]},{id:"grp_note",name:"Note for the kitchen",kind:"text",required:false,selection:{min:0},isAttribute:false,choices:[],input:{maxLength:140,placeholder:"No onions, please"}}],tags:["popular"]},item_zobo:{id:"item_zobo",name:"Zobo",images:[],price:ngn(12e4),isAvailable:true,quantity:{min:1,step:1},variants:[{id:"variant_zobo_small",attributeChoices:{grp_size:"opt_small"},images:[],price:ngn(12e4),isAvailable:true},{id:"variant_zobo_large",attributeChoices:{grp_size:"opt_large"},images:[],price:ngn(2e5),isAvailable:false}],optionGroups:[{id:"grp_size",name:"Size",kind:"select",required:true,selection:{min:1,max:1},isAttribute:true,choices:[{id:"opt_small",name:"Small",price:ngn(0),isAvailable:true},{id:"opt_large",name:"Large",price:ngn(0),isAvailable:false}]}],tags:[]},item_cake:{id:"item_cake",name:"Chocolate cake",images:[],price:ngn(35e4),compareAtPrice:ngn(4e5),isAvailable:false,quantity:{min:1,step:1},variants:[{id:"variant_cake",attributeChoices:{},images:[],price:ngn(35e4),isAvailable:false}],optionGroups:[],tags:[]}}};var fixtures={minimal:{store,menu},defaultTemplate:{store:templateStore,menu:templateMenu}};export{VERSION,createMockLoyalty,createMockZappie,fixtures};
|
|
1
|
+
import{estimateUnitPrice}from"../cart/price.js";import{validateLine}from"../cart/validate.js";import{createZappie}from"../client.js";import{ZappieError}from"../errors.js";import{delay,throwIfAborted}from"../internal/abort.js";import{multiplyMoney}from"../internal/money-math.js";import{money}from"../money.js";import{VERSION}from"../index.js";import{createMockLoyalty}from"./loyalty.js";function createMockZappie(input,opts={}){const fixtures2=structuredClone(input);const before=async(method,ctx)=>{throwIfAborted(ctx.signal);if(opts.latencyMs){await delay(opts.latencyMs,ctx.signal)}const code=opts.failWith?.[method];if(code){throw new ZappieError(code,`Mock ${method} failure`)}};const menu2=(id,mode)=>{const value=mode&&fixtures2.byFulfilment?.[id]?.[mode]||fixtures2.menus[id];if(!value){throw new ZappieError("branch_not_found","No fixture for this branch")}return structuredClone(value)};const transport={async quote(ctx,body){await before("quote",ctx);const type=body.fulfilment?.type;const value=menu2(body.branch_id,type==="dine_in"?"dineIn":type);const branch=fixtures2.store.branches.find(b=>b.id===body.branch_id);const issues=[];const lines=body.lines.map(line=>{const item=value.items[line.item_id];const input2={itemId:line.item_id,...line.menu_id!==void 0?{menuId:line.menu_id}:{},quantity:line.quantity,choices:line.options.map(c=>({groupId:c.group_id,choiceId:c.choice_id,quantity:c.quantity})),inputs:line.inputs,...line.variant_id?{variantId:line.variant_id}:{}};const invalid=validateLine(item,input2,{menu:value,branch});issues.push(...invalid.map(i=>({code:i.code,severity:i.severity,message:i.message,line_id:line.line_id,...i.groupId?{data:{group_id:i.groupId}}:{},fixes:[]})));const price=item&&!invalid.length?estimateUnitPrice(item,input2):money(0,fixtures2.store.currency);return{line_id:line.line_id,unit_price:{amount_minor:price.amountMinor,currency:price.currency},line_total:{amount_minor:multiplyMoney(price,line.quantity).amountMinor,currency:price.currency}}});const subtotal={amount_minor:lines.reduce((n,l)=>n+l.line_total.amount_minor,0),currency:fixtures2.store.currency};return{branch_id:body.branch_id,lines,subtotal,total:subtotal,charges:[],discounts:[],issues,can_checkout:!issues.some(issue=>issue.severity==="blocking"),checkout:issues.some(issue=>issue.severity==="blocking")?{ready:false,reason:"issues"}:{ready:true},menu_version:value.version,expires_at:new Date(Date.now()+3e5).toISOString()}},async getStore(ctx){await before("getStore",ctx);return structuredClone(fixtures2.store)},async getMenu(ctx){await before("getMenu",ctx);const value=menu2(ctx.branchId,ctx.fulfilment);return ctx.ifNoneMatch===value.version?{notModified:true}:{menu:value,etag:value.version}},async getMenuVersion(ctx){await before("getMenuVersion",ctx);const value=menu2(ctx.branchId,ctx.fulfilment);return{version:value.version,availabilityHash:value.version}},async getItem(ctx){await before("getItem",ctx);const value=[menu2(ctx.branchId),...Object.values(fixtures2.byFulfilment?.[ctx.branchId]??{})].find(entry=>entry.items[ctx.itemId])?.items[ctx.itemId];if(!value){throw new ZappieError("item_not_found","Item not found")}return value}};return createZappie({store:fixtures2.store.slug,key:"pk_test_fixture",transport})}var fulfilment={pickup:true,delivery:true,dineIn:false,scheduling:false};var store={id:"biz_fixture",slug:"default-store",name:"Default storefront",currency:"NGN",timezone:"Africa/Lagos",brand:{},fulfilment,paymentMethods:["card"],branches:[{id:"br_fixture",slug:"main",name:"Main",openingTimes:[{day:1,opens:"08:00",closes:"22:00"}],isOpen:true,fulfilment}]};var menu={id:"menu_fixture",branchId:"br_fixture",name:"Menu",version:"fixture-v1",categories:[{id:"cat_fixture",name:"Food",itemIds:["item_fixture"]}],items:{item_fixture:{id:"item_fixture",name:"Lunch",images:[],price:money(65e4,"NGN"),isAvailable:true,quantity:{min:1,step:1},variants:[{id:"variant_fixture",attributeChoices:{},images:[],price:money(65e4,"NGN"),isAvailable:true}],optionGroups:[],tags:[]}}};var ngn=amountMinor=>money(amountMinor,"NGN");var templateStore={id:"biz_template",slug:"default-template",name:"Default template",description:"A public storefront fixture for template authors.",templateSettings:{accent:"#175c3a",headerPhoto:"https://example.com/default-template-cover.png"},currency:"NGN",timezone:"Africa/Lagos",brand:{logoUrl:"https://example.com/default-template-logo.png",coverImageUrl:"https://example.com/default-template-cover.png"},fulfilment:{pickup:true,delivery:true,dineIn:true,scheduling:true},paymentMethods:["card","bank_transfer","wallet"],branches:[{id:"br_template_main",slug:"main",name:"Main",timezone:"Africa/Lagos",address:"1 Example Street, Lagos",phone:"+234 800 000 0000",pickupAddress:{placeId:"place_template_main",coordinates:{lat:6.5244,lng:3.3792}},socialLinks:[{type:"INSTAGRAM",url:"https://instagram.com/default-template"},{type:"WEBSITE",url:"https://example.com"}],openingTimes:[1,2,3,4,5].map(day=>({day,opens:"08:00",closes:"22:00"})),isOpen:true,isDefault:true,orderAheadDays:7,fulfilment:{pickup:true,delivery:true,dineIn:true,scheduling:true},minimumOrder:ngn(2e5)},{id:"br_template_island",slug:"island",name:"Island",timezone:"Africa/Lagos",openingTimes:[{day:6,opens:"10:00",closes:"18:00"}],specialHours:[{date:"2026-12-25",closed:true}],isOpen:false,closedUntil:"2026-12-26T10:00:00+01:00",orderAheadDays:0,fulfilment:{pickup:false,delivery:true,dineIn:false,scheduling:false}}]};var templateMenu={id:"menu_template",branchId:"br_template_main",name:"All day",version:"template-v1",categories:[{id:"cat_popular",name:"Popular",itemIds:["item_jollof","item_zobo"]},{id:"cat_mains",name:"Mains",itemIds:["item_jollof"]},{id:"cat_drinks",name:"Drinks and desserts",itemIds:["item_zobo","item_cake"]}],items:{item_jollof:{id:"item_jollof",name:"Jollof rice",description:"Smoky party jollof.",images:[],price:ngn(45e4),isAvailable:true,quantity:{min:1,max:10,step:1},variants:[{id:"variant_jollof",attributeChoices:{},images:[],price:ngn(45e4),isAvailable:true}],optionGroups:[{id:"grp_protein",name:"Protein",kind:"select",required:true,selection:{min:1,max:1},isAttribute:false,choices:[{id:"opt_chicken",name:"Chicken",price:ngn(0),isAvailable:true},{id:"opt_beef",name:"Beef",price:ngn(5e4),isAvailable:true},{id:"opt_fish",name:"Fish",price:ngn(8e4),isAvailable:false}]},{id:"grp_sauce",name:"Sauce",helpText:"Required with chicken.",kind:"select",required:false,selection:{min:0,max:1},isAttribute:false,choices:[{id:"opt_pepper",name:"Pepper sauce",price:ngn(0),isAvailable:true},{id:"opt_stew",name:"Stew",price:ngn(2e4),isAvailable:true}],conditions:[{groupId:"grp_protein",choiceIds:["opt_chicken"],match:"any",setRequired:true,setMin:1}]},{id:"grp_extras",name:"Extras",kind:"select",required:false,selection:{min:0,max:3},isAttribute:false,choices:[{id:"opt_plantain",name:"Plantain",price:ngn(3e4),isAvailable:true,quantity:{min:1,max:3}},{id:"opt_egg",name:"Boiled egg",price:ngn(15e3),isAvailable:true}]},{id:"grp_note",name:"Note for the kitchen",kind:"text",required:false,selection:{min:0},isAttribute:false,choices:[],input:{maxLength:140,placeholder:"No onions, please"}}],tags:["popular"]},item_zobo:{id:"item_zobo",name:"Zobo",images:[],price:ngn(12e4),isAvailable:true,quantity:{min:1,step:1},variants:[{id:"variant_zobo_small",attributeChoices:{grp_size:"opt_small"},images:[],price:ngn(12e4),isAvailable:true},{id:"variant_zobo_large",attributeChoices:{grp_size:"opt_large"},images:[],price:ngn(2e5),isAvailable:false}],optionGroups:[{id:"grp_size",name:"Size",kind:"select",required:true,selection:{min:1,max:1},isAttribute:true,choices:[{id:"opt_small",name:"Small",price:ngn(0),isAvailable:true},{id:"opt_large",name:"Large",price:ngn(0),isAvailable:false}]}],tags:[]},item_cake:{id:"item_cake",name:"Chocolate cake",images:[],price:ngn(35e4),compareAtPrice:ngn(4e5),isAvailable:false,quantity:{min:1,step:1},variants:[{id:"variant_cake",attributeChoices:{},images:[],price:ngn(35e4),isAvailable:false}],optionGroups:[],tags:[]}}};var fixtures={minimal:{store,menu},defaultTemplate:{store:templateStore,menu:templateMenu}};export{VERSION,createMockLoyalty,createMockZappie,fixtures};
|
|
@@ -1,17 +1,31 @@
|
|
|
1
1
|
import { Menu, CategoryPage } from '../index.js';
|
|
2
2
|
|
|
3
|
+
/** One page of a catalogue read: the response, then its body and catalogue unless it is a 304. */
|
|
4
|
+
type MenuPageRead = (cursor: string) => Promise<readonly [Response] | readonly [Response, Record<string, unknown>, Menu]>;
|
|
3
5
|
/**
|
|
4
|
-
*
|
|
6
|
+
* Reads, validates and maps one category page. Only progressive catalogues read
|
|
5
7
|
* pages, so this loads on the first `menu.page()` call and stays out of the
|
|
6
|
-
* core bundle, like the quote client (PRD 03 §4). The mapper and error
|
|
7
|
-
* in as arguments: importing them would split the core's shared code into
|
|
8
|
-
* separate chunk, which costs the core more than this module saves.
|
|
8
|
+
* core bundle, like the quote client (PRD 03 §4). The request, mapper and error
|
|
9
|
+
* come in as arguments: importing them would split the core's shared code into
|
|
10
|
+
* a separate chunk, which costs the core more than this module saves.
|
|
9
11
|
*/
|
|
10
|
-
declare function categoryPage(
|
|
12
|
+
declare function categoryPage(ctx: {
|
|
11
13
|
branchId: string;
|
|
12
14
|
menuId: string;
|
|
13
15
|
categoryId: string;
|
|
14
16
|
cursor?: string;
|
|
15
|
-
}, mapMenu: (value: unknown, branchId: string) => Menu, invalid: () => Error): Promise<CategoryPage>;
|
|
17
|
+
}, read: (path: string) => Promise<Record<string, unknown>>, mapMenu: (value: unknown, branchId: string) => Menu, invalid: () => Error): Promise<CategoryPage>;
|
|
18
|
+
/**
|
|
19
|
+
* Reads the later pages of a paged catalogue read and adds them to the first page. The API sends a
|
|
20
|
+
* branch's catalogue in one page, so this loads only when a server pages one, with the other paged
|
|
21
|
+
* reads here rather than in the core bundle.
|
|
22
|
+
*
|
|
23
|
+
* @param output - The first page's catalogue. It is changed in place and returned.
|
|
24
|
+
* @param raw - The first page's body, which names the next page.
|
|
25
|
+
* @param read - Reads the page at a cursor.
|
|
26
|
+
* @param error - Makes the error to throw with a message.
|
|
27
|
+
* @returns The whole catalogue.
|
|
28
|
+
*/
|
|
29
|
+
declare function readMenuPages(output: Menu, raw: Record<string, unknown>, read: MenuPageRead, error: (message: string) => Error): Promise<Menu>;
|
|
16
30
|
|
|
17
|
-
export { categoryPage };
|
|
31
|
+
export { categoryPage, readMenuPages };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
async function categoryPage(
|
|
1
|
+
var nextCursor=raw=>typeof raw.next_cursor==="string"&&raw.next_cursor?raw.next_cursor:void 0;async function categoryPage(ctx,read,mapMenu,invalid){const query=new URLSearchParams({branch:ctx.branchId,...ctx.cursor?{cursor:ctx.cursor}:{}});const raw=await read(`/menus/${encodeURIComponent(ctx.menuId)}/categories/${encodeURIComponent(ctx.categoryId)}/items?${query}`);const menu=(await import("./presentation.js")).presentMenu(mapMenu(raw,ctx.branchId),raw,invalid);if(raw.next_cursor!=null&&(typeof raw.next_cursor!=="string"||!raw.next_cursor||raw.next_cursor===ctx.cursor)||menu.categories.some(c=>c.id!==ctx.categoryId)||Object.keys(menu.items).some(id=>!menu.categories.some(c=>c.itemIds.includes(id)))||!menu.menus?.some(m=>m.id===ctx.menuId&&m.categoryIds.includes(ctx.categoryId))){throw invalid()}const next=nextCursor(raw);return{menu:{...menu,completeness:"partial"},menuId:ctx.menuId,categoryId:ctx.categoryId,...next?{nextCursor:next}:{}}}async function readMenuPages(output,raw,read,error){const{addMenuPage}=await import("./menu-pages.js");const seen=new Set;for(let cursor=nextCursor(raw);cursor;cursor=nextCursor(raw)){if(seen.has(cursor)){throw error("Repeated menu pagination cursor")}seen.add(cursor);const[,body,page]=await read(cursor);if(!page){throw error("Unexpected 304 on a continuation page")}addMenuPage(output,page,()=>error("Menu changed while fetching pages; retry the read"));raw=body}return output}export{categoryPage,readMenuPages};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ZappieError}from"../errors.js";import{money}from"../money.js";var UnsupportedValue=class extends Error{};function record(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ZappieError("server_error","Invalid storefront response object")}return value}function text(value){if(typeof value!=="string"){throw new ZappieError("server_error","Invalid storefront response string")}return value}function list(value){if(!Array.isArray(value)){throw new ZappieError("server_error","Invalid storefront response list")}return value}function number(value){if(typeof value!=="number"||!Number.isFinite(value)){throw new ZappieError("server_error","Invalid storefront response number")}return value}function nonnegative(value){const result=number(value);if(result<0){throw new ZappieError("server_error","Negative selection or quantity bound")}return result}function bounds(min,max){const lower=nonnegative(min);if(!max){return{min:lower}}const upper=nonnegative(max);if(upper<lower){throw new UnsupportedValue("a maximum below its minimum")}return{min:lower,max:upper}}var isString=value=>typeof value==="string";var isBoolean=value=>typeof value==="boolean";function opt(key,value,is){return is(value)?{[key]:value}:{}}function mapMoney(value){const v=record(value);return money(number(v.amount_minor),text(v.currency))}function hours(value){return list(value??[]).map(slot=>{const v=record(slot);const day=number(v.day);if(!Number.isInteger(day)||day<0||day>6){throw new ZappieError("server_error","Invalid opening day")}return{day,opens:text(v.open),closes:text(v.close),...opt("disabled",v.disabled,isBoolean)}})}function schedule(v){if(v.hours===void 0&&v.preorder===void 0){return void 0}const preorder=v.preorder===void 0?void 0:record(v.preorder);return{openingTimes:hours(v.hours),...preorder?{preorder:true,preorderNoticeHours:number(preorder.notice_hours),preorderMaxDays:number(preorder.max_days)}:{}}}function mapGroup(value){const g=record(value);const isAttribute=g.kind==="attribute";const kind=text(g.kind);if(!["attribute","choice","text"].includes(kind)){throw new UnsupportedValue(`an option input kind "${kind}"`)}return{id:text(g.id),name:text(g.name),kind:kind==="text"?"text":"select",required:typeof g.required==="boolean"?g.required:number(g.min)>0,selection:bounds(g.min,g.max),isAttribute,choices:list(g.choices??[]).map(raw=>{const c=record(raw);const price=mapMoney(c.price);return{id:text(c.id),name:text(c.name),price:isAttribute?money(0,price.currency):price,...isAttribute&&c.price_hint!==void 0?{priceHint:mapMoney(c.price_hint)}:{},isAvailable:c.available===true,...c.variable_quantity===true?{quantity:bounds(c.min_quantity??1,c.max_quantity)}:{}}}),...opt("helpText",g.help_text,isString),...isString(g.placeholder)?{input:{placeholder:g.placeholder}}:{},...g.conditions?{conditions:list(g.conditions).map(raw=>{const c=record(raw);const count=c.count?record(c.count):void 0;if(count&&!["eq","gte","lte"].includes(text(count.op))){throw new UnsupportedValue(`an option count operator "${text(count.op)}"`)}if(c.match!==void 0&&c.match!=="any"&&c.match!=="all"){throw new UnsupportedValue(`an option match operator "${String(c.match)}"`)}if(c.set_required!=null&&typeof c.set_required!=="boolean"){throw new ZappieError("server_error","Invalid conditional required flag")}return{groupId:text(c.group_id),choiceIds:list(c.choice_ids??[]).map(text),match:c.match==="all"?"all":"any",...count?{count:{op:text(count.op),value:nonnegative(count.value)}}:{},...c.set_required!==void 0?{setRequired:c.set_required}:{},...c.set_min!==void 0?{setMin:c.set_min===null?null:nonnegative(c.set_min)}:{},...c.set_max!==void 0?{setMax:c.set_max===null?null:nonnegative(c.set_max)}:{}}})}:{}}}function mapPromo(value){const p=record(value);return{name:text(p.name)}}function mapItem(value){const v=record(value);const id=text(v.id);let unsupported=false;const tolerate=map=>{try{return map()}catch(error){if(!(error instanceof UnsupportedValue)){throw error}unsupported=true;console.warn(`Zappie item ${id} uses ${error.message} this SDK can't validate; it is shown as unavailable`)}};const optionGroups=list(v.option_groups??[]).flatMap(raw=>tolerate(()=>mapGroup(raw))??[]);const quantity=tolerate(()=>bounds(v.min_quantity??1,v.max_quantity))??{min:1};let unresolved=false;const variants=list(v.variants).map(raw=>{const x=record(raw);const seen=new Set;return{id:text(x.id),attributeChoices:Object.fromEntries(list(x.choice_ids).map(rawId=>{const choiceId=text(rawId);const groups=optionGroups.filter(group=>group.isAttribute&&group.choices.some(choice=>choice.id===choiceId));if(groups.length!==1||seen.has(groups[0].id)){unresolved=true;return["",choiceId]}seen.add(groups[0].id);return[groups[0].id,choiceId]}).filter(([groupId])=>groupId)),price:mapMoney(x.price),...opt("lowStock",x.low_stock,isBoolean),isAvailable:x.available===true,images:list(x.images??[]).map(text)}});if(unresolved){console.warn(`Zappie item ${id} has a variant whose choices don't match its attributes; it is shown as unavailable`)}if(unsupported||unresolved){for(const variant of variants){variant.isAvailable=false}}if(!variants.length){throw new ZappieError("server_error","An item must carry at least one exact variant")}if(new Set(variants.map(variant=>variant.id)).size!==variants.length){throw new ZappieError("server_error","Duplicate variant identity")}return{...v.placements!==void 0?{placements:list(v.placements).map(raw=>{const placement=record(raw);return{menuId:text(placement.menu_id),categoryId:text(placement.category_id)}})}:{},id,name:text(v.name),images:list(v.images??[]).map(text),price:mapMoney(v.price),isAvailable:!unsupported&&!unresolved&&v.available===true,quantity:{...quantity,step:1},variants,optionGroups,tags:list(v.tags??[]).map(text),...v.fulfilment!==void 0?{fulfilment:list(v.fulfilment).map(text)}:{},...opt("stockLabel",v.stock_label,isString),...v.promo!==void 0?{promo:mapPromo(v.promo)}:{},...opt("description",v.description,isString),...opt("descriptionHtml",v.description_html,isString),...v.previous_price?{compareAtPrice:mapMoney(v.previous_price)}:{}}}function mapMenu(value,branchId){const v=record(value);const sources=list(v.menus);if(v.completeness!==void 0&&v.completeness!=="partial"&&v.completeness!=="complete"){throw new ZappieError("server_error","Invalid catalogue completeness")}const categories=new Map;const menus=sources.map(raw=>{const m=record(raw);if(m.placement_count!==void 0&&(!Number.isSafeInteger(m.placement_count)||Number(m.placement_count)<0)||m.paginated!==void 0&&typeof m.paginated!=="boolean"){throw new ZappieError("server_error","Invalid menu loading metadata")}const categoryIds=list(m.categories??[]).map(rawCategory=>{const c=record(rawCategory);const id=text(c.id);const previous=categories.get(id);const itemIds=[...new Set([...previous?.itemIds??[],...list(c.item_ids??[]).map(text)])];categories.set(id,{id,name:text(c.name),itemIds});return id});const s=schedule(m);return{id:text(m.id),name:text(m.name),categoryIds,...m.fulfilment!==void 0?{fulfilment:list(m.fulfilment).map(text)}:{},...m.placement_count!==void 0?{placementCount:m.placement_count}:{},...opt("paginated",m.paginated,isBoolean),...s?{schedule:s}:{},...opt("infoBanner",m.info_banner,isString)}});const items=Object.fromEntries(Object.entries(record(v.items)).flatMap(([id,item])=>{try{const mapped=mapItem(item);if(mapped.id===id){return[[id,mapped]]}}catch{}console.warn(`Zappie item ${id} can't be read; it is left out of the menu`);return[]}));if(v.branch_id!==void 0&&v.branch_id!==branchId){throw new ZappieError("server_error","Menu branch mismatch")}return{id:menus.length===1?menus[0].id:`branch:${branchId}`,branchId,...v.completeness==="partial"?{completeness:"partial"}:{},name:menus.length===1?menus[0].name:"Catalogue",version:text(v.menu_version),categories:[...categories.values()],items,menus,...menus.length===1&&menus[0].schedule?{schedule:menus[0].schedule}:{}}}function mapSeo(value){const seo=record(value);if(typeof seo.hidden!=="boolean"){throw new ZappieError("server_error","Invalid store search visibility")}return{titlePattern:text(seo.title_pattern),description:text(seo.description),shareImageUrl:text(seo.share_image_url),searchConsoleToken:text(seo.search_console_token),hidden:seo.hidden,redirects:list(seo.redirects).map(raw=>{const redirect=record(raw);return{from:text(redirect.from),to:text(redirect.to)}})}}export{hours,isBoolean,isString,list,mapItem,mapMenu,mapMoney,mapSeo,opt,record,text};
|
|
1
|
+
import{ZappieError}from"../errors.js";import{money}from"../money.js";var UnsupportedValue=class extends Error{};function record(value){if(!value||typeof value!=="object"||Array.isArray(value)){throw new ZappieError("server_error","Invalid storefront response object")}return value}function text(value){if(typeof value!=="string"){throw new ZappieError("server_error","Invalid storefront response string")}return value}function list(value){if(!Array.isArray(value)){throw new ZappieError("server_error","Invalid storefront response list")}return value}function number(value){if(typeof value!=="number"||!Number.isFinite(value)){throw new ZappieError("server_error","Invalid storefront response number")}return value}function nonnegative(value){const result=number(value);if(result<0){throw new ZappieError("server_error","Negative selection or quantity bound")}return result}function bounds(min,max){const lower=nonnegative(min);if(!max){return{min:lower}}const upper=nonnegative(max);if(upper<lower){throw new UnsupportedValue("a maximum below its minimum")}return{min:lower,max:upper}}var isString=value=>typeof value==="string";var isBoolean=value=>typeof value==="boolean";function opt(key,value,is){return is(value)?{[key]:value}:{}}function mapMoney(value){const v=record(value);return money(number(v.amount_minor),text(v.currency))}function hours(value){return list(value??[]).map(slot=>{const v=record(slot);const day=number(v.day);if(!Number.isInteger(day)||day<0||day>6){throw new ZappieError("server_error","Invalid opening day")}return{day,opens:text(v.open),closes:text(v.close),...opt("disabled",v.disabled,isBoolean)}})}function schedule(v){if(v.hours===void 0&&v.preorder===void 0){return void 0}const preorder=v.preorder===void 0?void 0:record(v.preorder);return{openingTimes:hours(v.hours),...preorder?{preorder:true,preorderNoticeHours:number(preorder.notice_hours),preorderMaxDays:number(preorder.max_days)}:{}}}function mapGroup(value){const g=record(value);const isAttribute=g.kind==="attribute";const kind=text(g.kind);if(!["attribute","choice","text"].includes(kind)){throw new UnsupportedValue(`an option input kind "${kind}"`)}return{id:text(g.id),name:text(g.name),kind:kind==="text"?"text":"select",required:typeof g.required==="boolean"?g.required:number(g.min)>0,selection:bounds(g.min,g.max),isAttribute,choices:list(g.choices??[]).map(raw=>{const c=record(raw);const price=mapMoney(c.price);return{id:text(c.id),name:text(c.name),price:isAttribute?money(0,price.currency):price,...isAttribute&&c.price_hint!==void 0?{priceHint:mapMoney(c.price_hint)}:{},isAvailable:c.available===true,...c.variable_quantity===true?{quantity:bounds(c.min_quantity??1,c.max_quantity)}:{}}}),...opt("helpText",g.help_text,isString),...isString(g.placeholder)?{input:{placeholder:g.placeholder}}:{},...g.conditions?{conditions:list(g.conditions).map(raw=>{const c=record(raw);const count=c.count?record(c.count):void 0;if(count&&!["eq","gte","lte"].includes(text(count.op))){throw new UnsupportedValue(`an option count operator "${text(count.op)}"`)}if(c.match!==void 0&&c.match!=="any"&&c.match!=="all"){throw new UnsupportedValue(`an option match operator "${String(c.match)}"`)}if(c.set_required!=null&&typeof c.set_required!=="boolean"){throw new ZappieError("server_error","Invalid conditional required flag")}return{groupId:text(c.group_id),choiceIds:list(c.choice_ids??[]).map(text),match:c.match==="all"?"all":"any",...count?{count:{op:text(count.op),value:nonnegative(count.value)}}:{},...c.set_required!==void 0?{setRequired:c.set_required}:{},...c.set_min!==void 0?{setMin:c.set_min===null?null:nonnegative(c.set_min)}:{},...c.set_max!==void 0?{setMax:c.set_max===null?null:nonnegative(c.set_max)}:{}}})}:{}}}function mapPromo(value){const p=record(value);return{name:text(p.name)}}function mapItem(value){const v=record(value);const id=text(v.id);let unsupported=false;const tolerate=map=>{try{return map()}catch(error){if(!(error instanceof UnsupportedValue)){throw error}unsupported=true;console.warn(`Zappie item ${id} uses ${error.message} this SDK can't validate; it is shown as unavailable`)}};const optionGroups=list(v.option_groups??[]).flatMap(raw=>tolerate(()=>mapGroup(raw))??[]);const quantity=tolerate(()=>bounds(v.min_quantity??1,v.max_quantity))??{min:1};let unresolved=false;const variants=list(v.variants).map(raw=>{const x=record(raw);const seen=new Set;return{id:text(x.id),attributeChoices:Object.fromEntries(list(x.choice_ids).map(rawId=>{const choiceId=text(rawId);const groups=optionGroups.filter(group=>group.isAttribute&&group.choices.some(choice=>choice.id===choiceId));if(groups.length!==1||seen.has(groups[0].id)){unresolved=true;return["",choiceId]}seen.add(groups[0].id);return[groups[0].id,choiceId]}).filter(([groupId])=>groupId)),price:mapMoney(x.price),...opt("lowStock",x.low_stock,isBoolean),isAvailable:x.available===true,images:list(x.images??[]).map(text)}});if(unresolved){console.warn(`Zappie item ${id} has a variant whose choices don't match its attributes; it is shown as unavailable`)}if(unsupported||unresolved){for(const variant of variants){variant.isAvailable=false}}if(!variants.length){throw new ZappieError("server_error","An item must carry at least one exact variant")}if(new Set(variants.map(variant=>variant.id)).size!==variants.length){throw new ZappieError("server_error","Duplicate variant identity")}return{...v.placements!==void 0?{placements:list(v.placements).map(raw=>{const placement=record(raw);return{menuId:text(placement.menu_id),categoryId:text(placement.category_id)}})}:{},id,name:text(v.name),images:list(v.images??[]).map(text),price:mapMoney(v.price),isAvailable:!unsupported&&!unresolved&&v.available===true,quantity:{...quantity,step:1},variants,optionGroups,tags:list(v.tags??[]).map(text),...v.fulfilment!==void 0?{fulfilment:list(v.fulfilment).map(text)}:{},...opt("stockLabel",v.stock_label,isString),...v.promo!==void 0?{promo:mapPromo(v.promo)}:{},...opt("description",v.description,isString),...opt("descriptionHtml",v.description_html,isString),...v.previous_price?{compareAtPrice:mapMoney(v.previous_price)}:{}}}function mapMenu(value,branchId){const v=record(value);const sources=list(v.menus);if(v.completeness!==void 0&&v.completeness!=="partial"&&v.completeness!=="complete"){throw new ZappieError("server_error","Invalid catalogue completeness")}const categories=new Map;const menus=sources.map(raw=>{const m=record(raw);if(m.placement_count!==void 0&&(!Number.isSafeInteger(m.placement_count)||Number(m.placement_count)<0)||m.paginated!==void 0&&typeof m.paginated!=="boolean"){throw new ZappieError("server_error","Invalid menu loading metadata")}const categoryIds=list(m.categories??[]).map(rawCategory=>{const c=record(rawCategory);const id=text(c.id);const previous=categories.get(id);const itemIds=[...new Set([...previous?.itemIds??[],...list(c.item_ids??[]).map(text)])];categories.set(id,{id,name:text(c.name),itemIds});return id});const s=schedule(m);return{id:text(m.id),name:text(m.name),categoryIds,...m.fulfilment!==void 0?{fulfilment:list(m.fulfilment).map(text)}:{},...m.placement_count!==void 0?{placementCount:m.placement_count}:{},...opt("paginated",m.paginated,isBoolean),...s?{schedule:s}:{},...opt("infoBanner",m.info_banner,isString)}});const items=Object.fromEntries(Object.entries(record(v.items)).flatMap(([id,item])=>{try{const mapped=mapItem(item);if(mapped.id===id){return[[id,mapped]]}}catch{}console.warn(`Zappie item ${id} can't be read; it is left out of the menu`);return[]}));if(v.branch_id!==void 0&&v.branch_id!==branchId){throw new ZappieError("server_error","Menu branch mismatch")}return{id:menus.length===1?menus[0].id:`branch:${branchId}`,branchId,...opt("fulfilment",{delivery:"delivery",pickup:"pickup",dine_in:"dineIn"}[String(v.fulfilment)],isString),...v.completeness==="partial"?{completeness:"partial"}:{},name:menus.length===1?menus[0].name:"Catalogue",version:text(v.menu_version),categories:[...categories.values()],items,menus,...menus.length===1&&menus[0].schedule?{schedule:menus[0].schedule}:{}}}function mapSeo(value){const seo=record(value);if(typeof seo.hidden!=="boolean"){throw new ZappieError("server_error","Invalid store search visibility")}return{titlePattern:text(seo.title_pattern),description:text(seo.description),shareImageUrl:text(seo.share_image_url),searchConsoleToken:text(seo.search_console_token),hidden:seo.hidden,redirects:list(seo.redirects).map(raw=>{const redirect=record(raw);return{from:text(redirect.from),to:text(redirect.to)}})}}export{hours,isBoolean,isString,list,mapItem,mapMenu,mapMoney,mapSeo,opt,record,text};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function addMenuPage(output,page,changed){if(page.version!==output.version){throw changed()}Object.assign(output.items,page.items);for(const category of page.categories){const existing=output.categories.find(c=>c.id===category.id);if(existing){existing.itemIds=[...new Set([...existing.itemIds,...category.itemIds])]}else{output.categories.push(category)}}for(const section of page.menus??[]){const existing=output.menus?.find(m=>m.id===section.id);if(existing){existing.categoryIds=[...new Set([...existing.categoryIds,...section.categoryIds])]}else{output.menus?.push(section)}}if(output.menus&&output.menus.length>1){output.id=`branch:${output.branchId}`;output.name="Catalogue";delete output.schedule}}export{addMenuPage};
|
package/dist/transport/rest.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ZappieError,wireError}from"../errors.js";import{delay,throwIfAborted}from"../internal/abort.js";import{money}from"../money.js";import{hours,isBoolean,isString,list,mapItem,mapMenu,mapMoney,mapSeo,opt,record,text}from"./mappers.js";var MAX_RETRY_WAIT_MS=5e3;var wireFulfilment=value=>value==="dineIn"?"dine_in":value;var presentationError=()=>new ZappieError("server_error","Invalid storefront presentation");var RestTransport=class{constructor(opts={}){const url=new URL(opts.baseUrl??"https://api.zappie.ai/storefront/v1");if(url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(url.hostname))){throw new ZappieError("invalid_request","REST baseUrl requires HTTPS, or HTTP on localhost")}this.baseUrl=url.href.replace(/\/$/,"");this.fetcher=opts.fetch??((input,init)=>globalThis.fetch(input,init))}async request(path,ctx,etag,body){if(typeof window!=="undefined"&&ctx.key.startsWith("sk_")){throw new ZappieError("invalid_request","Secret keys cannot be sent from a browser")}for(let attempt=0;;attempt++){throwIfAborted(ctx.signal);let response;try{response=await this.fetcher(this.baseUrl+path,{method:body?"POST":"GET",...body?{body:JSON.stringify(body)}:{},redirect:"manual",headers:{...body?{"Content-Type":"application/json"}:{},...ctx.idempotencyKey?{"Idempotency-Key":ctx.idempotencyKey}:{},Authorization:`Bearer ${ctx.key}`,"Zappie-Version":ctx.version,...etag?{"If-None-Match":etag}:{}},...ctx.signal?{signal:ctx.signal}:{}})}catch(error){throwIfAborted(ctx.signal);if(attempt>=2){throw new ZappieError("network_error","Could not reach the storefront service",{cause:error})}await delay(100*2**attempt+Math.random()*100,ctx.signal);continue}if(response.ok||response.status===304){return response}const retry=response.headers.get("Retry-After");const seconds=retry!==null?Number(retry):NaN;const wait=retry!==null?Number.isFinite(seconds)?Math.max(0,seconds*1e3):Math.max(0,Date.parse(retry)-Date.now()):NaN;const tooLong=Number.isFinite(wait)&&wait>MAX_RETRY_WAIT_MS;if(attempt<2&&!tooLong&&(response.status===429||response.status>=500)){await response.body?.cancel();await delay(Number.isFinite(wait)?wait:100*2**attempt+Math.random()*100,ctx.signal);continue}const errorBody=await response.json().catch(()=>({}));throw wireError(errorBody,response.status,response.headers.get("Zappie-Request-Id")??void 0)}}async json(response){try{return await response.json()}catch(cause){if(cause instanceof Error&&cause.name==="AbortError"){throw cause}throw new ZappieError("server_error","The storefront service returned invalid JSON",{status:response.status,cause})}}async quote(ctx,body){body=(await import("./quote-body.js")).quoteBody(body);const raw=await this.json(await this.request("/quote",ctx,void 0,body));return raw}async getStore(ctx){const mapper=import("./store.js").catch(cause=>{throw new ZappieError("server_error","Could not load the storefront store mapper",{cause})});const presentation=import("./presentation.js");const response=this.request("/store",ctx).then(value=>this.json(value));const[{mapStore},{presentStore},raw]=await Promise.all([mapper,presentation,response]);const store=mapStore(raw,record,text,list,hours,mapMoney,money,opt,isString,isBoolean,mapSeo);return presentStore(store,raw,presentationError)}async getMenu(ctx){const presentation=import("./presentation.js");
|
|
1
|
+
import{ZappieError,wireError}from"../errors.js";import{delay,throwIfAborted}from"../internal/abort.js";import{money}from"../money.js";import{hours,isBoolean,isString,list,mapItem,mapMenu,mapMoney,mapSeo,opt,record,text}from"./mappers.js";var MAX_RETRY_WAIT_MS=5e3;var wireFulfilment=value=>value==="dineIn"?"dine_in":value;var presentationError=()=>new ZappieError("server_error","Invalid storefront presentation");var RestTransport=class{constructor(opts={}){const url=new URL(opts.baseUrl??"https://api.zappie.ai/storefront/v1");if(url.username||url.password||url.search||url.hash||url.protocol!=="https:"&&!(url.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(url.hostname))){throw new ZappieError("invalid_request","REST baseUrl requires HTTPS, or HTTP on localhost")}this.baseUrl=url.href.replace(/\/$/,"");this.fetcher=opts.fetch??((input,init)=>globalThis.fetch(input,init))}async request(path,ctx,etag,body){if(typeof window!=="undefined"&&ctx.key.startsWith("sk_")){throw new ZappieError("invalid_request","Secret keys cannot be sent from a browser")}for(let attempt=0;;attempt++){throwIfAborted(ctx.signal);let response;try{response=await this.fetcher(this.baseUrl+path,{method:body?"POST":"GET",...body?{body:JSON.stringify(body)}:{},redirect:"manual",headers:{...body?{"Content-Type":"application/json"}:{},...ctx.idempotencyKey?{"Idempotency-Key":ctx.idempotencyKey}:{},Authorization:`Bearer ${ctx.key}`,"Zappie-Version":ctx.version,...etag?{"If-None-Match":etag}:{}},...ctx.signal?{signal:ctx.signal}:{}})}catch(error){throwIfAborted(ctx.signal);if(attempt>=2){throw new ZappieError("network_error","Could not reach the storefront service",{cause:error})}await delay(100*2**attempt+Math.random()*100,ctx.signal);continue}if(response.ok||response.status===304){return response}const retry=response.headers.get("Retry-After");const seconds=retry!==null?Number(retry):NaN;const wait=retry!==null?Number.isFinite(seconds)?Math.max(0,seconds*1e3):Math.max(0,Date.parse(retry)-Date.now()):NaN;const tooLong=Number.isFinite(wait)&&wait>MAX_RETRY_WAIT_MS;if(attempt<2&&!tooLong&&(response.status===429||response.status>=500)){await response.body?.cancel();await delay(Number.isFinite(wait)?wait:100*2**attempt+Math.random()*100,ctx.signal);continue}const errorBody=await response.json().catch(()=>({}));throw wireError(errorBody,response.status,response.headers.get("Zappie-Request-Id")??void 0)}}async json(response){try{return await response.json()}catch(cause){if(cause instanceof Error&&cause.name==="AbortError"){throw cause}throw new ZappieError("server_error","The storefront service returned invalid JSON",{status:response.status,cause})}}async quote(ctx,body){body=(await import("./quote-body.js")).quoteBody(body);const raw=await this.json(await this.request("/quote",ctx,void 0,body));return raw}async getStore(ctx){const mapper=import("./store.js").catch(cause=>{throw new ZappieError("server_error","Could not load the storefront store mapper",{cause})});const presentation=import("./presentation.js");const response=this.request("/store",ctx).then(value=>this.json(value));const[{mapStore},{presentStore},raw]=await Promise.all([mapper,presentation,response]);const store=mapStore(raw,record,text,list,hours,mapMoney,money,opt,isString,isBoolean,mapSeo);return presentStore(store,raw,presentationError)}async getMenu(ctx){const presentation=import("./presentation.js");const read=async cursor=>{const response2=await this.request(`/menus?${new URLSearchParams({branch:ctx.branchId,...ctx.fulfilment?{fulfilment:wireFulfilment(ctx.fulfilment)}:{},...ctx.metadataOnly?{metadata_only:"true"}:{},...cursor?{cursor}:{}})}`,ctx,cursor?void 0:ctx.ifNoneMatch);if(response2.status===304){return[response2]}const raw2=record(await this.json(response2));return[response2,raw2,(await presentation).presentMenu(mapMenu(raw2,ctx.branchId),raw2,presentationError)]};const[response,body,page]=await read();const etag=response.headers.get("ETag")??void 0;if(!page){return{notModified:true,...etag?{etag}:{}}}const raw=body;if(ctx.metadataOnly){if(Object.keys(page.items).length||raw.next_cursor){throw new ZappieError("server_error","Invalid metadata response")}return{menu:{...page,completeness:"partial"}}}const output=raw.next_cursor?await(await import("./category-page.js")).readMenuPages(page,raw,read,message=>new ZappieError("server_error",message)):page;for(const category of output.categories){category.itemIds=category.itemIds.filter(id=>Object.hasOwn(output.items,id))}if(Object.keys(output.items).length>2e3){console.warn("Zappie menu contains more than 2,000 items")}return{menu:output,...etag?{etag}:{}}}async getSelectedMenu(ctx){return(await import("./selected-menu.js")).selectedMenu(ctx,path=>this.request(path,ctx,ctx.ifNoneMatch),response=>this.json(response),mapMenu,()=>new ZappieError("server_error","Invalid selected menu"))}async search(ctx){return(await import("./search.js")).searchPage(ctx,async path=>this.json(await this.request(path,ctx)),mapMenu,()=>new ZappieError("server_error","Invalid search page"))}async getCategoryPage(ctx){return(await import("./category-page.js")).categoryPage(ctx,async path=>record(await this.json(await this.request(path,ctx))),mapMenu,()=>new ZappieError("server_error","Invalid category page"))}async getMenuVersion(ctx){const value=record(await this.json(await this.request(`/menus/version?${new URLSearchParams({branch:ctx.branchId,...ctx.fulfilment?{fulfilment:wireFulfilment(ctx.fulfilment)}:{}})}`,ctx)));if(typeof value.menu_version!=="string"||typeof value.availability_hash!=="string"){throw new ZappieError("server_error","Invalid menu version response")}return{version:value.menu_version,availabilityHash:value.availability_hash}}async getItem(ctx){const item=mapItem(await this.json(await this.request(`/items/${encodeURIComponent(ctx.itemId)}?${new URLSearchParams({branch:ctx.branchId})}`,ctx)));if(item.id!==ctx.itemId){throw new ZappieError("server_error","Item response identity does not match the request")}return item}};export{RestTransport};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Menu } from '../index.js';
|
|
2
2
|
import { SearchRequest, SearchPage } from '../index.js';
|
|
3
|
-
import '../types-
|
|
3
|
+
import '../types-BB1F1Ita.js';
|
|
4
4
|
|
|
5
5
|
/** Loaded only when search is used; request authentication/retries stay in REST. */
|
|
6
6
|
declare function searchPage(ctx: SearchRequest, read: (path: string) => Promise<unknown>, mapMenu: (value: unknown, branchId: string) => Menu, invalid: () => Error): Promise<SearchPage>;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export {
|
|
2
|
-
import '../models-
|
|
3
|
-
import '../types-
|
|
1
|
+
export { y as SelectedMenu, h as SelectedMenuRequest, i as SelectedMenuResponse, z as SelectedMenuTransport, B as createSelectedMenuReader, D as selectedMenu, F as selectedMenuKey } from '../client-Co7NAvVq.js';
|
|
2
|
+
import '../models-BA7vWQIL.js';
|
|
3
|
+
import '../types-BB1F1Ita.js';
|