@zappie/sdk 0.28.1 → 0.29.0

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.
Files changed (364) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/account/index.d.ts +16 -2
  3. package/dist/account/index.js +0 -1
  4. package/dist/account/url.js +0 -1
  5. package/dist/branches/index.d.ts +2 -0
  6. package/dist/branches/index.js +0 -1
  7. package/dist/cart/branch.d.ts +18 -0
  8. package/dist/cart/branch.js +0 -1
  9. package/dist/cart/errors.js +0 -1
  10. package/dist/cart/held.js +0 -1
  11. package/dist/cart/index.js +1 -2
  12. package/dist/cart/item.d.ts +1 -1
  13. package/dist/cart/item.js +0 -1
  14. package/dist/cart/preview.js +0 -1
  15. package/dist/cart/price.js +0 -1
  16. package/dist/cart/quote-client.js +0 -1
  17. package/dist/cart/quote-response.js +1 -2
  18. package/dist/cart/quote.d.ts +1 -1
  19. package/dist/cart/reconcile.js +0 -1
  20. package/dist/cart/source-menu.js +0 -1
  21. package/dist/cart/storage.js +0 -1
  22. package/dist/cart/types.js +0 -1
  23. package/dist/cart/validate.js +0 -1
  24. package/dist/cart/wire.js +0 -1
  25. package/dist/cart/working-set.js +0 -1
  26. package/dist/checkout/client.js +0 -1
  27. package/dist/checkout/embed.d.ts +67 -2
  28. package/dist/checkout/embed.js +0 -1
  29. package/dist/checkout/error.js +0 -1
  30. package/dist/checkout/index.d.ts +74 -3
  31. package/dist/checkout/index.js +0 -1
  32. package/dist/checkout/react.d.ts +67 -2
  33. package/dist/checkout/react.js +0 -1
  34. package/dist/checkout/readiness.js +0 -1
  35. package/dist/checkout/sdk.js +0 -1
  36. package/dist/checkout/session.js +0 -1
  37. package/dist/checkout/types.js +0 -1
  38. package/dist/checkout-defaults/index.d.ts +10 -1
  39. package/dist/checkout-defaults/index.js +0 -1
  40. package/dist/{client-B89-aNcl.d.ts → client-B8lItidz.d.ts} +229 -5
  41. package/dist/client.js +0 -1
  42. package/dist/config/index.d.ts +31 -0
  43. package/dist/config/index.js +0 -1
  44. package/dist/config.js +0 -1
  45. package/dist/customer/client.js +0 -1
  46. package/dist/customer/error.js +0 -1
  47. package/dist/customer/index.d.ts +180 -5
  48. package/dist/customer/index.js +0 -1
  49. package/dist/customer/navigation.js +0 -1
  50. package/dist/customer/react.js +0 -1
  51. package/dist/customer/reorder.d.ts +8 -0
  52. package/dist/customer/reorder.js +0 -1
  53. package/dist/customer/request.js +0 -1
  54. package/dist/customer/types.js +0 -1
  55. package/dist/customer/watch-order.js +0 -1
  56. package/dist/debug.js +1 -2
  57. package/dist/display/index.d.ts +5 -1
  58. package/dist/display/index.js +0 -1
  59. package/dist/error-pages/art.js +0 -1
  60. package/dist/error-pages/index.d.ts +12 -1
  61. package/dist/error-pages/index.js +0 -1
  62. package/dist/error-pages/react.js +0 -1
  63. package/dist/errors.js +1 -2
  64. package/dist/in-venue/bill.js +0 -1
  65. package/dist/in-venue/client.js +0 -1
  66. package/dist/in-venue/error.js +0 -1
  67. package/dist/in-venue/index.d.ts +110 -2
  68. package/dist/in-venue/index.js +0 -1
  69. package/dist/in-venue/react/bill-page.js +0 -1
  70. package/dist/in-venue/react/in-venue-page.js +0 -1
  71. package/dist/in-venue/react/order-panel.js +0 -1
  72. package/dist/in-venue/react/pay-point-page.js +0 -1
  73. package/dist/in-venue/react/shared.js +0 -1
  74. package/dist/in-venue/react/table-menus-page.js +0 -1
  75. package/dist/in-venue/react.js +0 -1
  76. package/dist/in-venue/table.js +0 -1
  77. package/dist/in-venue/types.js +0 -1
  78. package/dist/in-venue/watch.js +0 -1
  79. package/dist/index.d.ts +32 -8
  80. package/dist/index.js +1 -2
  81. package/dist/integrations/index.d.ts +15 -2
  82. package/dist/integrations/index.js +0 -1
  83. package/dist/internal/abort.js +0 -1
  84. package/dist/internal/cache.js +0 -1
  85. package/dist/internal/customer-http.js +1 -2
  86. package/dist/internal/emitter.js +0 -1
  87. package/dist/internal/image-widths.js +0 -1
  88. package/dist/internal/money-math.js +0 -1
  89. package/dist/internal/perk-hold.js +0 -1
  90. package/dist/internal/remembered-address.js +0 -1
  91. package/dist/internal/return-path.js +0 -1
  92. package/dist/internal/service-url.js +0 -1
  93. package/dist/internal.d.ts +2 -2
  94. package/dist/internal.js +0 -1
  95. package/dist/loyalty/cart.js +0 -1
  96. package/dist/loyalty/client.js +0 -1
  97. package/dist/loyalty/index.d.ts +410 -2
  98. package/dist/loyalty/index.js +0 -1
  99. package/dist/loyalty/react.d.ts +15 -1
  100. package/dist/loyalty/react.js +0 -1
  101. package/dist/loyalty/release.js +0 -1
  102. package/dist/loyalty/types.js +0 -1
  103. package/dist/menu/index.d.ts +5 -1
  104. package/dist/menu/index.js +0 -1
  105. package/dist/models-C77LjkK8.d.ts +540 -0
  106. package/dist/models.js +0 -1
  107. package/dist/money.js +0 -1
  108. package/dist/navigation/index.d.ts +8 -0
  109. package/dist/navigation/index.js +0 -1
  110. package/dist/navigation/react.js +0 -1
  111. package/dist/navigation-progress/index.js +0 -1
  112. package/dist/options/index.d.ts +5 -1
  113. package/dist/options/index.js +0 -1
  114. package/dist/persist/catalogue.d.ts +3 -3
  115. package/dist/persist/catalogue.js +0 -1
  116. package/dist/places/client.js +0 -1
  117. package/dist/places/error.js +0 -1
  118. package/dist/places/index.d.ts +41 -1
  119. package/dist/places/index.js +0 -1
  120. package/dist/places/request.js +0 -1
  121. package/dist/places/sdk.js +0 -1
  122. package/dist/places/search.js +0 -1
  123. package/dist/places/types.js +0 -1
  124. package/dist/pricing/index.js +0 -1
  125. package/dist/react/cart.js +0 -1
  126. package/dist/react/changes.js +0 -1
  127. package/dist/react/hooks.js +0 -1
  128. package/dist/react/index.js +0 -1
  129. package/dist/react/provider.js +0 -1
  130. package/dist/react/rollback.js +0 -1
  131. package/dist/receipts/index.js +1 -2
  132. package/dist/redirect/index.js +0 -1
  133. package/dist/rich-text/index.d.ts +4 -0
  134. package/dist/rich-text/index.js +0 -1
  135. package/dist/server/auth/crypto.js +0 -1
  136. package/dist/server/auth/jwt.js +0 -1
  137. package/dist/server/auth/session-store.js +0 -1
  138. package/dist/server/chosen-branch.js +0 -1
  139. package/dist/server/edge-cache.js +0 -1
  140. package/dist/server/edge-snapshot.js +0 -1
  141. package/dist/server/index.d.ts +174 -6
  142. package/dist/server/index.js +0 -1
  143. package/dist/server/legacy-order.js +0 -1
  144. package/dist/server/page-cache.js +0 -1
  145. package/dist/server/security.js +0 -1
  146. package/dist/server/sign-in.js +0 -1
  147. package/dist/server/site-seo.js +0 -1
  148. package/dist/server/site-worker.js +0 -1
  149. package/dist/server/storefront-url/build-v1.js +0 -1
  150. package/dist/server/storefront-url/build-v2.js +0 -1
  151. package/dist/server/storefront-url/build.js +0 -1
  152. package/dist/server/storefront-url/canonical.js +0 -1
  153. package/dist/server/storefront-url/contract.js +0 -1
  154. package/dist/server/storefront-url/index.js +0 -1
  155. package/dist/server/storefront-url/installation.js +0 -1
  156. package/dist/server/storefront-url/params.js +0 -1
  157. package/dist/server/storefront-url/parse-v1.js +0 -1
  158. package/dist/server/storefront-url/parse-v2.js +0 -1
  159. package/dist/server/storefront-url/parse.js +0 -1
  160. package/dist/server/storefront-url/public-id.js +0 -1
  161. package/dist/server/storefront-url/redirect.js +0 -1
  162. package/dist/server/storefront-url/sign-in.js +0 -1
  163. package/dist/server/storefront-url/types.js +0 -1
  164. package/dist/server/storefront-url/url.js +0 -1
  165. package/dist/server/webhook.js +0 -1
  166. package/dist/services/index.d.ts +5 -1
  167. package/dist/services/index.js +0 -1
  168. package/dist/site-closed/index.d.ts +3 -0
  169. package/dist/site-closed/index.js +0 -1
  170. package/dist/site-config/helpers.js +0 -1
  171. package/dist/site-config/sections.js +0 -1
  172. package/dist/site-config/types.js +0 -1
  173. package/dist/site-config/validate.js +0 -1
  174. package/dist/site-error/index.d.ts +9 -1
  175. package/dist/site-error/index.js +0 -1
  176. package/dist/site-error/react.js +0 -1
  177. package/dist/studio/index.d.ts +2 -0
  178. package/dist/template/index.d.ts +7 -1
  179. package/dist/template/index.js +0 -1
  180. package/dist/template/react.js +0 -1
  181. package/dist/testing/index.d.ts +28 -1
  182. package/dist/testing/index.js +1 -1
  183. package/dist/testing/loyalty.js +0 -1
  184. package/dist/transport/category-page.js +0 -1
  185. package/dist/transport/mappers.js +0 -1
  186. package/dist/transport/presentation.js +0 -1
  187. package/dist/transport/quote-body.js +0 -1
  188. package/dist/transport/rest.js +0 -1
  189. package/dist/transport/search.d.ts +1 -1
  190. package/dist/transport/search.js +0 -1
  191. package/dist/transport/selected-menu.d.ts +3 -3
  192. package/dist/transport/selected-menu.js +0 -1
  193. package/dist/transport/store.js +0 -1
  194. package/dist/transport/types.js +0 -1
  195. package/dist/types-CuPaBf6k.d.ts +838 -0
  196. package/dist/uploads/index.js +0 -1
  197. package/dist/url/index.d.ts +31 -0
  198. package/dist/url/index.js +0 -1
  199. package/dist/visits/index.d.ts +26 -1
  200. package/dist/visits/index.js +0 -1
  201. package/dist/visits/page-views.js +0 -1
  202. package/dist/vite/index.d.ts +2 -0
  203. package/package.json +2 -2
  204. package/dist/account/index.js.map +0 -6
  205. package/dist/account/url.js.map +0 -6
  206. package/dist/branches/index.js.map +0 -6
  207. package/dist/cart/branch.js.map +0 -6
  208. package/dist/cart/errors.js.map +0 -6
  209. package/dist/cart/held.js.map +0 -6
  210. package/dist/cart/index.js.map +0 -6
  211. package/dist/cart/item.js.map +0 -6
  212. package/dist/cart/preview.js.map +0 -6
  213. package/dist/cart/price.js.map +0 -6
  214. package/dist/cart/quote-client.js.map +0 -6
  215. package/dist/cart/quote-response.js.map +0 -6
  216. package/dist/cart/reconcile.js.map +0 -6
  217. package/dist/cart/source-menu.js.map +0 -6
  218. package/dist/cart/storage.js.map +0 -6
  219. package/dist/cart/types.js.map +0 -6
  220. package/dist/cart/validate.js.map +0 -6
  221. package/dist/cart/wire.js.map +0 -6
  222. package/dist/cart/working-set.js.map +0 -6
  223. package/dist/checkout/client.js.map +0 -6
  224. package/dist/checkout/embed.js.map +0 -6
  225. package/dist/checkout/error.js.map +0 -6
  226. package/dist/checkout/index.js.map +0 -6
  227. package/dist/checkout/react.js.map +0 -6
  228. package/dist/checkout/readiness.js.map +0 -6
  229. package/dist/checkout/sdk.js.map +0 -6
  230. package/dist/checkout/session.js.map +0 -6
  231. package/dist/checkout/types.js.map +0 -6
  232. package/dist/checkout-defaults/index.js.map +0 -6
  233. package/dist/client.js.map +0 -6
  234. package/dist/config/index.js.map +0 -6
  235. package/dist/config.js.map +0 -6
  236. package/dist/customer/client.js.map +0 -6
  237. package/dist/customer/error.js.map +0 -6
  238. package/dist/customer/index.js.map +0 -6
  239. package/dist/customer/navigation.js.map +0 -6
  240. package/dist/customer/react.js.map +0 -6
  241. package/dist/customer/reorder.js.map +0 -6
  242. package/dist/customer/request.js.map +0 -6
  243. package/dist/customer/types.js.map +0 -6
  244. package/dist/customer/watch-order.js.map +0 -6
  245. package/dist/debug.js.map +0 -6
  246. package/dist/display/index.js.map +0 -6
  247. package/dist/error-pages/art.js.map +0 -6
  248. package/dist/error-pages/index.js.map +0 -6
  249. package/dist/error-pages/react.js.map +0 -6
  250. package/dist/errors.js.map +0 -6
  251. package/dist/in-venue/bill.js.map +0 -6
  252. package/dist/in-venue/client.js.map +0 -6
  253. package/dist/in-venue/error.js.map +0 -6
  254. package/dist/in-venue/index.js.map +0 -6
  255. package/dist/in-venue/react/bill-page.js.map +0 -6
  256. package/dist/in-venue/react/in-venue-page.js.map +0 -6
  257. package/dist/in-venue/react/order-panel.js.map +0 -6
  258. package/dist/in-venue/react/pay-point-page.js.map +0 -6
  259. package/dist/in-venue/react/shared.js.map +0 -6
  260. package/dist/in-venue/react/table-menus-page.js.map +0 -6
  261. package/dist/in-venue/react.js.map +0 -6
  262. package/dist/in-venue/table.js.map +0 -6
  263. package/dist/in-venue/types.js.map +0 -6
  264. package/dist/in-venue/watch.js.map +0 -6
  265. package/dist/index.js.map +0 -6
  266. package/dist/integrations/index.js.map +0 -6
  267. package/dist/internal/abort.js.map +0 -6
  268. package/dist/internal/cache.js.map +0 -6
  269. package/dist/internal/customer-http.js.map +0 -6
  270. package/dist/internal/emitter.js.map +0 -6
  271. package/dist/internal/image-widths.js.map +0 -6
  272. package/dist/internal/money-math.js.map +0 -6
  273. package/dist/internal/perk-hold.js.map +0 -6
  274. package/dist/internal/remembered-address.js.map +0 -6
  275. package/dist/internal/return-path.js.map +0 -6
  276. package/dist/internal/service-url.js.map +0 -6
  277. package/dist/internal.js.map +0 -6
  278. package/dist/loyalty/cart.js.map +0 -6
  279. package/dist/loyalty/client.js.map +0 -6
  280. package/dist/loyalty/index.js.map +0 -6
  281. package/dist/loyalty/react.js.map +0 -6
  282. package/dist/loyalty/release.js.map +0 -6
  283. package/dist/loyalty/types.js.map +0 -6
  284. package/dist/menu/index.js.map +0 -6
  285. package/dist/models-DLGs3UI2.d.ts +0 -307
  286. package/dist/models.js.map +0 -6
  287. package/dist/money.js.map +0 -6
  288. package/dist/navigation/index.js.map +0 -6
  289. package/dist/navigation/react.js.map +0 -6
  290. package/dist/navigation-progress/index.js.map +0 -6
  291. package/dist/options/index.js.map +0 -6
  292. package/dist/persist/catalogue.js.map +0 -6
  293. package/dist/places/client.js.map +0 -6
  294. package/dist/places/error.js.map +0 -6
  295. package/dist/places/index.js.map +0 -6
  296. package/dist/places/request.js.map +0 -6
  297. package/dist/places/sdk.js.map +0 -6
  298. package/dist/places/search.js.map +0 -6
  299. package/dist/places/types.js.map +0 -6
  300. package/dist/pricing/index.js.map +0 -6
  301. package/dist/react/cart.js.map +0 -6
  302. package/dist/react/changes.js.map +0 -6
  303. package/dist/react/hooks.js.map +0 -6
  304. package/dist/react/index.js.map +0 -6
  305. package/dist/react/provider.js.map +0 -6
  306. package/dist/react/rollback.js.map +0 -6
  307. package/dist/receipts/index.js.map +0 -6
  308. package/dist/redirect/index.js.map +0 -6
  309. package/dist/rich-text/index.js.map +0 -6
  310. package/dist/server/auth/crypto.js.map +0 -6
  311. package/dist/server/auth/jwt.js.map +0 -6
  312. package/dist/server/auth/session-store.js.map +0 -6
  313. package/dist/server/chosen-branch.js.map +0 -6
  314. package/dist/server/edge-cache.js.map +0 -6
  315. package/dist/server/edge-snapshot.js.map +0 -6
  316. package/dist/server/index.js.map +0 -6
  317. package/dist/server/legacy-order.js.map +0 -6
  318. package/dist/server/page-cache.js.map +0 -6
  319. package/dist/server/security.js.map +0 -6
  320. package/dist/server/sign-in.js.map +0 -6
  321. package/dist/server/site-seo.js.map +0 -6
  322. package/dist/server/site-worker.js.map +0 -6
  323. package/dist/server/storefront-url/build-v1.js.map +0 -6
  324. package/dist/server/storefront-url/build-v2.js.map +0 -6
  325. package/dist/server/storefront-url/build.js.map +0 -6
  326. package/dist/server/storefront-url/canonical.js.map +0 -6
  327. package/dist/server/storefront-url/contract.js.map +0 -6
  328. package/dist/server/storefront-url/index.js.map +0 -6
  329. package/dist/server/storefront-url/installation.js.map +0 -6
  330. package/dist/server/storefront-url/params.js.map +0 -6
  331. package/dist/server/storefront-url/parse-v1.js.map +0 -6
  332. package/dist/server/storefront-url/parse-v2.js.map +0 -6
  333. package/dist/server/storefront-url/parse.js.map +0 -6
  334. package/dist/server/storefront-url/public-id.js.map +0 -6
  335. package/dist/server/storefront-url/redirect.js.map +0 -6
  336. package/dist/server/storefront-url/sign-in.js.map +0 -6
  337. package/dist/server/storefront-url/types.js.map +0 -6
  338. package/dist/server/storefront-url/url.js.map +0 -6
  339. package/dist/server/webhook.js.map +0 -6
  340. package/dist/services/index.js.map +0 -6
  341. package/dist/site-closed/index.js.map +0 -6
  342. package/dist/site-config/helpers.js.map +0 -6
  343. package/dist/site-config/sections.js.map +0 -6
  344. package/dist/site-config/types.js.map +0 -6
  345. package/dist/site-config/validate.js.map +0 -6
  346. package/dist/site-error/index.js.map +0 -6
  347. package/dist/site-error/react.js.map +0 -6
  348. package/dist/template/index.js.map +0 -6
  349. package/dist/template/react.js.map +0 -6
  350. package/dist/testing/loyalty.js.map +0 -6
  351. package/dist/transport/category-page.js.map +0 -6
  352. package/dist/transport/mappers.js.map +0 -6
  353. package/dist/transport/presentation.js.map +0 -6
  354. package/dist/transport/quote-body.js.map +0 -6
  355. package/dist/transport/rest.js.map +0 -6
  356. package/dist/transport/search.js.map +0 -6
  357. package/dist/transport/selected-menu.js.map +0 -6
  358. package/dist/transport/store.js.map +0 -6
  359. package/dist/transport/types.js.map +0 -6
  360. package/dist/types-8HB4-7D9.d.ts +0 -457
  361. package/dist/uploads/index.js.map +0 -6
  362. package/dist/url/index.js.map +0 -6
  363. package/dist/visits/index.js.map +0 -6
  364. package/dist/visits/page-views.js.map +0 -6
