@zappie/sdk 0.1.0 → 0.1.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/dist/debug.js CHANGED
@@ -1 +1 @@
1
- var c="0.1.0";function g(t){if(typeof window>"u"||t.mode!=="test")return;let s=[],i,r=(e,n)=>{let o={name:e,detail:n,at:new Date().toISOString()};s.push(o),window.dispatchEvent(new CustomEvent("zappie:event",{detail:o}));};globalThis.__zappieEmit=r,window.__zappie={version:c,store:t.config.store,async catalogue(){await t.cart.hydrate();let e=(await t.store.get()).branches.find(n=>n.id===t.cart.getSnapshot().branchId);return {branch:e,menu:await t.menu.get({branch:e.id})}},cart:Object.assign(()=>t.cart.getSnapshot(),{async inject(e){if(await t.cart.hydrate(),e.lines.length>100||e.lines.some(a=>!Number.isInteger(a.quantity??1)||(a.quantity??1)<1||(a.quantity??1)>99))throw new Error("Use up to 100 cart lines with whole quantities from 1 to 99.");let n=t.cart.getSnapshot(),o={v:1,menuVersion:t._internal.cartCatalogue().version,updatedAt:Date.now(),fulfilment:n.fulfilment,promoCode:n.promoCode,lines:e.lines.map((a,d)=>({...a,id:`debug_${d}`,name:a.itemId,quantity:a.quantity??1,choices:(a.choices??[]).map(p=>({...p,quantity:p.quantity??1})),inputs:a.inputs??{},addedAt:new Date().toISOString()}))},u=t.config.cart?.storageScope;(t.config.storage??window.localStorage).setItem(`zappie:cart:v1:${t.config.store}:${n.branchId}${u?`:${u}`:""}`,JSON.stringify(o));}}),quote:()=>i,events:s},t.on("add_to_cart",e=>r("add_to_cart",e)),t.cart.subscribe(()=>{let e=t.cart.state,n="quote"in e?e.quote:void 0;n&&n!==i&&(i=n,r("quote",n));});}export{g as installDebug};//# sourceMappingURL=debug.js.map
1
+ var c="0.1.1";function g(t){if(typeof window>"u"||t.mode!=="test")return;let s=[],i,r=(e,n)=>{let o={name:e,detail:n,at:new Date().toISOString()};s.push(o),window.dispatchEvent(new CustomEvent("zappie:event",{detail:o}));};globalThis.__zappieEmit=r,window.__zappie={version:c,store:t.config.store,async catalogue(){await t.cart.hydrate();let e=(await t.store.get()).branches.find(n=>n.id===t.cart.getSnapshot().branchId);return {branch:e,menu:await t.menu.get({branch:e.id})}},cart:Object.assign(()=>t.cart.getSnapshot(),{async inject(e){if(await t.cart.hydrate(),e.lines.length>100||e.lines.some(a=>!Number.isInteger(a.quantity??1)||(a.quantity??1)<1||(a.quantity??1)>99))throw new Error("Use up to 100 cart lines with whole quantities from 1 to 99.");let n=t.cart.getSnapshot(),o={v:1,menuVersion:t._internal.cartCatalogue().version,updatedAt:Date.now(),fulfilment:n.fulfilment,promoCode:n.promoCode,lines:e.lines.map((a,d)=>({...a,id:`debug_${d}`,name:a.itemId,quantity:a.quantity??1,choices:(a.choices??[]).map(p=>({...p,quantity:p.quantity??1})),inputs:a.inputs??{},addedAt:new Date().toISOString()}))},u=t.config.cart?.storageScope;(t.config.storage??window.localStorage).setItem(`zappie:cart:v1:${t.config.store}:${n.branchId}${u?`:${u}`:""}`,JSON.stringify(o));}}),quote:()=>i,events:s},t.on("add_to_cart",e=>r("add_to_cart",e)),t.cart.subscribe(()=>{let e=t.cart.state,n="quote"in e?e.quote:void 0;n&&n!==i&&(i=n,r("quote",n));});}export{g as installDebug};//# sourceMappingURL=debug.js.map
package/dist/debug.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/debug.ts"],"names":["VERSION","installDebug","client","events","quote","emit","name","detail","event","branch","value","input","line","snapshot","index","choice","scope","state","next"],"mappings":"AAKA,IAAMA,CAAAA,CAAU,OAAA,CAoCT,SAASC,CAAAA,CAAaC,EAAgB,CAC3C,GAAI,OAAO,MAAA,CAAW,KAAeA,CAAAA,CAAO,IAAA,GAAS,MAAA,CACnD,OAEF,IAAMC,CAAAA,CAAuB,EAAC,CAC1BC,CAAAA,CACEC,EAAO,CAACC,CAAAA,CAAcC,CAAAA,GAAoB,CAC9C,IAAMC,CAAAA,CAAQ,CAAE,IAAA,CAAA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ACAD,CAAAA,CAAO,EAAA,CAAG,aAAA,CAAgBK,CAAAA,EAAWF,EAAK,aAAA,CAAeE,CAAM,CAAC,CAAA,CAChEL,EAAO,IAAA,CAAK,SAAA,CAAU,IAAM,CAC1B,IAAMe,CAAAA,CAAQf,CAAAA,CAAO,IAAA,CAAK,KAAA,CACpBgB,EAAO,OAAA,GAAWD,CAAAA,CAAQA,CAAAA,CAAM,KAAA,CAAQ,OAC1CC,CAAAA,EAAQA,CAAAA,GAASd,CAAAA,GACnBA,CAAAA,CAAQc,EACRb,CAAAA,CAAK,OAAA,CAASa,CAAI,CAAA,EAEtB,CAAC,EACH","file":"debug.js","sourcesContent":["import type { StoredLine } from \"./cart/storage\";\nimport type { CartLineInput, Quote } from \"./cart/types\";\nimport type { Zappie } from \"./client\";\nimport type { Branch, Menu } from \"./models\";\n\nconst VERSION = \"0.1.0\";\n\nexport type DebugEvent = {\n name: string;\n detail: unknown;\n at: string;\n};\n\nexport type ZappieDebug = {\n version: string;\n store: string;\n /** Read this cart's branch and full menu through its client. */\n catalogue(): Promise<{ menu: Menu; branch: Branch }>;\n cart: (() => ReturnType<Zappie[\"cart\"][\"getSnapshot\"]>) & {\n /**\n * Save test cart lines for the next reload. Reload to reconcile them with today's menu.\n * Your unitPrice is only a local estimate, like a price edited in browser storage.\n * The server re-prices every line and never trusts this estimate.\n */\n inject(input: {\n lines: (CartLineInput & Pick<StoredLine, \"unitPrice\">)[];\n }): Promise<void>;\n };\n quote: () => Quote | undefined;\n events: DebugEvent[];\n};\n\ndeclare global {\n interface Window {\n __zappie?: ZappieDebug;\n }\n // On globalThis so the lazy checkout and customer entries can reach it\n // with the shortest possible call; in a browser it is window's.\n var __zappieEmit: ((name: string, detail: unknown) => void) | undefined;\n}\n\nexport function installDebug(client: Zappie) {\n if (typeof window === \"undefined\" || client.mode !== \"test\") {\n return;\n }\n const events: DebugEvent[] = [];\n let quote: Quote | undefined;\n const emit = (name: string, detail: unknown) => {\n const event = { name, detail, at: new Date().toISOString() };\n events.push(event);\n window.dispatchEvent(new CustomEvent(\"zappie:event\", { detail: event }));\n };\n globalThis.__zappieEmit = emit;\n window.__zappie = {\n version: VERSION,\n store: client.config.store,\n async catalogue() {\n await client.cart.hydrate();\n const branch = (await client.store.get()).branches.find(\n (value) => value.id === client.cart.getSnapshot().branchId,\n )!;\n return { branch, menu: await client.menu.get({ branch: branch.id }) };\n },\n cart: Object.assign(() => client.cart.getSnapshot(), {\n async inject(input: {\n lines: (CartLineInput & Pick<StoredLine, \"unitPrice\">)[];\n }) {\n await client.cart.hydrate();\n if (\n input.lines.length > 100 ||\n input.lines.some(\n (line) =>\n !Number.isInteger(line.quantity ?? 1) ||\n (line.quantity ?? 1) < 1 ||\n (line.quantity ?? 1) > 99,\n )\n ) {\n throw new Error(\n \"Use up to 100 cart lines with whole quantities from 1 to 99.\",\n );\n }\n const snapshot = client.cart.getSnapshot();\n const value = {\n v: 1,\n menuVersion: client._internal.cartCatalogue()!.version,\n updatedAt: Date.now(),\n fulfilment: snapshot.fulfilment,\n promoCode: snapshot.promoCode,\n lines: input.lines.map((line, index) => ({\n ...line,\n id: `debug_${index}`,\n name: line.itemId,\n quantity: line.quantity ?? 1,\n choices: (line.choices ?? []).map((choice) => ({\n ...choice,\n quantity: choice.quantity ?? 1,\n })),\n inputs: line.inputs ?? {},\n addedAt: new Date().toISOString(),\n })),\n };\n const scope = client.config.cart?.storageScope;\n (client.config.storage ?? window.localStorage).setItem(\n `zappie:cart:v1:${client.config.store}:${snapshot.branchId}${scope ? `:${scope}` : \"\"}`,\n JSON.stringify(value),\n );\n },\n }),\n quote: () => quote,\n events,\n };\n client.on(\"add_to_cart\", (detail) => emit(\"add_to_cart\", detail));\n client.cart.subscribe(() => {\n const state = client.cart.state;\n const next = \"quote\" in state ? state.quote : undefined;\n if (next && next !== quote) {\n quote = next;\n emit(\"quote\", next);\n }\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/debug.ts"],"names":["VERSION","installDebug","client","events","quote","emit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AO,OAAA,EAAW,MAAA,CAAO,cAAc,OAAA,CAC7C,CAAA,eAAA,EAAkBA,CAAAA,CAAO,MAAA,CAAO,KAAK,CAAA,CAAA,EAAIW,CAAAA,CAAS,QAAQ,CAAA,EAAGG,EAAQ,CAAA,CAAA,EAAIA,CAAK,CAAA,CAAA,CAAK,EAAE,GACrF,IAAA,CAAK,SAAA,CAAUN,CAAK,CACtB,EACF,CACF,CAAC,CAAA,CACD,KAAA,CAAO,IAAMN,CAAAA,CACb,MAAA,CAAAD,CACF,CAAA,CACAD,CAAAA,CAAO,EAAA,CAAG,aAAA,CAAgBK,CAAAA,EAAWF,EAAK,aAAA,CAAeE,CAAM,CAAC,CAAA,CAChEL,EAAO,IAAA,CAAK,SAAA,CAAU,IAAM,CAC1B,IAAMe,CAAAA,CAAQf,CAAAA,CAAO,IAAA,CAAK,KAAA,CACpBgB,EAAO,OAAA,GAAWD,CAAAA,CAAQA,CAAAA,CAAM,KAAA,CAAQ,OAC1CC,CAAAA,EAAQA,CAAAA,GAASd,CAAAA,GACnBA,CAAAA,CAAQc,EACRb,CAAAA,CAAK,OAAA,CAASa,CAAI,CAAA,EAEtB,CAAC,EACH","file":"debug.js","sourcesContent":["import type { StoredLine } from \"./cart/storage\";\nimport type { CartLineInput, Quote } from \"./cart/types\";\nimport type { Zappie } from \"./client\";\nimport type { Branch, Menu } from \"./models\";\n\n// Inline like VERSION in index.ts: tsup fills in the version from package.json.\ndeclare const __ZAPPIE_SDK_VERSION__: string | undefined;\nconst VERSION =\n typeof __ZAPPIE_SDK_VERSION__ === \"string\"\n ? __ZAPPIE_SDK_VERSION__\n : \"0.0.0-development\";\n\nexport type DebugEvent = {\n name: string;\n detail: unknown;\n at: string;\n};\n\nexport type ZappieDebug = {\n version: string;\n store: string;\n /** Read this cart's branch and full menu through its client. */\n catalogue(): Promise<{ menu: Menu; branch: Branch }>;\n cart: (() => ReturnType<Zappie[\"cart\"][\"getSnapshot\"]>) & {\n /**\n * Save test cart lines for the next reload. Reload to reconcile them with today's menu.\n * Your unitPrice is only a local estimate, like a price edited in browser storage.\n * The server re-prices every line and never trusts this estimate.\n */\n inject(input: {\n lines: (CartLineInput & Pick<StoredLine, \"unitPrice\">)[];\n }): Promise<void>;\n };\n quote: () => Quote | undefined;\n events: DebugEvent[];\n};\n\ndeclare global {\n interface Window {\n __zappie?: ZappieDebug;\n }\n // On globalThis so the lazy checkout and customer entries can reach it\n // with the shortest possible call; in a browser it is window's.\n var __zappieEmit: ((name: string, detail: unknown) => void) | undefined;\n}\n\nexport function installDebug(client: Zappie) {\n if (typeof window === \"undefined\" || client.mode !== \"test\") {\n return;\n }\n const events: DebugEvent[] = [];\n let quote: Quote | undefined;\n const emit = (name: string, detail: unknown) => {\n const event = { name, detail, at: new Date().toISOString() };\n events.push(event);\n window.dispatchEvent(new CustomEvent(\"zappie:event\", { detail: event }));\n };\n globalThis.__zappieEmit = emit;\n window.__zappie = {\n version: VERSION,\n store: client.config.store,\n async catalogue() {\n await client.cart.hydrate();\n const branch = (await client.store.get()).branches.find(\n (value) => value.id === client.cart.getSnapshot().branchId,\n )!;\n return { branch, menu: await client.menu.get({ branch: branch.id }) };\n },\n cart: Object.assign(() => client.cart.getSnapshot(), {\n async inject(input: {\n lines: (CartLineInput & Pick<StoredLine, \"unitPrice\">)[];\n }) {\n await client.cart.hydrate();\n if (\n input.lines.length > 100 ||\n input.lines.some(\n (line) =>\n !Number.isInteger(line.quantity ?? 1) ||\n (line.quantity ?? 1) < 1 ||\n (line.quantity ?? 1) > 99,\n )\n ) {\n throw new Error(\n \"Use up to 100 cart lines with whole quantities from 1 to 99.\",\n );\n }\n const snapshot = client.cart.getSnapshot();\n const value = {\n v: 1,\n menuVersion: client._internal.cartCatalogue()!.version,\n updatedAt: Date.now(),\n fulfilment: snapshot.fulfilment,\n promoCode: snapshot.promoCode,\n lines: input.lines.map((line, index) => ({\n ...line,\n id: `debug_${index}`,\n name: line.itemId,\n quantity: line.quantity ?? 1,\n choices: (line.choices ?? []).map((choice) => ({\n ...choice,\n quantity: choice.quantity ?? 1,\n })),\n inputs: line.inputs ?? {},\n addedAt: new Date().toISOString(),\n })),\n };\n const scope = client.config.cart?.storageScope;\n (client.config.storage ?? window.localStorage).setItem(\n `zappie:cart:v1:${client.config.store}:${snapshot.branchId}${scope ? `:${scope}` : \"\"}`,\n JSON.stringify(value),\n );\n },\n }),\n quote: () => quote,\n events,\n };\n client.on(\"add_to_cart\", (detail) => emit(\"add_to_cart\", detail));\n client.cart.subscribe(() => {\n const state = client.cart.state;\n const next = \"quote\" in state ? state.quote : undefined;\n if (next && next !== quote) {\n quote = next;\n emit(\"quote\", next);\n }\n });\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -78,7 +78,7 @@ declare function validateLine(item: Item | undefined, raw: CartLineInput, ctx: {
78
78
  branch: Branch;
79
79
  }): CartIssue[];
