@zappie/sdk 0.28.2 → 0.29.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.
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-CW_OWZ0l.d.ts} +229 -5
  41. package/dist/client.js +0 -1
  42. package/dist/config/index.d.ts +38 -3
  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 +179 -8
  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
@@ -7,7 +7,11 @@ declare const LIMIT_REACHED_HINT = "Limit reached. Remove one to choose another.
7
7
  /** The shopper's chosen options, as a cart line holds them. */
8
8
  type OptionSelection = CartLineInput["choices"];
9
9
  /** How a group's choices are picked: one dot from a required set, or tick boxes. */
10
- type SelectionControl = "radio" | "checkbox";
10
+ type SelectionControl =
11
+ /** One dot to pick, for a required group that takes exactly one choice. */
12
+ "radio"
13
+ /** Tick boxes, for every other group, so the shopper can untick an optional choice. */
14
+ | "checkbox";
11
15
  /**
12
16
  * The most units a group takes, or undefined when it has no limit. Zappie
13
17
  * sends 0 for a group with no limit.
@@ -1,2 +1 @@
1
1
  var ITEM_NOTE_MAX_LENGTH=280;var LIMIT_REACHED_HINT="Limit reached. Remove one to choose another.";function selectionMax(group){return group.selection.max||void 0}function selectionControl(group){return group.isAttribute||group.required&&swaps(group)?"radio":"checkbox"}var swaps=group=>group.selection.max===1;function selectionCount(group,choices){return(choices??[]).reduce((count,choice)=>choice.groupId===group.id?count+Math.max(choice.quantity??1,1):count,0)}var left=(group,choices)=>(selectionMax(group)??Infinity)-selectionCount(group,choices);function groupRoom(group,choices){const room=left(group,choices);return room===Infinity?void 0:Math.max(0,room)}var held=(group,choices,choiceId)=>selectionCount(group,choices?.filter(c=>c.choiceId===choiceId));function canChoose(group,choices,choiceId){const choice=group.choices.find(c=>c.id===choiceId);return Boolean(choice?.isAvailable&&(held(group,choices,choiceId)||swaps(group)||left(group,choices)>=(choice.quantity?.min??1)))}function atLimit(group,choices){return!swaps(group)&&left(group,choices)<=0}function choiceQuantityMax(group,choices,choiceId){return Math.min(group.choices.find(c=>c.id===choiceId)?.quantity?.max??99,swaps(group)?1:Math.max(0,left(group,choices))+held(group,choices,choiceId))}function requirementLabel(group){const{min}=group.selection;const max=selectionMax(group);if(!group.required){if(max!==void 0){return min>1?`(Optional \xB7 ${min} to ${max})`:`(Optional \xB7 up to ${max})`}return min>1?`(Optional \xB7 at least ${min})`:"(Optional)"}if(max===void 0){return`(Min ${min})`}return min===max?`(Exactly ${min})`:min>0?`(${min} to ${max})`:`(Max ${max})`}var items=n=>`${n} item${n===1?"":"s"}`;function boundMessage(group,count){const{required}=group;const{min}=group.selection;const max=selectionMax(group);if(max!==void 0&&count>max){return min===max?`Remove ${items(count-max)}.`:`Remove ${items(count-max)}. Choose up to ${items(max)} in total.`}if(!count&&required&&selectionControl(group)==="radio"){return"Choose one option."}if(!count&&required&&min<=1&&max!==void 0){return`Choose at least one option. You can choose up to ${items(max)} in total.`}const short=(required?Math.max(1,min):min)-count;if(short>0){return`Choose ${short} more item${short===1?"":"s"}.`}return max!==void 0?`Choose up to ${items(max)} in total.`:`Choose at least ${items(min)}.`}function outOfBounds(group,count){if(!count){return group.required}return count<group.selection.min||count>(selectionMax(group)??Infinity)}function countLabel(group,count){const{min}=group.selection;const max=selectionMax(group);if(max!==void 0){return min===max?`${count} of ${max} chosen`:`${count} of up to ${max} chosen`}return min>0?`${count} chosen (at least ${min})`:`${count} chosen`}export{ITEM_NOTE_MAX_LENGTH,LIMIT_REACHED_HINT,atLimit,boundMessage,canChoose,choiceQuantityMax,countLabel,groupRoom,outOfBounds,requirementLabel,selectionControl,selectionCount,selectionMax};
2
- //# sourceMappingURL=index.js.map
@@ -1,3 +1,3 @@
1
- export { q as CATALOGUE_MAX_AGE_MS, r as CATALOGUE_MAX_BYTES, s as CatalogueScope, t as SavedCatalogue, u as catalogueDigest, w as catalogueKey, x as createCatalogueStorage, y as createSavedCatalogue } from '../client-B89-aNcl.js';
2
- import '../models-DLGs3UI2.js';
3
- import '../types-8HB4-7D9.js';
1
+ export { q as CATALOGUE_MAX_AGE_MS, r as CATALOGUE_MAX_BYTES, s as CatalogueScope, t as SavedCatalogue, u as catalogueDigest, w as catalogueKey, x as createCatalogueStorage, y as createSavedCatalogue } from '../client-CW_OWZ0l.js';
2
+ import '../models-C77LjkK8.js';
3
+ import '../types-CuPaBf6k.js';
@@ -1,2 +1 @@
1
1
  var CATALOGUE_MAX_AGE_MS=24*60*60*1e3;var CATALOGUE_MAX_BYTES=16*1024*1024;function catalogueKey(scope){return JSON.stringify(["catalogue:v1",scope.store,scope.branchId,scope.orderContext,scope.menuId])}function createCatalogueStorage(store,options={}){const maxAge=options.maxAgeMs??CATALOGUE_MAX_AGE_MS;const maxBytes=options.maxBytes??CATALOGUE_MAX_BYTES;function open(){return new Promise(resolve=>{let settled=false;const timer=setTimeout(()=>finish(),1e3);function finish(db){if(settled){db?.close();return}settled=true;clearTimeout(timer);resolve(db)}try{const request=indexedDB.open(`zappie:catalogue:v1:${store}`,1);request.onupgradeneeded=()=>{request.result.createObjectStore("catalogues",{keyPath:"key"})};request.onerror=()=>finish();request.onblocked=()=>finish();request.onsuccess=()=>finish(request.result)}catch{finish()}})}function idle(work){if(typeof requestIdleCallback==="function"){requestIdleCallback(work,{timeout:2e3})}else{setTimeout(work,0)}}function mutate(work){idle(()=>{void open().then(db=>{if(!db){return}try{const tx=db.transaction("catalogues","readwrite");tx.oncomplete=tx.onabort=tx.onerror=()=>db.close();work(tx.objectStore("catalogues"))}catch{db.close()}})})}return{async read(scope){if(scope.store!==store){return}const db=await open();if(!db){return}return new Promise(resolve=>{const key=catalogueKey(scope);try{const tx=db.transaction("catalogues","readonly");tx.oncomplete=()=>db.close();tx.onabort=tx.onerror=()=>{db.close();resolve(void 0)};const request=tx.objectStore("catalogues").get(key);request.onsuccess=()=>{const value=request.result;const now=Date.now();if(!value||!Number.isFinite(value.savedAt)||now<value.savedAt||now-value.savedAt>=maxAge||value.menu?.branchId!==scope.branchId||value.scope?.store!==store||catalogueKey(value.scope)!==key||!Array.isArray(value.coverage?.menuIds)||value.coverage.menuIds.length!==1||value.coverage.menuIds[0]!==scope.menuId||!value.etag){if(value){mutate(table=>table.delete(key))}resolve(void 0);return}mutate(table=>{const latest=table.get(key);latest.onsuccess=()=>{if(latest.result){try{table.put({...latest.result,usedAt:now})}catch{}}}});resolve(value)}}catch{db.close();resolve(void 0)}})},save(value){if(value.scope.store!==store){return}mutate(table=>{try{const bytes=new TextEncoder().encode(JSON.stringify(value)).length;if(bytes>maxBytes){return}const key=catalogueKey(value.scope);const request=table.getAll();request.onsuccess=()=>{const now=Date.now();const entries=request.result.filter(entry=>entry.key!==key).sort((a,b)=>a.usedAt-b.usedAt);let total=entries.reduce((sum,entry)=>sum+entry.bytes,bytes);for(const entry of entries){if(now-entry.savedAt>=maxAge||total>maxBytes){table.delete(entry.key);total-=entry.bytes}}try{table.put({...value,key,bytes,usedAt:now})}catch{}}}catch{}})}}}async function catalogueDigest(menu){const canonical=value=>{if(Array.isArray(value)){return value.map(canonical)}if(value&&typeof value==="object"){return Object.fromEntries(Object.entries(value).sort(([a],[b])=>a.localeCompare(b)).map(([key,entry])=>[key,canonical(entry)]))}return value};const{version:_version,...content}=menu;const bytes=new TextEncoder().encode(JSON.stringify(canonical(content)));const hash=await crypto.subtle.digest("SHA-256",bytes);return Array.from(new Uint8Array(hash),byte=>byte.toString(16).padStart(2,"0")).join("")}function createSavedCatalogue(client,scope){const storage=createCatalogueStorage(scope.store);const key=catalogueKey(scope);let lastDigest;return{async restore(){const saved=await storage.read(scope);if(saved){lastDigest=catalogueDigest(saved.menu);client._internal.cache.set(key,saved,saved.etag)}return saved},async publish(value){const previous=lastDigest;const next=catalogueDigest(value.menu);lastDigest=next;const digest=await next;const changed=digest!==await previous;const saved={...value,etag:digest};if(changed){client._internal.cache.set(key,saved,digest)}storage.save(saved);return changed}}}export{CATALOGUE_MAX_AGE_MS,CATALOGUE_MAX_BYTES,catalogueDigest,catalogueKey,createCatalogueStorage,createSavedCatalogue};
2
- //# sourceMappingURL=catalogue.js.map
@@ -1,2 +1 @@
1
1
  import{createPlacesRequest}from"./request.js";import{API_VERSION,RestTransport,validateConfig}from"./sdk.js";import{createAddressSearch}from"./search.js";var DEFAULT_CUSTOMER_BASE="/_zappie/api";function createPlaces(options){validateConfig({store:"places",key:options.key});const base=new RestTransport({...options.baseUrl?{baseUrl:options.baseUrl}:{},...options.fetch?{fetch:options.fetch}:{}}).baseUrl;const customerBase=(options.customerBase??DEFAULT_CUSTOMER_BASE).replace(/\/+$/,"");const request=createPlacesRequest(base,options.key,options.version??API_VERSION,options.fetch??globalThis.fetch);const readPlace=(id,read)=>{const params=new URLSearchParams;if(read.branchId!==void 0){params.set("branch_id",read.branchId)}if(read.sessionToken!==void 0){params.set("session",read.sessionToken)}const suffix=params.size>0?`?${params}`:"";return request(`/places/${encodeURIComponent(id)}${suffix}`,{method:"GET",...read.signal?{signal:read.signal}:{}})};const client={async autocomplete(query,sessionToken,read={}){if(!query.trim()){return[]}const params=new URLSearchParams({q:query.trim(),session:sessionToken});const result=await request(`/places/autocomplete?${params}`,{method:"GET",...read.signal?{signal:read.signal}:{}});return result.suggestions},place(id,read){return readPlace(id,read)},reverse(lat,lng,read={}){const params=new URLSearchParams({lat:String(lat),lng:String(lng)});return request(`/places/reverse?${params}`,{method:"GET",...read.signal?{signal:read.signal}:{}})},staticMapUrl(lat,lng,branchId){const params=new URLSearchParams({lat:String(lat),lng:String(lng)});if(branchId!==void 0){params.set("branch_id",branchId)}return`${customerBase}/places/static-map?${params}`},zoneCheck(body,read={}){return request("/delivery/zones/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body),...read.signal?{signal:read.signal}:{}})},createAddressSearch(searchOptions={}){return createAddressSearch({autocomplete:client.autocomplete,place:readPlace},searchOptions)}};return client}export{createPlaces};
2
- //# sourceMappingURL=client.js.map
@@ -1,2 +1 @@
1
1
  import{stableErrorCode,ZappieError}from"../internal/customer-http.js";var PlacesError=class extends ZappieError{constructor(status,apiCode,message,param,issues){super(stableErrorCode(status,apiCode),message,{status,retryable:status===429||status>=500,...param!==void 0?{param}:{}});this.apiCode=apiCode;if(issues!==void 0){this.issues=issues}}};export{PlacesError};
2
- //# sourceMappingURL=error.js.map
@@ -4,19 +4,28 @@ import { ZappieError } from '@zappie/sdk';
4
4
  * An autocomplete match with its place ID, primary text and optional secondary text.
5
5
  */