@@ -1,5 +1,9 @@
1
1
  /** The Zappie environment a service URL points at. */
2
- type ZappieEnvironment = "production" | "staging";
2
+ type ZappieEnvironment =
3
+ /** Zappie's live services, such as `checkout.zappie.ai`. */
4
+ "production"
5
+ /** Zappie's staging services, such as `checkout.stg.zappie.ai`. */
6
+ | "staging";
3
7
 
4
8
  /**
5
9
  * Build a URL on Zappie's checkout, such as an old payment link's new home.
@@ -1,2 +1 @@
1
1
  import{serviceUrl}from"../internal/service-url.js";var CHECKOUT={production:"https://checkout.zappie.ai",staging:"https://checkout.stg.zappie.ai"};var APP={production:"https://app.zappie.ai",staging:"https://app.stg.zappie.ai"};var checkoutUrl=(path,environment="production")=>serviceUrl(CHECKOUT,path,environment);var appUrl=(path,environment="production")=>serviceUrl(APP,path,environment);var ZAPPIE_SUPPORT_WHATSAPP="15558956471";export{ZAPPIE_SUPPORT_WHATSAPP,appUrl,checkoutUrl};
2
- //# sourceMappingURL=index.js.map
@@ -1,12 +1,15 @@
1
1
  /** A switched-off storefront, as the site host asks for its closed page. */