80
80
 
81
- /** Public package release version. */
82
- declare const VERSION = "0.0.0";
81
+ /** The installed @zappie/sdk version. */
82
+ declare const VERSION: string;
83
83
 
84
84
  export { Branch, CartIssue, CartLine, CartLineInput, CategoryPage, Item, Menu, MenuResponse, MenuVersion, Money, OptionGroup, QuoteRequest, RequestCtx, RestTransport, type RestTransportOptions, SearchPage, SearchRequest, Store, Transport, VERSION, WireQuote, ZappieCartError, ZappieError, estimateUnitPrice, previewItem, resolveSourceMenu, validateLine };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- export{g as API_VERSION,k as RestTransport,o as VERSION,a as ZappieCartError,m as createZappie,b as estimateUnitPrice,n as previewItem,c as resolveSourceMenu,d as validateLine}from'./chunk-VG7NKIKR.js';export{a as ZappieError,f as format,b as isZappieError,e as money}from'./chunk-I55A5QXJ.js';//# sourceMappingURL=index.js.map
1
+ export{g as API_VERSION,k as RestTransport,o as VERSION,a as ZappieCartError,m as createZappie,b as estimateUnitPrice,n as previewItem,c as resolveSourceMenu,d as validateLine}from'./chunk-LFBQICYU.js';export{a as ZappieError,f as format,b as isZappieError,e as money}from'./chunk-I55A5QXJ.js';//# sourceMappingURL=index.js.map
package/dist/internal.js CHANGED
@@ -1 +1 @@
1
- export{h as validateConfig,e as wireFulfilment}from'./chunk-VG7NKIKR.js';import'./chunk-I55A5QXJ.js';//# sourceMappingURL=internal.js.map
1
+ export{h as validateConfig,e as wireFulfilment}from'./chunk-LFBQICYU.js';import'./chunk-I55A5QXJ.js';//# sourceMappingURL=internal.js.map
@@ -1,2 +1,2 @@
1
1
  "use client";