6
6
  type PlaceSuggestion = {
7
+ /** The place's ID. Pass it to `place` or the address search's `select` for the whole place. */
7
8
  place_id: string;
9
+ /** The place's main name. */
8
10
  text: string;
11
+ /** The rest of the address. Left out when there is none. */
9
12
  secondary?: string;
10
13
  };
11
14
  /**
12
15
  * A resolved place with address text, coordinates and, when you pass a branch, the route from that branch.
13
16
  */
14
17
  type Place = {
18
+ /** The place's ID. */
15
19
  place_id: string;
20
+ /** The address's first line. */
16
21
  line1: string;
22
+ /** The city. Left out when the API doesn't send one. */
17
23
  city?: string;
24
+ /** The country as an ISO 3166-1 alpha-2 code, such as `NG`. Left out when the API doesn't send one. */
18
25
  country?: string;
26
+ /** Latitude in decimal degrees. */
19
27
  lat: number;
28
+ /** Longitude in decimal degrees. */
20
29
  lng: number;
21
30
  /**
22
31
  * The drive from the branch, measured by road. Absent when there is no road between them. Each
@@ -33,47 +42,72 @@ type Place = {
33
42
  * Address text, a place ID or coordinates you can submit for a delivery-zone check.
34
43
  */
35
44
  type ZoneAddress = {
45
+ /** The address's first line. Send it, `place_id`, or `lat` with `lng`. */
36
46
  line1?: string;
47
+ /** The city. */
37
48
  city?: string;
49
+ /** A place ID from the places lookups. */
38
50
  place_id?: string;
51
+ /** Latitude in decimal degrees. Send it with `lng`. */
39
52
  lat?: number;
53
+ /** Longitude in decimal degrees. Send it with `lat`. */
40
54
  lng?: number;
41
55
  };
42
56
  /**
43
57
  * The branch and delivery address to check, with an optional selected delivery region.
44
58
  */
45
59
  type ZoneCheckRequest = {
60
+ /** The branch that would deliver. */
46
61
  branch_id: string;
62
+ /** Where to deliver. Send `line1`, `place_id`, or `lat` with `lng`. */
47
63
  address: ZoneAddress;
64
+ /** The region the shopper picked after a `region_required` answer. */
48
65
  delivery_region_id?: string;
49
66
  };
50
67
  /**
51
68
  * Delivery eligibility, optional region and estimate, fee and any reason delivery is unavailable.
52
69
  */
53
70
  type ZoneCheck = {
71
+ /** True when the branch delivers to the address. */
54
72
  deliverable: boolean;
73
+ /** The region the address matched. Left out when it matched none. */
55
74
  delivery_region_id?: string;
75
+ /** The delivery fee in minor units of the currency, when the address is deliverable. Null otherwise. */
56
76
  fee: {
57
77
  amount_minor: number;
58
78
  currency: string;
59
79
  } | null;
80
+ /** Reserved for the delivery time range in minutes. The API doesn't send it today. */
60
81
  eta_minutes?: number[];
82
+ /**
83
+ * Why the address is not deliverable, or null when it is. `outside_zone` means the branch
84
+ * doesn't deliver there. `branch_no_delivery` means the branch isn't taking delivery.
85
+ * `address_unresolved` means Zappie could not find the address. `region_required` means the
86
+ * address is outside the drawn areas and the shopper picks one of the branch's delivery regions.
87
+ * Send that back as `delivery_region_id`.
88
+ */
61
89
  reason: "outside_zone" | "branch_no_delivery" | "address_unresolved" | "region_required" | null;
62
90
  };
63
91
  /**
64
92
  * A publishable API key and optional endpoint, version and fetch overrides for place lookups.
65
93
  */
66
94
  type PlacesClientOptions = {
95
+ /** Your publishable API key. */
67
96
  key: string;
97
+ /** The storefront API base. Defaults to `https://api.zappie.ai/storefront/v1`. Must be HTTPS, or HTTP on localhost. */
68
98
  baseUrl?: string;
99
+ /** The `Zappie-Version` the requests send. Defaults to the SDK's `API_VERSION`. */
69
100
  version?: string;
101
+ /** The fetch implementation for every request. Defaults to the global `fetch`. */
70
102
  fetch?: typeof fetch;
103
+ /** The same-origin API base that `staticMapUrl` builds on. Defaults to `/_zappie/api`. */
71
104
  customerBase?: string;
72
105
  };
73
106
  /**
74
107
  * An optional abort signal for cancelling a places request.
75
108
  */
76
109
  type SignalOptions = {
110
+ /** Aborting it cancels the request. */
77
111
  signal?: AbortSignal;
78
112
  };
79
113
  /**
@@ -87,7 +121,9 @@ type PlaceOptions = SignalOptions & {
87
121
  * Optional debounce interval in milliseconds and branch ID for an address search controller.
88
122
  */
89
123
  type AddressSearchOptions = {
124
+ /** How long `suggest` waits after the last keystroke before it asks, in milliseconds. Defaults to 250. */
90
125
  debounceMs?: number;
126
+ /** The branch whose road route `select` adds to the place. Leave it out for a place without a route. */
91
127
  branchId?: string;
92
128
  };
93
129
 
@@ -120,9 +156,13 @@ type PlacesClient = ReturnType<typeof createPlaces>;
120
156
  * Statuses 429 and 5xx are marked retryable.
121
157
  */
122
158
  declare class PlacesError extends ZappieError {
159
+ /** The API's own error code, such as `parameter_invalid`. `server_error` when the body carried none. */
123
160
  readonly apiCode: string;
161
+ /** The `issues` list from the error body, as the API sent it. Left out when the body has none. */
124
162
  readonly issues?: unknown;
125
- constructor(status: number, apiCode: string, message: string, param?: string, issues?: unknown);
163
+ constructor(status: number,
164
+ /** The API's own error code, such as `parameter_invalid`. `server_error` when the body carried none. */
165
+ apiCode: string, message: string, param?: string, issues?: unknown);
126
166
  }
127
167
 
128
168
  export { PlacesError, createPlaces };
@@ -1,2 +1 @@
1
1
  import{createPlaces}from"./client.js";import{PlacesError}from"./error.js";export{PlacesError,createPlaces};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  import{apiError,requestWithRetry}from"../internal/customer-http.js";import{PlacesError}from"./error.js";function createPlacesRequest(base,key,version,fetcher){return async(path,init={})=>{const response=await requestWithRetry(fetcher,base+path,{...init,redirect:"manual",headers:{Authorization:`Bearer ${key}`,"Zappie-Version":version,...init.headers}},"Could not reach the places service");if(!response.ok){const value=await apiError(response,`The places service answered ${response.status}`);throw new PlacesError(response.status,value.apiCode,value.message,value.param,value.issues)}return await response.json()}}export{createPlacesRequest};
2
- //# sourceMappingURL=request.js.map
@@ -1,2 +1 @@
1
1
  import{API_VERSION,RestTransport,ZappieError}from"@zappie/sdk";import{validateConfig}from"@zappie/sdk/internal";export{API_VERSION,RestTransport,ZappieError,validateConfig};
2
- //# sourceMappingURL=sdk.js.map
@@ -1,2 +1 @@
1
1
  var aborted=()=>new DOMException("Superseded","AbortError");function createAddressSearch(client,options={}){const debounceMs=options.debounceMs??250;let token=crypto.randomUUID();let controller;let timer;let rejectPending;let revision=0;const cancel=()=>{revision++;if(timer!==void 0){clearTimeout(timer);timer=void 0}controller?.abort(aborted());controller=void 0;rejectPending?.(aborted());rejectPending=void 0};return{suggest(query){cancel();const current=revision;if(!query.trim()){return Promise.resolve([])}return new Promise((resolve,reject)=>{rejectPending=reject;timer=setTimeout(async()=>{timer=void 0;controller=new AbortController;try{const value=await client.autocomplete(query.trim(),token,{signal:controller.signal});if(current===revision){resolve(value)}}catch(failure){if(current===revision){reject(failure)}}finally{if(current===revision){rejectPending=void 0;controller=void 0}}},debounceMs)})},async select(placeId){cancel();const current=revision;controller=new AbortController;try{const value=await client.place(placeId,{...options.branchId!==void 0?{branchId:options.branchId}:{},sessionToken:token,signal:controller.signal});if(current!==revision){throw aborted()}token=crypto.randomUUID();return value}finally{if(current===revision){controller=void 0}}},dispose:cancel}}export{createAddressSearch};
2
- //# sourceMappingURL=search.js.map
@@ -1 +0,0 @@
1
- //# sourceMappingURL=types.js.map
@@ -1,2 +1 @@
1
1
  import{money,ZappieError}from"@zappie/sdk";var byPrice=(a,b)=>a.price.amountMinor-b.price.amountMinor;function fill(group,choices){const need=Math.max(group.selection.min,1);const prices=[];let count=0;for(const choice of choices.sort(byPrice)){const{min=1,max=choice.quantity?Infinity:1}=choice.quantity??{};const units=Math.max(min,Math.min(need-count,max));if(count<need&&count+units<=(group.selection.max||Infinity)){prices.push(...Array(units).fill(choice.price));count+=units}}return[prices,count>=need]}function startingPrice(item){const available=item.variants.filter(variant=>variant.isAvailable);const base=(available.length?available:item.variants).filter(variant=>variant.price.amountMinor>=0).sort(byPrice)[0]?.price??item.price;const prices=item.optionGroups.flatMap(group=>{if(group.isAttribute||!group.required||group.kind!=="select"){return[]}const priced=group.choices.filter(choice=>choice.price.amountMinor>=0);const[taken,filled]=fill(group,priced.filter(choice=>choice.isAvailable));return filled?taken:fill(group,priced)[0]});let total=base.amountMinor;for(const price of prices){if(price.currency!==base.currency){throw new ZappieError("invalid_request","Cannot combine different currencies")}total+=price.amountMinor}return money(total,base.currency)}function startingPriceWith(item,choices){const keeps=(groupId,choiceId)=>!choices.some(picked=>picked.groupId===groupId)||choices.some(picked=>picked.groupId===groupId&&picked.choiceId===choiceId);const variants=item.variants.filter(variant=>Object.entries(variant.attributeChoices).every(([groupId,choiceId])=>keeps(groupId,choiceId)));return startingPrice({...item,variants:variants.length?variants:item.variants,optionGroups:item.optionGroups.map(group=>({...group,choices:group.choices.filter(choice=>keeps(group.id,choice.id))}))})}function showsFromPrice(item){const prices=[...new Set(item.variants.filter(variant=>variant.isAvailable).map(variant=>variant.price.amountMinor))];return prices.length>1||prices.length===1&&startingPrice(item).amountMinor>prices[0]}export{showsFromPrice,startingPrice,startingPriceWith};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{useEffect,useSyncExternalStore}from"react";import{EMPTY_CART}from"../cart/index.js";import{cartActions}from"./changes.js";import{useZappie}from"./provider.js";function useCart(){const{cart}=useZappie();const snapshot=useSyncExternalStore(cart.subscribe,cart.getSnapshot,()=>EMPTY_CART);useEffect(()=>cart.mount(),[cart]);return{...snapshot,actions:cartActions(cart).actions}}function useCartLine(lineId){return useCart().lines.find(line=>line.id===lineId)}function useCartCatalogue(){const client=useZappie();useCart();return client._internal.cartCatalogue()}function useCartNotice(){const tracker=cartActions(useZappie().cart);const notice=useSyncExternalStore(tracker.subscribe,tracker.notice,()=>null);return{notice,dismiss:tracker.dismiss}}export{useCart,useCartCatalogue,useCartLine,useCartNotice};
2
- //# sourceMappingURL=cart.js.map
@@ -1,2 +1 @@
1
1
  var trackers=new WeakMap;function cartActions(cart){let tracker=trackers.get(cart);if(tracker){return tracker}const confirmed=new Map;const keyed=new Map;const listeners=new Set;let notice=null;let watching=false;const emit=()=>{for(const fn of[...listeners]){fn()}};const find=lineId=>cart.lines.find(candidate=>candidate.id===lineId);const remember=(lineId,prior)=>{if(!confirmed.has(lineId)){confirmed.set(lineId,prior??null)}if(!watching){watching=true;void import("./rollback.js").then(({watch})=>watch(cart,confirmed,value=>{notice=value;emit()}))}};const actions=Object.freeze(Object.create(cart,{add:{value(item,input,{key}={}){const done=key?keyed.get(key):void 0;if(done){return find(done.id)??done}const before=cart.lines;const line=cart.add(item,input);remember(line.id,before.find(candidate=>candidate.id===line.id));if(key){keyed.set(key,line);if(keyed.size>100){keyed.delete(keyed.keys().next().value)}}return line}},update:{value(lineId,patch){const prior=find(lineId);const line=cart.update(lineId,patch);remember(lineId,prior);return line}},remove:{value(lineId){confirmed.delete(lineId);cart.remove(lineId)}}}));tracker={actions,notice:()=>notice,dismiss(){if(notice){notice=null;emit()}},subscribe(fn){listeners.add(fn);return()=>{listeners.delete(fn)}}};trackers.set(cart,tracker);return tracker}export{cartActions};
2
- //# sourceMappingURL=changes.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{useEffect,useMemo,useSyncExternalStore}from"react";import{ZappieError}from"../errors.js";import{useZappie}from"./provider.js";function useStore(){const client=useZappie();const cache=client._internal.cache;const snapshot=useSyncExternalStore(cache.subscribe,()=>cache.snapshot("store"),()=>cache.snapshot("store"));useEffect(()=>{const abort=new AbortController;void client.store.get({signal:abort.signal}).catch(()=>{});return()=>abort.abort()},[client]);return{data:snapshot.value,error:snapshot.error,isLoading:!snapshot.value&&!snapshot.error}}function useMenu(branch,options={}){const metadataOnly=options.metadataOnly===true;const client=useZappie();const store=useStore();const cache=client._internal.cache;let key;let branchError;try{key=client._internal.menuKey(branch);if(metadataOnly&&!cache.snapshot(key).value){key+=":partial"}}catch(error2){key="menu:invalid";branchError=error2}const snapshot=useSyncExternalStore(cache.subscribe,()=>cache.snapshot(key),()=>cache.snapshot(key));useEffect(()=>{if(!store.data||branchError){return}if(metadataOnly&&cache.snapshot(client._internal.menuKey(branch)).value){return}const abort=new AbortController;void client.menu.get({...branch?{branch}:{},...metadataOnly?{metadataOnly:true}:{},signal:abort.signal}).catch(()=>{});return()=>abort.abort()},[client,branch,store.data,branchError?.code,metadataOnly,cache]);const error=branchError??snapshot.error??store.error;return{data:snapshot.value,error,isLoading:!snapshot.value&&!error,isStale:cache.stale(key)}}function useItem(id,branch){const menu=useMenu(branch);const data=menu.data&&Object.prototype.hasOwnProperty.call(menu.data.items,id)?menu.data.items[id]:void 0;const missing=Boolean(menu.data)&&!data;const notFound=useMemo(()=>missing?new ZappieError("item_not_found","Item not found"):void 0,[missing,id]);return{data,error:menu.error??notFound,isLoading:menu.isLoading}}export{useItem,useMenu,useStore};
2
- //# sourceMappingURL=hooks.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{VERSION}from"../index.js";import{useItem,useMenu,useStore}from"./hooks.js";import{ZappieProvider,useZappie}from"./provider.js";import{useCart,useCartCatalogue,useCartLine,useCartNotice}from"./cart.js";export{VERSION,ZappieProvider,useCart,useCartCatalogue,useCartLine,useCartNotice,useItem,useMenu,useStore,useZappie};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  "use client";import{createContext,useContext,useMemo}from"react";import{jsx}from"react/jsx-runtime";var Context=createContext(null);function ZappieProvider({client,initialData,children}){const value=useMemo(()=>{if(initialData?.store&&!client.store.peek()){client._internal.hydrateStore(initialData.store)}if(initialData?.menu&&!client._internal.cache.snapshot(`menu:${initialData.menu.branchId}`).value){client.menu.hydrate(initialData.menu)}return client},[client,initialData]);return jsx(Context.Provider,{value,children})}function useZappie(){const client=useContext(Context);if(!client){throw new Error("useZappie requires ZappieProvider")}return client}export{ZappieProvider,useZappie};
2
- //# sourceMappingURL=provider.js.map
@@ -1,2 +1 @@
1
1
  var refusals=/^(quantity_limit|item_unavailable|item_not_found|option_)/;var refuses=issue=>issue.severity==="blocking"&&refusals.test(issue.code)&&!issue.fixes.some(fix=>fix.action==="schedule");var region;function announce(message){if(typeof document==="undefined"){return}if(!region?.isConnected){region=document.createElement("div");region.setAttribute("role","status");region.setAttribute("aria-live","polite");region.setAttribute("data-zappie-announcer","");region.style.cssText="position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)";document.body.appendChild(region)}const target=region;target.textContent="";setTimeout(()=>{target.textContent=message},50)}function watch(cart,confirmed,show){let seen;let sequence=0;const settle=()=>{const snapshot=cart.getSnapshot();const quote="quote"in snapshot.state?snapshot.state.quote:void 0;if(!quote||quote===seen){return}seen=quote;let first;let count=0;for(const[lineId,prior]of[...confirmed]){const line=snapshot.lines.find(candidate=>candidate.id===lineId);const quoted=quote.lines.find(candidate=>candidate.lineId===lineId)?.quantity;if(line&&quoted!==void 0&&quoted!==line.quantity){continue}confirmed.delete(lineId);const problem=quote.issues.find(issue=>issue.lineId===lineId&&refuses(issue));if(!line||!problem){continue}const fix=problem.fixes.find(candidate=>candidate.action==="set_quantity"&&candidate.quantity>(prior?.quantity??0)&&candidate.quantity<line.quantity);try{if(fix?.action==="set_quantity"){cart.update(lineId,{quantity:fix.quantity})}else if(prior){cart.update(lineId,{quantity:prior.quantity,choices:prior.choices,inputs:prior.inputs,variantId:prior.variantId,note:prior.note})}else{cart.remove(lineId)}first??(first=problem);count++}catch{}}if(first){announce(first.message);show({id:++sequence,code:first.code,message:first.message,...first.lineId?{lineId:first.lineId}:{},count})}};cart.subscribe(settle);settle()}export{watch};
2
- //# sourceMappingURL=rollback.js.map
@@ -1,2 +1 @@
1
- import{apiError,requestWithRetry,stableErrorCode,ZappieError}from"../internal/customer-http.js";async function receiptFile(url,fetcher=globalThis.fetch){const response=await requestWithRetry(fetcher,url,{cache:"no-store",headers:{Accept:"application/pdf"}},"Could not reach the receipt");if(!response.ok){const value=await apiError(response,"The receipt didn't load");throw new ZappieError(stableErrorCode(response.status,value.apiCode),value.message,{status:response.status})}const name=/filename="?([^";]+)/.exec(response.headers.get("content-disposition")??"")?.[1]??"Receipt.pdf";return new File([await response.arrayBuffer()],name,{type:"application/pdf"})}function orderReceipt(customerBase,id,fetcher){return receiptFile(`${customerBase}/me/orders/${encodeURIComponent(id)}/receipt`,fetcher)}function canShareReceipt(){const navigator=globalThis.navigator;return Boolean(navigator?.canShare?.({files:[new File([],"Receipt.pdf",{type:"application/pdf"})]}))}export{canShareReceipt,orderReceipt,receiptFile};
2
- //# sourceMappingURL=index.js.map
1
+ import{apiError,requestWithRetry,stableErrorCode,ZappieError}from"../internal/customer-http.js";async function receiptFile(url,fetcher=globalThis.fetch){const response=await requestWithRetry(fetcher,url,{cache:"no-store",headers:{Accept:"application/pdf"}},"Could not reach the receipt");if(!response.ok){const value=await apiError(response,"The receipt didn't load");throw new ZappieError(stableErrorCode(response.status,value.apiCode),value.message,{status:response.status,apiCode:value.apiCode})}const name=/filename="?([^";]+)/.exec(response.headers.get("content-disposition")??"")?.[1]??"Receipt.pdf";return new File([await response.arrayBuffer()],name,{type:"application/pdf"})}function orderReceipt(customerBase,id,fetcher){return receiptFile(`${customerBase}/me/orders/${encodeURIComponent(id)}/receipt`,fetcher)}function canShareReceipt(){const navigator=globalThis.navigator;return Boolean(navigator?.canShare?.({files:[new File([],"Receipt.pdf",{type:"application/pdf"})]}))}export{canShareReceipt,orderReceipt,receiptFile};
@@ -1,2 +1 @@
1
1
  function safeRedirect(to,fallback){if(typeof to!=="string"||/[\u0000-\u0020\u007f\s\\]/u.test(to)||/%(?:0[\da-f]|1[\da-f]|20|7f)/iu.test(to)){return fallback}try{const browserOrigin=typeof location==="undefined"?void 0:location.origin;if(browserOrigin==="null"){return fallback}const origin=browserOrigin??"https://safe-redirect.invalid";const target=new URL(to,origin);const path=`${target.pathname}${target.search}${target.hash}`;return(target.protocol==="http:"||target.protocol==="https:")&&target.origin===origin&&/^\/(?!\/)/.test(path)?path:fallback}catch{return fallback}}function redirectToCheckout(url,target){if(!/^(https:\/\/checkout(\.stg)?\.zappie\.ai|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)\//.test(url)){throw new TypeError("Not a Zappie checkout URL")}(target??globalThis).location.assign(url)}export{redirectToCheckout,safeRedirect};
2
- //# sourceMappingURL=index.js.map
@@ -1,8 +1,12 @@
1
1
  /** A node of merchant rich text: a tag with its children, or text. Attributes are not kept. */
2
2
  type RichTextNode = {
3
+ /** What the node is. `tag` is an element, `text` is text, and `root` holds the top-level nodes while parsing. */
3
4
  type: string;
5
+ /** The tag name in lower case, such as `p` or `strong`. Set on a `tag` node only. */
4
6
  name?: string;
7
+ /** The text with its entities decoded. Set on a `text` node only. */
5
8
  data?: string;
9
+ /** The nodes inside a `tag` node, in order. Empty for a void tag such as `br`. Left out on a `text` node. */
6
10
  children?: RichTextNode[];
7
11
  };
8
12
  /**
@@ -1,2 +1 @@
1
1
  var tag=/<(\/?)\s*([a-zA-Z][a-zA-Z0-9]*)\b[^>]*>/g;var voidTags=new Set(["br","hr","img","input","meta","link"]);var latin1="iexcl cent pound curren yen brvbar sect uml copy ordf laquo not shy reg macr deg plusmn sup2 sup3 acute micro para middot cedil sup1 ordm raquo frac14 frac12 frac34 iquest Agrave Aacute Acirc Atilde Auml Aring AElig Ccedil Egrave Eacute Ecirc Euml Igrave Iacute Icirc Iuml ETH Ntilde Ograve Oacute Ocirc Otilde Ouml times Oslash Ugrave Uacute Ucirc Uuml Yacute THORN szlig agrave aacute acirc atilde auml aring aelig ccedil egrave eacute ecirc euml igrave iacute icirc iuml eth ntilde ograve oacute ocirc otilde ouml divide oslash ugrave uacute ucirc uuml yacute thorn yuml";var marks="OElig 152 oelig 153 Scaron 160 scaron 161 Yuml 178 fnof 192 circ 2c6 tilde 2dc ensp 2002 emsp 2003 thinsp 2009 ndash 2013 mdash 2014 lsquo 2018 rsquo 2019 sbquo 201a ldquo 201c rdquo 201d bdquo 201e dagger 2020 Dagger 2021 bull 2022 hellip 2026 permil 2030 prime 2032 Prime 2033 lsaquo 2039 rsaquo 203a euro 20ac trade 2122 larr 2190 rarr 2192 minus 2212 check 2713";var named;var entities=()=>{if(!named){named={amp:"&",AMP:"&",apos:"'",gt:">",GT:">",lt:"<",LT:"<",nbsp:"\xA0",quot:'"',QUOT:'"'};latin1.split(" ").forEach((name,index)=>{named[name]=String.fromCodePoint(161+index)});const pairs=marks.split(" ");for(let index=0;index<pairs.length;index+=2){named[pairs[index]]=String.fromCodePoint(Number.parseInt(pairs[index+1],16))}}return named};var decodeEntities=value=>value.replace(/&(?:#([0-9]+)|#x([0-9a-f]+)|([a-z][a-z0-9]*));/gi,(entity,decimal,hexadecimal,name)=>{if(name){return entities()[name]??entity}const code=Number.parseInt(decimal||hexadecimal,hexadecimal?16:10);return code>0&&code<=1114111&&!(code>=55296&&code<=57343)?String.fromCodePoint(code):"\uFFFD"});function parseRichText(html){const root={type:"root",children:[]};const stack=[root];let last=0;const appendText=value=>{if(value){stack.at(-1)?.children?.push({type:"text",data:decodeEntities(value)})}};for(const match of html.matchAll(tag)){appendText(html.slice(last,match.index));last=match.index+match[0].length;const name=match[2].toLowerCase();if(match[1]){let position=stack.length-1;while(position>0&&stack[position].name!==name){position--}if(position>0){stack.length=position}continue}const node={type:"tag",name,children:[]};stack.at(-1)?.children?.push(node);if(!voidTags.has(name)&&!match[0].endsWith("/>")){stack.push(node)}}appendText(html.slice(last));return root.children}function plainText(html){const text=[];const walk=nodes=>{for(const node of nodes){if(node.type==="text"){text.push(node.data)}else{walk(node.children);text.push(" ")}}};walk(parseRichText(html));return text.join("").replace(/\s+/g," ").trim()}export{parseRichText,plainText};
2
- //# sourceMappingURL=index.js.map
@@ -1,2 +1 @@
1
1
  var encoder=new TextEncoder;var decoder=new TextDecoder;function base64UrlEncode(bytes){let binary="";for(const byte of bytes){binary+=String.fromCharCode(byte)}return btoa(binary).replaceAll("+","-").replaceAll("/","_").replace(/=+$/,"")}function base64UrlDecode(text){return/^[\w-]*$/.test(text)&&text.length%4!==1?Uint8Array.from(atob(text.replaceAll("-","+").replaceAll("_","/")),c=>c.charCodeAt(0)):null}function randomToken(bytes=32){if(!Number.isInteger(bytes)||bytes<16||bytes>1024){throw new RangeError("randomToken takes between 16 and 1024 bytes.")}return base64UrlEncode(crypto.getRandomValues(new Uint8Array(bytes)))}async function pkceChallenge(verifier){const digest=await crypto.subtle.digest("SHA-256",encoder.encode(verifier));return base64UrlEncode(new Uint8Array(digest))}async function createPkce(){const verifier=randomToken();return{verifier,challenge:await pkceChallenge(verifier),method:"S256"}}function secretsOf(secret){const list=typeof secret==="string"?[secret]:secret;if(!list.length||list.some(value=>encoder.encode(value).length<32)){throw new TypeError("Each sealing secret needs at least 32 bytes.")}return list}var keys=new Map;function keyFor(secret){if(!keys.has(secret)){if(keys.size>=16){keys.clear()}keys.set(secret,crypto.subtle.digest("SHA-256",encoder.encode(secret)).then(digest=>crypto.subtle.importKey("raw",digest,"AES-GCM",false,["encrypt","decrypt"])))}return keys.get(secret)}var params=(iv,purpose)=>({name:"AES-GCM",iv,...purpose===void 0?{}:{additionalData:encoder.encode(purpose)}});async function sealValue(value,{secret,purpose}){const iv=crypto.getRandomValues(new Uint8Array(12));const cipher=await crypto.subtle.encrypt(params(iv,purpose),await keyFor(secretsOf(secret)[0]),encoder.encode(JSON.stringify(value)));return`${base64UrlEncode(iv)}.${base64UrlEncode(new Uint8Array(cipher))}`}async function openSealedValue(sealed,{secret,purpose}){const list=secretsOf(secret);const[ivText="",cipherText="",extra]=(sealed??"").split(".");const iv=base64UrlDecode(ivText);const cipher=base64UrlDecode(cipherText);if(iv?.length!==12||!cipher?.length||extra!==void 0){return null}for(const candidate of list){try{const plain=await crypto.subtle.decrypt(params(iv,purpose),await keyFor(candidate),cipher);return JSON.parse(decoder.decode(plain))}catch{}}return null}export{base64UrlDecode,base64UrlEncode,createPkce,decoder,encoder,openSealedValue,pkceChallenge,randomToken,sealValue,secretsOf};
2
- //# sourceMappingURL=crypto.js.map
@@ -1,2 +1 @@
1
1
  import{ZappieError}from"../../errors.js";import{base64UrlDecode,decoder,encoder}from"./crypto.js";var messages={malformed:"The token isn't a signed JWT.",unsupported_algorithm:"The token uses an algorithm this verifier refuses.",unknown_key:"The token was signed with a key the issuer doesn't publish.",invalid_signature:"The token's signature doesn't match.",wrong_issuer:"The token comes from a different issuer.",wrong_audience:"The token was issued for a different audience.",wrong_nonce:"The token wasn't issued for this sign-in.",wrong_subject:"The token's subject isn't a Zappie customer.",wrong_type:"The token isn't an ID token.",expired:"The token has expired.",not_yet_valid:"The token isn't valid yet.",keys_unavailable:"The identity issuer's signing keys couldn't be read."};var ZappieTokenError=class extends ZappieError{constructor(reason,cause){super(reason==="keys_unavailable"?"network_error":"unauthorized",messages[reason],cause===void 0?{}:{cause});this.reason=reason;this.name="ZappieTokenError"}};var specs={RS256:{kty:"RSA",jwk:key=>({kty:"RSA",n:key.n,e:key.e}),import:{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},verify:{name:"RSASSA-PKCS1-v1_5"}},ES256:{kty:"EC",jwk:key=>({kty:"EC",crv:"P-256",x:key.x,y:key.y}),import:{name:"ECDSA",namedCurve:"P-256"},verify:{name:"ECDSA",hash:"SHA-256"}}};var fail=(reason,cause)=>{throw new ZappieTokenError(reason,cause)};var numeric=value=>typeof value==="number"&&Number.isFinite(value);var trimSlash=value=>value.replace(/\/+$/,"");var KEY_RETRY_MS=3e4;function decodeJson(text){const bytes=base64UrlDecode(text)??fail("malformed");let value;try{value=JSON.parse(decoder.decode(bytes))}catch{}return value&&typeof value==="object"&&!Array.isArray(value)?value:fail("malformed")}function createTokenVerifier(options){const issuer=trimSlash(options.issuer);const allowed=options.algorithms??["RS256","ES256"];const tolerance=options.clockToleranceSec??60;const ttl=(options.cacheTtlSec??3600)*1e3;const prefix=options.subjectPrefix===void 0?"cus_":options.subjectPrefix;const now=options.now??Date.now;const read=options.fetch??((url,init)=>fetch(url,init));if(!issuer||!options.audience||!allowed.length||allowed.some(alg=>!(alg in specs))||!numeric(tolerance)||tolerance<0||!numeric(ttl)||ttl<0){throw new TypeError("createTokenVerifier needs an issuer, an audience, RS256 or ES256, and a clock tolerance and cache time of 0 or more.")}let cached;let pending;let triedAt=Number.NEGATIVE_INFINITY;let lastError;const load=async()=>{try{const response=await read(options.jwksUrl??`${issuer}/.well-known/jwks.json`,{headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)});const text=response.ok?await response.text():"";if(!text||text.length>1<<20){throw new Error(`The key set answered ${response.status}.`)}const keys=new Map;const list=JSON.parse(text).keys;for(const jwk of Array.isArray(list)?list:[]){for(const alg of allowed){const spec=specs[alg];if(jwk.kty===spec.kty&&(jwk.use??"sig")==="sig"&&(jwk.alg??alg)===alg&&(alg==="RS256"||jwk.crv==="P-256")){await crypto.subtle.importKey("jwk",spec.jwk(jwk),spec.import,false,["verify"]).then(key=>keys.set(`${alg}:${String(jwk.kid??"")}`,key)).catch(()=>void 0)}}}if(!keys.size){throw new Error("The key set has no keys this verifier can use.")}return cached={keys,at:now()}}catch(error){return fail("keys_unavailable",error)}};const find=(set,kid,alg)=>{if(typeof kid==="string"){return set.keys.get(`${alg}:${kid}`)}const fits=[...set.keys].filter(([id])=>id.startsWith(`${alg}:`));return fits.length===1?fits[0]?.[1]:void 0};const keyFor=async(kid,alg)=>{if(!pending){const key=cached&&find(cached,kid,alg);if(key&&cached&&now()-cached.at<ttl){return key}if(now()-triedAt<KEY_RETRY_MS){return cached?key:fail("keys_unavailable",lastError)}triedAt=now();pending=load().finally(()=>pending=void 0)}try{const set=await pending;lastError=void 0;return find(set,kid,alg)}catch(error){lastError=error;return(cached&&find(cached,kid,alg))??fail("keys_unavailable",error)}};const check=async(token,checks,idToken)=>{const parts=typeof token==="string"&&token.length<16384?token.split("."):[];const[head="",body="",sig=""]=parts.length===3?parts:fail("malformed");const header=decodeJson(head);const claims=decodeJson(body);const signature=base64UrlDecode(sig)??fail("malformed");const alg=header.alg;if(!allowed.includes(alg)||header.crit!==void 0){fail("unsupported_algorithm")}if(idToken&&header.typ!==void 0&&(typeof header.typ!=="string"||header.typ.toLowerCase().replace(/^application\//,"")!=="jwt")){fail("wrong_type")}const key=await keyFor(header.kid,alg)??fail("unknown_key");if(alg==="ES256"&&signature.length!==64||!await crypto.subtle.verify(specs[alg].verify,key,signature,encoder.encode(`${head}.${body}`))){fail("invalid_signature")}const seconds=now()/1e3;const times=[claims.nbf,claims.iat];const sub=claims.sub;if(typeof claims.iss!=="string"||trimSlash(claims.iss)!==issuer){fail("wrong_issuer")}if(![claims.aud].flat().includes(checks.audience??options.audience)){fail("wrong_audience")}if(!numeric(claims.exp)||times.some(time=>time!==void 0&&!numeric(time))){fail("malformed")}if(seconds>claims.exp+tolerance){fail("expired")}if(times.some(time=>time>seconds+tolerance)){fail("not_yet_valid")}if(checks.nonce!==void 0&&claims.nonce!==checks.nonce){fail("wrong_nonce")}if((prefix!==null||idToken)&&(typeof sub!=="string"||!sub||prefix!==null&&(!sub.startsWith(prefix)||sub.length===prefix.length))){fail("wrong_subject")}return claims};return{verify:(token,checks={})=>check(token,checks,false),async verifyIdToken(token,checks){if(typeof checks?.nonce!=="string"||!checks.nonce){throw new TypeError("verifyIdToken needs the nonce you sent with the sign-in.")}return await check(token,checks,true)}}}export{ZappieTokenError,createTokenVerifier};
2
- //# sourceMappingURL=jwt.js.map
@@ -1,2 +1 @@
1
1
  import{ZappieError}from"../../errors.js";import{openSealedValue,sealValue,secretsOf}from"./crypto.js";function cookieSessionStore(options){const maxAge=(options.maxAgeSec??30*24*60*60)*1e3;const now=options.now??Date.now;const sealing={secret:options.secret,purpose:"zappie_session"};secretsOf(options.secret);if(!(maxAge>0&&Number.isFinite(maxAge))){throw new TypeError("maxAgeSec must be a positive number of seconds.")}const refuse=message=>{throw new ZappieError("invalid_request",message)};const seal=async envelope=>{const sealed=await sealValue(envelope,sealing);return sealed.length>3800?refuse("This session is too large for a cookie. Use a session store that keeps sessions on the server."):sealed};const open=async sid=>{const envelope=await openSealedValue(sid,sealing);return envelope?.v===1&&envelope.exp>now()?envelope:null};return{create:data=>seal({v:1,exp:now()+maxAge,data}),get:async sid=>(await open(sid))?.data??null,async update(sid,patch){const envelope=await open(sid);return envelope?seal({...envelope,data:{...envelope.data,...patch}}):null},delete:async()=>void 0,deleteBySub:async()=>refuse("A cookie session store can't end sessions from the server. Use a session store that keeps sessions on the server for back-channel logout.")}}export{cookieSessionStore};
2
- //# sourceMappingURL=session-store.js.map
@@ -1,2 +1 @@
1
1
  var find=(store,wanted)=>wanted?store.branches.find(b=>b.id===wanted||b.slug===wanted):void 0;function readCookie(request,name){if(!name){return void 0}for(const part of(request.headers.get("cookie")??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name){try{return decodeURIComponent(part.slice(index+1).trim())}catch{return void 0}}}return void 0}function resolveBranch(store,request,{cookie,fallback,param="branch"}){const chosen=find(store,new URL(request.url).searchParams.get(param))??find(store,readCookie(request,cookie));const branch=chosen??find(store,fallback)??store.branches.find(b=>b.isDefault)??store.branches[0];return{branch,chosen:Boolean(chosen),mustChoose:!chosen&&store.branches.length>1}}function requestedBranch(request,{cookie,fallback,param="branch"}){return new URL(request.url).searchParams.get(param)||readCookie(request,cookie)||fallback||void 0}var ignore=()=>{};async function loadStoreAndMenu(client,request,options){const named=requestedBranch(request,options);const learned=slugs(client);const guess=named?.startsWith("br_")?named:named&&learned.get(named);const early=guess&&!client.store.peek()?client._internal.readMenu(guess,{}):void 0;early?.catch(ignore);const store=await client.store.get();for(const entry of store.branches){learned.set(entry.slug,entry.id)}const resolved=resolveBranch(store,request,options);const{branch}=resolved;if(!branch){return{store,...resolved,menu:void 0}}const menu=await(early&&branch.id===guess?early:client.menu.get({branch:branch.id}));return{store,...resolved,menu}}var learnedSlugs=new Map;function slugs(client){const{config}=client;const id=JSON.stringify([config.baseUrl??"",config.store,config.key]);let found=learnedSlugs.get(id);if(!found){if(learnedSlugs.size>=100){learnedSlugs.clear()}found=new Map;learnedSlugs.set(id,found)}return found}export{loadStoreAndMenu,requestedBranch,resolveBranch};
2
- //# sourceMappingURL=chosen-branch.js.map
@@ -1,2 +1 @@
1
1
  import{createSecurityNonce}from"./security.js";var EDGE_CACHE_HEADER="x-zappie-edge-cache";var DATA_VERSION_HEADER="x-zappie-data-version";var dataVersions=new WeakMap;function rememberDataVersion(request,ctx){const version=request.headers.get(DATA_VERSION_HEADER);if(ctx&&version){dataVersions.set(ctx,version)}}var STORED_AT="x-zappie-stored-at";var FRESH_FOR="x-zappie-fresh-for";var STALE_FOR="x-zappie-stale-for";var ORIGIN_CACHE_CONTROL="x-zappie-origin-cache-control";var CACHE_NAME="zappie";var opened;function openEdgeCache(){opened??(opened=(async()=>{try{return typeof caches==="undefined"?void 0:await caches.open(CACHE_NAME)}catch{return void 0}})());return opened}async function sha256(value){const digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(value));return[...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,"0")).join("")}function sharedFreshness(cacheControl){if(!cacheControl||/\b(?:private|no-store|no-cache)\b/i.test(cacheControl)){return void 0}const seconds=name=>{const match=new RegExp(`(?:^|[,\\s])${name}=(\\d+)`,"i").exec(cacheControl);return match?Number(match[1]):void 0};const fresh=seconds("s-maxage")??seconds("max-age")??0;if(fresh<=0){return void 0}return{fresh,stale:seconds("stale-while-revalidate")??0}}function storable(response,life,now){const headers=new Headers(response.headers);headers.delete("set-cookie");headers.delete(EDGE_CACHE_HEADER);const origin=response.headers.get("cache-control");if(origin){headers.set(ORIGIN_CACHE_CONTROL,origin)}headers.set(STORED_AT,String(now));headers.set(FRESH_FOR,String(life.fresh));headers.set(STALE_FOR,String(life.stale));headers.set("cache-control",`public, max-age=${life.fresh+life.stale}`);return new Response(response.body,{status:response.status,headers})}function served(cached,status,age){const headers=new Headers(cached.headers);const origin=headers.get(ORIGIN_CACHE_CONTROL);if(origin){headers.set("cache-control",origin)}else{headers.delete("cache-control")}for(const name of[STORED_AT,FRESH_FOR,STALE_FOR,ORIGIN_CACHE_CONTROL]){headers.delete(name)}headers.set("age",String(Math.max(0,Math.floor(age))));headers.set(EDGE_CACHE_HEADER,status);return new Response(cached.body,{status:cached.status,headers})}function discard(response){response.body?.cancel().catch(()=>{})}function marked(response,status){const out=new Response(response.body,response);out.headers.set(EDGE_CACHE_HEADER,status);return out}async function lookup(cache,key,now){const cached=await cache.match(key);if(!cached){return void 0}const storedAt=Number(cached.headers.get(STORED_AT));const life={fresh:Number(cached.headers.get(FRESH_FOR)),stale:Number(cached.headers.get(STALE_FOR))};if(!Number.isFinite(storedAt)||!Number.isFinite(life.fresh)||!Number.isFinite(life.stale)){discard(cached);return void 0}return{response:cached,age:(now-storedAt)/1e3,life}}var refreshing=new Map;function refreshOnce(ctx,key,refresh){if(refreshing.has(key.url)){return}const running=refresh().catch(()=>{}).finally(()=>refreshing.delete(key.url));refreshing.set(key.url,running);ctx.waitUntil(running)}var SHARED_READS=/\/(?:store|menus)$/;function apiCacheBypass(request){if(request.method!=="GET"){return"method"}if(!SHARED_READS.test(new URL(request.url).pathname)){return"path"}if(!/^Bearer pk_(?:test|live)_/.test(request.headers.get("authorization")??"")){return"credentials"}if(request.headers.has("cookie")){return"cookie"}if(request.headers.has("if-none-match")){return"conditional"}return void 0}async function apiCacheKey(request,dataVersion=""){const key=(request.headers.get("authorization")??"").replace(/^Bearer\s+/,"");const url=new URL(request.url);const parts=[key,request.headers.get("zappie-version")??""];const identity=await sha256(JSON.stringify(dataVersion?[...parts,dataVersion]:parts));return new Request(`https://zappie-api-cache.internal/${identity.slice(0,40)}/${url.host}${url.pathname}${url.search}`)}function cachedApiFetch(options={}){const upstream=options.fetch??((input,init)=>globalThis.fetch(input,init));const now=options.now??Date.now;const source=()=>options.cache??openEdgeCache();return async(input,init)=>{const request=new Request(input,init);if(apiCacheBypass(request)){return upstream(request)}let cache;let key;let hit;try{cache=await source();if(cache){key=await apiCacheKey(request,options.dataVersion??(options.ctx?dataVersions.get(options.ctx):void 0));hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache){return upstream(request)}const store=async response=>{const life=sharedFreshness(response.headers.get("cache-control"));if(response.status!==200||!life||response.headers.has("set-cookie")){return response}const copy=response.clone();const put=cache.put(key,storable(copy,life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return response};if(hit&&hit.age<hit.life.fresh){return served(hit.response,"HIT",hit.age)}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){const etag=hit.response.headers.get("etag");const kept=hit.response.clone();refreshOnce(options.ctx,key,async()=>{const headers=new Headers(request.headers);if(etag){headers.set("if-none-match",etag)}const response=await upstream(new Request(request.url,{method:"GET",headers,redirect:"manual"}));if(response.status===304){discard(response);const life2=sharedFreshness(response.headers.get("cache-control"))??hit.life;const restamped=served(kept,"HIT",0);restamped.headers.delete("age");restamped.headers.delete(EDGE_CACHE_HEADER);await cache.put(key,storable(restamped,life2,now()));return}const life=sharedFreshness(response.headers.get("cache-control"));if(response.status===200&&life&&!response.headers.has("set-cookie")){await cache.put(key,storable(response,life,now()))}else{discard(response)}});return served(hit.response,"STALE",hit.age)}if(hit){discard(hit.response)}return store(await upstream(request))}}var SESSION_COOKIE=/^(?:__Host-zappie_|__Host-zp_)|(?:^|[_-])(?:session|sess|sid|auth|token|jwt)(?:$|[_-])/i;function cookieNames(request){return(request.headers.get("cookie")??"").split(";").map(part=>part.slice(0,part.indexOf("=")>>>0).trim()).filter(Boolean)}function cookieValue(request,name){for(const part of(request.headers.get("cookie")??"").split(";")){const index=part.indexOf("=");if(index>0&&part.slice(0,index).trim()===name){return part.slice(index+1).trim()}}return""}function pageCacheBypass(request,options={}){if(request.method!=="GET"){return"method"}if(["x-zappie-draft","x-zappie-review","x-zappie-preview"].some(name=>request.headers.has(name))||new URL(request.url).searchParams.has("preview")){return"preview"}if(request.headers.has("x-zappie-site-state")){return"closed"}if(request.headers.has("authorization")){return"authorization"}if(request.headers.has("x-forwarded-host")||request.headers.has("forwarded")){return"forwarded"}const own=new Set(options.privateCookies??[]);if(cookieNames(request).some(name=>own.has(name)||SESSION_COOKIE.test(name))){return"session"}return void 0}async function pageCacheKey(request,options){const parts=[request.url,options.branchCookie?cookieValue(request,options.branchCookie):"",options.deployId,request.headers.get("x-zappie-site")??"",request.headers.get("x-zappie-key")??""];const version=request.headers.get(DATA_VERSION_HEADER);const identity=await sha256(JSON.stringify(version?[...parts,version]:parts));return new Request(`https://zappie-page-cache.internal/${identity}`)}function pageStoreBypass(response,fallback){if(response.status!==200){return"status"}if(response.headers.has("set-cookie")){return"set-cookie"}if(response.headers.has("x-zappie-closed-page")){return"closed"}if(/(?:^|,)\s*\*\s*(?:,|$)/.test(response.headers.get("vary")??"")){return"vary"}if(!sharedFreshness(response.headers.get("cache-control")??fallback??null)){return"cache-control"}return void 0}var NONCE=/'nonce-([A-Za-z0-9_+/=-]+)'/;var POLICY_HEADERS=["content-security-policy","content-security-policy-report-only"];async function rotatePageNonce(response,nonce=createSecurityNonce()){const old=POLICY_HEADERS.map(name=>NONCE.exec(response.headers.get(name)??"")?.[1]).find(Boolean);if(!old||!/^text\/html/i.test(response.headers.get("content-type")??"")){return response}const headers=new Headers(response.headers);for(const name of POLICY_HEADERS){const value=headers.get(name);if(value){headers.set(name,value.replaceAll(`'nonce-${old}'`,`'nonce-${nonce}'`))}}headers.delete("content-length");const body=(await response.text()).replaceAll(`nonce="${old}"`,`nonce="${nonce}"`).replaceAll(`nonce=${old}`,`nonce=${nonce}`);return new Response(body,{status:response.status,headers})}async function cachePage(request,render,options){rememberDataVersion(request,options.ctx);if(pageCacheBypass(request,options)){return marked(await render(request),"BYPASS")}const now=options.now??Date.now;let cache;let key;let hit;try{cache=await(options.cache??openEdgeCache());if(cache){key=await pageCacheKey(request,options);hit=await lookup(cache,key,now())}}catch{cache=void 0}if(!cache||!key){return marked(await render(request),"BYPASS")}const fallback=()=>options.cacheControl?.(new URL(request.url));const keep=async response=>{const control=response.headers.get("cache-control")??fallback();if(pageStoreBypass(response,control)){return void 0}const life=sharedFreshness(control??null);const shared=new Response(response.body,response);if(control&&!shared.headers.has("cache-control")){shared.headers.set("cache-control",control)}return{shared,life}};if(hit&&hit.age<hit.life.fresh){return rotatePageNonce(served(hit.response,"HIT",hit.age))}if(hit&&options.ctx&&hit.age<hit.life.fresh+hit.life.stale){refreshOnce(options.ctx,key,async()=>{const kept2=await keep(await render(new Request(request.url,{method:"GET",headers:request.headers})));if(kept2){await cache.put(key,storable(kept2.shared,kept2.life,now()))}else{await cache.delete(key)}});return rotatePageNonce(served(hit.response,"STALE",hit.age))}if(hit){discard(hit.response)}const rendered=await render(request);const kept=await keep(rendered);if(!kept){return marked(rendered,"MISS")}const put=cache.put(key,storable(kept.shared.clone(),kept.life,now())).catch(()=>{});if(options.ctx){options.ctx.waitUntil(put)}else{await put}return marked(kept.shared,"MISS")}export{DATA_VERSION_HEADER,EDGE_CACHE_HEADER,apiCacheBypass,apiCacheKey,cachePage,cachedApiFetch,openEdgeCache,pageCacheBypass,pageCacheKey,pageStoreBypass,rememberDataVersion,rotatePageNonce,sharedFreshness};
2
- //# sourceMappingURL=edge-cache.js.map
@@ -1,2 +1 @@
1
1
  import{mapMenu}from"../transport/mappers.js";var snapshotKeys={store:storeId=>`store:${storeId}`,menu:(storeId,branchId)=>branchId===void 0?`menu:${storeId}`:`menu:${storeId}:${branchId}`,availability:(storeId,branchId)=>`avail:${storeId}:${branchId}`,version:storeId=>`ver:${storeId}`};function canonical(value,seen){if(value===null||typeof value==="boolean"){return JSON.stringify(value)}if(typeof value==="string"){return JSON.stringify(value)}if(typeof value==="number"){if(!Number.isFinite(value)){throw new TypeError("Canonical JSON can't hold a non-finite number.")}return JSON.stringify(value)}if(typeof value!=="object"){throw new TypeError(`Canonical JSON can't hold a ${typeof value}.`)}if(seen.has(value)){throw new TypeError("Canonical JSON can't hold a cycle.")}seen.add(value);let out;if(Array.isArray(value)){out=`[${value.map(entry=>entry===void 0?"null":canonical(entry,seen)).join(",")}]`}else{const prototype=Object.getPrototypeOf(value);if(prototype!==Object.prototype&&prototype!==null){throw new TypeError("Canonical JSON holds plain objects only.")}out=`{${Object.keys(value).filter(key=>value[key]!==void 0).sort().map(key=>`${JSON.stringify(key)}:${canonical(value[key],seen)}`).join(",")}}`}seen.delete(value);return out}function canonicalJson(value){return canonical(value,new Set)}async function snapshotHash(value){const digest=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(canonicalJson(value)));return Array.from(new Uint8Array(digest).slice(0,8),byte=>byte.toString(16).padStart(2,"0")).join("")}var isoTime=value=>{const time=value===void 0?new Date:new Date(value);if(Number.isNaN(time.getTime())){throw new TypeError("Snapshot times must be valid dates.")}return time.toISOString()};async function createMenuSnapshot({storeId,menu,builtAt,sourceUpdatedAt}){if(!storeId||!menu.branchId||!menu.version){throw new TypeError("A menu snapshot needs a store, a branch and a menu version.")}if(menu.completeness==="partial"){throw new TypeError("A partial menu can't become a snapshot.")}return{v:1,storeId,branchId:menu.branchId,version:menu.version,contentHash:await snapshotHash(menu),builtAt:isoTime(builtAt),...sourceUpdatedAt===void 0?{}:{sourceUpdatedAt:isoTime(sourceUpdatedAt)},menu}}async function menuSnapshotFromPayload({storeId,branchId,payload,builtAt}){const menu=mapMenu(payload,branchId);const updates=(Array.isArray(payload?.menus)?payload.menus:[]).map(source=>source?.updated_at).filter(value=>typeof value==="string"&&!Number.isNaN(Date.parse(value))).sort((left,right)=>Date.parse(right)-Date.parse(left));return createMenuSnapshot({storeId,menu,...builtAt===void 0?{}:{builtAt},...updates[0]===void 0?{}:{sourceUpdatedAt:updates[0]}})}async function createStoreSnapshot({store,builtAt}){if(!store.id){throw new TypeError("A store snapshot needs a store id.")}return{v:1,storeId:store.id,contentHash:await snapshotHash(store),builtAt:isoTime(builtAt),store}}var ids=values=>[...new Set(values??[])].sort();async function createAvailabilityPatch(input){if(!input.menuVersion){throw new TypeError("An availability patch needs the API's menu version.")}const content={v:1,menuVersion:input.menuVersion,soldOutItems:ids(input.soldOutItems),soldOutVariants:ids(input.soldOutVariants),soldOutOptions:ids(input.soldOutOptions),...input.closedUntil===void 0?{}:{closedUntil:isoTime(input.closedUntil)}};return{...content,version:await snapshotHash(content),updatedAt:isoTime(input.updatedAt)}}function applyAvailability(snapshot,patch){if(!patch||Date.parse(patch.updatedAt)<Date.parse(snapshot.builtAt)){return snapshot.menu}const items=new Set(patch.soldOutItems);const variants=new Set(patch.soldOutVariants);const options=new Set(patch.soldOutOptions);return{...snapshot.menu,version:patch.menuVersion,items:Object.fromEntries(Object.entries(snapshot.menu.items).map(([id,item])=>{const touched=item.variants.some(variant=>variants.has(variant.id));const patched=item.variants.map(variant=>variants.has(variant.id)?{...variant,isAvailable:false}:variant);return[id,{...item,isAvailable:item.isAvailable&&!items.has(id)&&(!touched||patched.some(variant=>variant.isAvailable)),variants:patched,optionGroups:item.optionGroups.map(group=>({...group,choices:group.choices.map(choice=>options.has(choice.id)?{...choice,isAvailable:false}:choice)}))}]}))}}function isMenuSnapshot(value){if(!value||typeof value!=="object"){return false}const snapshot=value;const menu=snapshot.menu;return snapshot.v===1&&typeof snapshot.storeId==="string"&&typeof snapshot.branchId==="string"&&typeof snapshot.version==="string"&&typeof snapshot.contentHash==="string"&&typeof snapshot.builtAt==="string"&&!!menu&&typeof menu==="object"&&menu.branchId===snapshot.branchId&&menu.version===snapshot.version&&menu.completeness!=="partial"&&Array.isArray(menu.categories)&&!!menu.items&&typeof menu.items==="object"}export{applyAvailability,canonicalJson,createAvailabilityPatch,createMenuSnapshot,createStoreSnapshot,isMenuSnapshot,menuSnapshotFromPayload,snapshotHash,snapshotKeys};
2
- //# sourceMappingURL=edge-snapshot.js.map