2
2
  type SiteClosed = {
3
+ /** Always true. `siteClosed` returns `null` instead when the storefront is open. */
3
4
  closed: true;
4
5
  /** The merchant's own message, as plain text, or `null` when they set none. Escape it when you render it. */
5
6
  message: string | null;
6
7
  };
7
8
  /** A closed page's heading and the sentence under it. */
8
9
  type SiteClosedCopy = {
10
+ /** The page's heading. Defaults to "Closed for now". */
9
11
  title: string;
12
+ /** The sentence under the heading. The merchant's message when they set one. */
10
13
  message: string;
11
14
  };
12
15
  /** The longest merchant message `siteClosed` keeps, in characters. */
@@ -1,2 +1 @@
1
1
  var CLOSED_MESSAGE_LIMIT=280;var CLOSED_PAGE_HEADER="x-zappie-closed-page";var COPY={title:"Closed for now",message:"We're closed for now. Please check back soon."};function siteClosed(request){if(request.headers.get("x-zappie-site-state")!=="closed"){return null}let message=null;try{message=Array.from(decodeURIComponent(request.headers.get("x-zappie-closed-message")??"").trim()).slice(0,CLOSED_MESSAGE_LIMIT).join("").trim()||null}catch{}return{closed:true,message}}function siteClosedCopy(closed,copy){const page={...COPY,...copy};return{title:page.title,message:closed.message??page.message}}function markClosedPage(response){const marked=new Response(response.body,response);marked.headers.set(CLOSED_PAGE_HEADER,"1");return marked}export{CLOSED_MESSAGE_LIMIT,CLOSED_PAGE_HEADER,markClosedPage,siteClosed,siteClosedCopy};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  import{GLOBAL_PACKAGE_ALLOWLIST}from"./types.js";var record=value=>!!value&&typeof value==="object"&&!Array.isArray(value);function distance(left,right){let row=[...Array(right.length+1).keys()];for(let leftIndex=1;leftIndex<=left.length;leftIndex+=1){const next=[leftIndex];for(let rightIndex=1;rightIndex<=right.length;rightIndex+=1){next[rightIndex]=Math.min(next[rightIndex-1]+1,row[rightIndex]+1,row[rightIndex-1]+(left[leftIndex-1]===right[rightIndex-1]?0:1))}row=next}return row[right.length]}function unknownKeys(value,allowed,path,issue){for(const key of Object.keys(value)){if(allowed.includes(key)){continue}let hint;let best=3;for(const candidate of allowed){const score=distance(key,candidate);if(score<best){best=score;hint=candidate}}issue({path:path?`${path}.${key}`:key,code:"unknown_key",message:hint?`Unknown field "${key}". Rename it to "${hint}".`:`Unknown field "${key}". Remove it from the configuration.`,severity:"error"})}}var nonblank=value=>typeof value==="string"&&value.trim().length>0;var packageName=value=>value.length<=214&&/^(?:@[a-z0-9][a-z0-9._~-]*\/[a-z0-9][a-z0-9._~-]*|[a-z0-9][a-z0-9._~-]*)$/.test(value);var globallyAllowed=value=>GLOBAL_PACKAGE_ALLOWLIST.some(allowed=>allowed.endsWith("/*")?value.startsWith(allowed.slice(0,-1)):value===allowed);function hostname(value){const wildcard=value.startsWith("*.");const host=wildcard?value.slice(2):value;if(!host.includes(".")||/^\d+(?:\.\d+){3}$/.test(host)||host.length>253||wildcard&&/^(?:ac|co|com|edu|gov|net|org)\.[^.]+$/i.test(host)){return false}return host.split(".").every(label=>/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label))}export{globallyAllowed,hostname,nonblank,packageName,record,unknownKeys};