2
- import {f}from'../chunk-VG7NKIKR.js';export{o as VERSION}from'../chunk-VG7NKIKR.js';import {a}from'../chunk-I55A5QXJ.js';import {createContext,useMemo,useContext,useSyncExternalStore,useEffect}from'react';import {jsx}from'react/jsx-runtime';var h=createContext(null);function M({client:e,initialData:t,children:r}){let o=useMemo(()=>(t?.store&&!e.store.peek()&&e._internal.hydrateStore(t.store),t?.menu&&!e._internal.cache.snapshot(`menu:${t.menu.branchId}`).value&&e.menu.hydrate(t.menu),e),[e,t]);return jsx(h.Provider,{value:o,children:r})}function s(){let e=useContext(h);if(!e)throw new Error("useZappie requires ZappieProvider");return e}function v(){let e=s(),t=e._internal.cache,r=useSyncExternalStore(t.subscribe,()=>t.snapshot("store"),()=>t.snapshot("store"));return useEffect(()=>{let o=new AbortController;return e.store.get({signal:o.signal}).catch(()=>{}),()=>o.abort()},[e]),{data:r.value,error:r.error,isLoading:!r.value&&!r.error}}function x(e,t={}){let r=t.metadataOnly===true,o=s(),u=v(),n=o._internal.cache,a,i;try{a=o._internal.menuKey(e),r&&!n.snapshot(a).value&&(a+=":partial");}catch(p){a="menu:invalid",i=p;}let c=useSyncExternalStore(n.subscribe,()=>n.snapshot(a),()=>n.snapshot(a));useEffect(()=>{if(!u.data||i||r&&n.snapshot(o._internal.menuKey(e)).value)return;let p=new AbortController;return o.menu.get({...e?{branch:e}:{},...r?{metadataOnly:true}:{},signal:p.signal}).catch(()=>{}),()=>p.abort()},[o,e,u.data,i?.code,r,n]);let m=i??c.error??u.error;return {data:c.value,error:m,isLoading:!c.value&&!m,isStale:n.stale(a)}}function O(e,t){let r=x(t),o=r.data&&Object.prototype.hasOwnProperty.call(r.data.items,e)?r.data.items[e]:void 0,u=!!r.data&&!o,n=useMemo(()=>u?new a("item_not_found","Item not found"):void 0,[u,e]);return {data:o,error:r.error??n,isLoading:r.isLoading}}function l(){let{cart:e}=s(),t=useSyncExternalStore(e.subscribe,e.getSnapshot,()=>f);return useEffect(()=>e.mount(),[e]),{...t,actions:e}}function L(e){return l().lines.find(t=>t.id===e)}function I(){let e=s();return l(),e._internal.cartCatalogue()}export{M as ZappieProvider,l as useCart,I as useCartCatalogue,L as useCartLine,O as useItem,x as useMenu,v as useStore,s as useZappie};//# sourceMappingURL=index.js.map
2
+ import {f}from'../chunk-LFBQICYU.js';export{o as VERSION}from'../chunk-LFBQICYU.js';import {a}from'../chunk-I55A5QXJ.js';import {createContext,useMemo,useContext,useSyncExternalStore,useEffect}from'react';import {jsx}from'react/jsx-runtime';var h=createContext(null);function M({client:e,initialData:t,children:r}){let o=useMemo(()=>(t?.store&&!e.store.peek()&&e._internal.hydrateStore(t.store),t?.menu&&!e._internal.cache.snapshot(`menu:${t.menu.branchId}`).value&&e.menu.hydrate(t.menu),e),[e,t]);return jsx(h.Provider,{value:o,children:r})}function s(){let e=useContext(h);if(!e)throw new Error("useZappie requires ZappieProvider");return e}function v(){let e=s(),t=e._internal.cache,r=useSyncExternalStore(t.subscribe,()=>t.snapshot("store"),()=>t.snapshot("store"));return useEffect(()=>{let o=new AbortController;return e.store.get({signal:o.signal}).catch(()=>{}),()=>o.abort()},[e]),{data:r.value,error:r.error,isLoading:!r.value&&!r.error}}function x(e,t={}){let r=t.metadataOnly===true,o=s(),u=v(),n=o._internal.cache,a,i;try{a=o._internal.menuKey(e),r&&!n.snapshot(a).value&&(a+=":partial");}catch(p){a="menu:invalid",i=p;}let c=useSyncExternalStore(n.subscribe,()=>n.snapshot(a),()=>n.snapshot(a));useEffect(()=>{if(!u.data||i||r&&n.snapshot(o._internal.menuKey(e)).value)return;let p=new AbortController;return o.menu.get({...e?{branch:e}:{},...r?{metadataOnly:true}:{},signal:p.signal}).catch(()=>{}),()=>p.abort()},[o,e,u.data,i?.code,r,n]);let m=i??c.error??u.error;return {data:c.value,error:m,isLoading:!c.value&&!m,isStale:n.stale(a)}}function O(e,t){let r=x(t),o=r.data&&Object.prototype.hasOwnProperty.call(r.data.items,e)?r.data.items[e]:void 0,u=!!r.data&&!o,n=useMemo(()=>u?new a("item_not_found","Item not found"):void 0,[u,e]);return {data:o,error:r.error??n,isLoading:r.isLoading}}function l(){let{cart:e}=s(),t=useSyncExternalStore(e.subscribe,e.getSnapshot,()=>f);return useEffect(()=>e.mount(),[e]),{...t,actions:e}}function L(e){return l().lines.find(t=>t.id===e)}function I(){let e=s();return l(),e._internal.cartCatalogue()}export{M as ZappieProvider,l as useCart,I as useCartCatalogue,L as useCartLine,O as useItem,x as useMenu,v as useStore,s as useZappie};//# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import {l}from'../chunk-VG7NKIKR.js';export{o as VERSION}from'../chunk-VG7NKIKR.js';import {a as a$1}from'../chunk-I55A5QXJ.js';var f="review-menu",y="payment",w="send-otp",E=new Set([w,"verify-otp","update-profile"]),h=t=>t.contract!=="v1"&&t.installation!==void 0,C=t=>({type:"order-menu",business:t.business,...t.branch!==void 0?{branch:t.branch}:{},state:t.state});var g=["ref","utm_source","payment_id","context","prefetch","business_tag","pay_point_id","dine_in_order_id","no_context","payment_context_id","ws","preview","device","auto_scroll","pickup","branch_closed","order_id","modal_id","lightbox","menu_id","payment_method","beacon_id","menu_group_id","category_id","menu_layout","can_schedule","refresh","success","grant","portal","can_download_receipt","auth_modal_id","experimental_otp","branch","business","env","switched_branch","from","template","catalog_rendering","catalogue_search","catalogue_categories"],_=[...g,"return","session"];var et="https://storefront.invalid",d="product_",V=t=>{try{return decodeURIComponent(t)}catch{return t}},a=t=>encodeURIComponent(t),m=t=>{if(t instanceof URL)return new URL(t.toString());let e=typeof t=="string"?t:t.url;return new URL(e,et)},rt=(t,e)=>{let r={};return t.forEach((o,s)=>{(e==="v2"?_:g).includes(s)&&(r[s]=o);}),r},k=(t,e="v2")=>{let r=rt(t.searchParams,e),o=t.searchParams.get("pickup");return {query:r,...t.searchParams.has("menu_id")?{menuId:t.searchParams.get("menu_id")??""}:{},...t.searchParams.has("category_id")?{categoryId:t.searchParams.get("category_id")??""}:{},...t.searchParams.has("menu_layout")?{menuLayout:t.searchParams.get("menu_layout")??""}:{},...o==="true"?{mode:"pickup"}:o==="false"?{mode:"delivery"}:{},...t.searchParams.has("modal_id")?{modalId:t.searchParams.get("modal_id")??""}:{},...t.searchParams.has("auth_modal_id")?{authModalId:t.searchParams.get("auth_modal_id")??""}:{},...t.searchParams.has("payment_id")?{paymentId:t.searchParams.get("payment_id")??""}:{},...t.searchParams.has("lightbox")?{lightbox:t.searchParams.get("lightbox")??""}:{},...t.searchParams.has("catalogue_search")?{catalogueSearch:t.searchParams.get("catalogue_search")??""}:{},...t.searchParams.has("catalogue_categories")?{catalogueCategories:t.searchParams.get("catalogue_categories")??""}:{}}};var S=t=>t.replace(/\/+$/,"")||"/",D=(t,e)=>{if(!e)return t;let r=`/order/${a(e.business)}`;if(t==="/")return r;if(t==="/order")return e.defaultBranch?`${r}/${a(e.defaultBranch)}`:r;if(t.startsWith("/pages/"))return `${r}${t}`;if(!t.startsWith("/order/")||t===r||t.startsWith(`${r}/`))return t;let o=t.slice(6);return e.defaultBranch&&(o==="/products"||o.startsWith("/products/")||o.startsWith("/pages/"))?`${r}/${a(e.defaultBranch)}${o}`:`${r}${o}`},F=(t,e,r)=>{if(!r||!("business"in e)||e.business!==r.business)return t;if(e.type==="content-page"&&!e.branch)return `/pages/${a(e.slug)}`;if(e.type==="order-menu"&&!e.branch)return "/";let o=`/order/${a(e.business)}/${a(e.branch??"")}`,s=t.slice(o.length);return e.branch===r.defaultBranch?`/order${s}`:`/order/${a(e.branch??"")}${s}`},p=(t,e)=>V(t[e]??"");var q=t=>{let e=new URLSearchParams(t.state.query),r=t.state;return [["menu_id",r.menuId],["category_id",r.categoryId],["menu_layout",r.menuLayout],["pickup",r.mode?String(r.mode==="pickup"):void 0],["modal_id",r.modalId],["auth_modal_id",r.authModalId],["payment_id",r.paymentId],["lightbox",r.lightbox],["catalogue_search",r.catalogueSearch],["catalogue_categories",r.catalogueCategories]].forEach(([s,n])=>{n!==void 0&&e.set(s,n);}),e},Q=t=>{let e=q(t);return t.type==="item"?e.delete("modal_id"):t.type==="cart"?e.set("modal_id",f):t.type==="checkout"?e.set("modal_id",y):t.type==="sign-in"?(e.set("auth_modal_id",w),t.returnTo!==void 0&&e.set("return",t.returnTo)):t.type==="checkout-return"&&t.session!==void 0&&e.set("session",t.session),e.sort(),e},v=(t,e)=>{let r=q(t);return (t.type==="order-menu"||t.type==="item"||t.type==="cart"||t.type==="checkout"||t.type==="checkout-return"||t.type==="sign-in"||t.type==="content-page")&&(t.branch&&t.branch!==e.defaultBranch?r.set("branch",t.branch):r.delete("branch")),(t.type==="item"||t.type==="cart"||t.type==="checkout"||t.type==="checkout-return")&&r.delete("modal_id"),t.type==="sign-in"&&(r.delete("auth_modal_id"),t.returnTo!==void 0&&r.set("return",t.returnTo)),t.type==="checkout-return"&&t.session!==void 0&&r.set("session",t.session),r.sort(),r};var T=(t,e={})=>{switch(t.type){case "order-menu":return `/order/${a(t.business)}${t.branch?`/${a(t.branch)}`:""}${t.cataloguePath?"/products":""}`;case "item":{let r=t.branch??e.installation?.defaultBranch;return r?`/order/${a(t.business)}/${a(r)}/products/${a(t.item)}`:`/order/${a(t.business)}`}case "cart":case "checkout":case "checkout-return":case "sign-in":return T(C(t),e);case "content-page":return `/order/${a(t.business)}${t.branch?`/${a(t.branch)}`:""}/pages/${a(t.slug)}`;case "dine-in":return `/dine-in/${a(t.order)}`;case "dine-in-menus":return "/dine-in/menus";case "self-service-menus":return "/self-service/menus";case "pay-point":return `/pay-point/${a(t.payPoint)}`;case "beacon":return `/beacons/${a(t.beacon)}`;case "link":return `/links/${a(t.link)}`;case "collect-payment":return "/collect-payment";case "reservation":return "/reservation";case "pay-session":return `/pay/${a(t.session)}`;case "payment-step":return `/payment/${a(t.payment)}${t.step==="payment"?"":`/${t.step}`}`;case "payment-card":return `/payment/card/${a(t.transaction)}`;case "profile":return `/profile/${t.page}${t.order?`/${a(t.order)}`:""}`;case "explore":return t.home?"/":"/explore";case "unknown":return t.pathname||"/"}},B=(t,e={})=>{let r=T(t,e),o=t.type==="item"&&t.branch===void 0&&e.installation?.defaultBranch?{...t,branch:e.installation.defaultBranch}:t,s=F(r,o,e.installation),n=Q(t).toString(),c=`${s}${n?`?${n}`:""}`;if(!e.origin)return c;try{return new URL(c,e.origin).toString()}catch{return c}};var $=(t,e)=>{let r=v(t,e);r.delete("auth_modal_id");let o=r.toString();return {type:"sign-in",business:t.business,state:{query:{}},returnTo:`/${o?`?${o}`:""}`}};var nt=(t,e)=>{if(t.type!=="order-menu")return t;let r={business:t.business,...t.branch!==void 0?{branch:t.branch}:{},state:t.state};return t.state.authModalId&&E.has(t.state.authModalId)?$(t,e):t.state.modalId?.startsWith(d)?{type:"item",...r,item:t.state.modalId.slice(d.length)}:t.state.modalId===f?{type:"cart",...r}:t.state.modalId===y?{type:"checkout",...r}:t},ot=t=>t.page==="orders"?`/orders${t.order?`/${a(t.order)}`:""}`:t.page==="edit"?"/account":`/account/${t.page==="add-store-credit"?"store-credit":t.page}`,st=(t,e)=>{switch(t.type){case "order-menu":return "/";case "item":return `/item/${a(t.item)}`;case "cart":return "/cart";case "checkout":return "/checkout";case "checkout-return":return "/checkout/return";case "sign-in":return "/sign-in";case "content-page":return `/pages/${a(t.slug)}`;case "profile":return ot(t);default:return T(t,e)}},Y=(t,e)=>{let r=e.installation;if(!r)return "";let o=nt(t,r),s=st(o,e),n=v(o,r).toString();return `${s}${n?`?${n}`:""}`};var R=(t,e={})=>{let r=h(e)?Y(t,e):B(t,e);if(!e.origin)return r;try{return new URL(r,e.origin).toString()}catch{return r}};var H={"/dine-in/menus":"dine-in-menus","/self-service/menus":"self-service-menus","/collect-payment":"collect-payment","/reservation":"reservation"},K={"dine-in":(t,e)=>({type:"dine-in",order:t,state:e}),"pay-point":(t,e)=>({type:"pay-point",payPoint:t,state:e}),beacons:(t,e)=>({type:"beacon",beacon:t,state:e}),links:(t,e)=>({type:"link",link:t,state:e}),pay:(t,e)=>({type:"pay-session",session:t,state:e})},Z=(t,e)=>Object.hasOwn(t,e),x=(t,e={})=>{try{let r=m(t),o=k(r,"v1"),s=D(S(r.pathname),e.installation),n=s.split("/").filter(Boolean);if(n[0]==="order"&&n[1]){let i=p(n,1);if(n[2]==="pages"&&n.length===4)return {type:"content-page",business:i,slug:p(n,3),state:o};let l=n[2]?p(n,2):void 0;if(l&&n[3]==="pages"&&n.length===5)return {type:"content-page",business:i,branch:l,slug:p(n,4),state:o};if(l&&n[3]==="products"&&n[4]&&n.length===5)return {type:"item",business:i,branch:l,item:p(n,4),state:o};if(n.length<=3||n.length===4&&n[3]==="products"){let A=o.modalId?.startsWith(d)?o.modalId.slice(d.length):"";return l&&A?{type:"item",business:i,branch:l,item:A,state:o}:{type:"order-menu",business:i,...l?{branch:l}:{},...n[3]==="products"?{cataloguePath:!0}:{},state:o}}}if(Z(H,s))return {type:H[s],state:o};let[c="",u]=n;if(n.length===2&&u&&Z(K,c))return K[c](p(n,1),o);if(n[0]==="payment"&&n[1]==="card"&&n[2]&&n.length===3)return {type:"payment-card",transaction:p(n,2),state:o};if(n[0]==="payment"&&n[1]&&n.length<=3){let i=n[2];if(!i||i==="successful"||i==="failed"||i==="refunded")return {type:"payment-step",payment:p(n,1),step:i==="successful"||i==="failed"||i==="refunded"?i:"payment",state:o}}if(n[0]==="orders"&&n.length<=2)return {type:"profile",page:"orders",...n[1]?{order:p(n,1)}:{},state:o};if(n[0]==="profile"&&n[1]&&n.length<=3){let i=n[1];if(i==="add-store-credit"||i==="edit"||i==="payment-methods"||i==="transactions")return {type:"profile",page:i,state:o};if(i==="orders")return {type:"profile",page:i,...n[2]?{order:p(n,2)}:{},state:o}}return s==="/"||s==="/explore"?{type:"explore",...s==="/"?{home:!0}:{},state:o}:{type:"unknown",pathname:s,state:o}}catch{return {type:"unknown",pathname:"",state:{query:{}}}}};var at=t=>t.searchParams.has("branch")?{branch:t.searchParams.get("branch")??""}:{},it=(t,e,r)=>{let o=S(t.pathname),s=o.split("/").filter(Boolean),n=at(t);if(o==="/")return {type:"order-menu",business:r,...n,state:e};if(s[0]==="item"&&s[1]&&s.length===2)return {type:"item",business:r,...n,item:p(s,1),state:e};if(o==="/cart"||o==="/checkout")return {type:o==="/cart"?"cart":"checkout",business:r,...n,state:e};if(o==="/checkout/return"){let c=t.searchParams.get("session");return {type:"checkout-return",business:r,...n,...c!==null?{session:c}:{},state:e}}if(o==="/sign-in"){let c=t.searchParams.get("return");return {type:"sign-in",business:r,...n,...c!==null?{returnTo:c}:{},state:e}}if(s[0]==="pages"&&s[1]&&s.length===2)return {type:"content-page",business:r,...n,slug:p(s,1),state:e};if(s[0]==="orders"&&s.length<=2)return {type:"profile",page:"orders",...s[1]?{order:p(s,1)}:{},state:e};if(s[0]==="account"&&s.length<=2){let c={"payment-methods":"payment-methods",transactions:"transactions","store-credit":"add-store-credit"};if(s.length===1)return {type:"profile",page:"edit",state:e};let u=s[1];if(u&&Object.hasOwn(c,u))return {type:"profile",page:c[u],state:e}}return null},j=(t,e)=>{if(t.type!=="order-menu")return t;let{authModalId:r,modalId:o}=t.state;return r&&E.has(r)?$(t,e):o?.startsWith(d)?{type:"item",business:t.business,...t.branch!==void 0?{branch:t.branch}:{},item:o.slice(d.length),state:t.state}:o===f||o===y?{type:o===f?"cart":"checkout",business:t.business,...t.branch!==void 0?{branch:t.branch}:{},state:t.state}:t},G=(t,e)=>{try{let r=m(t),o=k(r),s=e.installation;if(!s)return x(t,e);let n=it(r,o,s.business);return n?n.type==="order-menu"?j(n,s):n:j(x(t,{...e,contract:"v1"}),s)}catch{return {type:"unknown",pathname:"",state:{query:{}}}}};var I=(t,e={})=>h(e)?G(t,e):x(t,e);var X=t=>{let e=m(t);return e.searchParams.sort(),`${S(e.pathname)}${e.search}`},M=(t,e={})=>{if(!h(e))return null;try{let r=I(t,e);if(r.type==="unknown")return null;let o=R(r,e);return X(m(t))===X(o)?null:o}catch{return null}};var U=class extends a$1{constructor(){super("invalid_request","Zappie could not verify this webhook signature."),this.name="ZappieWebhookSignatureError";}},W=new TextEncoder;async function ct({payload:t,header:e,secret:r,toleranceSec:o=300,now:s=new Date}){let n=pt(e);if(r.length===0||!n||!Number.isFinite(o)||o<0||Math.abs(s.getTime()/1e3-n.seconds)>o)throw new U;let c=typeof t=="string"?W.encode(t):t,u=W.encode(`${n.timestamp}.`),i=new Uint8Array(u.length+c.length);i.set(u),i.set(c,u.length);let l=await crypto.subtle.importKey("raw",W.encode(r),{name:"HMAC",hash:"SHA-256"},false,["verify"]);if(!(await Promise.all(n.signatures.map(async O=>{let L=/^[0-9a-f]{64}$/.test(O),z=L?ut(O):new Uint8Array(32),J=await crypto.subtle.verify("HMAC",l,z,i);return L&&J}))).some(Boolean))throw new U;let b;try{b=JSON.parse(new TextDecoder().decode(c));}catch(O){throw new a$1("invalid_request","The verified webhook payload is not valid JSON.",{cause:O})}if(!b||typeof b!="object"||Array.isArray(b))throw new a$1("invalid_request","The verified webhook payload is not a JSON object.");return b}function pt(t){let e="",r=[];for(let s of t?.split(",")??[]){let n=s.trim(),c=n.indexOf("=");if(c<0)continue;let u=n.slice(0,c),i=n.slice(c+1);u==="t"?e=i:u==="v1"&&r.push(i);}if(!/^[+-]?\d+$/.test(e)||r.length===0)return null;let o=Number(e);return Number.isSafeInteger(o)?{timestamp:e,seconds:o,signatures:r}:null}function ut(t){let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r+=1)e[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return e}function le({secretKey:t,...e}){return l({...e,key:t},true)}
1
+ import {l}from'../chunk-LFBQICYU.js';export{o as VERSION}from'../chunk-LFBQICYU.js';import {a as a$1}from'../chunk-I55A5QXJ.js';var f="review-menu",y="payment",w="send-otp",E=new Set([w,"verify-otp","update-profile"]),h=t=>t.contract!=="v1"&&t.installation!==void 0,C=t=>({type:"order-menu",business:t.business,...t.branch!==void 0?{branch:t.branch}:{},state:t.state});var g=["ref","utm_source","payment_id","context","prefetch","business_tag","pay_point_id","dine_in_order_id","no_context","payment_context_id","ws","preview","device","auto_scroll","pickup","branch_closed","order_id","modal_id","lightbox","menu_id","payment_method","beacon_id","menu_group_id","category_id","menu_layout","can_schedule","refresh","success","grant","portal","can_download_receipt","auth_modal_id","experimental_otp","branch","business","env","switched_branch","from","template","catalog_rendering","catalogue_search","catalogue_categories"],_=[...g,"return","session"];var et="https://storefront.invalid",d="product_",V=t=>{try{return decodeURIComponent(t)}catch{return t}},a=t=>encodeURIComponent(t),m=t=>{if(t instanceof URL)return new URL(t.toString());let e=typeof t=="string"?t:t.url;return new URL(e,et)},rt=(t,e)=>{let r={};return t.forEach((o,s)=>{(e==="v2"?_:g).includes(s)&&(r[s]=o);}),r},k=(t,e="v2")=>{let r=rt(t.searchParams,e),o=t.searchParams.get("pickup");return {query:r,...t.searchParams.has("menu_id")?{menuId:t.searchParams.get("menu_id")??""}:{},...t.searchParams.has("category_id")?{categoryId:t.searchParams.get("category_id")??""}:{},...t.searchParams.has("menu_layout")?{menuLayout:t.searchParams.get("menu_layout")??""}:{},...o==="true"?{mode:"pickup"}:o==="false"?{mode:"delivery"}:{},...t.searchParams.has("modal_id")?{modalId:t.searchParams.get("modal_id")??""}:{},...t.searchParams.has("auth_modal_id")?{authModalId:t.searchParams.get("auth_modal_id")??""}:{},...t.searchParams.has("payment_id")?{paymentId:t.searchParams.get("payment_id")??""}:{},...t.searchParams.has("lightbox")?{lightbox:t.searchParams.get("lightbox")??""}:{},...t.searchParams.has("catalogue_search")?{catalogueSearch:t.searchParams.get("catalogue_search")??""}:{},...t.searchParams.has("catalogue_categories")?{catalogueCategories:t.searchParams.get("catalogue_categories")??""}:{}}};var S=t=>t.replace(/\/+$/,"")||"/",D=(t,e)=>{if(!e)return t;let r=`/order/${a(e.business)}`;if(t==="/")return r;if(t==="/order")return e.defaultBranch?`${r}/${a(e.defaultBranch)}`:r;if(t.startsWith("/pages/"))return `${r}${t}`;if(!t.startsWith("/order/")||t===r||t.startsWith(`${r}/`))return t;let o=t.slice(6);return e.defaultBranch&&(o==="/products"||o.startsWith("/products/")||o.startsWith("/pages/"))?`${r}/${a(e.defaultBranch)}${o}`:`${r}${o}`},F=(t,e,r)=>{if(!r||!("business"in e)||e.business!==r.business)return t;if(e.type==="content-page"&&!e.branch)return `/pages/${a(e.slug)}`;if(e.type==="order-menu"&&!e.branch)return "/";let o=`/order/${a(e.business)}/${a(e.branch??"")}`,s=t.slice(o.length);return e.branch===r.defaultBranch?`/order${s}`:`/order/${a(e.branch??"")}${s}`},p=(t,e)=>V(t[e]??"");var q=t=>{let e=new URLSearchParams(t.state.query),r=t.state;return [["menu_id",r.menuId],["category_id",r.categoryId],["menu_layout",r.menuLayout],["pickup",r.mode?String(r.mode==="pickup"):void 0],["modal_id",r.modalId],["auth_modal_id",r.authModalId],["payment_id",r.paymentId],["lightbox",r.lightbox],["catalogue_search",r.catalogueSearch],["catalogue_categories",r.catalogueCategories]].forEach(([s,n])=>{n!==void 0&&e.set(s,n);}),e},Q=t=>{let e=q(t);return t.type==="item"?e.delete("modal_id"):t.type==="cart"?e.set("modal_id",f):t.type==="checkout"?e.set("modal_id",y):t.type==="sign-in"?(e.set("auth_modal_id",w),t.returnTo!==void 0&&e.set("return",t.returnTo)):t.type==="checkout-return"&&t.session!==void 0&&e.set("session",t.session),e.sort(),e},v=(t,e)=>{let r=q(t);return (t.type==="order-menu"||t.type==="item"||t.type==="cart"||t.type==="checkout"||t.type==="checkout-return"||t.type==="sign-in"||t.type==="content-page")&&(t.branch&&t.branch!==e.defaultBranch?r.set("branch",t.branch):r.delete("branch")),(t.type==="item"||t.type==="cart"||t.type==="checkout"||t.type==="checkout-return")&&r.delete("modal_id"),t.type==="sign-in"&&(r.delete("auth_modal_id"),t.returnTo!==void 0&&r.set("return",t.returnTo)),t.type==="checkout-return"&&t.session!==void 0&&r.set("session",t.session),r.sort(),r};var T=(t,e={})=>{switch(t.type){case "order-menu":return `/order/${a(t.business)}${t.branch?`/${a(t.branch)}`:""}${t.cataloguePath?"/products":""}`;case "item":{let r=t.branch??e.installation?.defaultBranch;return r?`/order/${a(t.business)}/${a(r)}/products/${a(t.item)}`:`/order/${a(t.business)}`}case "cart":case "checkout":case "checkout-return":case "sign-in":return T(C(t),e);case "content-page":return `/order/${a(t.business)}${t.branch?`/${a(t.branch)}`:""}/pages/${a(t.slug)}`;case "dine-in":return `/dine-in/${a(t.order)}`;case "dine-in-menus":return "/dine-in/menus";case "self-service-menus":return "/self-service/menus";case "pay-point":return `/pay-point/${a(t.payPoint)}`;case "beacon":return `/beacons/${a(t.beacon)}`;case "link":return `/links/${a(t.link)}`;case "collect-payment":return "/collect-payment";case "reservation":return "/reservation";case "pay-session":return `/pay/${a(t.session)}`;case "payment-step":return `/payment/${a(t.payment)}${t.step==="payment"?"":`/${t.step}`}`;case "payment-card":return `/payment/card/${a(t.transaction)}`;case "profile":return `/profile/${t.page}${t.order?`/${a(t.order)}`:""}`;case "explore":return t.home?"/":"/explore";case "unknown":return t.pathname||"/"}},B=(t,e={})=>{let r=T(t,e),o=t.type==="item"&&t.branch===void 0&&e.installation?.defaultBranch?{...t,branch:e.installation.defaultBranch}:t,s=F(r,o,e.installation),n=Q(t).toString(),c=`${s}${n?`?${n}`:""}`;if(!e.origin)return c;try{return new URL(c,e.origin).toString()}catch{return c}};var $=(t,e)=>{let r=v(t,e);r.delete("auth_modal_id");let o=r.toString();return {type:"sign-in",business:t.business,state:{query:{}},returnTo:`/${o?`?${o}`:""}`}};var nt=(t,e)=>{if(t.type!=="order-menu")return t;let r={business:t.business,...t.branch!==void 0?{branch:t.branch}:{},state:t.state};return t.state.authModalId&&E.has(t.state.authModalId)?$(t,e):t.state.modalId?.startsWith(d)?{type:"item",...r,item:t.state.modalId.slice(d.length)}:t.state.modalId===f?{type:"cart",...r}:t.state.modalId===y?{type:"checkout",...r}:t},ot=t=>t.page==="orders"?`/orders${t.order?`/${a(t.order)}`:""}`:t.page==="edit"?"/account":`/account/${t.page==="add-store-credit"?"store-credit":t.page}`,st=(t,e)=>{switch(t.type){case "order-menu":return "/";case "item":return `/item/${a(t.item)}`;case "cart":return "/cart";case "checkout":return "/checkout";case "checkout-return":return "/checkout/return";case "sign-in":return "/sign-in";case "content-page":return `/pages/${a(t.slug)}`;case "profile":return ot(t);default:return T(t,e)}},Y=(t,e)=>{let r=e.installation;if(!r)return "";let o=nt(t,r),s=st(o,e),n=v(o,r).toString();return `${s}${n?`?${n}`:""}`};var R=(t,e={})=>{let r=h(e)?Y(t,e):B(t,e);if(!e.origin)return r;try{return new URL(r,e.origin).toString()}catch{return r}};var H={"/dine-in/menus":"dine-in-menus","/self-service/menus":"self-service-menus","/collect-payment":"collect-payment","/reservation":"reservation"},K={"dine-in":(t,e)=>({type:"dine-in",order:t,state:e}),"pay-point":(t,e)=>({type:"pay-point",payPoint:t,state:e}),beacons:(t,e)=>({type:"beacon",beacon:t,state:e}),links:(t,e)=>({type:"link",link:t,state:e}),pay:(t,e)=>({type:"pay-session",session:t,state:e})},Z=(t,e)=>Object.hasOwn(t,e),x=(t,e={})=>{try{let r=m(t),o=k(r,"v1"),s=D(S(r.pathname),e.installation),n=s.split("/").filter(Boolean);if(n[0]==="order"&&n[1]){let i=p(n,1);if(n[2]==="pages"&&n.length===4)return {type:"content-page",business:i,slug:p(n,3),state:o};let l=n[2]?p(n,2):void 0;if(l&&n[3]==="pages"&&n.length===5)return {type:"content-page",business:i,branch:l,slug:p(n,4),state:o};if(l&&n[3]==="products"&&n[4]&&n.length===5)return {type:"item",business:i,branch:l,item:p(n,4),state:o};if(n.length<=3||n.length===4&&n[3]==="products"){let A=o.modalId?.startsWith(d)?o.modalId.slice(d.length):"";return l&&A?{type:"item",business:i,branch:l,item:A,state:o}:{type:"order-menu",business:i,...l?{branch:l}:{},...n[3]==="products"?{cataloguePath:!0}:{},state:o}}}if(Z(H,s))return {type:H[s],state:o};let[c="",u]=n;if(n.length===2&&u&&Z(K,c))return K[c](p(n,1),o);if(n[0]==="payment"&&n[1]==="card"&&n[2]&&n.length===3)return {type:"payment-card",transaction:p(n,2),state:o};if(n[0]==="payment"&&n[1]&&n.length<=3){let i=n[2];if(!i||i==="successful"||i==="failed"||i==="refunded")return {type:"payment-step",payment:p(n,1),step:i==="successful"||i==="failed"||i==="refunded"?i:"payment",state:o}}if(n[0]==="orders"&&n.length<=2)return {type:"profile",page:"orders",...n[1]?{order:p(n,1)}:{},state:o};if(n[0]==="profile"&&n[1]&&n.length<=3){let i=n[1];if(i==="add-store-credit"||i==="edit"||i==="payment-methods"||i==="transactions")return {type:"profile",page:i,state:o};if(i==="orders")return {type:"profile",page:i,...n[2]?{order:p(n,2)}:{},state:o}}return s==="/"||s==="/explore"?{type:"explore",...s==="/"?{home:!0}:{},state:o}:{type:"unknown",pathname:s,state:o}}catch{return {type:"unknown",pathname:"",state:{query:{}}}}};var at=t=>t.searchParams.has("branch")?{branch:t.searchParams.get("branch")??""}:{},it=(t,e,r)=>{let o=S(t.pathname),s=o.split("/").filter(Boolean),n=at(t);if(o==="/")return {type:"order-menu",business:r,...n,state:e};if(s[0]==="item"&&s[1]&&s.length===2)return {type:"item",business:r,...n,item:p(s,1),state:e};if(o==="/cart"||o==="/checkout")return {type:o==="/cart"?"cart":"checkout",business:r,...n,state:e};if(o==="/checkout/return"){let c=t.searchParams.get("session");return {type:"checkout-return",business:r,...n,...c!==null?{session:c}:{},state:e}}if(o==="/sign-in"){let c=t.searchParams.get("return");return {type:"sign-in",business:r,...n,...c!==null?{returnTo:c}:{},state:e}}if(s[0]==="pages"&&s[1]&&s.length===2)return {type:"content-page",business:r,...n,slug:p(s,1),state:e};if(s[0]==="orders"&&s.length<=2)return {type:"profile",page:"orders",...s[1]?{order:p(s,1)}:{},state:e};if(s[0]==="account"&&s.length<=2){let c={"payment-methods":"payment-methods",transactions:"transactions","store-credit":"add-store-credit"};if(s.length===1)return {type:"profile",page:"edit",state:e};let u=s[1];if(u&&Object.hasOwn(c,u))return {type:"profile",page:c[u],state:e}}return null},j=(t,e)=>{if(t.type!=="order-menu")return t;let{authModalId:r,modalId:o}=t.state;return r&&E.has(r)?$(t,e):o?.startsWith(d)?{type:"item",business:t.business,...t.branch!==void 0?{branch:t.branch}:{},item:o.slice(d.length),state:t.state}:o===f||o===y?{type:o===f?"cart":"checkout",business:t.business,...t.branch!==void 0?{branch:t.branch}:{},state:t.state}:t},G=(t,e)=>{try{let r=m(t),o=k(r),s=e.installation;if(!s)return x(t,e);let n=it(r,o,s.business);return n?n.type==="order-menu"?j(n,s):n:j(x(t,{...e,contract:"v1"}),s)}catch{return {type:"unknown",pathname:"",state:{query:{}}}}};var I=(t,e={})=>h(e)?G(t,e):x(t,e);var X=t=>{let e=m(t);return e.searchParams.sort(),`${S(e.pathname)}${e.search}`},M=(t,e={})=>{if(!h(e))return null;try{let r=I(t,e);if(r.type==="unknown")return null;let o=R(r,e);return X(m(t))===X(o)?null:o}catch{return null}};var U=class extends a$1{constructor(){super("invalid_request","Zappie could not verify this webhook signature."),this.name="ZappieWebhookSignatureError";}},W=new TextEncoder;async function ct({payload:t,header:e,secret:r,toleranceSec:o=300,now:s=new Date}){let n=pt(e);if(r.length===0||!n||!Number.isFinite(o)||o<0||Math.abs(s.getTime()/1e3-n.seconds)>o)throw new U;let c=typeof t=="string"?W.encode(t):t,u=W.encode(`${n.timestamp}.`),i=new Uint8Array(u.length+c.length);i.set(u),i.set(c,u.length);let l=await crypto.subtle.importKey("raw",W.encode(r),{name:"HMAC",hash:"SHA-256"},false,["verify"]);if(!(await Promise.all(n.signatures.map(async O=>{let L=/^[0-9a-f]{64}$/.test(O),z=L?ut(O):new Uint8Array(32),J=await crypto.subtle.verify("HMAC",l,z,i);return L&&J}))).some(Boolean))throw new U;let b;try{b=JSON.parse(new TextDecoder().decode(c));}catch(O){throw new a$1("invalid_request","The verified webhook payload is not valid JSON.",{cause:O})}if(!b||typeof b!="object"||Array.isArray(b))throw new a$1("invalid_request","The verified webhook payload is not a JSON object.");return b}function pt(t){let e="",r=[];for(let s of t?.split(",")??[]){let n=s.trim(),c=n.indexOf("=");if(c<0)continue;let u=n.slice(0,c),i=n.slice(c+1);u==="t"?e=i:u==="v1"&&r.push(i);}if(!/^[+-]?\d+$/.test(e)||r.length===0)return null;let o=Number(e);return Number.isSafeInteger(o)?{timestamp:e,seconds:o,signatures:r}:null}function ut(t){let e=new Uint8Array(t.length/2);for(let r=0;r<e.length;r+=1)e[r]=Number.parseInt(t.slice(r*2,r*2+2),16);return e}function le({secretKey:t,...e}){return l({...e,key:t},true)}
2
2
  export{_ as STOREFRONT_QUERY_PARAMETERS,g as STOREFRONT_V1_QUERY_PARAMETERS,U as ZappieWebhookSignatureError,R as buildStorefrontUrl,le as createZappieServer,I as parseStorefrontUrl,M as storefrontRedirect,ct as verifyWebhook};//# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- import {m,d,b,i,j}from'../chunk-VG7NKIKR.js';export{o as VERSION}from'../chunk-VG7NKIKR.js';import {e,a,h}from'../chunk-I55A5QXJ.js';function W(s,_={}){let n=structuredClone(s),u=async(i$1,e)=>{i(e.signal),_.latencyMs&&await j(_.latencyMs,e.signal);let o=_.failWith?.[i$1];if(o)throw new a(o,`Mock ${i$1} failure`)},m$1=i=>{let e=n.menus[i];if(!e)throw new a("branch_not_found","No fixture for this branch");return structuredClone(e)},w={async quote(i,e$1){await u("quote",i);let o=m$1(e$1.branch_id),S=n.store.branches.find(t=>t.id===e$1.branch_id),p=[],g=e$1.lines.map(t=>{let l=o.items[t.item_id],b$1={itemId:t.item_id,...t.menu_id!==void 0?{menuId:t.menu_id}:{},quantity:t.quantity,choices:t.options.map(a=>({groupId:a.group_id,choiceId:a.choice_id,quantity:a.quantity})),inputs:t.inputs,...t.variant_id?{variantId:t.variant_id}:{}},y=d(l,b$1,{menu:o,branch:S});p.push(...y.map(a=>({code:a.code,severity:a.severity,message:a.message,line_id:t.line_id,...a.groupId?{group_id:a.groupId}:{},fixes:[]})));let d$1=l&&!y.length?b(l,b$1):e(0,n.store.currency);return {line_id:t.line_id,unit_price:{amount_minor:d$1.amountMinor,currency:d$1.currency},line_total:{amount_minor:h(d$1,t.quantity).amountMinor,currency:d$1.currency}}}),h$1={amount_minor:g.reduce((t,l)=>t+l.line_total.amount_minor,0),currency:n.store.currency};return {branch_id:e$1.branch_id,lines:g,subtotal:h$1,total:h$1,charges:[],discounts:[],issues:p,can_checkout:!p.some(t=>t.severity==="blocking"),checkout:p.some(t=>t.severity==="blocking")?{ready:false,reason:"issues"}:{ready:true},menu_version:o.version,expires_at:new Date(Date.now()+3e5).toISOString()}},async getStore(i){return await u("getStore",i),structuredClone(n.store)},async getMenu(i){await u("getMenu",i);let e=m$1(i.branchId);return i.ifNoneMatch===e.version?{notModified:true}:{menu:e,etag:e.version}},async getMenuVersion(i){await u("getMenuVersion",i);let e=m$1(i.branchId);return {version:e.version,availabilityHash:e.version}},async getItem(i){await u("getItem",i);let e=m$1(i.branchId).items[i.itemId];if(!e)throw new a("item_not_found","Item not found");return e}};return m({store:n.store.slug,key:"pk_test_fixture",transport:w})}var q={pickup:true,delivery:true,dineIn:false,scheduling:false},N={id:"biz_fixture",slug:"default-store",name:"Default storefront",currency:"NGN",timezone:"Africa/Lagos",brand:{},fulfilment:q,paymentMethods:["card"],branches:[{id:"br_fixture",slug:"main",name:"Main",openingTimes:[{day:1,opens:"08:00",closes:"22:00"}],isOpen:true,fulfilment:q}]},C={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:e(65e4,"NGN"),isAvailable:true,quantity:{min:1,step:1},variants:[{id:"variant_fixture",attributeChoices:{},price:e(65e4,"NGN"),isAvailable:true}],optionGroups:[],tags:[]}}},r=s=>e(s,"NGN"),T={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(s=>({day:s,opens:"08:00",closes:"22:00"})),isOpen:true,isDefault:true,fulfilment:{pickup:true,delivery:true,dineIn:true,scheduling:true},minimumOrder:r(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",fulfilment:{pickup:false,delivery:true,dineIn:false,scheduling:false}}]},G={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:r(45e4),isAvailable:true,quantity:{min:1,max:10,step:1},variants:[{id:"variant_jollof",attributeChoices:{},price:r(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:r(0),isAvailable:true},{id:"opt_beef",name:"Beef",price:r(5e4),isAvailable:true},{id:"opt_fish",name:"Fish",price:r(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:r(0),isAvailable:true},{id:"opt_stew",name:"Stew",price:r(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:r(3e4),isAvailable:true,quantity:{min:1,max:3}},{id:"opt_egg",name:"Boiled egg",price:r(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:r(12e4),isAvailable:true,quantity:{min:1,step:1},variants:[{id:"variant_zobo_small",attributeChoices:{grp_size:"opt_small"},price:r(12e4),isAvailable:true},{id:"variant_zobo_large",attributeChoices:{grp_size:"opt_large"},price:r(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:r(0),isAvailable:true},{id:"opt_large",name:"Large",price:r(0),isAvailable:false}]}],tags:[]},item_cake:{id:"item_cake",name:"Chocolate cake",images:[],price:r(35e4),compareAtPrice:r(4e5),isAvailable:false,quantity:{min:1,step:1},variants:[{id:"variant_cake",attributeChoices:{},price:r(35e4),isAvailable:false}],optionGroups:[],tags:[]}}},Z={minimal:{store:N,menu:C},defaultTemplate:{store:T,menu:G}};
