@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.
- package/CHANGELOG.md +18 -0
- package/dist/account/index.d.ts +16 -2
- package/dist/account/index.js +0 -1
- package/dist/account/url.js +0 -1
- package/dist/branches/index.d.ts +2 -0
- package/dist/branches/index.js +0 -1
- package/dist/cart/branch.d.ts +18 -0
- package/dist/cart/branch.js +0 -1
- package/dist/cart/errors.js +0 -1
- package/dist/cart/held.js +0 -1
- package/dist/cart/index.js +1 -2
- package/dist/cart/item.d.ts +1 -1
- package/dist/cart/item.js +0 -1
- package/dist/cart/preview.js +0 -1
- package/dist/cart/price.js +0 -1
- package/dist/cart/quote-client.js +0 -1
- package/dist/cart/quote-response.js +1 -2
- package/dist/cart/quote.d.ts +1 -1
- package/dist/cart/reconcile.js +0 -1
- package/dist/cart/source-menu.js +0 -1
- package/dist/cart/storage.js +0 -1
- package/dist/cart/types.js +0 -1
- package/dist/cart/validate.js +0 -1
- package/dist/cart/wire.js +0 -1
- package/dist/cart/working-set.js +0 -1
- package/dist/checkout/client.js +0 -1
- package/dist/checkout/embed.d.ts +67 -2
- package/dist/checkout/embed.js +0 -1
- package/dist/checkout/error.js +0 -1
- package/dist/checkout/index.d.ts +74 -3
- package/dist/checkout/index.js +0 -1
- package/dist/checkout/react.d.ts +67 -2
- package/dist/checkout/react.js +0 -1
- package/dist/checkout/readiness.js +0 -1
- package/dist/checkout/sdk.js +0 -1
- package/dist/checkout/session.js +0 -1
- package/dist/checkout/types.js +0 -1
- package/dist/checkout-defaults/index.d.ts +10 -1
- package/dist/checkout-defaults/index.js +0 -1
- package/dist/{client-B89-aNcl.d.ts → client-CW_OWZ0l.d.ts} +229 -5
- package/dist/client.js +0 -1
- package/dist/config/index.d.ts +38 -3
- package/dist/config/index.js +0 -1
- package/dist/config.js +0 -1
- package/dist/customer/client.js +0 -1
- package/dist/customer/error.js +0 -1
- package/dist/customer/index.d.ts +180 -5
- package/dist/customer/index.js +0 -1
- package/dist/customer/navigation.js +0 -1
- package/dist/customer/react.js +0 -1
- package/dist/customer/reorder.d.ts +8 -0
- package/dist/customer/reorder.js +0 -1
- package/dist/customer/request.js +0 -1
- package/dist/customer/types.js +0 -1
- package/dist/customer/watch-order.js +0 -1
- package/dist/debug.js +1 -2
- package/dist/display/index.d.ts +5 -1
- package/dist/display/index.js +0 -1
- package/dist/error-pages/art.js +0 -1
- package/dist/error-pages/index.d.ts +12 -1
- package/dist/error-pages/index.js +0 -1
- package/dist/error-pages/react.js +0 -1
- package/dist/errors.js +1 -2
- package/dist/in-venue/bill.js +0 -1
- package/dist/in-venue/client.js +0 -1
- package/dist/in-venue/error.js +0 -1
- package/dist/in-venue/index.d.ts +110 -2
- package/dist/in-venue/index.js +0 -1
- package/dist/in-venue/react/bill-page.js +0 -1
- package/dist/in-venue/react/in-venue-page.js +0 -1
- package/dist/in-venue/react/order-panel.js +0 -1
- package/dist/in-venue/react/pay-point-page.js +0 -1
- package/dist/in-venue/react/shared.js +0 -1
- package/dist/in-venue/react/table-menus-page.js +0 -1
- package/dist/in-venue/react.js +0 -1
- package/dist/in-venue/table.js +0 -1
- package/dist/in-venue/types.js +0 -1
- package/dist/in-venue/watch.js +0 -1
- package/dist/index.d.ts +32 -8
- package/dist/index.js +1 -2
- package/dist/integrations/index.d.ts +15 -2
- package/dist/integrations/index.js +0 -1
- package/dist/internal/abort.js +0 -1
- package/dist/internal/cache.js +0 -1
- package/dist/internal/customer-http.js +1 -2
- package/dist/internal/emitter.js +0 -1
- package/dist/internal/image-widths.js +0 -1
- package/dist/internal/money-math.js +0 -1
- package/dist/internal/perk-hold.js +0 -1
- package/dist/internal/remembered-address.js +0 -1
- package/dist/internal/return-path.js +0 -1
- package/dist/internal/service-url.js +0 -1
- package/dist/internal.d.ts +2 -2
- package/dist/internal.js +0 -1
- package/dist/loyalty/cart.js +0 -1
- package/dist/loyalty/client.js +0 -1
- package/dist/loyalty/index.d.ts +410 -2
- package/dist/loyalty/index.js +0 -1
- package/dist/loyalty/react.d.ts +15 -1
- package/dist/loyalty/react.js +0 -1
- package/dist/loyalty/release.js +0 -1
- package/dist/loyalty/types.js +0 -1
- package/dist/menu/index.d.ts +5 -1
- package/dist/menu/index.js +0 -1
- package/dist/models-C77LjkK8.d.ts +540 -0
- package/dist/models.js +0 -1
- package/dist/money.js +0 -1
- package/dist/navigation/index.d.ts +8 -0
- package/dist/navigation/index.js +0 -1
- package/dist/navigation/react.js +0 -1
- package/dist/navigation-progress/index.js +0 -1
- package/dist/options/index.d.ts +5 -1
- package/dist/options/index.js +0 -1
- package/dist/persist/catalogue.d.ts +3 -3
- package/dist/persist/catalogue.js +0 -1
- package/dist/places/client.js +0 -1
- package/dist/places/error.js +0 -1
- package/dist/places/index.d.ts +41 -1
- package/dist/places/index.js +0 -1
- package/dist/places/request.js +0 -1
- package/dist/places/sdk.js +0 -1
- package/dist/places/search.js +0 -1
- package/dist/places/types.js +0 -1
- package/dist/pricing/index.js +0 -1
- package/dist/react/cart.js +0 -1
- package/dist/react/changes.js +0 -1
- package/dist/react/hooks.js +0 -1
- package/dist/react/index.js +0 -1
- package/dist/react/provider.js +0 -1
- package/dist/react/rollback.js +0 -1
- package/dist/receipts/index.js +1 -2
- package/dist/redirect/index.js +0 -1
- package/dist/rich-text/index.d.ts +4 -0
- package/dist/rich-text/index.js +0 -1
- package/dist/server/auth/crypto.js +0 -1
- package/dist/server/auth/jwt.js +0 -1
- package/dist/server/auth/session-store.js +0 -1
- package/dist/server/chosen-branch.js +0 -1
- package/dist/server/edge-cache.js +0 -1
- package/dist/server/edge-snapshot.js +0 -1
- package/dist/server/index.d.ts +179 -8
- package/dist/server/index.js +0 -1
- package/dist/server/legacy-order.js +0 -1
- package/dist/server/page-cache.js +0 -1
- package/dist/server/security.js +0 -1
- package/dist/server/sign-in.js +0 -1
- package/dist/server/site-seo.js +0 -1
- package/dist/server/site-worker.js +0 -1
- package/dist/server/storefront-url/build-v1.js +0 -1
- package/dist/server/storefront-url/build-v2.js +0 -1
- package/dist/server/storefront-url/build.js +0 -1
- package/dist/server/storefront-url/canonical.js +0 -1
- package/dist/server/storefront-url/contract.js +0 -1
- package/dist/server/storefront-url/index.js +0 -1
- package/dist/server/storefront-url/installation.js +0 -1
- package/dist/server/storefront-url/params.js +0 -1
- package/dist/server/storefront-url/parse-v1.js +0 -1
- package/dist/server/storefront-url/parse-v2.js +0 -1
- package/dist/server/storefront-url/parse.js +0 -1
- package/dist/server/storefront-url/public-id.js +0 -1
- package/dist/server/storefront-url/redirect.js +0 -1
- package/dist/server/storefront-url/sign-in.js +0 -1
- package/dist/server/storefront-url/types.js +0 -1
- package/dist/server/storefront-url/url.js +0 -1
- package/dist/server/webhook.js +0 -1
- package/dist/services/index.d.ts +5 -1
- package/dist/services/index.js +0 -1
- package/dist/site-closed/index.d.ts +3 -0
- package/dist/site-closed/index.js +0 -1
- package/dist/site-config/helpers.js +0 -1
- package/dist/site-config/sections.js +0 -1
- package/dist/site-config/types.js +0 -1
- package/dist/site-config/validate.js +0 -1
- package/dist/site-error/index.d.ts +9 -1
- package/dist/site-error/index.js +0 -1
- package/dist/site-error/react.js +0 -1
- package/dist/studio/index.d.ts +2 -0
- package/dist/template/index.d.ts +7 -1
- package/dist/template/index.js +0 -1
- package/dist/template/react.js +0 -1
- package/dist/testing/index.d.ts +28 -1
- package/dist/testing/index.js +1 -1
- package/dist/testing/loyalty.js +0 -1
- package/dist/transport/category-page.js +0 -1
- package/dist/transport/mappers.js +0 -1
- package/dist/transport/presentation.js +0 -1
- package/dist/transport/quote-body.js +0 -1
- package/dist/transport/rest.js +0 -1
- package/dist/transport/search.d.ts +1 -1
- package/dist/transport/search.js +0 -1
- package/dist/transport/selected-menu.d.ts +3 -3
- package/dist/transport/selected-menu.js +0 -1
- package/dist/transport/store.js +0 -1
- package/dist/transport/types.js +0 -1
- package/dist/types-CuPaBf6k.d.ts +838 -0
- package/dist/uploads/index.js +0 -1
- package/dist/url/index.d.ts +31 -0
- package/dist/url/index.js +0 -1
- package/dist/visits/index.d.ts +26 -1
- package/dist/visits/index.js +0 -1
- package/dist/visits/page-views.js +0 -1
- package/dist/vite/index.d.ts +2 -0
- package/package.json +2 -2
- package/dist/account/index.js.map +0 -6
- package/dist/account/url.js.map +0 -6
- package/dist/branches/index.js.map +0 -6
- package/dist/cart/branch.js.map +0 -6
- package/dist/cart/errors.js.map +0 -6
- package/dist/cart/held.js.map +0 -6
- package/dist/cart/index.js.map +0 -6
- package/dist/cart/item.js.map +0 -6
- package/dist/cart/preview.js.map +0 -6
- package/dist/cart/price.js.map +0 -6
- package/dist/cart/quote-client.js.map +0 -6
- package/dist/cart/quote-response.js.map +0 -6
- package/dist/cart/reconcile.js.map +0 -6
- package/dist/cart/source-menu.js.map +0 -6
- package/dist/cart/storage.js.map +0 -6
- package/dist/cart/types.js.map +0 -6
- package/dist/cart/validate.js.map +0 -6
- package/dist/cart/wire.js.map +0 -6
- package/dist/cart/working-set.js.map +0 -6
- package/dist/checkout/client.js.map +0 -6
- package/dist/checkout/embed.js.map +0 -6
- package/dist/checkout/error.js.map +0 -6
- package/dist/checkout/index.js.map +0 -6
- package/dist/checkout/react.js.map +0 -6
- package/dist/checkout/readiness.js.map +0 -6
- package/dist/checkout/sdk.js.map +0 -6
- package/dist/checkout/session.js.map +0 -6
- package/dist/checkout/types.js.map +0 -6
- package/dist/checkout-defaults/index.js.map +0 -6
- package/dist/client.js.map +0 -6
- package/dist/config/index.js.map +0 -6
- package/dist/config.js.map +0 -6
- package/dist/customer/client.js.map +0 -6
- package/dist/customer/error.js.map +0 -6
- package/dist/customer/index.js.map +0 -6
- package/dist/customer/navigation.js.map +0 -6
- package/dist/customer/react.js.map +0 -6
- package/dist/customer/reorder.js.map +0 -6
- package/dist/customer/request.js.map +0 -6
- package/dist/customer/types.js.map +0 -6
- package/dist/customer/watch-order.js.map +0 -6
- package/dist/debug.js.map +0 -6
- package/dist/display/index.js.map +0 -6
- package/dist/error-pages/art.js.map +0 -6
- package/dist/error-pages/index.js.map +0 -6
- package/dist/error-pages/react.js.map +0 -6
- package/dist/errors.js.map +0 -6
- package/dist/in-venue/bill.js.map +0 -6
- package/dist/in-venue/client.js.map +0 -6
- package/dist/in-venue/error.js.map +0 -6
- package/dist/in-venue/index.js.map +0 -6
- package/dist/in-venue/react/bill-page.js.map +0 -6
- package/dist/in-venue/react/in-venue-page.js.map +0 -6
- package/dist/in-venue/react/order-panel.js.map +0 -6
- package/dist/in-venue/react/pay-point-page.js.map +0 -6
- package/dist/in-venue/react/shared.js.map +0 -6
- package/dist/in-venue/react/table-menus-page.js.map +0 -6
- package/dist/in-venue/react.js.map +0 -6
- package/dist/in-venue/table.js.map +0 -6
- package/dist/in-venue/types.js.map +0 -6
- package/dist/in-venue/watch.js.map +0 -6
- package/dist/index.js.map +0 -6
- package/dist/integrations/index.js.map +0 -6
- package/dist/internal/abort.js.map +0 -6
- package/dist/internal/cache.js.map +0 -6
- package/dist/internal/customer-http.js.map +0 -6
- package/dist/internal/emitter.js.map +0 -6
- package/dist/internal/image-widths.js.map +0 -6
- package/dist/internal/money-math.js.map +0 -6
- package/dist/internal/perk-hold.js.map +0 -6
- package/dist/internal/remembered-address.js.map +0 -6
- package/dist/internal/return-path.js.map +0 -6
- package/dist/internal/service-url.js.map +0 -6
- package/dist/internal.js.map +0 -6
- package/dist/loyalty/cart.js.map +0 -6
- package/dist/loyalty/client.js.map +0 -6
- package/dist/loyalty/index.js.map +0 -6
- package/dist/loyalty/react.js.map +0 -6
- package/dist/loyalty/release.js.map +0 -6
- package/dist/loyalty/types.js.map +0 -6
- package/dist/menu/index.js.map +0 -6
- package/dist/models-DLGs3UI2.d.ts +0 -307
- package/dist/models.js.map +0 -6
- package/dist/money.js.map +0 -6
- package/dist/navigation/index.js.map +0 -6
- package/dist/navigation/react.js.map +0 -6
- package/dist/navigation-progress/index.js.map +0 -6
- package/dist/options/index.js.map +0 -6
- package/dist/persist/catalogue.js.map +0 -6
- package/dist/places/client.js.map +0 -6
- package/dist/places/error.js.map +0 -6
- package/dist/places/index.js.map +0 -6
- package/dist/places/request.js.map +0 -6
- package/dist/places/sdk.js.map +0 -6
- package/dist/places/search.js.map +0 -6
- package/dist/places/types.js.map +0 -6
- package/dist/pricing/index.js.map +0 -6
- package/dist/react/cart.js.map +0 -6
- package/dist/react/changes.js.map +0 -6
- package/dist/react/hooks.js.map +0 -6
- package/dist/react/index.js.map +0 -6
- package/dist/react/provider.js.map +0 -6
- package/dist/react/rollback.js.map +0 -6
- package/dist/receipts/index.js.map +0 -6
- package/dist/redirect/index.js.map +0 -6
- package/dist/rich-text/index.js.map +0 -6
- package/dist/server/auth/crypto.js.map +0 -6
- package/dist/server/auth/jwt.js.map +0 -6
- package/dist/server/auth/session-store.js.map +0 -6
- package/dist/server/chosen-branch.js.map +0 -6
- package/dist/server/edge-cache.js.map +0 -6
- package/dist/server/edge-snapshot.js.map +0 -6
- package/dist/server/index.js.map +0 -6
- package/dist/server/legacy-order.js.map +0 -6
- package/dist/server/page-cache.js.map +0 -6
- package/dist/server/security.js.map +0 -6
- package/dist/server/sign-in.js.map +0 -6
- package/dist/server/site-seo.js.map +0 -6
- package/dist/server/site-worker.js.map +0 -6
- package/dist/server/storefront-url/build-v1.js.map +0 -6
- package/dist/server/storefront-url/build-v2.js.map +0 -6
- package/dist/server/storefront-url/build.js.map +0 -6
- package/dist/server/storefront-url/canonical.js.map +0 -6
- package/dist/server/storefront-url/contract.js.map +0 -6
- package/dist/server/storefront-url/index.js.map +0 -6
- package/dist/server/storefront-url/installation.js.map +0 -6
- package/dist/server/storefront-url/params.js.map +0 -6
- package/dist/server/storefront-url/parse-v1.js.map +0 -6
- package/dist/server/storefront-url/parse-v2.js.map +0 -6
- package/dist/server/storefront-url/parse.js.map +0 -6
- package/dist/server/storefront-url/public-id.js.map +0 -6
- package/dist/server/storefront-url/redirect.js.map +0 -6
- package/dist/server/storefront-url/sign-in.js.map +0 -6
- package/dist/server/storefront-url/types.js.map +0 -6
- package/dist/server/storefront-url/url.js.map +0 -6
- package/dist/server/webhook.js.map +0 -6
- package/dist/services/index.js.map +0 -6
- package/dist/site-closed/index.js.map +0 -6
- package/dist/site-config/helpers.js.map +0 -6
- package/dist/site-config/sections.js.map +0 -6
- package/dist/site-config/types.js.map +0 -6
- package/dist/site-config/validate.js.map +0 -6
- package/dist/site-error/index.js.map +0 -6
- package/dist/site-error/react.js.map +0 -6
- package/dist/template/index.js.map +0 -6
- package/dist/template/react.js.map +0 -6
- package/dist/testing/loyalty.js.map +0 -6
- package/dist/transport/category-page.js.map +0 -6
- package/dist/transport/mappers.js.map +0 -6
- package/dist/transport/presentation.js.map +0 -6
- package/dist/transport/quote-body.js.map +0 -6
- package/dist/transport/rest.js.map +0 -6
- package/dist/transport/search.js.map +0 -6
- package/dist/transport/selected-menu.js.map +0 -6
- package/dist/transport/store.js.map +0 -6
- package/dist/transport/types.js.map +0 -6
- package/dist/types-8HB4-7D9.d.ts +0 -457
- package/dist/uploads/index.js.map +0 -6
- package/dist/url/index.js.map +0 -6
- package/dist/visits/index.js.map +0 -6
- package/dist/visits/page-views.js.map +0 -6
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
# @zappie/sdk
|
|
2
2
|
|
|
3
|
+
## 0.29.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 529f284: Verify's hint for an error a check has no code for now says what such a failure means and where to look: the report's message, the check's screenshot and `verify.trace.zip` in the artifacts folder. A check that is not released yet says so and that verify skips it, and the reset step no longer names an internal plan. Each eslint-plugin-zappie option now describes itself in its schema, with its default, and the rule docs end without a semicolon. The SDK's budget docs give each budget's unit, in KiB, and its default. The SDK and verify call the store's identifier the business tag, as the dashboard does, and the starter README's verify example uses the real storefront API address.
|
|
8
|
+
|
|
9
|
+
## 0.29.0
|
|
10
|
+
|
|
11
|
+
### Minor Changes
|
|
12
|
+
|
|
13
|
+
- 6c550cd: The quote now carries the API's `fill_field` fix as `{ action: "fill_field", field }`. `useCheckoutFlow`'s `fix` opens the contact step at that field, and the kit checkout page offers no button for it. A quote issue takes its option group from the API's `data.group_id` into `groupId`, so a problem the cart and the quote both report shows once. A quote whose checkout reason is newer than the SDK is read without that reason instead of failing. `WireIssue` loses `group_id`, which the API never sent.
|
|
14
|
+
- 61d813f: An API error code this SDK doesn't know yet no longer becomes `server_error`. The error takes the code its HTTP status names, such as `invalid_request` for a 4xx, and keeps the API's own code in the new `apiCode` field on every `ZappieError`. A customer, checkout, places, in-venue or loyalty request refused with a 409 or another unnamed 4xx is now `invalid_request`, not `server_error`. The error message no longer starts with the API's code.
|
|
15
|
+
|
|
16
|
+
### Patch Changes
|
|
17
|
+
|
|
18
|
+
- f9cc0ca: Ship no `.js.map` files. They held no source, so they only made the download bigger. Type declarations and their TSDoc still ship, so editor hovers are unchanged.
|
|
19
|
+
- c7a941b: Document every member of the public types and the meaning of every value of their string unions.
|
|
20
|
+
|
|
3
21
|
## 0.28.2
|
|
4
22
|
|
|
5
23
|
### Patch Changes
|
package/dist/account/index.d.ts
CHANGED
|
@@ -1,8 +1,22 @@
|
|
|
1
1
|
/** The Zappie environment a service URL points at. */
|
|
2
|
-
type ZappieEnvironment =
|
|
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
|
/** A page on the Zappie accounts portal. */
|
|
5
|
-
type AccountsPage =
|
|
9
|
+
type AccountsPage =
|
|
10
|
+
/** The portal's home page. */
|
|
11
|
+
"/account"
|
|
12
|
+
/** Where the shopper changes their name or email. */
|
|
13
|
+
| "/account/profile"
|
|
14
|
+
/** Where the shopper adds a payout account. */
|
|
15
|
+
| "/account/payouts"
|
|
16
|
+
/** Where the shopper withdraws from their wallet. */
|
|
17
|
+
| "/account/withdraw"
|
|
18
|
+
/** Where the shopper sees all their activity. */
|
|
19
|
+
| "/account/activity";
|
|
6
20
|
/**
|
|
7
21
|
* Build a link to a page on the Zappie accounts portal, where the shopper changes their name or
|
|
8
22
|
* email, adds a payout account, withdraws from their wallet or sees all their activity. The portal
|
package/dist/account/index.js
CHANGED
package/dist/account/url.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{serviceUrl}from"../internal/service-url.js";var ACCOUNTS={production:"https://accounts.zappie.ai",staging:"https://accounts.stg.zappie.ai"};function accountsUrl(path,environment="production",options={}){const url=new URL(serviceUrl(ACCOUNTS,path,environment));if(options.returnTo!==void 0){const back=new URL(options.returnTo,typeof location==="undefined"?void 0:location.href);if(back.protocol!=="https:"&&back.protocol!=="http:"){throw new TypeError("Pass an http or https page to return to")}url.searchParams.set("return",back.href)}return url.href}export{accountsUrl};
|
|
2
|
-
//# sourceMappingURL=url.js.map
|
package/dist/branches/index.d.ts
CHANGED
|
@@ -4,7 +4,9 @@ import { SavedAddress } from '@zappie/sdk/customer';
|
|
|
4
4
|
|
|
5
5
|
/** A point on the map, in degrees. */
|
|
6
6
|
type Coordinates = {
|
|
7
|
+
/** Latitude, from -90 to 90. */
|
|
7
8
|
lat: number;
|
|
9
|
+
/** Longitude, from -180 to 180. */
|
|
8
10
|
lng: number;
|
|
9
11
|
};
|
|
10
12
|
/** A branch with a location on file. */
|
package/dist/branches/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{defaultAddress}from"@zappie/sdk/checkout-defaults";function isCoordinates(value){return!!value&&Number.isFinite(value.lat)&&Number.isFinite(value.lng)&&Math.abs(value.lat)<=90&&Math.abs(value.lng)<=180}function locatedBranches(branches){return branches.filter(branch=>isCoordinates(branch.coordinates)&&(branch.coordinates.lat!==0||branch.coordinates.lng!==0))}function distanceKm(from,to){const radians=degrees=>degrees*Math.PI/180;const dLat=radians(to.lat-from.lat);const dLng=radians(to.lng-from.lng);const a=Math.sin(dLat/2)**2+Math.cos(radians(from.lat))*Math.cos(radians(to.lat))*Math.sin(dLng/2)**2;return 6371*2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a))}function sortBranchesByDistance(branches,from){if(!isCoordinates(from)){return[]}return locatedBranches(branches).map(branch=>({...branch,distanceKm:distanceKm(from,branch.coordinates)})).sort((a,b)=>a.distanceKm-b.distanceKm)}function nearestBranch(branches,from){return sortBranchesByDistance(branches,from)[0]}function startingLocation(options={}){const start=defaultAddress({...options,feeType:"fixed"});return isCoordinates(start?.coordinates)?start:void 0}export{distanceKm,isCoordinates,locatedBranches,nearestBranch,sortBranchesByDistance,startingLocation};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
package/dist/cart/branch.d.ts
CHANGED
|
@@ -3,19 +3,37 @@ import { Money, Item, Menu } from '../index.js';
|
|
|
3
3
|
|
|
4
4
|
/** A line that can move to the destination branch, with its old and new estimates. */
|
|
5
5
|
type BranchSwitchKeptLine = {
|
|
6
|
+
/** The line as it would be at the destination, with that branch's menu and price. */
|
|
6
7
|
line: CartLine;
|
|
8
|
+
/**
|
|
9
|
+
* The item's name from the current menu, or from the destination when the current one lacks
|
|
10
|
+
* it.
|
|
11
|
+
*/
|
|
7
12
|
name: string;
|
|
13
|
+
/**
|
|
14
|
+
* The line's estimate at the current branch, or the same as `after` when the current menu
|
|
15
|
+
* lacks the item.
|
|
16
|
+
*/
|
|
8
17
|
before: Money;
|
|
18
|
+
/** The line's estimate at the destination branch. */
|
|
9
19
|
after: Money;
|
|
10
20
|
};
|
|
11
21
|
/** The lines that can and cannot move to another branch, with the new subtotal. */
|
|
12
22
|
type BranchSwitchPlan = {
|
|
23
|
+
/** The lines the destination sells, with their old and new estimates. */
|
|
13
24
|
kept: BranchSwitchKeptLine[];
|
|
25
|
+
/**
|
|
26
|
+
* The lines the destination can't sell, because the item, its variant or a choice is
|
|
27
|
+
* unavailable there, or no menu there lists it. `name` is the item's name, or "An item" when
|
|
28
|
+
* neither menu has it.
|
|
29
|
+
*/
|
|
14
30
|
dropped: {
|
|
15
31
|
line: CartLine;
|
|
16
32
|
name: string;
|
|
17
33
|
}[];
|
|
34
|
+
/** The kept lines as they would be at the destination, in cart order. */
|
|
18
35
|
lines: CartLine[];
|
|
36
|
+
/** The sum of the kept lines' new estimates. Null when no line is kept. */
|
|
19
37
|
subtotal: Money | null;
|
|
20
38
|
};
|
|
21
39
|
/** Estimate a cart line from its exact variant and selected choices. */
|
package/dist/cart/branch.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{estimateUnitPrice,money}from"@zappie/sdk";function estimateLine(line,item){const unit=estimateUnitPrice(item,line);return money(unit.amountMinor*line.quantity,unit.currency)}function destinationMenu(menu,line){const categories=menu.categories.filter(category=>category.itemIds.includes(line.itemId));const sources=menu.menus??[{id:menu.id,categoryIds:menu.categories.map(category=>category.id)}];const placements=menu.items[line.itemId]?.placements;const candidates=sources.filter(source=>(!placements||placements.some(placement=>placement.menuId===source.id&&source.categoryIds.includes(placement.categoryId)))&&source.categoryIds.some(id=>categories.some(category=>category.id===id)));return(candidates.find(candidate=>candidate.id===line.menuId)??candidates[0])?.id}function sells(line,item){if(!item?.isAvailable){return false}if(line.variantId&&!item.variants.some(variant=>variant.id===line.variantId&&variant.isAvailable)){return false}return line.choices.every(selected=>item.optionGroups.some(group=>group.id===selected.groupId&&group.choices.some(choice=>choice.id===selected.choiceId&&choice.isAvailable)))}function planBranchSwitch(lines,from,to){const plan={kept:[],dropped:[],lines:[],subtotal:null};for(const line of lines){const before=from.items[line.itemId];const after=to.items[line.itemId];const name=before?.name??after?.name??"An item";const menuId=destinationMenu(to,line);if(!sells(line,after)||!menuId){plan.dropped.push({line,name});continue}const unitPrice=estimateUnitPrice(after,line);const next=money(unitPrice.amountMinor*line.quantity,unitPrice.currency);const moved={...line,menuId,unitPrice,lineSubtotal:next};const previous=before?estimateLine(line,before):next;plan.kept.push({line:moved,name,before:previous,after:next});plan.lines.push(moved);plan.subtotal=money((plan.subtotal?.amountMinor??0)+next.amountMinor,next.currency)}return plan}export{estimateLine,planBranchSwitch};
|
|
2
|
-
//# sourceMappingURL=branch.js.map
|
package/dist/cart/errors.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{ZappieError}from"../errors.js";var ZappieCartError=class extends ZappieError{constructor(issues){super("cart_invalid",issues[0]?.message??"The cart needs attention");this.issues=issues;this.name="ZappieCartError"}};export{ZappieCartError};
|
|
2
|
-
//# sourceMappingURL=errors.js.map
|
package/dist/cart/held.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
function holdsForLater(issue){return issue.fixes.some(fix=>fix.action==="schedule")}function isHeldQuote(quote){return Boolean(quote?.lines.some(line=>line.status==="invalid"&"e.issues.some(issue=>issue.lineId===line.lineId&&holdsForLater(issue))))}export{holdsForLater,isHeldQuote};
|
|
2
|
-
//# sourceMappingURL=held.js.map
|
package/dist/cart/index.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{asError,ZappieError}from"../errors.js";import{multiplyMoney,sumMoney}from"../internal/money-math.js";import{money}from"../money.js";import{ZappieCartError}from"./errors.js";import{estimateUnitPrice}from"./price.js";import{freezeLine,lineInput,reconcile}from"./reconcile.js";import{withDefaultMenu}from"./source-menu.js";import{createCartStorage,parseCart,validFulfilment}from"./storage.js";import{issue,normalizeInput,resolveVariant,validateLine}from"./validate.js";import{wireFulfilment,wireLine}from"./wire.js";var EMPTY_CART=deepFreeze({branchId:void 0,lines:[],count:0,subtotal:null,fulfilment:null,promoCode:null,perks:[],state:{status:"ready"},issues:[],isHydrated:false});function deepFreeze(value){if(value&&typeof value==="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const child of Object.values(value)){deepFreeze(child)}}return value}function identity(input){return JSON.stringify([input.itemId,input.menuId,input.variantId,input.note??"",[...input.choices??[]].sort((a,b)=>a.groupId.localeCompare(b.groupId)||a.choiceId.localeCompare(b.choiceId)),Object.entries(input.inputs??{}).sort(([a],[b])=>a.localeCompare(b))])}function createCart(deps){const{config,menu:menus,store,events}=deps;const ttl=config.cart?.ttl??7*24*60*60*1e3;if(!Number.isFinite(ttl)||ttl<=0){throw new ZappieError("invalid_request","Cart ttl must be positive milliseconds")}let snapshot=EMPTY_CART;let menu;let branch;let selected=config.branch;let updatedAt=0;let timer;let revision=0;let quoteRevision=0;let moveSequence=0;let refreshSequence=0;let chased;let chasedAt=0;let mounted=0;let detach;let hydration;let lifecycle=0;let legacy;const listeners=new Set;const prefix=`zappie:cart:v1:${config.store}:`;const scope=config.cart?.storageScope;const keyFor=id=>`${prefix}${id}${scope?`:${scope}`:""}`;const key=()=>keyFor(branch.id);const storage=createCartStorage(config.storage,message=>events.emit("warning",{message}));const readSaved=id=>{let raw=storage.read(keyFor(id));if(raw===null&&scope){raw=storage.read(prefix+id);if(raw!==null){storage.remove(prefix+id);storage.write(keyFor(id),raw)}}return raw};let quotes;let loadingQuotes;const quoteClient=()=>loadingQuotes??(loadingQuotes=import("./quote-client.js").then(({createQuoteClient})=>quotes=createQuoteClient(deps.transport,deps.context,config),error=>{loadingQuotes=void 0;throw error}));const publish=patch=>{snapshot=deepFreeze({...snapshot,...patch,branchId:branch?.id});for(const fn of[...listeners]){try{fn()}catch(error){events.emit("error",{error:asError(error)})}}};const attention=(issues,quote)=>issues.some(i=>i.severity!=="info")?{status:"needs_attention",issues,...quote?{quote}:{}}:quote?{status:"quoted",quote}:{status:"ready"};const cancel=()=>{revision++;quoteRevision++;clearTimeout(timer);quotes?.cancel()};let customer=null;let planned=null;const wire=()=>({lines:snapshot.lines.map(wireLine),...customer?{customer}:{},...snapshot.promoCode?{promo_code:snapshot.promoCode}:{},...snapshot.perks.length&&snapshot.fulfilment?.type!="dine_in"?{perk_redemption_ids:snapshot.perks.map(p=>p.redemptionId)}:{},menu_version:menu.version});const persist=()=>{const value={v:1,lines:snapshot.lines.map(line=>({...lineInput(line),id:line.id,name:line.name,addedAt:line.addedAt,unitPrice:line.unitPrice})),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,perks:snapshot.perks,menuVersion:menu.version,updatedAt};storage.write(key(),JSON.stringify(value))};const schedule=()=>{clearTimeout(timer);if(snapshot.lines.length){timer=setTimeout(()=>{void cart.quote().catch(()=>{})},300)}};const resume=()=>{if(!("quote"in snapshot.state)){schedule()}};const recompute=(lines,pending=snapshot.issues.filter(i=>i.source==="local"),patch={})=>{const currency=store.peek().currency;const result=reconcile(lines,menu,branch,currency,pending);const subtotal=result.priced?sumMoney(result.lines.map(l=>l.lineSubtotal),money(0,currency)):null;publish({...patch,lines:result.lines,count:result.lines.reduce((n,l)=>n+l.quantity,0),subtotal,issues:result.issues,state:attention(result.issues)});for(const i of result.issues){events.emit("cart_issue",{code:i.code})}};const changed=(lines=snapshot.lines,patch={})=>{cancel();recompute(lines,void 0,patch);updatedAt=Date.now();persist();schedule()};const choose=value=>{const found=store.peek()?.branches.find(b=>b.id===value.branchId);if(!found){throw new ZappieError("branch_not_found","Load the storefront branch before using its cart")}menu=value;branch=found;selected=found.id};const load=(raw,writeBack=true)=>{cancel();let saved;try{saved=raw?parseCart(raw):void 0;if(saved&&Date.now()-saved.updatedAt>ttl){saved=void 0;storage.remove(key());events.emit("cart_expired",{branchId:branch.id})}}catch{storage.remove(key());storage.warning("Invalid saved cart discarded")}updatedAt=saved?.updatedAt??Date.now();const idle=Date.now()-updatedAt;let fulfilment=saved?.fulfilment??null;if(fulfilment?.branchId!==branch.id||idle>864e5&&fulfilment.type==="delivery"){fulfilment=null}if(fulfilment&&"scheduledFor"in fulfilment&&fulfilment.scheduledFor&&Date.parse(fulfilment.scheduledFor)<Date.now()){fulfilment={...fulfilment};delete fulfilment.scheduledFor}const lines=(saved?.lines??[]).map(line=>({...line,...idle>864e5?{inputs:{}}:{}}));const result=reconcile(lines,menu,branch,store.peek().currency);recompute(result.lines,result.issues,{fulfilment,promoCode:saved?.promoCode??null,perks:saved?.perks??[],isHydrated:true});if(raw!==null&&writeBack){persist()}storage.sweep(prefix,key(),ttl)};const ensure=()=>{const id=branch?.id??store.peek()?.branches.find(b=>b.id===selected||b.slug===selected||!selected&&b.isDefault)?.id??(!selected?store.peek()?.branches[0]?.id:void 0);if(snapshot.isHydrated){return}const loaded=menu??(id?deps.workingSet.peek(id,[]):void 0);if(!loaded||!store.peek()){throw new ZappieError("invalid_request","Load the store and menu before editing the cart")}choose(loaded);const raw=readSaved(branch.id);let migrated=[];if(raw===null&&legacy){try{migrated=legacy(storage.read)}catch{storage.warning("Invalid legacy cart discarded")}}load(raw);if(raw===null&&legacy){persist()}for(const input of migrated.slice(0,100)){try{cart.add(input.itemId,input)}catch{events.emit("cart_issue",{code:"item_unavailable"})}}};const refresh=async target=>{const id=branch?.id;const seq=moveSequence;const request=++refreshSequence;const rev=revision;if(!id||!menu){return}if(!snapshot.lines.length){return}if(menu.completeness!=="partial"){const version=await deps.transport.getMenuVersion({...deps.context(),branchId:id});if(version.version===menu.version){return}target=version.version}if(target&&target===chased&&Date.now()-chasedAt<3e4){return}chased=target;chasedAt=Date.now();const value=await deps.workingSet.read(id,snapshot.lines.map(l=>l.itemId),true);if(seq!==moveSequence||request!==refreshSequence||rev!==revision||JSON.stringify(value)===JSON.stringify(menu)){return}menu=value;cancel();recompute(snapshot.lines);persist();schedule()};const current=input=>{const{itemId}=input;const candidate=deps.workingSet.peek(branch.id,[...snapshot.lines.map(l=>l.itemId),itemId]);if(candidate.items[itemId]){menu=candidate}return withDefaultMenu(menu,input)};const validated=(given,id,addedAt)=>{const raw=current(given);const item=Object.hasOwn(menu.items,raw.itemId)?menu.items[raw.itemId]:void 0;const problems=validateLine(item,raw,{menu,branch});if(problems.length||!item){throw new ZappieCartError(problems)}const input=normalizeInput(item,raw);const variant=resolveVariant(item,input);const choices=(input.choices??[]).map(c=>({...c,quantity:c.quantity??1}));const unitPrice=estimateUnitPrice(item,{choices,variantId:variant.id});return freezeLine({id:id??`line_${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(10)),byte=>(byte%36).toString(36)).join("")}`,itemId:item.id,...input.menuId!==void 0?{menuId:input.menuId}:{},name:item.name,quantity:input.quantity,choices,inputs:input.inputs??{},variantId:variant.id,...input.note!==void 0?{note:input.note}:{},unitPrice,lineSubtotal:multiplyMoney(unitPrice,input.quantity),addedAt:addedAt??new Date().toISOString()})};const offMenu=events.on("menu:updated",({branchId,version})=>{if(branch?.id===branchId){const value=menus.peek(branchId);if(value&&value.completeness!=="partial"&&value.version===version&&value.version!==menu?.version){refreshSequence++;menu=value;cancel();recompute(snapshot.lines);persist();schedule()}}});const cart={getSnapshot:()=>snapshot,subscribe(fn){listeners.add(fn);return()=>{listeners.delete(fn)}},async hydrate(){if(snapshot.isHydrated){resume();return refresh()}const life=lifecycle;hydration??(hydration=(async()=>{const value=await store.get();const target=value.branches.find(b=>b.id===selected||b.slug===selected)??(!selected?value.branches.find(b=>b.isDefault)??value.branches[0]:void 0);if(!target){throw new ZappieError("branch_not_found","Cart branch is unavailable")}let inputs=snapshot.lines;if(!snapshot.isHydrated){const raw=readSaved(target.id);try{const saved=raw?parseCart(raw):void 0;inputs=saved&&Date.now()-saved.updatedAt<=ttl?saved.lines:raw===null?legacy?.(storage.read)??[]:[]}catch{inputs=[]}}const loaded=await deps.workingSet.read(target.id,inputs.map(l=>l.itemId));if(life!==lifecycle){return}choose(loaded);ensure();resume();if(loaded.completeness!=="partial"){await refresh()}})().finally(()=>{hydration=void 0}));return hydration},mount(){mounted++;if(!detach&&typeof window!=="undefined"){const onStorage=event=>{if(branch&&event.key===key()&&storage.accepts(event.storageArea)){const raw=event.newValue;let ids;try{ids=raw?parseCart(raw).lines.map(l=>l.itemId):[]}catch{load(raw,false);return}const cached=deps.workingSet.peek(branch.id,ids);if(cached.completeness!=="partial"||ids.every(id=>cached.items[id])){menu=cached;load(raw,false);schedule();return}const rev=revision;const request=++refreshSequence;const life=lifecycle;void deps.workingSet.read(branch.id,ids).then(value=>{if(life===lifecycle&&rev===revision&&request===refreshSequence){menu=value;load(raw,false);schedule()}}).catch(error=>events.emit("error",{error:asError(error)}))}};const onFocus=()=>{void refresh().catch(error=>events.emit("error",{error:asError(error)}))};window.addEventListener("storage",onStorage);window.addEventListener("focus",onFocus);detach=()=>{window.removeEventListener("storage",onStorage);window.removeEventListener("focus",onFocus)}}if(mounted===1){void cart.hydrate().catch(error=>events.emit("error",{error:asError(error)}))}let active=true;return()=>{if(active){active=false;mounted--;if(mounted===0){detach?.();detach=void 0;cancel()}}}},dispose(){lifecycle++;moveSequence++;offMenu();cancel();detach?.();detach=void 0;listeners.clear()},validate(input){ensure();const line=current(input);const problems=validateLine(Object.hasOwn(menu.items,line.itemId)?menu.items[line.itemId]:void 0,line,{menu,branch});return problems.length?{ok:false,issues:problems}:{ok:true}},add(item,input={}){ensure();let line=validated({...input,itemId:typeof item==="string"?item:item.id});const existing=snapshot.lines.find(l=>identity(lineInput(l))===identity(lineInput(line)));if(existing){line=validated({...lineInput(line),quantity:existing.quantity+line.quantity},existing.id,existing.addedAt)}else if(snapshot.lines.length>=100){throw new ZappieCartError([issue("quantity_limit","A cart can contain at most 100 lines")])}changed(existing?snapshot.lines.map(l=>l.id===existing.id?line:l):[...snapshot.lines,line]);events.emit("add_to_cart",{itemId:line.itemId,quantity:line.quantity-(existing?.quantity??0),value:multiplyMoney(line.unitPrice,line.quantity-(existing?.quantity??0))});return line},update(lineId,patch){ensure();const old=snapshot.lines.find(l=>l.id===lineId);if(!old){throw new ZappieCartError([issue("item_not_found","Cart line not found")])}const input={...lineInput(old),...patch};if(patch.choices&&!patch.variantId){delete input.variantId}let line=validated(input,old.id,old.addedAt);const duplicate=snapshot.lines.find(l=>l.id!==lineId&&identity(lineInput(l))===identity(lineInput(line)));if(duplicate){line=validated({...lineInput(line),quantity:line.quantity+duplicate.quantity},old.id,old.addedAt)}changed(snapshot.lines.filter(l=>l.id!==duplicate?.id).map(l=>l.id===lineId?line:l));events.emit("update_cart_line",{lineId,itemId:line.itemId,quantity:line.quantity});return line},remove(lineId){ensure();const line=snapshot.lines.find(l=>l.id===lineId);changed(snapshot.lines.filter(l=>l.id!==lineId));if(line){events.emit("remove_from_cart",{itemId:line.itemId,quantity:line.quantity,value:line.lineSubtotal})}},clear(){ensure();changed([],{fulfilment:null,promoCode:null,perks:[]})},setFulfilment(value){ensure();if(!validFulfilment(value)||value.branchId!==branch.id){throw new ZappieCartError([issue("fulfilment_unavailable","Select fulfilment for the cart's branch")])}changed(snapshot.lines,{fulfilment:structuredClone(value)})},setPromoCode(code){ensure();changed(snapshot.lines,{promoCode:code?.trim()||null})},setPerks(perks){ensure();changed(snapshot.lines,{perks:[...perks]})},setCustomer(next){if(JSON.stringify(next)!=JSON.stringify(customer)){customer=next;schedule()}},setPendingFulfilment(next){planned=next&&{type:next.type,...next.scheduledFor&&{scheduled_for:next.scheduledFor}};schedule()},async moveTo(branchId){ensure();const seq=++moveSequence;cancel();publish({state:attention(snapshot.issues)});const value=await deps.workingSet.read(branchId,snapshot.lines.map(l=>l.itemId));if(seq!==moveSequence){return}const oldKey=key();const oldLines=snapshot.lines;choose(value);const kept=oldLines.filter(line=>!validateLine(value.items[line.itemId],lineInput(line),{menu:value,branch}).length);changed(kept,{fulfilment:null,promoCode:null,perks:[]});const dropped=oldLines.filter(line=>!kept.includes(line)).map(line=>({...issue("item_unavailable",`${line.name} is unavailable at this branch`),severity:"warning",lineId:line.id}));const issues=[...snapshot.issues,...dropped];publish({issues,state:attention(issues)});if(oldKey!==key()){storage.remove(oldKey)}},async quote(opts={}){ensure();clearTimeout(timer);if(opts.force){events.emit("view_cart",{})}const body={branch_id:branch.id,...snapshot.fulfilment?{fulfilment:wireFulfilment(snapshot.fulfilment)}:planned&&{fulfilment:planned},...wire()};const failure=opts.force?void 0:quotes?.failure(body);if(failure!==void 0){throw asError(failure)}const seq=revision;const attempt=++quoteRevision;publish({state:{status:"quoting"}});try{const client=await quoteClient();return await client.get(body,opts.force??false,quote=>{if(seq!==revision){return}const local=snapshot.issues.filter(i=>i.source==="local");const remote=quote.issues.filter(q=>!local.some(l=>l.code===q.code&&l.lineId===q.lineId&&l.groupId===q.groupId));const issues=[...local,...remote];publish({issues,state:attention(issues,quote)});for(const i of remote){events.emit("cart_issue",{code:i.code})}if(quote.menuVersion!==menu.version||quote.issues.some(i=>i.code==="menu_version_stale")){void refresh(quote.menuVersion).catch(error=>events.emit("error",{error:asError(error)}))}})}catch(error){if(seq===revision&&attempt===quoteRevision){const local=snapshot.issues.filter(i=>i.source==="local");publish({issues:local,state:attention(local)});events.emit("quote_failed",{code:asError(error).code})}throw error instanceof Error&&error.name==="AbortError"?error:asError(error)}},applyFix(problem,fix=problem.fixes[0]){if(!snapshot.issues.includes(problem)||!fix||!problem.fixes.some(f=>JSON.stringify(f)===JSON.stringify(fix))){throw new ZappieError("invalid_request","Choose a current cart issue and one of its fixes")}switch(fix.action){case"remove_line":{if(problem.lineId){cart.remove(problem.lineId)}return}case"remove_promo":cart.setPromoCode(null);return;case"remove_perks":cart.setPerks([]);return;case"set_quantity":{if(problem.lineId){cart.update(problem.lineId,{quantity:fix.quantity})}return}case"accept_price":{quotes?.accept(problem);const issues=snapshot.issues.filter(i=>i!==problem);const quote="quote"in snapshot.state?snapshot.state.quote:void 0;const accepted=quote?{...quote,issues:quote.issues.filter(i=>!(i.code===problem.code&&i.lineId===problem.lineId))}:void 0;publish({issues,state:attention(issues,accepted)});return}case"choose_region":throw new ZappieError("invalid_request","Choose a delivery region and call setFulfilment with deliveryRegionId");default:throw new ZappieError("invalid_request",`${fix.action} needs the shopper's selection; use update or setFulfilment`)}},toCheckoutPayload(){ensure();const blocking=snapshot.issues.filter(i=>i.severity==="blocking");if(!snapshot.lines.length||!snapshot.fulfilment){blocking.push(issue("fulfilment_unavailable","Add items and select fulfilment before checkout"))}if(blocking.length){throw new ZappieCartError(blocking)}return{fulfilment:structuredClone(snapshot.fulfilment),...wire()}}};for(const field of Object.keys(EMPTY_CART)){Object.defineProperty(cart,field,{get:()=>snapshot[field]})}return{cart:Object.freeze(cart),cartCatalogue:()=>menu,setLegacyReader(reader){legacy=reader}}}export{EMPTY_CART,createCart};
|
|
2
|
-
//# sourceMappingURL=index.js.map
|
|
1
|
+
import{asError,ZappieError}from"../errors.js";import{multiplyMoney,sumMoney}from"../internal/money-math.js";import{money}from"../money.js";import{ZappieCartError}from"./errors.js";import{estimateUnitPrice}from"./price.js";import{freezeLine,lineInput,reconcile}from"./reconcile.js";import{withDefaultMenu}from"./source-menu.js";import{createCartStorage,parseCart,validFulfilment}from"./storage.js";import{issue,normalizeInput,resolveVariant,validateLine}from"./validate.js";import{wireFulfilment,wireLine}from"./wire.js";var EMPTY_CART=deepFreeze({branchId:void 0,lines:[],count:0,subtotal:null,fulfilment:null,promoCode:null,perks:[],state:{status:"ready"},issues:[],isHydrated:false});function deepFreeze(value){if(value&&typeof value==="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const child of Object.values(value)){deepFreeze(child)}}return value}function identity(input){return JSON.stringify([input.itemId,input.menuId,input.variantId,input.note??"",[...input.choices??[]].sort((a,b)=>a.groupId.localeCompare(b.groupId)||a.choiceId.localeCompare(b.choiceId)),Object.entries(input.inputs??{}).sort(([a],[b])=>a.localeCompare(b))])}function createCart(deps){const{config,menu:menus,store,events}=deps;const ttl=config.cart?.ttl??7*24*60*60*1e3;if(!Number.isFinite(ttl)||ttl<=0){throw new ZappieError("invalid_request","Cart ttl must be positive milliseconds")}let snapshot=EMPTY_CART;let menu;let branch;let selected=config.branch;let updatedAt=0;let timer;let revision=0;let quoteRevision=0;let moveSequence=0;let refreshSequence=0;let chased;let chasedAt=0;let mounted=0;let detach;let hydration;let lifecycle=0;let legacy;const listeners=new Set;const prefix=`zappie:cart:v1:${config.store}:`;const scope=config.cart?.storageScope;const keyFor=id=>`${prefix}${id}${scope?`:${scope}`:""}`;const key=()=>keyFor(branch.id);const storage=createCartStorage(config.storage,message=>events.emit("warning",{message}));const readSaved=id=>{let raw=storage.read(keyFor(id));if(raw===null&&scope){raw=storage.read(prefix+id);if(raw!==null){storage.remove(prefix+id);storage.write(keyFor(id),raw)}}return raw};let quotes;let loadingQuotes;const quoteClient=()=>loadingQuotes??(loadingQuotes=import("./quote-client.js").then(({createQuoteClient})=>quotes=createQuoteClient(deps.transport,deps.context,config),error=>{loadingQuotes=void 0;throw error}));const publish=patch=>{snapshot=deepFreeze({...snapshot,...patch,branchId:branch?.id});for(const fn of[...listeners]){try{fn()}catch(error){events.emit("error",{error:asError(error)})}}};const attention=(issues,quote)=>issues.some(i=>i.severity!=="info")?{status:"needs_attention",issues,...quote?{quote}:{}}:quote?{status:"quoted",quote}:{status:"ready"};const cancel=()=>{revision++;quoteRevision++;clearTimeout(timer);quotes?.cancel()};let customer=null;let planned=null;const wire=()=>({lines:snapshot.lines.map(wireLine),...customer?{customer}:{},...snapshot.promoCode?{promo_code:snapshot.promoCode}:{},...snapshot.perks.length&&snapshot.fulfilment?.type!="dine_in"?{perk_redemption_ids:snapshot.perks.map(p=>p.redemptionId)}:{},menu_version:menu.version});const persist=()=>{const value={v:1,lines:snapshot.lines.map(line=>({...lineInput(line),id:line.id,name:line.name,addedAt:line.addedAt,unitPrice:line.unitPrice})),fulfilment:snapshot.fulfilment,promoCode:snapshot.promoCode,perks:snapshot.perks,menuVersion:menu.version,updatedAt};storage.write(key(),JSON.stringify(value))};const schedule=()=>{clearTimeout(timer);if(snapshot.lines.length){timer=setTimeout(()=>{void cart.quote().catch(()=>{})},300)}};const resume=()=>{if(!("quote"in snapshot.state)){schedule()}};const recompute=(lines,pending=snapshot.issues.filter(i=>i.source==="local"),patch={})=>{const currency=store.peek().currency;const result=reconcile(lines,menu,branch,currency,pending);const subtotal=result.priced?sumMoney(result.lines.map(l=>l.lineSubtotal),money(0,currency)):null;publish({...patch,lines:result.lines,count:result.lines.reduce((n,l)=>n+l.quantity,0),subtotal,issues:result.issues,state:attention(result.issues)});for(const i of result.issues){events.emit("cart_issue",{code:i.code})}};const changed=(lines=snapshot.lines,patch={})=>{cancel();recompute(lines,void 0,patch);updatedAt=Date.now();persist();schedule()};const choose=value=>{const found=store.peek()?.branches.find(b=>b.id===value.branchId);if(!found){throw new ZappieError("branch_not_found","Load the storefront branch before using its cart")}menu=value;branch=found;selected=found.id};const load=(raw,writeBack=true)=>{cancel();let saved;try{saved=raw?parseCart(raw):void 0;if(saved&&Date.now()-saved.updatedAt>ttl){saved=void 0;storage.remove(key());events.emit("cart_expired",{branchId:branch.id})}}catch{storage.remove(key());storage.warning("Invalid saved cart discarded")}updatedAt=saved?.updatedAt??Date.now();const idle=Date.now()-updatedAt;let fulfilment=saved?.fulfilment??null;if(fulfilment?.branchId!==branch.id||idle>864e5&&fulfilment.type==="delivery"){fulfilment=null}if(fulfilment&&"scheduledFor"in fulfilment&&fulfilment.scheduledFor&&Date.parse(fulfilment.scheduledFor)<Date.now()){fulfilment={...fulfilment};delete fulfilment.scheduledFor}const lines=(saved?.lines??[]).map(line=>({...line,...idle>864e5?{inputs:{}}:{}}));const result=reconcile(lines,menu,branch,store.peek().currency);recompute(result.lines,result.issues,{fulfilment,promoCode:saved?.promoCode??null,perks:saved?.perks??[],isHydrated:true});if(raw!==null&&writeBack){persist()}storage.sweep(prefix,key(),ttl)};const ensure=()=>{const id=branch?.id??store.peek()?.branches.find(b=>b.id===selected||b.slug===selected||!selected&&b.isDefault)?.id??(!selected?store.peek()?.branches[0]?.id:void 0);if(snapshot.isHydrated){return}const loaded=menu??(id?deps.workingSet.peek(id,[]):void 0);if(!loaded||!store.peek()){throw new ZappieError("invalid_request","Load the store and menu before editing the cart")}choose(loaded);const raw=readSaved(branch.id);let migrated=[];if(raw===null&&legacy){try{migrated=legacy(storage.read)}catch{storage.warning("Invalid legacy cart discarded")}}load(raw);if(raw===null&&legacy){persist()}for(const input of migrated.slice(0,100)){try{cart.add(input.itemId,input)}catch{events.emit("cart_issue",{code:"item_unavailable"})}}};const refresh=async target=>{const id=branch?.id;const seq=moveSequence;const request=++refreshSequence;const rev=revision;if(!id||!menu){return}if(!snapshot.lines.length){return}if(menu.completeness!=="partial"){const version=await deps.transport.getMenuVersion({...deps.context(),branchId:id});if(version.version===menu.version){return}target=version.version}if(target&&target===chased&&Date.now()-chasedAt<3e4){return}chased=target;chasedAt=Date.now();const value=await deps.workingSet.read(id,snapshot.lines.map(l=>l.itemId),true);if(seq!==moveSequence||request!==refreshSequence||rev!==revision||JSON.stringify(value)===JSON.stringify(menu)){return}menu=value;cancel();recompute(snapshot.lines);persist();schedule()};const current=input=>{const{itemId}=input;const candidate=deps.workingSet.peek(branch.id,[...snapshot.lines.map(l=>l.itemId),itemId]);if(candidate.items[itemId]){menu=candidate}return withDefaultMenu(menu,input)};const validated=(given,id,addedAt)=>{const raw=current(given);const item=Object.hasOwn(menu.items,raw.itemId)?menu.items[raw.itemId]:void 0;const problems=validateLine(item,raw,{menu,branch});if(problems.length||!item){throw new ZappieCartError(problems)}const input=normalizeInput(item,raw);const variant=resolveVariant(item,input);const choices=(input.choices??[]).map(c=>({...c,quantity:c.quantity??1}));const unitPrice=estimateUnitPrice(item,{choices,variantId:variant.id});return freezeLine({id:id??`line_${Array.from(globalThis.crypto.getRandomValues(new Uint8Array(10)),byte=>(byte%36).toString(36)).join("")}`,itemId:item.id,...input.menuId!==void 0?{menuId:input.menuId}:{},name:item.name,quantity:input.quantity,choices,inputs:input.inputs??{},variantId:variant.id,...input.note!==void 0?{note:input.note}:{},unitPrice,lineSubtotal:multiplyMoney(unitPrice,input.quantity),addedAt:addedAt??new Date().toISOString()})};const offMenu=events.on("menu:updated",({branchId,version})=>{if(branch?.id===branchId){const value=menus.peek(branchId);if(value&&value.completeness!=="partial"&&value.version===version&&value.version!==menu?.version){refreshSequence++;menu=value;cancel();recompute(snapshot.lines);persist();schedule()}}});const cart={getSnapshot:()=>snapshot,subscribe(fn){listeners.add(fn);return()=>{listeners.delete(fn)}},async hydrate(){if(snapshot.isHydrated){resume();return refresh()}const life=lifecycle;hydration??(hydration=(async()=>{const value=await store.get();const target=value.branches.find(b=>b.id===selected||b.slug===selected)??(!selected?value.branches.find(b=>b.isDefault)??value.branches[0]:void 0);if(!target){throw new ZappieError("branch_not_found","Cart branch is unavailable")}let inputs=snapshot.lines;if(!snapshot.isHydrated){const raw=readSaved(target.id);try{const saved=raw?parseCart(raw):void 0;inputs=saved&&Date.now()-saved.updatedAt<=ttl?saved.lines:raw===null?legacy?.(storage.read)??[]:[]}catch{inputs=[]}}const loaded=await deps.workingSet.read(target.id,inputs.map(l=>l.itemId));if(life!==lifecycle){return}choose(loaded);ensure();resume();if(loaded.completeness!=="partial"){await refresh()}})().finally(()=>{hydration=void 0}));return hydration},mount(){mounted++;if(!detach&&typeof window!=="undefined"){const onStorage=event=>{if(branch&&event.key===key()&&storage.accepts(event.storageArea)){const raw=event.newValue;let ids;try{ids=raw?parseCart(raw).lines.map(l=>l.itemId):[]}catch{load(raw,false);return}const cached=deps.workingSet.peek(branch.id,ids);if(cached.completeness!=="partial"||ids.every(id=>cached.items[id])){menu=cached;load(raw,false);schedule();return}const rev=revision;const request=++refreshSequence;const life=lifecycle;void deps.workingSet.read(branch.id,ids).then(value=>{if(life===lifecycle&&rev===revision&&request===refreshSequence){menu=value;load(raw,false);schedule()}}).catch(error=>events.emit("error",{error:asError(error)}))}};const onFocus=()=>{void refresh().catch(error=>events.emit("error",{error:asError(error)}))};window.addEventListener("storage",onStorage);window.addEventListener("focus",onFocus);detach=()=>{window.removeEventListener("storage",onStorage);window.removeEventListener("focus",onFocus)}}if(mounted===1){void cart.hydrate().catch(error=>events.emit("error",{error:asError(error)}))}let active=true;return()=>{if(active){active=false;mounted--;if(mounted===0){detach?.();detach=void 0;cancel()}}}},dispose(){lifecycle++;moveSequence++;offMenu();cancel();detach?.();detach=void 0;listeners.clear()},validate(input){ensure();const line=current(input);const problems=validateLine(Object.hasOwn(menu.items,line.itemId)?menu.items[line.itemId]:void 0,line,{menu,branch});return problems.length?{ok:false,issues:problems}:{ok:true}},add(item,input={}){ensure();let line=validated({...input,itemId:typeof item==="string"?item:item.id});const existing=snapshot.lines.find(l=>identity(lineInput(l))===identity(lineInput(line)));if(existing){line=validated({...lineInput(line),quantity:existing.quantity+line.quantity},existing.id,existing.addedAt)}else if(snapshot.lines.length>=100){throw new ZappieCartError([issue("quantity_limit","A cart can contain at most 100 lines")])}changed(existing?snapshot.lines.map(l=>l.id===existing.id?line:l):[...snapshot.lines,line]);events.emit("add_to_cart",{itemId:line.itemId,quantity:line.quantity-(existing?.quantity??0),value:multiplyMoney(line.unitPrice,line.quantity-(existing?.quantity??0))});return line},update(lineId,patch){ensure();const old=snapshot.lines.find(l=>l.id===lineId);if(!old){throw new ZappieCartError([issue("item_not_found","Cart line not found")])}const input={...lineInput(old),...patch};if(patch.choices&&!patch.variantId){delete input.variantId}let line=validated(input,old.id,old.addedAt);const duplicate=snapshot.lines.find(l=>l.id!==lineId&&identity(lineInput(l))===identity(lineInput(line)));if(duplicate){line=validated({...lineInput(line),quantity:line.quantity+duplicate.quantity},old.id,old.addedAt)}changed(snapshot.lines.filter(l=>l.id!==duplicate?.id).map(l=>l.id===lineId?line:l));events.emit("update_cart_line",{lineId,itemId:line.itemId,quantity:line.quantity});return line},remove(lineId){ensure();const line=snapshot.lines.find(l=>l.id===lineId);changed(snapshot.lines.filter(l=>l.id!==lineId));if(line){events.emit("remove_from_cart",{itemId:line.itemId,quantity:line.quantity,value:line.lineSubtotal})}},clear(){ensure();changed([],{fulfilment:null,promoCode:null,perks:[]})},setFulfilment(value){ensure();if(!validFulfilment(value)||value.branchId!==branch.id){throw new ZappieCartError([issue("fulfilment_unavailable","Select fulfilment for the cart's branch")])}changed(snapshot.lines,{fulfilment:structuredClone(value)})},setPromoCode(code){ensure();changed(snapshot.lines,{promoCode:code?.trim()||null})},setPerks(perks){ensure();changed(snapshot.lines,{perks:[...perks]})},setCustomer(next){if(JSON.stringify(next)!=JSON.stringify(customer)){customer=next;schedule()}},setPendingFulfilment(next){planned=next&&{type:next.type,...next.scheduledFor&&{scheduled_for:next.scheduledFor}};schedule()},async moveTo(branchId){ensure();const seq=++moveSequence;cancel();publish({state:attention(snapshot.issues)});const value=await deps.workingSet.read(branchId,snapshot.lines.map(l=>l.itemId));if(seq!==moveSequence){return}const oldKey=key();const oldLines=snapshot.lines;choose(value);const kept=oldLines.filter(line=>!validateLine(value.items[line.itemId],lineInput(line),{menu:value,branch}).length);changed(kept,{fulfilment:null,promoCode:null,perks:[]});const dropped=oldLines.filter(line=>!kept.includes(line)).map(line=>({...issue("item_unavailable",`${line.name} is unavailable at this branch`),severity:"warning",lineId:line.id}));const issues=[...snapshot.issues,...dropped];publish({issues,state:attention(issues)});if(oldKey!==key()){storage.remove(oldKey)}},async quote(opts={}){ensure();clearTimeout(timer);if(opts.force){events.emit("view_cart",{})}const body={branch_id:branch.id,...snapshot.fulfilment?{fulfilment:wireFulfilment(snapshot.fulfilment)}:planned&&{fulfilment:planned},...wire()};const failure=opts.force?void 0:quotes?.failure(body);if(failure!==void 0){throw asError(failure)}const seq=revision;const attempt=++quoteRevision;publish({state:{status:"quoting"}});try{const client=await quoteClient();return await client.get(body,opts.force??false,quote=>{if(seq!==revision){return}const local=snapshot.issues.filter(i=>i.source==="local");const remote=quote.issues.filter(q=>!local.some(l=>l.code===q.code&&l.lineId===q.lineId&&l.groupId===q.groupId));const issues=[...local,...remote];publish({issues,state:attention(issues,quote)});for(const i of remote){events.emit("cart_issue",{code:i.code})}if(quote.menuVersion!==menu.version||quote.issues.some(i=>i.code==="menu_version_stale")){void refresh(quote.menuVersion).catch(error=>events.emit("error",{error:asError(error)}))}})}catch(error){if(seq===revision&&attempt===quoteRevision){const local=snapshot.issues.filter(i=>i.source==="local");publish({issues:local,state:attention(local)});events.emit("quote_failed",{code:asError(error).code})}throw error instanceof Error&&error.name==="AbortError"?error:asError(error)}},applyFix(problem,fix=problem.fixes[0]){if(!snapshot.issues.includes(problem)||!fix||!problem.fixes.some(f=>JSON.stringify(f)===JSON.stringify(fix))){throw new ZappieError("invalid_request","Choose a current cart issue and one of its fixes")}switch(fix.action){case"remove_line":{if(problem.lineId){cart.remove(problem.lineId)}return}case"remove_promo":cart.setPromoCode(null);return;case"remove_perks":cart.setPerks([]);return;case"set_quantity":{if(problem.lineId){cart.update(problem.lineId,{quantity:fix.quantity})}return}case"accept_price":{quotes?.accept(problem);const issues=snapshot.issues.filter(i=>i!==problem);const quote="quote"in snapshot.state?snapshot.state.quote:void 0;const accepted=quote?{...quote,issues:quote.issues.filter(i=>!(i.code===problem.code&&i.lineId===problem.lineId))}:void 0;publish({issues,state:attention(issues,accepted)});return}case"choose_region":throw new ZappieError("invalid_request","Choose a delivery region and call setFulfilment with deliveryRegionId");default:throw new ZappieError("invalid_request",`${fix.action} needs the shopper's input`)}},toCheckoutPayload(){ensure();const blocking=snapshot.issues.filter(i=>i.severity==="blocking");if(!snapshot.lines.length||!snapshot.fulfilment){blocking.push(issue("fulfilment_unavailable","Add items and select fulfilment before checkout"))}if(blocking.length){throw new ZappieCartError(blocking)}return{fulfilment:structuredClone(snapshot.fulfilment),...wire()}}};for(const field of Object.keys(EMPTY_CART)){Object.defineProperty(cart,field,{get:()=>snapshot[field]})}return{cart:Object.freeze(cart),cartCatalogue:()=>menu,setLegacyReader(reader){legacy=reader}}}export{EMPTY_CART,createCart};
|
package/dist/cart/item.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Zappie } from '../index.js';
|
|
2
2
|
import { Item } from '../index.js';
|
|
3
|
-
import '../types-
|
|
3
|
+
import '../types-CuPaBf6k.js';
|
|
4
4
|
|
|
5
5
|
/** Register an item already read by a partial/selected catalogue, without fetching it again. */
|
|
6
6
|
declare function prepareItem(client: Zappie, item: Item, options: {
|
package/dist/cart/item.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
async function prepareItem(client,item,options){options.signal?.throwIfAborted();await client.menu.get({...options,metadataOnly:true});options.signal?.throwIfAborted();client._internal.cache.set(`item:${options.branch}:${item.id}`,item);return client.menu.item(item.id,options)}export{prepareItem};
|
|
2
|
-
//# sourceMappingURL=item.js.map
|
package/dist/cart/preview.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{multiplyMoney}from"../internal/money-math.js";import{estimateUnitPrice}from"./price.js";import{effectiveGroups,normalizeInput,resolveVariant}from"./validate.js";function previewQuantity(value){return Number.isInteger(value)&&value>=0&&value<=99?value:0}function previewItem(item,raw){const input=normalizeInput(item,raw);const groups=effectiveGroups(item,input).filter(group=>group.isAvailable!==false);const variantId=resolveVariant(item,input)?.id;const choices=(input.choices??[]).filter(({groupId,choiceId})=>groups.some(group=>group.id===groupId&&group.choices.some(choice=>choice.id===choiceId))).map(selection=>({...selection,quantity:previewQuantity(selection.quantity)}));const unitPrice=estimateUnitPrice(item,{choices,...variantId?{variantId}:{}});const total=multiplyMoney(unitPrice,previewQuantity(input.quantity));return{groups,unitPrice,total}}export{previewItem};
|
|
2
|
-
//# sourceMappingURL=preview.js.map
|
package/dist/cart/price.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{ZappieError}from"../errors.js";import{multiplyMoney,sumMoney}from"../internal/money-math.js";function estimateUnitPrice(item,line){const variant=line.variantId?item.variants.find(v=>v.id===line.variantId):void 0;if(line.variantId&&!variant){throw new ZappieError("invalid_request","The selected variant is missing")}const extras=line.choices.flatMap(selected=>{const group=item.optionGroups.find(g=>g.id===selected.groupId);const choice=group?.choices.find(c=>c.id===selected.choiceId);if(!group||!choice){throw new ZappieError("invalid_request","The selected option is missing")}return group.isAttribute?[]:[multiplyMoney(choice.price,Math.max(selected.quantity,1))]});return sumMoney(extras,variant?.price??item.price)}export{estimateUnitPrice};
|
|
2
|
-
//# sourceMappingURL=price.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{wireError,ZappieError}from"../errors.js";import{requestWithRetry}from"../internal/customer-http.js";import{mapQuote}from"./quote-response.js";var FAILURE_WINDOW_MS=3e4;function createQuoteClient(transport,context,options={}){const customerBase=options.customerBase?.replace(/\/+$/,"");const signedQuote=async(body,signal)=>{const response=await requestWithRetry(options.fetch??globalThis.fetch,`${customerBase}/quote`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify((await import("../transport/quote-body.js")).quoteBody(body)),signal},"Could not reach the storefront quote service");if(!response.ok){throw wireError(await response.json().catch(()=>({})),response.status,response.headers.get("Zappie-Request-Id")??void 0)}return await response.json()};let controller;let sequence=0;let cached;let flight;let failed;const cancel=()=>{sequence++;controller?.abort();flight=void 0};return{cancel,failure(body){return failed?.key===JSON.stringify(body)&&Date.now()-failed.at<FAILURE_WINDOW_MS?failed.error:void 0},async get(body,force,apply){const key=JSON.stringify(body);if(!force&&cached?.key===key&&Date.parse(cached.quote.expiresAt)>Date.now()){apply(cached.quote);return cached.quote}if(!force&&flight?.key===key){return flight.promise}cancel();const seq=sequence;controller=new AbortController;const signal=controller.signal;const promise=(async()=>{const raw=customerBase?await signedQuote(body,signal):await transport.quote({...context(),signal},body);signal.throwIfAborted();const quote=mapQuote(raw,body.branch_id);const ids=new Set(quote.lines.map(line=>line.lineId));if(ids.size!==quote.lines.length||quote.lines.length!==body.lines.length||body.lines.some(line=>!ids.has(line.line_id))){throw new ZappieError("server_error","Quote line identities do not match the cart")}if(seq===sequence){cached={key,quote};failed=void 0;apply(quote)}return quote})();flight={key,promise};try{return await promise}catch(error){if(seq===sequence&&!(error instanceof Error&&error.name==="AbortError")){failed={key,error,at:Date.now()}}throw error}finally{if(seq===sequence){flight=void 0}}},accept(issue){if(cached){cached.quote={...cached.quote,issues:cached.quote.issues.filter(i=>!(i.code===issue.code&&i.lineId===issue.lineId))}}}}}export{createQuoteClient};
|
|
2
|
-
//# sourceMappingURL=quote-client.js.map
|
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{ZappieError}from"../errors.js";import{sumMoney}from"../internal/money-math.js";import{money}from"../money.js";import{mapMoney,record}from"../transport/mappers.js";function fail(){throw new ZappieError("server_error","Invalid quote response")}function text(value){if(typeof value!=="string"){return fail()}return value}function list(value){if(!Array.isArray(value)){return fail()}return value}function fix(value){const v=record(value);switch(
|
|
2
|
-
//# sourceMappingURL=quote-response.js.map
|
|
1
|
+
import{ZappieError}from"../errors.js";import{sumMoney}from"../internal/money-math.js";import{money}from"../money.js";import{mapMoney,record}from"../transport/mappers.js";function fail(){throw new ZappieError("server_error","Invalid quote response")}function text(value){if(typeof value!=="string"){return fail()}return value}function list(value){if(!Array.isArray(value)){return fail()}return value}function fix(value){const v=record(value);const{action}=v;switch(action){case"remove_line":case"accept_price":case"remove_promo":case"change_address":case"choose_region":case"remove_perks":return{action};case"choose_option":case"choose_other_option":return{action,groupId:text(v.group_id)};case"fill_field":return{action,field:text(v.field)};case"set_quantity":{const quantity=v.quantity;if(!Number.isInteger(quantity)||quantity<1||quantity>99){return fail()}return{action,quantity}}case"schedule":return{action,...v.next_open_at?{nextOpenAt:text(v.next_open_at)}:{},...v.slots?{slots:list(v.slots).map(text)}:{}};case"switch_fulfilment":{const types=list(v.types).map(text).filter(t=>["pickup","delivery","dine_in"].includes(t));if(types.length){return{action,types}}}}return void 0}var codes=["item_unavailable","item_not_found","option_unavailable","option_required","option_limit","quantity_limit","price_changed","branch_closed","fulfilment_unavailable","outside_delivery_zone","delivery_region_required","schedule_invalid","promo_invalid","promo_min_spend","min_order","menu_version_stale","perk_invalid","checkout_field_required","checkout_field_invalid"];function mapQuote(value,branchId){const v=record(value);if(v.branch_id!==branchId||!Number.isFinite(Date.parse(text(v.expires_at)))){return fail()}const subtotal=mapMoney(v.subtotal);const checkout=record(v.checkout);if(typeof v.can_checkout!=="boolean"||typeof checkout.ready!=="boolean"){return fail()}const amount=raw=>{const result=mapMoney(raw);if(result.currency!==subtotal.currency){return fail()}return result};const charge=raw=>{const c=record(raw);return{code:text(c.code),label:text(c.label),amount:amount(c.amount),...c.redemption_id?{redemptionId:text(c.redemption_id)}:{}}};const charges=list(v.charges).map(charge);const discounts=list(v.discounts).map(charge);const total=amount(v.total);if(sumMoney([...charges,...discounts].map(c=>c.amount),subtotal).amountMinor!==total.amountMinor){return fail()}const deliveryCharges=charges.filter(c=>c.code==="delivery");const fees=charges.filter(c=>c.code!=="delivery");const integer=value2=>{if(!Number.isSafeInteger(value2)||value2<0){return fail()}return value2};const fulfilment=v.fulfilment===void 0?void 0:record(v.fulfilment);if(v.menu_version_stale!==void 0&&typeof v.menu_version_stale!=="boolean"){return fail()}const lines=list(v.lines).map(raw=>{const l=record(raw);if((l.unit_price==null||l.line_total==null)&&v.lines_unpriced!==true){return fail()}return{...l.item_id!==void 0?{itemId:text(l.item_id)}:{},...l.name!==void 0?{name:text(l.name)}:{},...l.quantity!==void 0?{quantity:integer(l.quantity)}:{},...l.status!==void 0?{status:text(l.status)}:{},...l.options_total!==void 0?{optionsTotal:l.options_total===null?null:amount(l.options_total)}:{},lineId:text(l.line_id),unitPrice:l.unit_price==null?null:amount(l.unit_price),total:l.line_total==null?null:amount(l.line_total)}});if(v.lines_unpriced!==true&&sumMoney(lines.filter(line=>line.status!=="invalid").map(line=>line.total),money(0,subtotal.currency)).amountMinor!==subtotal.amountMinor){return fail()}return{...v.menu_version_stale!==void 0?{menuVersionStale:v.menu_version_stale}:{},...fulfilment?{fulfilment:{type:text(fulfilment.type),scheduledFor:fulfilment.scheduled_for===null?null:text(fulfilment.scheduled_for),...fulfilment.eta_minutes!==void 0?{etaMinutes:list(fulfilment.eta_minutes).map(integer)}:{},...fulfilment.delivery_region_id!==void 0?{deliveryRegionId:text(fulfilment.delivery_region_id)}:{}}}:{},lines,...v.lines_unpriced===true?{linesUnpriced:true}:{},subtotal,total,fees,feesTotal:sumMoney(fees.map(c=>c.amount),money(0,subtotal.currency)),discounts,...deliveryCharges.length?{delivery:sumMoney(deliveryCharges.map(c=>c.amount),money(0,subtotal.currency))}:{},menuVersion:text(v.menu_version),expiresAt:text(v.expires_at),issues:list(v.issues).flatMap(raw=>{const i=record(raw);const code=text(i.code);const severity=text(i.severity);const known=codes.includes(code)&&["blocking","warning","info"].includes(severity);const fixes=list(i.fixes).flatMap(f=>fix(f)??[]);const lineId=i.line_id?text(i.line_id):void 0;const data=record(i.data??{});if(!known&&(severity==="warning"||severity==="info")){console.warn(`Zappie quote issue "${code}" is newer than this SDK and was skipped`);return[]}return[{code:known?code:"item_unavailable",severity:known?severity:"blocking",message:text(i.message),source:"quote",...lineId?{lineId}:{},...data.group_id?{groupId:text(data.group_id)}:{},...i.data||!known?{data:known?data:{...data,code}}:{},fixes:!known&&!fixes.length&&lineId?[{action:"remove_line"}]:fixes}]}),canCheckout:v.can_checkout,checkout:{ready:checkout.ready,...checkout.reason==="issues"||checkout.reason==="customer_required"?{reason:checkout.reason}:{},...checkout.fields?{fields:checkout.fields}:{}}}}export{mapQuote};
|
package/dist/cart/quote.d.ts
CHANGED
package/dist/cart/reconcile.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{multiplyMoney}from"../internal/money-math.js";import{format,money}from"../money.js";import{estimateUnitPrice}from"./price.js";import{withDefaultMenu}from"./source-menu.js";import{issue,normalizeInput,resolveVariant,validateLine}from"./validate.js";function lineInput(line){return{itemId:line.itemId,...line.menuId!==void 0?{menuId:line.menuId}:{},quantity:line.quantity,choices:line.choices.map(c=>({...c})),inputs:{...line.inputs},...line.variantId?{variantId:line.variantId}:{},...line.note!==void 0?{note:line.note}:{}}}function freezeLine(line){return Object.freeze({...line,choices:Object.freeze(line.choices.map(c=>Object.freeze({...c}))),inputs:Object.freeze({...line.inputs})})}function reconcile(lines,menu,branch,currency,previous=[]){const issues=[];let priced=true;const result=lines.map(old=>{const item=Object.hasOwn(menu.items,old.itemId)?menu.items[old.itemId]:void 0;const raw=withDefaultMenu(menu,{...old,choices:old.choices?.map(c=>({...c})),inputs:{...old.inputs}});const input=item?normalizeInput(item,raw):raw;issues.push(...validateLine(item,input,{menu,branch}).map(i=>({...i,lineId:old.id})));const variantId=input.variantId??(item?resolveVariant(item,input)?.id:void 0);let unitPrice=money(0,currency);let linePriced=true;try{if(!item){throw new Error("Missing item")}unitPrice=estimateUnitPrice(item,{choices:(input.choices??[]).map(c=>({...c,quantity:c.quantity??1})),...variantId?{variantId}:{}})}catch{priced=false;linePriced=false}if(old.unitPrice&&old.unitPrice.amountMinor!==unitPrice.amountMinor&&item&&linePriced){issues.push({...issue("price_changed",`${item.name} is now ${format.money(unitPrice)}`,[{action:"accept_price"},{action:"remove_line"}]),severity:"warning",lineId:old.id,data:{previous:old.unitPrice,current:unitPrice}})}return freezeLine({id:old.id,itemId:old.itemId,...input.menuId!==void 0?{menuId:input.menuId}:{},name:item?.name??old.name,quantity:input.quantity??1,choices:(input.choices??[]).map(c=>({...c,quantity:c.quantity??1})),inputs:input.inputs??{},...variantId?{variantId}:{},...input.note!==void 0?{note:input.note}:{},unitPrice,lineSubtotal:multiplyMoney(unitPrice,input.quantity??1),addedAt:old.addedAt})});for(const pending of previous){if(pending.code==="price_changed"&&result.some(l=>l.id===pending.lineId)&&!issues.some(i=>i.code===pending.code&&i.lineId===pending.lineId)){issues.push(pending)}}return{lines:Object.freeze(result),issues,priced}}export{freezeLine,lineInput,reconcile};
|
|
2
|
-
//# sourceMappingURL=reconcile.js.map
|
package/dist/cart/source-menu.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
function resolveSourceMenu(menu,itemId,menuId,fill){const categories=menu.categories.filter(c=>c.itemIds.includes(itemId));const sources=menu.menus??[{id:menu.id,categoryIds:menu.categories.map(c=>c.id)}];const placements=menu.items[itemId]?.placements;const candidates=sources.filter(source=>(!placements||placements.some(p=>p.menuId===source.id&&source.categoryIds.includes(p.categoryId)))&&source.categoryIds.some(id=>categories.some(c=>c.id===id)));if(menuId!==void 0){return typeof menuId==="string"&&menuId.trim().length>0&&menuId.length<=256&&candidates.some(source=>source.id===menuId)?menuId:void 0}return(fill?candidates[1]:candidates.length===1)?candidates[0].id:void 0}function withDefaultMenu(menu,input){const menuId=input.menuId===void 0&&resolveSourceMenu(menu,input.itemId,void 0,true);return menuId?{...input,menuId}:input}export{resolveSourceMenu,withDefaultMenu};
|
|
2
|
-
//# sourceMappingURL=source-menu.js.map
|
package/dist/cart/storage.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{money}from"../money.js";function storedMoney(value){try{return value&&money(value.amountMinor,value.currency)}catch{return void 0}}function parseCart(raw){const v=JSON.parse(raw);if(!v||v.v!==1||!Array.isArray(v.lines)||v.lines.length>100||!Number.isFinite(v.updatedAt)||typeof v.menuVersion!=="string"||v.promoCode!==null&&typeof v.promoCode!=="string"){throw new Error("Invalid saved cart")}const ids=new Set;for(const line of v.lines){if(!line||typeof line.id!=="string"||ids.has(line.id)||typeof line.itemId!=="string"||typeof line.name!=="string"||!Number.isFinite(Date.parse(line.addedAt))||!Number.isInteger(line.quantity)||line.quantity<1||line.quantity>99||line.note!==void 0&&(typeof line.note!=="string"||line.note.length>280)||line.menuId!==void 0&&(typeof line.menuId!=="string"||!line.menuId.trim()||line.menuId.length>256)||line.variantId!==void 0&&typeof line.variantId!=="string"){throw new Error("Invalid saved cart line")}ids.add(line.id);if(!Array.isArray(line.choices)||line.choices.length>1e3||line.choices.some(c=>!c||typeof c.groupId!=="string"||typeof c.choiceId!=="string"||!Number.isInteger(c.quantity)||c.quantity<1||c.quantity>99)){throw new Error("Invalid saved choices")}if(!line.inputs||typeof line.inputs!=="object"||Array.isArray(line.inputs)||Object.values(line.inputs).some(t=>typeof t!=="string")){throw new Error("Invalid saved inputs")}}if(v.fulfilment!==null&&!validFulfilment(v.fulfilment)){throw new Error("Invalid saved fulfilment")}return{v:1,lines:v.lines.map(l=>{const unitPrice=storedMoney(l.unitPrice);return{id:l.id,itemId:l.itemId,...l.menuId!==void 0?{menuId:l.menuId}:{},name:l.name,addedAt:l.addedAt,...unitPrice?{unitPrice}:{},quantity:l.quantity,choices:l.choices,inputs:l.inputs,...l.variantId?{variantId:l.variantId}:{},...l.note!==void 0?{note:l.note}:{}}}),fulfilment:v.fulfilment,promoCode:v.promoCode,perks:v.perks?.filter(p=>Date.parse(p.expiresAt)>Date.now()),menuVersion:v.menuVersion,updatedAt:v.updatedAt}}function validFulfilment(f){if(!f||!["pickup","delivery","dine_in"].includes(f.type)||typeof f.branchId!=="string"){return false}if("scheduledFor"in f&&f.scheduledFor!==void 0&&!Number.isFinite(Date.parse(f.scheduledFor))){return false}if(f.type==="delivery"){const a=f.address;if(!a||typeof a.line1!=="string"||!a.line1.trim()){return false}if([a.line2,a.city,a.placeId,a.instructions,f.deliveryRegionId].some(s=>s!==void 0&&typeof s!=="string")){return false}if(a.coordinates&&(!Number.isFinite(a.coordinates.lat)||!Number.isFinite(a.coordinates.lng)||Math.abs(a.coordinates.lat)>90||Math.abs(a.coordinates.lng)>180)){return false}}return f.type!=="dine_in"||f.table===void 0||typeof f.table==="string"}function createCartStorage(provided,warn){let storage;let initialized=false;let failed=false;let warned=false;const memory=new Map;const warning=message=>{if(!warned){warned=true;warn(message)}};const access=(fn,fallback)=>{try{if(!initialized){initialized=true;storage=provided??(typeof window==="undefined"?void 0:window.localStorage)}if(storage&&!failed){return fn(storage)}}catch{failed=true;warning("Cart storage unavailable; using memory for this client")}return fallback()};return{warning,read(key){return access(s=>{const value=s.getItem(key);if(value!==null){memory.set(key,value)}else{memory.delete(key)}return value},()=>memory.get(key)??null)},write(key,value){memory.set(key,value);access(s=>s.setItem(key,value),()=>{})},remove(key){memory.delete(key);access(s=>s.removeItem(key),()=>{})},accepts(area){return!failed&&(!area||area===storage)},sweep(prefix,current,ttl){access(s=>{const keys=Array.from({length:s.length??0},(_,index)=>s.key?.(index));for(const key of keys){if(!key||key===current||!key.startsWith(prefix)){continue}try{const raw=s.getItem(key);if(raw&&Date.now()-parseCart(raw).updatedAt>ttl){s.removeItem(key)}}catch{s.removeItem(key)}}},()=>{})}}}export{createCartStorage,parseCart,validFulfilment};
|
|
2
|
-
//# sourceMappingURL=storage.js.map
|
package/dist/cart/types.js
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=types.js.map
|
package/dist/cart/validate.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{ITEM_NOTE_MAX_LENGTH,selectionMax}from"../options/index.js";import{resolveSourceMenu}from"./source-menu.js";function issue(code,message,fixes=[],groupId){return{code,severity:"blocking",message,fixes,source:"local",...groupId?{groupId}:{}}}function effectiveGroups(item,input){const selected=new Map;for(const choice of input.choices??[]){const ids=selected.get(choice.groupId)??new Set;ids.add(choice.choiceId);selected.set(choice.groupId,ids)}return item.optionGroups.map(group=>{let required=group.required;let{min,max}=group.selection;for(const rule of group.conditions??[]){const chosen=selected.get(rule.groupId)??new Set;const matches=rule.count?rule.count.op==="eq"?chosen.size===rule.count.value:rule.count.op==="gte"?chosen.size>=rule.count.value:chosen.size<=rule.count.value:chosen.size>0&&rule.choiceIds.length>0&&(rule.match==="all"?rule.choiceIds.every(id=>chosen.has(id)):rule.choiceIds.some(id=>chosen.has(id)));if(!matches){continue}required=rule.setRequired??required;min=rule.setMin??min;if(rule.setMax!=null){max=rule.setMax>0?rule.setMax:void 0}}return{...group,required,selection:{min,...max!==void 0?{max}:{}}}})}function normalizeInput(item,input){const inactive=new Set(item.optionGroups.filter(g=>g.isAvailable===false).map(g=>g.id));return{...input,quantity:input.quantity??item.quantity.min,choices:(input.choices??[]).filter(c=>!inactive.has(c.groupId)).map(c=>({...c,quantity:c.quantity??1})),inputs:Object.fromEntries(Object.entries(input.inputs??{}).filter(([id])=>!inactive.has(id)))}}function resolveVariant(item,input){const attrs=item.optionGroups.filter(g=>g.isAttribute);const matches=item.variants.filter(variant=>(!input.variantId||variant.id===input.variantId)&&attrs.every(group=>{const selected=input.choices?.filter(c=>c.groupId===group.id)??[];return selected.length===1&&variant.attributeChoices[group.id]===selected[0].choiceId}));return matches.length===1?matches[0]:void 0}function validInput(kind,value){switch(kind){case"number":return Number.isFinite(Number(value));case"date":return/^\d{4}-\d{2}-\d{2}$/.test(value)&&Number.isFinite(Date.parse(value))&&new Date(value).toISOString().slice(0,10)===value;case"time":return/^([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/.test(value);case"toggle":return["true","false"].includes(value.toLowerCase());default:return true}}function validateLine(item,raw,ctx){if(!item||item.id!==raw.itemId||!Object.hasOwn(ctx.menu.items,raw.itemId)){return[issue("item_unavailable","This item is no longer on the menu",[{action:"remove_line"}])]}const issues=[];if(!resolveSourceMenu(ctx.menu,raw.itemId,raw.menuId)){issues.push(issue("item_unavailable",`Choose ${item.name} from a menu that lists it.`,[{action:"remove_line"}]))}if(!item.isAvailable){issues.push(issue("item_unavailable",`${item.name} is unavailable`,[{action:"remove_line"}]))}const input=normalizeInput(item,raw);const quantity=input.quantity;const{min,step}=item.quantity;const max=Math.min(item.quantity.max??99,99);if(!Number.isInteger(quantity)||quantity<min||quantity>max||quantity%step!==0){const lower=Math.ceil(min/step)*step;const upper=Math.floor(max/step)*step;const nearest=Math.max(lower,Math.min(upper,Math.round((Number.isFinite(quantity)?quantity:min)/step)*step));issues.push(issue("quantity_limit",`Choose a valid quantity of ${item.name} (${min}\u2013${max}, step ${step})`,lower<=upper?[{action:"set_quantity",quantity:nearest}]:[]))}if((input.note?.length??0)>ITEM_NOTE_MAX_LENGTH){issues.push(issue("option_limit",`Notes must be at most ${ITEM_NOTE_MAX_LENGTH} characters`))}for(const choice of input.choices??[]){if(!item.optionGroups.some(g=>g.id===choice.groupId)){issues.push(issue("option_unavailable","This option group no longer exists",[{action:"remove_line"}],choice.groupId))}}for(const id of Object.keys(input.inputs??{})){if(!item.optionGroups.some(g=>g.id===id)){issues.push(issue("option_unavailable","This input group no longer exists",[{action:"remove_line"}],id))}}const groups=effectiveGroups(item,input);const missing=groups.filter(g=>g.isAvailable!==false&&g.required&&!(input.choices??[]).some(c=>c.groupId===g.id)&&!(input.inputs?.[g.id]??"").trim());if(missing.length){return[...issues,...missing.map(g=>issue("option_required",`Choose ${g.name}`,[{action:"choose_option",groupId:g.id}],g.id))]}for(const group of groups){if(group.isAvailable===false){continue}const choices=input.choices?.filter(c=>c.groupId===group.id)??[];const text=input.inputs?.[group.id]??"";const value=text.trim();const hybrid=group.isInformational&&group.kind==="select";const isInput=group.kind!=="select"||hybrid&&!group.choices.length;const fix=[{action:"choose_option",groupId:group.id}];if(group.required&&!choices.length&&!value){issues.push(issue("option_required",`Choose ${group.name}`,fix,group.id))}if(value&&(!isInput&&!hybrid||choices.length>0)){issues.push(issue("option_limit",`Choose either an option or a response for ${group.name}`,fix,group.id))}if((isInput||hybrid)&&(text.length>(group.input?.maxLength??500)||value&&!validInput(group.kind,value))){issues.push(issue("option_limit",`Enter a valid response for ${group.name}`,fix,group.id))}const count=choices.reduce((sum,c)=>sum+(c.quantity??1),0);if(choices.length&&(isInput||count<group.selection.min||count>(selectionMax(group)??Infinity)||new Set(choices.map(c=>c.choiceId)).size!==choices.length)){issues.push(issue("option_limit",`Check the number of options for ${group.name}`,fix,group.id))}for(const selected of choices){const choice=group.choices.find(c=>c.id===selected.choiceId);if(!choice?.isAvailable){issues.push(issue("option_unavailable",`An option in ${group.name} is unavailable`,[{action:"choose_other_option",groupId:group.id},{action:"remove_line"}],group.id))}const n=selected.quantity??1;if(!Number.isInteger(n)||n<(choice?.quantity?.min??1)||n>(choice?.quantity?.max??99)){issues.push(issue("option_limit",`Check the option quantity for ${group.name}`,fix,group.id))}}}const variant=resolveVariant(item,input);if(!variant?.isAvailable){const groupId=item.optionGroups.find(g=>g.isAttribute)?.id;issues.push(issue("option_limit","Choose an available variant",groupId?[{action:"choose_option",groupId}]:[{action:"remove_line"}],groupId))}return issues}export{effectiveGroups,issue,normalizeInput,resolveVariant,validateLine};
|
|
2
|
-
//# sourceMappingURL=validate.js.map
|
package/dist/cart/wire.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
function wireLine(line){return{line_id:line.id,item_id:line.itemId,...line.menuId!==void 0?{menu_id:line.menuId}:{},quantity:line.quantity,...line.variantId?{variant_id:line.variantId}:{},options:line.choices.map(c=>({group_id:c.groupId,choice_id:c.choiceId,quantity:c.quantity})),inputs:{...line.inputs},...line.note!==void 0?{note:line.note}:{}}}function wireFulfilment(f){return{type:f.type,..."scheduledFor"in f&&f.scheduledFor?{scheduled_for:f.scheduledFor}:{},...f.type==="dine_in"&&f.table?{table:f.table}:{},...f.type==="delivery"?{...f.deliveryRegionId!==void 0?{delivery_region_id:f.deliveryRegionId}:{},address:{line1:f.address.line1,...f.address.line2?{line2:f.address.line2}:{},...f.address.city?{city:f.address.city}:{},...f.address.placeId?{place_id:f.address.placeId}:{},...f.address.instructions?{instructions:f.address.instructions}:{},...f.address.coordinates?{lat:f.address.coordinates.lat,lng:f.address.coordinates.lng}:{}}}:{}}}export{wireFulfilment,wireLine};
|
|
2
|
-
//# sourceMappingURL=wire.js.map
|
package/dist/cart/working-set.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{ZappieError}from"../errors.js";function createWorkingSet(deps){const compose=(branchId,ids,metadata)=>{const source=metadata??deps.menu.peek(branchId);const items=Object.fromEntries([...new Set(ids)].flatMap(id=>{const item=deps.peekItem(id,branchId)??source?.items[id];return item?[[id,item]]:[]}));return{id:`branch:${branchId}`,name:"Cart working set",branchId,version:"",...source,kind:"working-set",completeness:"partial",items,categories:(source?.categories??[]).map(category=>({...category,itemIds:Object.values(items).filter(item=>item.placements?item.placements.some(p=>p.categoryId===category.id&&(source?.menus??[{id:source?.id,categoryIds:[category.id]}]).some(m=>m.id===p.menuId&&m.categoryIds.includes(category.id))):category.itemIds.includes(item.id)).map(item=>item.id)}))}};const peek=(branchId,ids)=>{const value=deps.menu.peek(branchId);return value&&value.completeness!=="partial"?value:compose(branchId,ids)};return{peek,async read(branchId,ids,fresh=false){const cached=peek(branchId,ids);if(!ids.length||!fresh&&cached.completeness!=="partial"){return cached}const response=fresh?await deps.transport.getMenu({...deps.context(),branchId,metadataOnly:true}):void 0;const metadata=response&&"menu"in response?response.menu:await deps.menu.get({branch:branchId,metadataOnly:true});if(metadata.branchId!==branchId){throw new ZappieError("server_error","Cart metadata belongs to another branch")}deps.menu.hydrate(metadata);if(metadata.completeness!=="partial"){return metadata}await Promise.all([...new Set(ids)].map(async id=>{try{await deps.readItem(id,branchId,fresh)}catch(error){if(error.code!=="item_not_found"){throw error}}}));return compose(branchId,ids,metadata)}}}export{createWorkingSet};
|
|
2
|
-
//# sourceMappingURL=working-set.js.map
|
package/dist/checkout/client.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{apiError,requestWithRetry,wait}from"../internal/customer-http.js";import{CheckoutError}from"./error.js";import{ZappieError}from"./sdk.js";import{mapCheckoutSession}from"./session.js";var DEFAULT_CUSTOMER_BASE="/_zappie/api";async function error(response){const value=await apiError(response,`The checkout service answered ${response.status}`);return new CheckoutError(response.status,value.apiCode,value.message,value.param,value.issues)}function checkoutBody(body){const address=body.fulfilment.address;if(!address){return body}const{line2:_line2,instructions,...rest}=address;return{...body,fulfilment:{...body.fulfilment,...body.fulfilment.instructions===void 0&&instructions?{instructions}:{},address:rest}}}function createCheckout(options={}){const base=(options.customerBase??DEFAULT_CUSTOMER_BASE).replace(/\/+$/,"");const fetcher=options.fetch??globalThis.fetch;const request=async(path,init)=>{const response=await requestWithRetry(fetcher,base+path,init,"Could not reach checkout");if(!response.ok){throw await error(response)}return mapCheckoutSession(await response.json())};const read=(id,signal)=>request(`/checkout/sessions/${encodeURIComponent(id)}`,{method:"GET",...signal?{signal}:{}});return{async open(body,idempotencyKey){const session=await request("/checkout/sessions",{method:"POST",headers:{"Content-Type":"application/json","Idempotency-Key":idempotencyKey},body:JSON.stringify(checkoutBody(body))});if(!session.url){throw new ZappieError("server_error","Checkout session has no payment URL")}globalThis.__zappieEmit?.("checkout:open",session);return{...session,url:session.url}},session(id){return read(id)},async awaitCompletion(id,options2={}){const interval=options2.intervalMs??3e3;if(!Number.isFinite(interval)||interval<0){throw new ZappieError("invalid_request","intervalMs cannot be negative")}for(;;){options2.signal?.throwIfAborted();try{const session=await read(id,options2.signal);if(session.status==="completed"&&session.order_id){globalThis.__zappieEmit?.("checkout:completed",session);return{...session,status:"completed",order_id:session.order_id}}if(session.status==="expired"||session.status==="cancelled"){return{...session,status:session.status}}}catch(failure){options2.signal?.throwIfAborted();if(failure instanceof ZappieError&&failure.status!==void 0&&failure.status>=400&&failure.status<500){throw failure}}await wait(interval,options2.signal)}}}}export{createCheckout};
|
|
2
|
-
//# sourceMappingURL=client.js.map
|
package/dist/checkout/embed.d.ts
CHANGED
|
@@ -4,31 +4,54 @@ import { WireLine, CheckoutCustomer, WireMoney } from '@zappie/sdk';
|
|
|
4
4
|
* Address fields you can send with a delivery checkout request.
|
|
5
5
|
*/
|
|
6
6
|
type CheckoutAddress = {
|
|
7
|
+
/** The street address, such as "12 Admiralty Way". */
|
|
7
8
|
line1?: string;
|
|
9
|
+
/** The city, such as "Lagos". */
|
|
8
10
|
city?: string;
|
|
11
|
+
/** A place id from `@zappie/sdk/places`. Delivery is priced to that place. */
|
|
9
12
|
place_id?: string;
|
|
13
|
+
/** The latitude in decimal degrees. */
|
|
10
14
|
lat?: number;
|
|
15
|
+
/** The longitude in decimal degrees. */
|
|
11
16
|
lng?: number;
|
|
12
17
|
};
|
|
13
18
|
/**
|
|
14
19
|
* Pickup or delivery details for a checkout session, including an optional schedule.
|
|
15
20
|
*/
|
|
16
21
|
type CheckoutFulfilment = {
|
|
17
|
-
/**
|
|
22
|
+
/**
|
|
23
|
+
* How the customer gets the order. `pickup` means the customer collects it at the branch.
|
|
24
|
+
* `delivery` takes it to `address`. Dine-in orders are not checked out through a session.
|
|
25
|
+
*/
|
|
18
26
|
type: "pickup" | "delivery";
|
|
27
|
+
/** Where to deliver. A delivery checkout also needs a contact phone number from the branch's country. */
|
|
19
28
|
address?: CheckoutAddress;
|
|
29
|
+
/** When the order is for, RFC 3339 in UTC. Null or absent for as soon as possible. */
|
|
20
30
|
scheduled_for?: string | null;
|
|
31
|
+
/** The delivery region the shopper picked when the zone check or the quote asked for one. */
|
|
21
32
|
delivery_region_id?: string;
|
|
33
|
+
/**
|
|
34
|
+
* A note for the rider or the counter. Pricing ignores it. When you leave it out, the client
|
|
35
|
+
* sends the address's `instructions` here instead.
|
|
36
|
+
*/
|
|
22
37
|
instructions?: string;
|
|
23
38
|
};
|
|
24
39
|
/**
|
|
25
40
|
* Cart lines, branch, fulfilment and return URLs you send to open checkout.
|
|
26
41
|
*/
|
|
27
42
|
type CheckoutRequest = {
|
|
43
|
+
/** The branch the order is for. */
|
|
28
44
|
branch_id: string;
|
|
45
|
+
/** The menu version the cart was built against. */
|
|
29
46
|
menu_version: string;
|
|
47
|
+
/** The cart's lines, 1 to 100. A line that sends a price is refused. */
|
|
30
48
|
lines: WireLine[];
|
|
49
|
+
/** Pickup or delivery, with the address and the schedule. */
|
|
31
50
|
fulfilment: CheckoutFulfilment;
|
|
51
|
+
/**
|
|
52
|
+
* The phone number on the order: digits with an optional leading `+`. Without one, checkout uses
|
|
53
|
+
* the signed-in customer's verified number.
|
|
54
|
+
*/
|
|
32
55
|
contact_phone?: string;
|
|
33
56
|
/**
|
|
34
57
|
* Who collects or receives a pickup or delivery when the shopper orders for someone else. Send
|
|
@@ -37,25 +60,45 @@ type CheckoutRequest = {
|
|
|
37
60
|
contact_name?: string;
|
|
38
61
|
/** What the shopper typed for the store's checkout fields, from `cart.setCustomer`. */
|
|
39
62
|
customer?: CheckoutCustomer;
|
|
63
|
+
/** A promo code to apply. A code the quote refuses doesn't stop checkout. The order is placed without it, at the quoted total. */
|
|
40
64
|
promo_code?: string;
|
|
41
65
|
/** The perks in the bag, from `cart.perks`. The payment spends them. */
|
|
42
66
|
perk_redemption_ids?: string[];
|
|
67
|
+
/**
|
|
68
|
+
* Where the customer lands after paying, with `?session=` added. Use an https address on one of
|
|
69
|
+
* the storefront's own hosts, or an app redirect URI. A test key also takes a localhost address.
|
|
70
|
+
*/
|
|
43
71
|
return_url: string;
|
|
72
|
+
/** Where the customer goes back without paying. The same rules as `return_url` apply. */
|
|
44
73
|
cancel_url?: string;
|
|
74
|
+
/** Where the shopper's visit came from: the referrer address or `utm_source`. It counts the order toward that source in the business's analytics. */
|
|
45
75
|
source?: string;
|
|
76
|
+
/** The visit's `utm_campaign`, if any. */
|
|
46
77
|
campaign?: string;
|
|
47
78
|
};
|
|
48
79
|
/**
|
|
49
80
|
* A checkout session returned by the service, with its amount, expiry and order status.
|
|
50
81
|
*/
|
|
51
82
|
type CheckoutSession = {
|
|
83
|
+
/** The session's id, starting `cs_`. */
|
|
52
84
|
id: string;
|
|
85
|
+
/**
|
|
86
|
+
* Where the session stands. `open` means it is waiting for payment. `completed` means the order
|
|
87
|
+
* is placed, and `order_id` is set. `expired` means nobody paid before `expires_at`. `cancelled`
|
|
88
|
+
* is reserved. The API doesn't set it today.
|
|
89
|
+
*/
|
|
53
90
|
status: "open" | "completed" | "expired" | "cancelled";
|
|
91
|
+
/** The payment page. Only the session `open` returns has it. A read of the session leaves it out. */
|
|
54
92
|
url?: string;
|
|
93
|
+
/** What the customer pays. */
|
|
55
94
|
amount: WireMoney;
|
|
95
|
+
/** The placed order's id. Null until the session has completed. */
|
|
56
96
|
order_id: string | null;
|
|
97
|
+
/** Where the customer lands after paying. */
|
|
57
98
|
return_url: string;
|
|
99
|
+
/** Where the customer goes back without paying. Absent when the session has none. */
|
|
58
100
|
cancel_url?: string;
|
|
101
|
+
/** 30 minutes after the session opened, RFC 3339 in UTC. An open session expires within a minute after this time. */
|
|
59
102
|
expires_at: string;
|
|
60
103
|
};
|
|
61
104
|
/**
|
|
@@ -77,14 +120,22 @@ type CheckoutCompletion = (CheckoutSession & {
|
|
|
77
120
|
* Optional customer API base URL and fetch implementation for the checkout client.
|
|
78
121
|
*/
|
|
79
122
|
type CheckoutClientOptions = {
|
|
123
|
+
/** The base path of the customer API. Defaults to "/_zappie/api". */
|
|
80
124
|
customerBase?: string;
|
|
125
|
+
/** The fetch the client calls. Defaults to the global `fetch`. */
|
|
81
126
|
fetch?: typeof fetch;
|
|
82
127
|
};
|
|
83
128
|
/**
|
|
84
129
|
* Cancellation signal and polling interval in milliseconds for awaiting checkout completion.
|
|
85
130
|
*/
|
|
86
131
|
type AwaitCompletionOptions = {
|
|
132
|
+
/**
|
|
133
|
+
* Stops waiting when it aborts, and the promise rejects with the signal's reason. There is no
|
|
134
|
+
* timeout of its own. It waits until the session completes or expires, which an open session does
|
|
135
|
+
* within a minute after its `expires_at`.
|
|
136
|
+
*/
|
|
87
137
|
signal?: AbortSignal;
|
|
138
|
+
/** How long to wait between reads of the session, in milliseconds. Defaults to 3000. A negative value throws `invalid_request`. */
|
|
88
139
|
intervalMs?: number;
|
|
89
140
|
};
|
|
90
141
|
|
|
@@ -106,18 +157,32 @@ declare function createCheckout(options?: CheckoutClientOptions): {
|
|
|
106
157
|
type CheckoutClient = ReturnType<typeof createCheckout>;
|
|
107
158
|
|
|
108
159
|
/** How checkout opens. Auto redirects in in-app browsers and framed pages, else a modal on desktop and a sheet on mobile. */
|
|
109
|
-
type CheckoutPresentation =
|
|
160
|
+
type CheckoutPresentation =
|
|
161
|
+
/** Picks one of the others for this browser, as `checkoutPresentation` does. */
|
|
162
|
+
"auto"
|
|
163
|
+
/** A panel in the middle of the page, up to 480px wide, over a dimmed backdrop. */
|
|
164
|
+
| "modal"
|
|
165
|
+
/** A panel that slides up from the bottom to 92% of the viewport's height. The shopper drags its handle down to close it, except while paying. */
|
|
166
|
+
| "sheet"
|
|
167
|
+
/** A panel that fills the whole window. */
|
|
168
|
+
| "fullscreen"
|
|
169
|
+
/** Leaves the page for the checkout's own address, and `embedCheckout` resolves with the status `redirected`. */
|
|
170
|
+
| "redirect";
|
|
110
171
|
/**
|
|
111
172
|
* Why checkout can't go on. `code` is `session_expired`, `session_invalid` or `internal`. When `retryable` is true,
|
|
112
173
|
* checkout stays open and offers to try again.
|
|
113
174
|
*/
|
|
114
175
|
type CheckoutEmbedError = {
|
|
176
|
+
/** Why checkout can't go on: `session_expired`, `session_invalid` or `internal`. */
|
|
115
177
|
code: string;
|
|
178
|
+
/** A message from the checkout that says what went wrong. */
|
|
116
179
|
message: string;
|
|
180
|
+
/** True when checkout stays open and offers to try again. False when it closes. */
|
|
117
181
|
retryable: boolean;
|
|
118
182
|
};
|
|
119
183
|
/** Presentation, step and error reporting for an embedded checkout. The checkout always draws in Zappie's own design. */
|
|
120
184
|
type EmbedOptions = {
|
|
185
|
+
/** How checkout opens. Defaults to `auto`. */
|
|
121
186
|
presentation?: CheckoutPresentation;
|
|
122
187
|
/** Called with each checkout step, and whether a payment has started. */
|
|
123
188
|
onStep?: (step: string, paying: boolean) => void;
|
package/dist/checkout/embed.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{ZappieError}from"./sdk.js";var PARAM="zappie_checkout";var finished=new Set;var request;var media=query=>matchMedia(query).matches;function checkoutPresentation(presentation="auto"){if(presentation!=="auto"){return presentation}if(top!==window||/FBA[NV]|Instagram|TikTok|musical_ly|Bytedance|Line\//.test(navigator.userAgent)){return"redirect"}return media("(min-width:640px) and (pointer:fine),(min-width:1024px)")?"modal":"sheet"}function closeCheckout(){request?.()}async function resumeCheckout(checkout){const url=new URL(location.href);const id=url.searchParams.get(PARAM);if(!id){return null}url.searchParams.delete(PARAM);history.replaceState(history.state,"",url);const session=await checkout.session(id);return session.status==="completed"&&session.order_id?{status:"completed",orderId:session.order_id}:null}function embedCheckout(checkout,session,options={}){const url=new URL(session.url);if(request||session.status!=="open"||finished.has(session.id)||!/^(https:\/\/checkout\.(stg\.)?zappie\.ai|http:\/\/(localhost|127\.0\.0\.1)(:\d+)?)$/.test(url.origin)){return Promise.reject(new ZappieError("invalid_request","This checkout session can't be opened"))}const shown=checkoutPresentation(options.presentation);if(shown==="redirect"){location.assign(session.url);return Promise.resolve({status:"redirected"})}url.pathname=`/embed/${encodeURIComponent(session.id)}`;url.searchParams.set("origin",location.origin);const doc=document;const body=doc.body;const root=doc.createElement("div");const panel=doc.createElement("div");const handle=doc.createElement("div");const frame=doc.createElement("iframe");const sheet=shown==="sheet";const still=media("(prefers-reduced-motion:reduce)");const opener=doc.activeElement;const y=scrollY;const bodyStyle=body.style.cssText;const restoration=history.scrollRestoration;const inert=[...body.children].filter(el=>!el.inert);const abort=new AbortController;const vv=window.visualViewport;let ready=false;let paying=false;let height=640;let settle=()=>{};root.setAttribute("data-zappie-checkout",shown);root.setAttribute("role","dialog");root.setAttribute("aria-modal","true");root.setAttribute("aria-label","Checkout");root.style.cssText="position:fixed;inset:0;z-index:2147483647;background:var(--z-checkout-backdrop,#00000080)";panel.style.cssText=`position:absolute;overflow:hidden;display:flex;flex-direction:column;background:var(--z-surface,#fff);${shown==="fullscreen"?"inset:0":sheet?"left:0;right:0;border-radius:var(--z-checkout-radius,16px) var(--z-checkout-radius,16px) 0 0":"inset:0;margin:auto;width:min(480px,100vw - 32px);border-radius:var(--z-checkout-radius,16px)"}`;handle.style.cssText="flex:none;height:24px;touch-action:none;cursor:grab;background:radial-gradient(closest-side,var(--z-border,#ccc) 99%,#0000) 50%/40px 5px no-repeat";frame.title="Checkout";frame.src=url.href;frame.allow="payment 'src'; publickey-credentials-get 'src'";frame.referrerPolicy="no-referrer";frame.style.cssText="flex:1;width:100%;border:0";if(sheet){panel.append(handle)}panel.append(frame);root.append(panel);const layout=()=>{const view=vv??{height:innerHeight,offsetTop:0};if(sheet){panel.style.height=`${Math.round(view.height*.92)}px`;panel.style.bottom=`${Math.max(0,innerHeight-view.offsetTop-view.height)}px`}else if(shown==="modal"){panel.style.height=`${Math.min(height,view.height-32)}px`}};const post=(type,payload={})=>frame.contentWindow?.postMessage({source:"zappie-checkout",v:1,session:session.id,type,payload},url.origin);const finish=(result,popped)=>{abort.abort();request=void 0;root.remove();inert.forEach(el=>el.inert=false);body.style.cssText=bodyStyle;const restore=()=>{scrollTo(0,y);setTimeout(()=>{scrollTo(0,y);history.scrollRestoration=restoration})};restore();opener?.focus({preventScroll:true});if(!popped&&history.state?.[PARAM]===session.id){history.scrollRestoration="manual";addEventListener("popstate",restore,{once:true});history.back()}settle(result)};const close=()=>ready?post("close_request"):finish({status:"cancelled",reason:"user"});const onKey=event=>{if(event.key==="Escape"){close()}};const onPop=()=>{if(!ready){return finish({status:"cancelled",reason:"user"},true)}history.pushState({...history.state,[PARAM]:session.id},"",location.href);post("close_request")};const onMessage=event=>{const data=event.data;if(event.origin!==url.origin||event.source!==frame.contentWindow||data?.source!=="zappie-checkout"||data.v!==1||data.session!==session.id){return}const payload=Object(data.payload);if(data.type==="ready"||data.type==="step"){if(data.type==="ready"){ready=true;frame.focus()}paying=payload.paying===true;if(typeof payload.step==="string"){options.onStep?.(payload.step,paying)}}else if(data.type==="resize"&&Number.isFinite(payload.height)){height=payload.height;layout()}else if(data.type==="completed"){checkout.awaitCompletion(session.id,{signal:abort.signal,intervalMs:1500}).then(done=>{if(done.status==="completed"){finished.add(session.id);finish({status:"completed",orderId:done.order_id})}else{finish({status:"cancelled",reason:done.status})}},()=>{})}else if(data.type==="cancelled"||data.type==="error"){const retry=data.type==="error"&&payload.retryable===true;if(data.type==="error"){options.onError?.({code:payload.code,message:payload.message,retryable:retry})}if(retry){ready=paying=false}else{finish({status:"cancelled",reason:String(payload.reason??payload.code??"user")})}}};let start=0;handle.onpointerdown=event=>{if(paying){return}start=event.clientY;handle.setPointerCapture?.(event.pointerId)};handle.onpointermove=event=>{if(start){panel.style.transform=`translateY(${Math.max(0,event.clientY-start)}px)`}};handle.onpointerup=handle.onpointercancel=event=>{const moved=start?event.clientY-start:0;start=0;panel.style.transform="";if(!paying&&moved>panel.offsetHeight/4){finish({status:"cancelled",reason:"user"})}};history.pushState({...history.state,[PARAM]:session.id},"",(()=>{const here=new URL(location.href);here.searchParams.set(PARAM,session.id);return here})());const listen={signal:abort.signal};addEventListener("message",onMessage,listen);addEventListener("popstate",onPop,listen);addEventListener("keydown",onKey,listen);vv?.addEventListener("resize",layout,listen);vv?.addEventListener("scroll",layout,listen);inert.forEach(el=>el.inert=true);history.scrollRestoration="manual";body.style.cssText+=`;position:fixed;top:${-y}px;left:0;right:0;overflow:hidden`;body.append(root);layout();if(!still){panel.animate?.(sheet?[{transform:"translateY(100%)"},{transform:"none"}]:[{opacity:0},{opacity:1}],{duration:sheet?280:160,easing:"cubic-bezier(.2,.8,.2,1)"})}request=close;return new Promise(resolve=>settle=resolve)}export{checkoutPresentation,closeCheckout,embedCheckout,resumeCheckout};
|
|
2
|
-
//# sourceMappingURL=embed.js.map
|
package/dist/checkout/error.js
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
1
|
import{stableErrorCode,ZappieError}from"../internal/customer-http.js";var CheckoutError=class extends ZappieError{constructor(status,apiCode,message,param,issues){super(stableErrorCode(status,apiCode),message,{status,retryable:status===409||status===429||status>=500,...param!==void 0?{param}:{}});this.apiCode=apiCode;if(issues!==void 0){this.issues=issues}}};export{CheckoutError};
|
|
2
|
-
//# sourceMappingURL=error.js.map
|