2
- //# sourceMappingURL=helpers.js.map
@@ -1,2 +1 @@
1
1
  import{nonblank,record,unknownKeys}from"./helpers.js";import{DEFAULT_BUDGETS}from"./types.js";var budgetKeys=[...Object.keys(DEFAULT_BUDGETS),"routeCssKbGz","unusedCssPercent"];function nested(value,path,keys,issue,validate){if(value===void 0){return}if(!record(value)){issue({path,code:"invalid_type",message:`Expected an object. Set ${path} to an object or remove it.`,severity:"error"});return}unknownKeys(value,keys,path,issue);validate(value)}function budgets(value,issue,error){nested(value,"budgets",[...budgetKeys,"override"],issue,budget=>{nested(budget.override,"budgets.override",["reason"],issue,override=>{if(!nonblank(override.reason)){error("budgets.override.reason","invalid_format","Expected a non-blank reason. Explain why the default budget must be raised.")}});for(const key of budgetKeys){const value2=budget[key];for(const[route,amount]of Object.entries(key==="routeCssKbGz"&&record(value2)?value2:{"":value2})){const path=`budgets.${key}${route&&`.${route}`}`;if(amount===void 0){continue}if(!Number.isFinite(amount)||amount<=0){error(path,"invalid_type",`Expected a positive finite number. Set ${path} to a number greater than zero.`)}else if(key==="tappableMs"&&amount>5e3){error(path,"invalid_format",`The ${key} budget cannot exceed 5000. Set ${path} to 5000 or less.`)}else if(amount>DEFAULT_BUDGETS[key]){const message=`The ${key} budget exceeds the ${DEFAULT_BUDGETS[key]} default.`;if(!budget.override){error(path,"budget_override",`${message} Add budgets.override.reason to explain the increase.`)}else{issue({path,code:"budget_override",message:`${message} Lower it to the default when the exception is no longer needed.`,severity:"warning"})}}}}})}function analytics(value,issue,error){nested(value,"analytics",["forward"],issue,analyticsValue=>{nested(analyticsValue.forward,"analytics.forward",["ga4","metaPixel"],issue,forward=>{if(forward.ga4!==void 0&&(typeof forward.ga4!=="string"||!/^G-[A-Z0-9]+$/.test(forward.ga4))){error("analytics.forward.ga4","invalid_format","Expected a GA4 measurement id beginning with G-. Use a value such as G-XXXXXXXXXX.")}if(forward.metaPixel!==void 0&&(typeof forward.metaPixel!=="string"||!/^\d+$/.test(forward.metaPixel))){error("analytics.forward.metaPixel","invalid_format","Expected a numeric Meta Pixel id. Use digits only.")}})})}export{analytics,budgets,nested};
2
- //# sourceMappingURL=sections.js.map
@@ -1,2 +1 @@
1
1
  var DEFAULT_BUDGETS={jsKbGz:200,cssKbGz:50,lcpMs:2500,tappableMs:3e3};var GLOBAL_PACKAGE_ALLOWLIST=["react","react-dom","react-router","@react-router/*","@zappie/*","tailwindcss","@tailwindcss/*","clsx","tailwind-merge","class-variance-authority","lucide-react","date-fns","embla-carousel-react","framer-motion/motion","zod","@radix-ui/*","sonner","vaul"];export{DEFAULT_BUDGETS,GLOBAL_PACKAGE_ALLOWLIST};
2
- //# sourceMappingURL=types.js.map
@@ -1,2 +1 @@
1
1
  import{globallyAllowed,hostname,nonblank,packageName,record,unknownKeys}from"./helpers.js";import{analytics,budgets,nested}from"./sections.js";var rootKeys=["store","branches","theme","prerender","menu","packages","audit","outbound","security","budgets","readiness","analytics","verify","unused","corners"];function validateConfig(input){const issues=[];const issue=value=>issues.push(value);const error=(path,code,message)=>issue({path,code,message,severity:"error"});if(!record(input)){return{valid:false,issues:[{path:"$",code:"invalid_type",message:"Expected a configuration object. Export an object from zappie.config.ts.",severity:"error"}]}}unknownKeys(input,rootKeys,"",issue);if(!nonblank(input.store)){error("store",input.store===void 0?"missing_required":"invalid_type","Expected a non-empty storefront slug. Set store to the slug used by createZappie().")}theme(input.theme,error);branchList(stringList(input.branches,"branches",error),error);if(input.prerender!==void 0){issue({path:"prerender",code:"unused_setting",message:"Zappie hosting prerenders no page, so prerender does nothing. Remove it.",severity:"warning"})}nested(input.menu,"menu",["hiddenCategories"],issue,value=>{stringList(value.hiddenCategories,"menu.hiddenCategories",error)});nested(input.packages,"packages",["allow"],issue,value=>{const allow=stringList(value.allow,"packages.allow",error);allow?.forEach((name,index)=>{if(globallyAllowed(name)){issue({path:`packages.allow[${index}]`,code:"redundant_allowlist",message:`${name} is already globally allowed. Remove it from packages.allow.`,severity:"warning"})}else if(!packageName(name)){error(`packages.allow[${index}]`,"invalid_format","Expected a lowercase npm package name. Use a package name such as lucide-react or @scope/name.")}})});nested(input.outbound,"outbound",["allow"],issue,value=>{hostList(value.allow,"outbound.allow",error)});nested(input.security,"security",["csp","links"],issue,security=>{hostList(security.links,"security.links",error);nested(security.csp,"security.csp",["imgSrc","connectSrc","fontSrc","styleSrc","frameSrc"],issue,csp=>{for(const[name,value]of Object.entries(csp)){hostList(value,`security.csp.${name}`,error)}})});budgets(input.budgets,issue,error);nested(input.readiness,"readiness",["routeDiscovery"],issue,readiness=>{nested(readiness.routeDiscovery,"readiness.routeDiscovery",["optOut"],issue,routeDiscovery=>{nested(routeDiscovery.optOut,"readiness.routeDiscovery.optOut",["reason"],issue,optOut=>{if(!nonblank(optOut.reason)){error("readiness.routeDiscovery.optOut.reason","invalid_format","Expected a non-blank reason. Explain why the site disables initial route discovery.")}})})});analytics(input.analytics,issue,error);nested(input.verify,"verify",["startPath","cataloguePath"],issue,()=>{});for(const key of["unused","corners"]){nested(input[key],key,key==="unused"?["fail"]:["fail","files"],issue,value=>{if(value.fail!==void 0&&typeof value.fail!=="boolean"){error(`${key}.fail`,"invalid_type",`Expected a boolean. Set ${key}.fail to true or remove it.`)}stringList(value.files,`${key}.files`,error)})}return{valid:!issues.some(entry=>entry.severity==="error"),issues}}function theme(value,error){if(typeof value!=="string"||!/\.json$/.test(value)||/^(?:[a-z][a-z\d+.-]*:|\/)|\\/i.test(value)){error("theme",typeof value==="string"?"invalid_format":value===void 0?"missing_required":"invalid_type","Expected a relative .json path. Use a value such as ./theme.json.")}}function stringList(value,path,error){if(value===void 0){return void 0}if(!Array.isArray(value)||value.some(entry=>typeof entry!=="string")){error(path,"invalid_type",`Expected an array of strings. Set ${path} to string values.`);return void 0}return value}function branchList(value,error){if(!value){return}if(value.length===0){error("branches","invalid_format","Expected at least one value. Add a value to branches or remove the field.")}value.forEach((entry,index)=>{if(!nonblank(entry)){error(`branches[${index}]`,"invalid_format","Expected a non-empty branch slug. Remove the empty value or use a branch slug.")}});if(new Set(value).size!==value.length){error("branches","duplicate","Expected unique values. Remove duplicates from branches.")}}function hostList(value,path,error){stringList(value,path,error)?.forEach((host,index)=>{if(!hostname(host)){error(`${path}[${index}]`,"invalid_format","Expected a hostname or leading *. subdomain pattern without a scheme, path, port or IP. Use a value such as api.example.com.")}})}export{validateConfig};