1
+ import {m,d,b,i,j}from'../chunk-LFBQICYU.js';export{o as VERSION}from'../chunk-LFBQICYU.js';import {e,a,h}from'../chunk-I55A5QXJ.js';function W(s,_={}){let n=structuredClone(s),u=async(i$1,e)=>{i(e.signal),_.latencyMs&&await j(_.latencyMs,e.signal);let o=_.failWith?.[i$1];if(o)throw new a(o,`Mock ${i$1} failure`)},m$1=i=>{let e=n.menus[i];if(!e)throw new a("branch_not_found","No fixture for this branch");return structuredClone(e)},w={async quote(i,e$1){await u("quote",i);let o=m$1(e$1.branch_id),S=n.store.branches.find(t=>t.id===e$1.branch_id),p=[],g=e$1.lines.map(t=>{let l=o.items[t.item_id],b$1={itemId:t.item_id,...t.menu_id!==void 0?{menuId:t.menu_id}:{},quantity:t.quantity,choices:t.options.map(a=>({groupId:a.group_id,choiceId:a.choice_id,quantity:a.quantity})),inputs:t.inputs,...t.variant_id?{variantId:t.variant_id}:{}},y=d(l,b$1,{menu:o,branch:S});p.push(...y.map(a=>({code:a.code,severity:a.severity,message:a.message,line_id:t.line_id,...a.groupId?{group_id:a.groupId}:{},fixes:[]})));let d$1=l&&!y.length?b(l,b$1):e(0,n.store.currency);return {line_id:t.line_id,unit_price:{amount_minor:d$1.amountMinor,currency:d$1.currency},line_total:{amount_minor:h(d$1,t.quantity).amountMinor,currency:d$1.currency}}}),h$1={amount_minor:g.reduce((t,l)=>t+l.line_total.amount_minor,0),currency:n.store.currency};return {branch_id:e$1.branch_id,lines:g,subtotal:h$1,total:h$1,charges:[],discounts:[],issues:p,can_checkout:!p.some(t=>t.severity==="blocking"),checkout:p.some(t=>t.severity==="blocking")?{ready:false,reason:"issues"}:{ready:true},menu_version:o.version,expires_at:new Date(Date.now()+3e5).toISOString()}},async getStore(i){return await u("getStore",i),structuredClone(n.store)},async getMenu(i){await u("getMenu",i);let e=m$1(i.branchId);return i.ifNoneMatch===e.version?{notModified:true}:{menu:e,etag:e.version}},async getMenuVersion(i){await u("getMenuVersion",i);let e=m$1(i.branchId);return {version:e.version,availabilityHash:e.version}},async getItem(i){await u("getItem",i);let e=m$1(i.branchId).items[i.itemId];if(!e)throw new a("item_not_found","Item not found");return e}};return m({store:n.store.slug,key:"pk_test_fixture",transport:w})}var q={pickup:true,delivery:true,dineIn:false,scheduling:false},N={id:"biz_fixture",slug:"default-store",name:"Default storefront",currency:"NGN",timezone:"Africa/Lagos",brand:{},fulfilment:q,paymentMethods:["card"],branches:[{id:"br_fixture",slug:"main",name:"Main",openingTimes:[{day:1,opens:"08:00",closes:"22:00"}],isOpen:true,fulfilment:q}]},C={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:e(65e4,"NGN"),isAvailable:true,quantity:{min:1,step:1},variants:[{id:"variant_fixture",attributeChoices:{},price:e(65e4,"NGN"),isAvailable:true}],optionGroups:[],tags:[]}}},r=s=>e(s,"NGN"),T={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(s=>({day:s,opens:"08:00",closes:"22:00"})),isOpen:true,isDefault:true,fulfilment:{pickup:true,delivery:true,dineIn:true,scheduling:true},minimumOrder:r(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",fulfilment:{pickup:false,delivery:true,dineIn:false,scheduling:false}}]},G={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:r(45e4),isAvailable:true,quantity:{min:1,max:10,step:1},variants:[{id:"variant_jollof",attributeChoices:{},price:r(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:r(0),isAvailable:true},{id:"opt_beef",name:"Beef",price:r(5e4),isAvailable:true},{id:"opt_fish",name:"Fish",price:r(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:r(0),isAvailable:true},{id:"opt_stew",name:"Stew",price:r(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:r(3e4),isAvailable:true,quantity:{min:1,max:3}},{id:"opt_egg",name:"Boiled egg",price:r(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:r(12e4),isAvailable:true,quantity:{min:1,step:1},variants:[{id:"variant_zobo_small",attributeChoices:{grp_size:"opt_small"},price:r(12e4),isAvailable:true},{id:"variant_zobo_large",attributeChoices:{grp_size:"opt_large"},price:r(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:r(0),isAvailable:true},{id:"opt_large",name:"Large",price:r(0),isAvailable:false}]}],tags:[]},item_cake:{id:"item_cake",name:"Chocolate cake",images:[],price:r(35e4),compareAtPrice:r(4e5),isAvailable:false,quantity:{min:1,step:1},variants:[{id:"variant_cake",attributeChoices:{},price:r(35e4),isAvailable:false}],optionGroups:[],tags:[]}}},Z={minimal:{store:N,menu:C},defaultTemplate:{store:T,menu:G}};
2
2
  export{W as createMockZappie,Z as fixtures};//# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zappie/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Typed, framework-agnostic client for Zappie menus, carts, checkout, auth and events.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -79,7 +79,8 @@
79
79
  "provenance": false
80
80
  },
81
81
  "files": [
82
- "dist"
82
+ "dist",
83
+ "CHANGELOG.md"
83
84
  ],
84
85
  "peerDependencies": {
85
86
  "react": "^18.2.0 || ^19.0.0"