2
- //# sourceMappingURL=validate.js.map
@@ -2,10 +2,16 @@
2
2
  * The two error pages a storefront draws itself. `not-found` is a page, item or table that doesn't exist (404 or
3
3
  * 410). `went-wrong` is anything else a route threw.
4
4
  */
5
- type SiteErrorKind = "not-found" | "went-wrong";
5
+ type SiteErrorKind =
6
+ /** A page, item or table that doesn't exist. The route threw a 404 or 410. */
7
+ "not-found"
8
+ /** Anything else the route threw. The page stands for a 500. */
9
+ | "went-wrong";
6
10
  /** A page's heading and the sentence under it. */
7
11
  type SiteErrorCopy = {
12
+ /** The page's heading, such as "Page not found". */
8
13
  title: string;
14
+ /** The sentence under the heading, such as "This page doesn't exist or has moved." */
9
15
  message: string;
10
16
  };
11
17
  /** Options for `siteError`. */
@@ -19,7 +25,9 @@ type SiteErrorOptions = {
19
25
  };
20
26
  /** A link on the error page. */
21
27
  type SiteErrorLink = {
28
+ /** The link's text, such as "Try again" or "Go to the home page". */
22
29
  label: string;
30
+ /** Where the link leads. */
23
31
  href: string;
24
32
  };
25
33
  /** What a storefront's error page shows, for the template to style. */
@@ -1,2 +1 @@
1
1
  var COPY={"not-found":{title:"Page not found",message:"This page doesn't exist or has moved."},"went-wrong":{title:"Something went wrong",message:"This page didn't load. Try again in a moment."}};function siteError(error,{url,home="/",copy}={}){const thrown=error?.status;const kind=thrown===404||thrown===410?"not-found":"went-wrong";const location=globalThis.location;return{kind,status:kind==="not-found"?thrown:500,...COPY[kind],...copy?.[kind],...kind==="went-wrong"?{retry:{label:"Try again",href:url??(location?location.pathname+location.search:home)}}:{},home:{label:"Go to the home page",href:home}}}export{siteError};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  import{siteError}from"@zappie/sdk/site-error";function SiteErrorPage({error,children,...options}){return children(siteError(error,options))}export{SiteErrorPage};
2
- //# sourceMappingURL=react.js.map
@@ -4,6 +4,7 @@ declare const STUDIO_ORIGINS: readonly string[];
4
4
  declare const KIT_REGION_NAMES: Readonly<Record<string, string>>;
5
5
  /** A region the merchant selected, as the preview posts it to Studio. */
6
6
  type StudioRegion = {
7
+ /** The message's kind. Always `region`. */
7
8
  zappie: "region";
8
9
  /** Where the region is rendered, as `app/…:line`. */
9
10
  source: string;
@@ -20,6 +21,7 @@ type StudioRegion = {
20
21
  width: number;
21
22
  height: number;
22
23
  };
24
+ /** How far the page is scrolled down when the region is selected, in CSS pixels. */
23
25
  scrollY: number;
24
26
  /** The page path and query. */
25
27
  path: string;
@@ -4,7 +4,13 @@ declare const IMAGE_WIDTHS: readonly [320, 480, 640, 960, 1280, 1600];
4
4
  /** A value accepted by a template manifest and the live preview bridge. */
5
5
  type TemplateSettingValue = string | number | boolean;
6
6
  /** Where a template is running. Live sites never accept preview messages. */
7
- type TemplateMode = "site" | "draft" | "review";
7
+ type TemplateMode =
8
+ /** The live site. It uses the defaults and the saved settings and takes no preview values. */
9
+ "site"
10
+ /** A Studio draft preview. Preview values from the editor sit over the saved settings and the defaults. */
11
+ | "draft"
12
+ /** A template review preview. Preview values sit over the defaults, and saved settings are not used. */
13
+ | "review";
8
14
  /** Merge defaults, saved settings, and preview values for the current mode. */
9
15
  declare function templateSettings<T extends Record<string, unknown>>(defaults: T, saved: Record<string, TemplateSettingValue> | undefined, preview: Record<string, TemplateSettingValue> | null, mode: TemplateMode): T;
10
16
  /**
@@ -1,2 +1 @@
1
1
  import{IMAGE_WIDTHS}from"../internal/image-widths.js";function templateSettings(defaults,saved,preview,mode){if(mode==="review"){return{...defaults,...preview??{}}}if(mode==="draft"){return{...defaults,...saved,...preview??{}}}return{...defaults,...saved}}var EDITOR_ORIGINS=Object.freeze(["https://dashboard.zappie.ai","https://dashboard.stg.zappie.ai","https://admin.zappie.ai","https://admin.stg.zappie.ai","http://localhost:5181","http://localhost:5180"]);function editorOrigin(ancestorOrigins,referrer,allowed=EDITOR_ORIGINS){let origin=null;if(ancestorOrigins&&ancestorOrigins.length>0){origin=ancestorOrigins[0]??null}else if(referrer){try{origin=new URL(referrer).origin}catch{origin=null}}return origin&&allowed.includes(origin)?origin:null}var MAX_SETTINGS=200;var MAX_SETTING_KEY=100;var MAX_SETTING_TEXT=1e4;function settingsFromMessage(data){if(!data||typeof data!=="object"){return null}const message=data;if(message.zappie!=="settings"||!message.values||typeof message.values!=="object"||Array.isArray(message.values)){return null}const entries=Object.entries(message.values);if(entries.length>MAX_SETTINGS){return null}const values={};for(const[key,value]of entries){if(key.length>MAX_SETTING_KEY){continue}if(typeof value==="string"&&value.length<=MAX_SETTING_TEXT||typeof value==="number"&&Number.isFinite(value)||typeof value==="boolean"){values[key]=value}}return values}var RESIZE_HOSTS=Object.freeze(["zappie-public-prod.s3.eu-west-2.amazonaws.com"]);function canResize(src,resizeHosts=RESIZE_HOSTS){try{const url=new URL(src);return/^https?:$/.test(url.protocol)&&resizeHosts.includes(url.hostname)&&!/\.(avif|jxl|svg)$/i.test(url.pathname)}catch{return false}}function resized(src,width,quality=80,resizeHosts){return canResize(src,resizeHosts)?`/cdn-cgi/image/width=${width},quality=${quality},format=auto,fit=scale-down/${new URL(src).href}`:src}function srcSet(src,quality,resizeHosts){return canResize(src,resizeHosts)?IMAGE_WIDTHS.map(width=>`${resized(src,width,quality,resizeHosts)} ${width}w`).join(", "):""}export{EDITOR_ORIGINS,IMAGE_WIDTHS,RESIZE_HOSTS,canResize,editorOrigin,resized,settingsFromMessage,srcSet,templateSettings};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{useStore}from"@zappie/sdk/react";import{editorOrigin,settingsFromMessage,templateSettings}from"@zappie/sdk/template";import{createContext,useContext,useEffect,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";var Context=createContext({mode:"site",preview:null});function TemplateSettingsProvider({mode,children}){const[preview,setPreview]=useState(null);useEffect(()=>{setPreview(null);if(mode==="site"){return}if(window.parent===window){return}const parent=editorOrigin(location.ancestorOrigins,document.referrer);if(!parent){return}const send=message2=>window.parent.postMessage(message2,parent);const route=()=>send({zappie:"route",path:location.pathname+location.search});const scroll=()=>send({zappie:"scroll",y:window.scrollY,height:document.documentElement.scrollHeight});const message=event=>{if(event.origin!==parent||event.source!==window.parent){return}const values=settingsFromMessage(event.data);if(values){setPreview(values)}};const pushState=history.pushState;const replaceState=history.replaceState;history.pushState=function(...args){pushState.apply(this,args);route()};history.replaceState=function(...args){replaceState.apply(this,args);route()};window.addEventListener("message",message);window.addEventListener("popstate",route);window.addEventListener("scroll",scroll,{passive:true});send({zappie:"ready"});route();scroll();let live=true;let studio=null;if(mode==="draft"){if(import.meta.env.DEV&&document.querySelector("[data-zappie-source]")){import("@zappie/sdk/studio").then(({startStudio})=>{if(live){studio=startStudio(parent,send);send({zappie:"selectable",on:Boolean(studio)})}},()=>send({zappie:"selectable",on:false}))}else{send({zappie:"selectable",on:false})}}return()=>{live=false;studio?.();window.removeEventListener("message",message);window.removeEventListener("popstate",route);window.removeEventListener("scroll",scroll);history.pushState=pushState;history.replaceState=replaceState}},[mode]);const value=useMemo(()=>({mode,preview}),[mode,preview]);return jsx(Context.Provider,{value,children})}function useTemplateSettings(defaults){const store=useStore();const{mode,preview}=useContext(Context);return templateSettings(defaults,store.data?.templateSettings,preview,mode)}export{TemplateSettingsProvider,useTemplateSettings};
2
- //# sourceMappingURL=react.js.map
@@ -1,4 +1,4 @@
1
- import { C as Cache } from '../client-B89-aNcl.js';
1
+ import { C as Cache } from '../client-B8lItidz.js';
2
2
  import { Transport, ZappieErrorCode, StorageLike, StoreResource, MenuResource, ZappieEvents, MenuReadOptions } from '../index.js';
3
3
  import { Store, Menu, Formatters } from '../index.js';
4
4
  export { VERSION } from '../index.js';
@@ -6,12 +6,16 @@ import { WireMoney, CartModule, CartLineInput } from '../index.js';
6
6
 
7
7
  /** The customer's points with the business. `enabled` is false while it has no loyalty programme set up. */
8
8
  type Loyalty = {
9
+ /** Always `loyalty`. */
9
10
  object: "loyalty";
11
+ /** False while the business has no loyalty programme set up. */
10
12
  enabled: boolean;
13
+ /** The customer's points with the business. Test keys read 0. */
11
14
  points: number;
12
15
  };
13
16
  /** What a perk gives, to show the shopper. The quote prices it exactly. */
14
17
  type PerkReward = {
18
+ /** What kind of reward it is. `order_discount` takes `percent_off` or `amount_off` off the order. `free_item` gives the items in `items` for free. */
15
19
  type: "order_discount" | "free_item";
16
20
  /** A percentage off the order. */
17
21
  percent_off?: number;
@@ -25,19 +29,28 @@ type PerkReward = {
25
29
  };
26
30
  /** A perk the customer can spend points on at a branch. */
27
31
  type Perk = {
32
+ /** The perk's ID. Pass it to `redeem`. */
28
33
  id: string;
34
+ /** Always `perk`. */
29
35
  object: "perk";
36
+ /** The perk's name. */
30
37
  name: string;
38
+ /** The perk's description. Null when it has none. */
31
39
  description: string | null;
40
+ /** The points a redemption spends. At least 1. */
32
41
  points_cost: number;
42
+ /** What the perk gives. */
33
43
  reward: PerkReward;
34
44
  /** The order types the business made the perk for. */
35
45
  fulfilments: ("delivery" | "pickup" | "dine_in")[];
36
46
  };
37
47
  /** A redemption: points spent on a perk, reserved until an order uses it or it is cancelled. */
38
48
  type PerkRedemption = {
49
+ /** The redemption's ID. Pass it to `cancel`. */
39
50
  id: string;
51
+ /** Always `perk_redemption`. */
40
52
  object: "perk_redemption";
53
+ /** Where it stands. `reserved` means the points are taken and held for 24 hours, until `expires_at`, for an order to use. `cancelled` means you released it or it ran out unused, and its points went back. */
41
54
  status: "reserved" | "cancelled";
42
55
  /** Sent when it is reserved. */
43
56
  points_spent?: number;
@@ -51,15 +64,22 @@ type PerkRedemption = {
51
64
  };
52
65
  /** What claiming an order's points earned, and the balance after it. */
53
66
  type LoyaltyClaim = {
67
+ /** Always `loyalty_claim`. */
54
68
  object: "loyalty_claim";
69
+ /** The order the points were claimed for. */
55
70
  order_id: string;
71
+ /** The points this claim added. 0 when the order's points were already awarded. */
56
72
  points_earned: number;
73
+ /** The customer's balance after the claim. */
57
74
  points: number;
58
75
  };
59
76
  /** The customer's store credit at a branch. `enabled` is false when the branch doesn't take it. */
60
77
  type StoreCredit = {
78
+ /** Always `store_credit`. */
61
79
  object: "store_credit";
80
+ /** False when the branch doesn't take store credit. */
62
81
  enabled: boolean;
82
+ /** The customer's store credit at the branch, in minor units. Test keys read 0. */
63
83
  balance: WireMoney;
64
84
  };
65
85
 
@@ -67,8 +87,11 @@ type StoreCredit = {
67
87
  type MockLoyaltyOptions = {
68
88
  /** False for a business without a loyalty programme. Defaults to true. */
69
89
  enabled?: boolean;
90
+ /** The customer's starting points balance. Defaults to 0. */
70
91
  points?: number;
92
+ /** The perks the customer can redeem. Defaults to none. */
71
93
  perks?: Perk[];
94
+ /** The store credit to return. Defaults to store credit that is off, with a zero balance in NGN. */
72
95
  storeCredit?: StoreCredit;
73
96
  /** The points each order earns when claimed, by order ID. A second claim earns 0. */
74
97
  claims?: Record<string, number>;
@@ -94,12 +117,16 @@ declare function createMockLoyalty(options?: MockLoyaltyOptions): {
94
117
 
95
118
  /** Store and branch menus supplied to the deterministic mock transport. */
96
119
  type MockFixtures = {
120
+ /** The store the mock client serves. */
97
121
  store: Store;
122
+ /** Each branch's menu, keyed by branch ID. A branch with no entry fails with `branch_not_found`. */
98
123
  menus: Record<string, Menu>;
99
124
  };
100
125
  /** Mock timing and per-operation failures. */
101
126
  type MockOptions = {
127
+ /** How long each call waits before it answers, in milliseconds. No wait when left out. */
102
128
  latencyMs?: number;
129
+ /** An error code to throw for a transport method, keyed by the method's name. Methods left out answer normally. */
103
130
  failWith?: Partial<Record<keyof Transport, ZappieErrorCode>>;
104
131
  };
105
132
  /** Create an isolated in-memory SDK client without making network requests. */
@@ -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?{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=>{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,2 +1 @@
1
1
  import{ZappieError}from"../errors.js";var MockLoyaltyError=class extends ZappieError{constructor(status,apiCode,message){super(status===401?"unauthorized":status===404?"not_found":apiCode==="scope_required"?apiCode:status===403?"forbidden":"server_error",message,{status});this.apiCode=apiCode}};function createMockLoyalty(options={}){let points=options.points??0;let sequence=0;const reserved=new Map;const claimed=new Set;const listeners=new Set;const changed=()=>listeners.forEach(listener=>listener());const check=async()=>{await Promise.resolve();if(options.failWith){const status=options.failWith==="customer_required"?401:options.failWith.endsWith("_required")||options.failWith==="feature_off"?403:409;throw new MockLoyaltyError(status,options.failWith,`Mock ${options.failWith}`)}};const client={base:"/_zappie/api",async points(){await check();return{object:"loyalty",enabled:options.enabled??true,points}},async perks(){await check();return options.enabled===false?[]:structuredClone(options.perks??[])},async redeem(perkId){await check();const perk=options.perks?.find(candidate=>candidate.id===perkId);if(!perk){throw new MockLoyaltyError(404,"perk_not_found","No such perk")}if(points<perk.points_cost){throw new MockLoyaltyError(409,"insufficient_points","You don't have enough points for this perk.")}points-=perk.points_cost;const id=`rdm_mock${++sequence}`;reserved.set(id,perk.points_cost);changed();return{id,object:"perk_redemption",status:"reserved",points_spent:perk.points_cost,perk:{id:perk.id,name:perk.name},expires_at:new Date(Date.now()+864e5).toISOString()}},async cancel(redemptionId){await check();points+=reserved.get(redemptionId)??0;reserved.delete(redemptionId);changed()},async claim(orderId){await check();const earned=claimed.has(orderId)?0:options.claims?.[orderId]??0;claimed.add(orderId);points+=earned;changed();return{object:"loyalty_claim",order_id:orderId,points_earned:earned,points}},async storeCredit(){await check();return options.storeCredit??{object:"store_credit",enabled:false,balance:{amount_minor:0,currency:"NGN"}}},onChange(listener){listeners.add(listener);return()=>{listeners.delete(listener)}}};return client}export{createMockLoyalty};
2
- //# sourceMappingURL=loyalty.js.map
@@ -1,2 +1 @@
1
1
  async function categoryPage(raw,ctx,mapMenu,invalid){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()}return{menu:{...menu,completeness:"partial"},menuId:ctx.menuId,categoryId:ctx.categoryId,...typeof raw.next_cursor==="string"&&raw.next_cursor?{nextCursor:raw.next_cursor}:{}}}export{categoryPage};
2
- //# sourceMappingURL=category-page.js.map
@@ -1,2 +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(value){const input=record(value);const min=nonnegative(input.min);if(input.max==null){return{min}}const max=nonnegative(input.max);if(max<min){throw new ZappieError("server_error","Maximum quantity is below its minimum")}return{min,max}}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 selection={min:g.min,max:g.max===0?void 0:g.max};const isAttribute=g.kind==="attribute";const kind=text(g.kind);if(!["attribute","choice","text"].includes(kind)){throw new UnsupportedValue(`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(selection.min)>0,selection:bounds(selection),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({min:c.min_quantity??1,max: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(`option count operator "${text(count.op)}"`)}if(c.match!==void 0&&c.match!=="any"&&c.match!=="all"){throw new UnsupportedValue(`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);const optionGroups=[];let unsupported=false;for(const raw of list(v.option_groups??[])){try{optionGroups.push(mapGroup(raw))}catch(error){if(!(error instanceof UnsupportedValue)){throw error}unsupported=true;console.warn(`Zappie item ${id} uses an ${error.message} this SDK can't validate; it is shown as unavailable`)}}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")}const quantity={min:v.min_quantity??1,max:v.max_quantity};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:{...bounds(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)).map(([id,item])=>{const mapped=mapItem(item);if(mapped.id!==id){throw new ZappieError("server_error","Item map key does not match its identity")}return[id,mapped]}));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};
2
- //# sourceMappingURL=mappers.js.map
@@ -1,2 +1 @@
1
1
  var object=(value,invalid)=>{if(!value||typeof value!=="object"||Array.isArray(value)){throw invalid()}return value};var array=(value,invalid)=>{if(!Array.isArray(value)){throw invalid()}return value};var string=(value,invalid)=>{if(typeof value!=="string"){throw invalid()}return value};function presentStore(store,value,invalid){const source=value;source.branches.forEach((raw,index)=>{const branch=store.branches[index];if(raw.order_ahead_days!==void 0){if(!Number.isSafeInteger(raw.order_ahead_days)||Number(raw.order_ahead_days)<0){throw invalid()}branch.orderAheadDays=raw.order_ahead_days}if(raw.promos!==void 0){branch.promos=array(raw.promos,invalid).map(value2=>{const promo=object(value2,invalid);return{id:string(promo.id,invalid),name:string(promo.name,invalid),description:string(promo.description,invalid)}})}});return store}function presentMenu(menu,value,invalid){value.menus.forEach((raw,index)=>{const section=menu.menus[index];if(raw.layout!==void 0){if(!["LIST","GRID","CARD"].includes(raw.layout)){throw invalid()}section.layout=raw.layout}if(raw.is_active!==void 0){if(typeof raw.is_active!=="boolean"){throw invalid()}section.isActive=raw.is_active}if(raw.info_banner_html!==void 0){section.infoBannerHtml=string(raw.info_banner_html,invalid)}});return menu}export{presentMenu,presentStore};
2
- //# sourceMappingURL=presentation.js.map
@@ -1,2 +1 @@
1
1
  function quoteBody(body){const f=body.fulfilment;if(!f){return body}const{table:_table,address,...fulfilment}=f;if(!address){return{...body,fulfilment}}const{line2:_line2,instructions,...rest}=address;return{...body,fulfilment:{...fulfilment,...fulfilment.instructions===void 0&&instructions!==void 0?{instructions}:{},address:rest}}}export{quoteBody};
2
- //# sourceMappingURL=quote-body.js.map
@@ -1,2 +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");let cursor;const seen=new Set;let output;let etag;do{const query=new URLSearchParams({branch:ctx.branchId,...ctx.fulfilment?{fulfilment:wireFulfilment(ctx.fulfilment)}:{},...ctx.metadataOnly?{metadata_only:"true"}:{},...cursor?{cursor}:{}});const response=await this.request(`/menus?${query}`,ctx,cursor?void 0:ctx.ifNoneMatch);if(response.status===304){if(cursor){throw new ZappieError("server_error","Unexpected 304 on a continuation page")}return{notModified:true,...response.headers.get("ETag")?{etag:response.headers.get("ETag")}:{}}}const raw=record(await this.json(response));const page=(await presentation).presentMenu(mapMenu(raw,ctx.branchId),raw,presentationError);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"}}}if(!output){output=page;etag=response.headers.get("ETag")??void 0}else{if(page.version!==output.version){throw new ZappieError("server_error","Menu changed while fetching pages; retry the read")}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)}}}cursor=typeof raw.next_cursor==="string"&&raw.next_cursor?raw.next_cursor:void 0;if(cursor){if(seen.has(cursor)){throw new ZappieError("server_error","Repeated menu pagination cursor")}seen.add(cursor)}}while(cursor);if(output.menus&&output.menus.length>1){output.id=`branch:${ctx.branchId}`;output.name="Catalogue";delete output.schedule}for(const category of output.categories){for(const id of category.itemIds){if(!Object.prototype.hasOwnProperty.call(output.items,id)){throw new ZappieError("server_error","Category refers to a missing item")}}}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){const query=new URLSearchParams({branch:ctx.branchId,...ctx.cursor?{cursor:ctx.cursor}:{}});const raw=await this.json(await this.request(`/menus/${encodeURIComponent(ctx.menuId)}/categories/${encodeURIComponent(ctx.categoryId)}/items?${query}`,ctx));return(await import("./category-page.js")).categoryPage(record(raw),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};
2
- //# sourceMappingURL=rest.js.map
@@ -1,6 +1,6 @@
1
1
  import { Menu } from '../index.js';
2
2
  import { SearchRequest, SearchPage } from '../index.js';
3
- import '../types-8HB4-7D9.js';
3
+ import '../types-CuPaBf6k.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,2 +1 @@
1
1
  async function searchPage(ctx,read,mapMenu,invalid){const presentation=import("./presentation.js");ctx.signal?.throwIfAborted();const query=new URLSearchParams({branch:ctx.branchId,query:ctx.query.trim(),limit:"25",...ctx.cursor?{cursor:ctx.cursor}:{}});const raw=await read(`/items/search?${query}`);ctx.signal?.throwIfAborted();if(!raw||typeof raw!=="object"||Array.isArray(raw)){throw invalid()}const cursor=raw.next_cursor;const menu=(await presentation).presentMenu(mapMenu(raw,ctx.branchId),raw,invalid);if(Object.keys(menu.items).length>25||cursor!=null&&(typeof cursor!=="string"||!cursor||cursor===ctx.cursor)||Object.keys(menu.items).some(id=>!menu.categories.some(category=>category.itemIds.includes(id)))||menu.categories.some(category=>!menu.menus?.some(source=>source.categoryIds.includes(category.id)))){throw invalid()}return{menu:{...menu,completeness:"partial"},...typeof cursor==="string"?{nextCursor:cursor}:{}}}export{searchPage};
2
- //# sourceMappingURL=search.js.map
@@ -1,3 +1,3 @@
1
- export { z as SelectedMenu, i as SelectedMenuRequest, j as SelectedMenuResponse, B as SelectedMenuTransport, D as createSelectedMenuReader, F as selectedMenu, G as selectedMenuKey } from '../client-B89-aNcl.js';
2
- import '../models-DLGs3UI2.js';
3
- import '../types-8HB4-7D9.js';
1
+ export { z as SelectedMenu, i as SelectedMenuRequest, j as SelectedMenuResponse, B as SelectedMenuTransport, D as createSelectedMenuReader, F as selectedMenu, G as selectedMenuKey } from '../client-B8lItidz.js';
2
+ import '../models-C77LjkK8.js';
3
+ import '../types-CuPaBf6k.js';
@@ -1,2 +1 @@
1
1
  async function selectedMenu(ctx,request,json,mapMenu,invalid){const presentation=import("./presentation.js");const record=value=>{if(!value||typeof value!=="object"||Array.isArray(value)){throw invalid()}return value};const query=new URLSearchParams({branch:ctx.branchId,fulfilment:ctx.orderContext==="dineIn"?"dine_in":ctx.orderContext});const response=await request(`/menus/${encodeURIComponent(ctx.menuId)}?${query}`);const etag=response.headers.get("ETag");if(!etag){throw invalid()}if(response.status===304){return{notModified:true,etag}}const raw=record(await json(response));const coverage=record(raw.coverage);const menu=(await presentation).presentMenu(mapMenu(raw,ctx.branchId),raw,invalid);if(raw.next_cursor||coverage.complete!==true||!Array.isArray(coverage.menu_ids)||coverage.menu_ids.length!==1||coverage.menu_ids[0]!==ctx.menuId||menu.menus?.length!==1||menu.menus[0]?.id!==ctx.menuId){throw invalid()}return{menu:{...menu,completeness:"partial"},coverage:{menuIds:[ctx.menuId],complete:true},etag}}function selectedMenuKey(scope){return JSON.stringify(["selected-menu:v1",scope.store,scope.branchId,scope.orderContext,scope.menuId])}function createSelectedMenuReader(client){const transport=client._internal.transport;return{async read(scope,options={}){if(!transport.getSelectedMenu){throw new Error("Transport does not support selected menus")}const response=await transport.getSelectedMenu({key:client.config.key,version:client.config.version,branchId:scope.branchId,menuId:scope.menuId,orderContext:scope.orderContext,...options});options.signal?.throwIfAborted();if(!("notModified"in response)){if(response.menu.branchId!==scope.branchId||response.coverage.menuIds.length!==1||response.coverage.menuIds[0]!==scope.menuId){throw new Error("Selected menu belongs to another scope")}const key=selectedMenuKey(scope);const previous=client._internal.cache.snapshot(key).value;if(JSON.stringify(previous)!==JSON.stringify(response)){client._internal.cache.set(key,response,response.etag)}}return response}}}export{createSelectedMenuReader,selectedMenu,selectedMenuKey};
2
- //# sourceMappingURL=selected-menu.js.map
@@ -1,2 +1 @@
1
1
  function mapStore(value,record,text,list,hours,mapMoney,money,opt,isString,isBoolean,mapSeo){const coordinates=input=>{const coordinates2=record(input??{});return typeof coordinates2.lat==="number"&&typeof coordinates2.lng==="number"?{lat:coordinates2.lat,lng:coordinates2.lng}:void 0};const fulfilment=input=>{const value2=record(input);return{pickup:value2.pickup===true,delivery:value2.delivery===true,dineIn:value2.dine_in===true,scheduling:value2.scheduled===true}};const source=record(value);const brand=record(source.brand??{});const branches=list(source.branches).map(raw=>{const branch=record(raw);const pickup=record(branch.pickup_address??{});const pickupCoordinates=coordinates(pickup.coordinates);const pickupAddress={...opt("placeId",pickup.place_id,isString),...pickupCoordinates?{coordinates:pickupCoordinates}:{}};const address=typeof branch.address==="string"?branch.address:branch.address?text(record(branch.address).line1).trim():void 0;const addressFields=branch.address&&typeof branch.address==="object"?record(branch.address):{};const branchCoordinates=coordinates(addressFields);return{...branch.currency!==void 0?{currency:money(0,text(branch.currency)).currency}:{},...opt("country",addressFields.country,isString),...branch.delivery_regions!==void 0?{deliveryRegions:list(branch.delivery_regions).map(raw2=>{const region=record(raw2);return{id:text(region.id),name:text(region.name),fee:mapMoney(region.fee)}})}:{},id:text(branch.id),slug:text(branch.slug??branch.id),name:text(branch.name),openingTimes:hours(branch.hours),isOpen:branch.is_open===true,fulfilment:fulfilment(branch.fulfilment),...address!==void 0?{address}:{},...isString(branch.phone)?{phone:branch.phone.trim()}:{},...branch.category==="RESTAURANT"||branch.category==="RETAIL"?{category:branch.category}:{},...opt("timezone",branch.timezone,isString),...branchCoordinates?{coordinates:branchCoordinates}:{},...opt("closedUntil",branch.closed_until,isString),...opt("nextChangeAt",branch.next_change_at,isString),...opt("isDefault",branch.is_default,isBoolean),...Object.keys(pickupAddress).length>0?{pickupAddress}:{},...branch.social_links!==void 0?{socialLinks:list(branch.social_links).flatMap(rawLink=>{const link=record(rawLink);try{const url=new URL(text(link.url));return isString(link.type)&&(url.protocol==="https:"||url.protocol==="http:")?[{type:link.type,url:url.href}]:[]}catch{return[]}})}:{},...branch.minimum_order?{minimumOrder:mapMoney(branch.minimum_order)}:{},...branch.special_hours?{specialHours:list(branch.special_hours).map(rawHours=>{const special=record(rawHours);return{date:text(special.date),closed:special.closed===true,...opt("opens",special.open,isString),...opt("closes",special.close,isString)}})}:{}}});const allowed=["card","bank_transfer","wallet","zap","apple_pay","google_pay"];const paymentMethods=list(source.payment_methods).map(text).filter(method=>{if(allowed.includes(method)){return true}console.warn(`Zappie payment method "${method}" is newer than this SDK and was skipped`);return false});const aggregate={pickup:false,delivery:false,dineIn:false,scheduling:false};for(const branch of branches){for(const key of Object.keys(aggregate)){aggregate[key]||(aggregate[key]=branch.fulfilment[key])}}const templateSettings=record(source.template_settings??{});return{...source.seo!=null?{seo:mapSeo(source.seo)}:{},id:text(source.id),slug:text(source.slug),name:text(source.name),currency:money(0,text(source.currency)).currency,timezone:text(source.timezone),...opt("description",source.description,isString),...source.template_settings!==void 0?{templateSettings}:{},brand:{...opt("logoUrl",brand.logo_url,isString),...opt("coverImageUrl",brand.cover_image_url,isString)},fulfilment:source.fulfilment?fulfilment(source.fulfilment):aggregate,paymentMethods,branches,...Array.isArray(source.checkout_fields)?{checkoutFields:checkoutFields(source.checkout_fields)}:{}}}var checkoutFields=value=>value.filter(f=>["text","email","phone"].includes(f?.type)).map(({applies_to:to={},...f})=>({key:f.key,label:f.label,type:f.type,required:f.required===true,builtin:f.builtin===true,appliesTo:{branchIds:to.branch_ids??[],menuIds:to.menu_ids??[],fulfilment:(to.fulfilment??[]).filter(m=>m=="pickup"||m=="delivery")}}));export{mapStore};
2
- //# sourceMappingURL=store.js.map
@@ -1 +0,0 @@
1
- //# sourceMappingURL=types.js.map