@ecomweb/storefront-kit 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +85 -3
  2. package/dist/api/client.js +32 -1
  3. package/dist/api/client.js.map +1 -1
  4. package/dist/api/proxy.js +29 -4
  5. package/dist/api/proxy.js.map +1 -1
  6. package/dist/api/store-preview-header.js +42 -0
  7. package/dist/api/store-preview-header.js.map +1 -0
  8. package/dist/auth/error-copy.js +5 -1
  9. package/dist/auth/error-copy.js.map +1 -1
  10. package/dist/auth/session-refresh.js +2 -0
  11. package/dist/auth/session-refresh.js.map +1 -1
  12. package/dist/cart/server-context.js +26 -0
  13. package/dist/cart/server-context.js.map +1 -1
  14. package/dist/checkout/quote-changed.js +16 -0
  15. package/dist/checkout/quote-changed.js.map +1 -0
  16. package/dist/checkout/use-checkout.js +45 -5
  17. package/dist/checkout/use-checkout.js.map +1 -1
  18. package/dist/index.d.ts +152 -5
  19. package/dist/index.js +39 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/middleware/create-storefront-middleware.js +58 -11
  22. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  23. package/dist/middleware.d.ts +5 -2
  24. package/dist/orders/index.js +17 -1
  25. package/dist/orders/index.js.map +1 -1
  26. package/dist/orders/shipment-tracking.js +80 -0
  27. package/dist/orders/shipment-tracking.js.map +1 -0
  28. package/dist/provider.js +22 -0
  29. package/dist/provider.js.map +1 -1
  30. package/dist/redirects/lookup-redirect.js +2 -1
  31. package/dist/redirects/lookup-redirect.js.map +1 -1
  32. package/dist/server.d.ts +20 -1
  33. package/dist/server.js +4 -0
  34. package/dist/server.js.map +1 -1
  35. package/dist/shipping/format-shipping-option.js +28 -0
  36. package/dist/shipping/format-shipping-option.js.map +1 -1
  37. package/dist/shipping/messages.js +2 -0
  38. package/dist/shipping/messages.js.map +1 -1
  39. package/dist/shipping/option-id.js +7 -0
  40. package/dist/shipping/option-id.js.map +1 -0
  41. package/dist/shipping/shipping-calculation-reducer.js +60 -12
  42. package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
  43. package/dist/shipping/use-shipping-calculation.js +38 -5
  44. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  45. package/dist/stores/get-store-by-host.js +34 -7
  46. package/dist/stores/get-store-by-host.js.map +1 -1
  47. package/dist/stores/metadata.js +17 -0
  48. package/dist/stores/metadata.js.map +1 -1
  49. package/dist/stores/read-store-preview-token.js +10 -0
  50. package/dist/stores/read-store-preview-token.js.map +1 -0
  51. package/dist/stores/resolve-coming-soon.js +30 -0
  52. package/dist/stores/resolve-coming-soon.js.map +1 -0
  53. package/dist/stores/store-coming-soon.js +21 -0
  54. package/dist/stores/store-coming-soon.js.map +1 -0
  55. package/dist/stores/store-preview-cookie.js +64 -0
  56. package/dist/stores/store-preview-cookie.js.map +1 -0
  57. package/dist/stores/store-preview-guard.js +12 -0
  58. package/dist/stores/store-preview-guard.js.map +1 -0
  59. package/dist/stores/store-subdomain.js +10 -5
  60. package/dist/stores/store-subdomain.js.map +1 -1
  61. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\n\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n children,\n}: StorefrontKitProviderProps) {\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA2BI;AAvBJ,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAW9B,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAC7B,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useRef, type ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\nimport {\n setBrowserStorePreviewToken,\n setStorePreviewRenewer,\n} from \"./api/store-preview-header\";\n\n/**\n * How often a preview host's preview token is renewed: half of its 1 h, so\n * a long editor session never sends an expired one.\n */\nconst STORE_PREVIEW_RENEW_MS = 30 * 60 * 1000;\n\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n /**\n * The store preview token the browser's kit clients send as\n * `X-Store-Preview` (`readStorePreviewToken()` on the server). The layout\n * passes it only while the store is coming soon, else null.\n *\n * Why the browser gets it: the preview cookie stays httpOnly, but without\n * the token the client-side fetches on the home, collection and product\n * pages would get the API's 403 during a preview. It is one of three\n * tokens: the store preview cookie's (the dashboard's preview link), a\n * theme preview host's (`p-<slug>`, from the host lookup), or the theme\n * preview cookie's (`?preview_theme=` on the store's own host). Each is\n * read-only (the API opens GET and HEAD only) and bound to one store.\n * Merchant scripts are off during a store preview, so they never see it.\n */\n storePreviewToken?: string | null;\n /**\n * Fetches a fresh `storePreviewToken`, such as by re-rendering the layout.\n * The app passes it only on a theme preview host, whose token lasts 1 h:\n * the layout does not re-render on client navigation, so the first\n * render's token would run out in a long editor session. While both are\n * set, the kit calls it every 30 minutes, and when a read is refused with\n * `STORE_COMING_SOON` (at most once a minute). A link preview's 24 h\n * cookie is not renewed.\n */\n onStorePreviewRenew?: () => void;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n storePreviewToken,\n onStorePreviewRenew,\n children,\n}: StorefrontKitProviderProps) {\n // In the render body, not an effect: React renders this before any child\n // effect runs, so the first client fetch already carries the token. A\n // render without one clears it; until then it stays set (store-preview-\n // header.ts). A no-op on the server.\n setBrowserStorePreviewToken(storePreviewToken ?? null);\n\n // The latest callback, so an app that passes a new function on every\n // render does not restart the 30 minute timer each time.\n const renewRef = useRef(onStorePreviewRenew);\n renewRef.current = onStorePreviewRenew;\n const renews = !!storePreviewToken && !!onStorePreviewRenew;\n useEffect(() => {\n if (!renews) return;\n const renew = () => renewRef.current?.();\n setStorePreviewRenewer(renew);\n const timer = setInterval(renew, STORE_PREVIEW_RENEW_MS);\n return () => {\n clearInterval(timer);\n setStorePreviewRenewer(null);\n };\n }, [renews]);\n\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA8DI;AA5DJ,SAAS,WAAW,cAA8B;AAElD,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMP,MAAM,yBAAyB,KAAK,KAAK;AAoCzC,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAK7B,8BAA4B,qBAAqB,IAAI;AAIrD,QAAM,WAAW,OAAO,mBAAmB;AAC3C,WAAS,UAAU;AACnB,QAAM,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC;AACxC,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AACb,UAAM,QAAQ,MAAM,SAAS,UAAU;AACvC,2BAAuB,KAAK;AAC5B,UAAM,QAAQ,YAAY,OAAO,sBAAsB;AACvD,WAAO,MAAM;AACX,oBAAc,KAAK;AACnB,6BAAuB,IAAI;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","names":[]}
@@ -1,7 +1,8 @@
1
1
  import { sdk } from "../sdk.js";
2
+ import { SKIP_STORE_PREVIEW } from "../stores/store-preview-cookie.js";
2
3
  async function lookupRedirect(storeId, path) {
3
4
  try {
4
- return await sdk.redirects.lookup(storeId, path);
5
+ return await sdk.redirects.lookup(storeId, path, SKIP_STORE_PREVIEW);
5
6
  } catch (error) {
6
7
  console.error("Error looking up redirect:", error);
7
8
  return null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/redirects/lookup-redirect.ts"],"sourcesContent":["import type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\n\n/**\n * Lookup URL redirect for a given store and path\n * Used by middleware to check if a path should be redirected\n */\nexport async function lookupRedirect(\n storeId: string,\n path: string\n): Promise<UrlRedirect | null> {\n try {\n return await sdk.redirects.lookup(storeId, path);\n } catch (error) {\n console.error(\"Error looking up redirect:\", error);\n return null;\n }\n}\n"],"mappings":"AACA,SAAS,WAAW;AAMpB,eAAsB,eACpB,SACA,MAC6B;AAC7B,MAAI;AACF,WAAO,MAAM,IAAI,UAAU,OAAO,SAAS,IAAI;AAAA,EACjD,SAAS,OAAO;AACd,YAAQ,MAAM,8BAA8B,KAAK;AACjD,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/redirects/lookup-redirect.ts"],"sourcesContent":["import type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\nimport { SKIP_STORE_PREVIEW } from \"../stores/store-preview-cookie\";\n\n/**\n * Lookup URL redirect for a given store and path\n * Used by middleware to check if a path should be redirected\n */\nexport async function lookupRedirect(\n storeId: string,\n path: string\n): Promise<UrlRedirect | null> {\n try {\n // The middleware's own call: `next/headers` there is its raw incoming\n // request, so the ambient preview token must not ride along.\n return await sdk.redirects.lookup(storeId, path, SKIP_STORE_PREVIEW);\n } catch (error) {\n console.error(\"Error looking up redirect:\", error);\n return null;\n }\n}\n"],"mappings":"AACA,SAAS,WAAW;AACpB,SAAS,0BAA0B;AAMnC,eAAsB,eACpB,SACA,MAC6B;AAC7B,MAAI;AAGF,WAAO,MAAM,IAAI,UAAU,OAAO,SAAS,MAAM,kBAAkB;AAAA,EACrE,SAAS,OAAO;AACd,YAAQ,MAAM,8BAA8B,KAAK;AACjD,WAAO;AAAA,EACT;AACF;","names":[]}
package/dist/server.d.ts CHANGED
@@ -58,6 +58,14 @@ declare function resolveRootStoreRef(): Promise<string | null>;
58
58
  /** The open theme preview's token, if any (server components only). */
59
59
  declare function readThemePreviewToken(): Promise<string | null>;
60
60
 
61
+ /**
62
+ * The token this request sends as `X-Store-Preview` (server components
63
+ * only): a preview host's token the middleware stamped, else the store
64
+ * preview cookie, else the theme preview cookie. The layout passes it to
65
+ * `StorefrontKitProvider` while the store is coming soon.
66
+ */
67
+ declare function readStorePreviewToken(): Promise<string | null>;
68
+
61
69
  /**
62
70
  * The theme preview host's slug when this request came in on one (server
63
71
  * components only); the middleware sets it, never the client.
@@ -82,4 +90,15 @@ declare function externalThemeRedirectFor(request: {
82
90
  external_url?: string | null;
83
91
  } | null | undefined, previewOpen: boolean): string | null;
84
92
 
85
- export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readThemePreviewToken, requireSession, resolveRootStoreRef, serverConfig };
93
+ /**
94
+ * Whether the store this request belongs to is coming soon, and its name
95
+ * (null when the API gave none). Null when the store is not coming soon.
96
+ *
97
+ * The name only ever comes from the API lookup, never from the request, so
98
+ * the /coming-soon page cannot be made to show text a visitor chose.
99
+ */
100
+ declare function resolveComingSoonStore(): Promise<{
101
+ name: string | null;
102
+ } | null>;
103
+
104
+ export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readStorePreviewToken, readThemePreviewToken, requireSession, resolveComingSoonStore, resolveRootStoreRef, serverConfig };
package/dist/server.js CHANGED
@@ -8,8 +8,10 @@ import { hasCustomerSession } from "./auth/session.js";
8
8
  import { parseServerConfig, serverConfig } from "./config/server.js";
9
9
  import { resolveRootStoreRef } from "./store-scope/root.js";
10
10
  import { readThemePreviewToken } from "./theme/read-preview-token.js";
11
+ import { readStorePreviewToken } from "./stores/read-store-preview-token.js";
11
12
  import { readPreviewHostSlug } from "./theme/read-preview-host.js";
12
13
  import { externalThemeRedirectFor } from "./theme/external-storefront.js";
14
+ import { resolveComingSoonStore } from "./stores/resolve-coming-soon.js";
13
15
  export {
14
16
  createAuthRoutes,
15
17
  createBackendProxy,
@@ -17,8 +19,10 @@ export {
17
19
  hasCustomerSession,
18
20
  parseServerConfig,
19
21
  readPreviewHostSlug,
22
+ readStorePreviewToken,
20
23
  readThemePreviewToken,
21
24
  requireSession,
25
+ resolveComingSoonStore,
22
26
  resolveRootStoreRef,
23
27
  serverConfig
24
28
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;","names":[]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { readStorePreviewToken } from \"./stores/read-store-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\nexport { resolveComingSoonStore } from \"./stores/resolve-coming-soon\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;AACzC,SAAS,8BAA8B;","names":[]}
@@ -1,11 +1,39 @@
1
1
  import { formatPrice } from "../currency.js";
2
+ import { formatShippingEstimate } from "./messages.js";
2
3
  function isFreeShippingRate(amount) {
3
4
  return amount === 0;
4
5
  }
5
6
  function formatShippingAmount(amount, freeLabel, locale, currency) {
6
7
  return isFreeShippingRate(amount) ? freeLabel : formatPrice(amount, locale, currency);
7
8
  }
9
+ function safeHttpUrl(url) {
10
+ if (!url) return null;
11
+ try {
12
+ const { protocol } = new URL(url);
13
+ return protocol === "http:" || protocol === "https:" ? url : null;
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+ function describeShippingOption(option) {
19
+ let eta = null;
20
+ if (option.estimated_label) {
21
+ eta = option.estimated_label;
22
+ } else if (option.estimated_days_min != null) {
23
+ eta = formatShippingEstimate(
24
+ option.estimated_days_min,
25
+ option.estimated_days_max ?? option.estimated_days_min
26
+ );
27
+ }
28
+ return {
29
+ title: option.display_name,
30
+ carrierName: option.carrier_name ? [option.carrier_name, option.carrier_service_name].filter(Boolean).join(" \xB7 ") : null,
31
+ carrierLogoUrl: safeHttpUrl(option.carrier_logo_url),
32
+ eta
33
+ };
34
+ }
8
35
  export {
36
+ describeShippingOption,
9
37
  formatShippingAmount,
10
38
  isFreeShippingRate
11
39
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/format-shipping-option.ts"],"sourcesContent":["import { formatPrice, type SupportedCurrency } from \"../currency\";\n\n/**\n * A free shipping rate is a VALUE comparison (amount === 0), not a rate\n * type the API tags for us. There is no \"FREE\" rate_type in the shipping\n * vocabulary on purpose — see @ecomweb/sdk's shipping types.\n */\nexport function isFreeShippingRate(amount: number): boolean {\n return amount === 0;\n}\n\n/**\n * Renders a shipping option's price for display: the free label when the\n * rate is free, the house money format otherwise.\n *\n * `freeLabel` is passed in (see lib/shipping/messages.ts) rather than\n * hardcoded here, so this stays a pure, generic function reachable from a\n * plain vitest spec.\n */\nexport function formatShippingAmount(\n amount: number,\n freeLabel: string,\n locale: string,\n currency: SupportedCurrency | string\n): string {\n return isFreeShippingRate(amount)\n ? freeLabel\n : formatPrice(amount, locale, currency);\n}\n"],"mappings":"AAAA,SAAS,mBAA2C;AAO7C,SAAS,mBAAmB,QAAyB;AAC1D,SAAO,WAAW;AACpB;AAUO,SAAS,qBACd,QACA,WACA,QACA,UACQ;AACR,SAAO,mBAAmB,MAAM,IAC5B,YACA,YAAY,QAAQ,QAAQ,QAAQ;AAC1C;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/format-shipping-option.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\nimport { formatPrice, type SupportedCurrency } from \"../currency\";\nimport { formatShippingEstimate } from \"./messages\";\n\n/**\n * A free shipping rate is a VALUE comparison (amount === 0), not a rate\n * type the API tags for us. There is no \"FREE\" rate_type in the shipping\n * vocabulary on purpose — see @ecomweb/sdk's shipping types.\n */\nexport function isFreeShippingRate(amount: number): boolean {\n return amount === 0;\n}\n\n/**\n * Renders a shipping option's price for display: the free label when the\n * rate is free, the house money format otherwise.\n *\n * `freeLabel` is passed in (see lib/shipping/messages.ts) rather than\n * hardcoded here, so this stays a pure, generic function reachable from a\n * plain vitest spec.\n */\nexport function formatShippingAmount(\n amount: number,\n freeLabel: string,\n locale: string,\n currency: SupportedCurrency | string\n): string {\n return isFreeShippingRate(amount)\n ? freeLabel\n : formatPrice(amount, locale, currency);\n}\n\nexport interface ShippingOptionDisplay {\n title: string;\n carrierName: string | null;\n carrierLogoUrl: string | null;\n eta: string | null;\n}\n\n/** Carrier-provided URLs are untrusted: only http(s) may reach an <img src>. */\nfunction safeHttpUrl(url: string | null | undefined): string | null {\n if (!url) return null;\n try {\n const { protocol } = new URL(url);\n return protocol === \"http:\" || protocol === \"https:\" ? url : null;\n } catch {\n return null;\n }\n}\n\n/**\n * What an option row shows: title, carrier (when carrier-quoted) and an ETA.\n * The carrier's own label wins over the fixed-rate day range. The carrier\n * line names the service too: one carrier can offer several at one price.\n */\nexport function describeShippingOption(\n option: ShippingOption\n): ShippingOptionDisplay {\n let eta: string | null = null;\n if (option.estimated_label) {\n eta = option.estimated_label;\n } else if (option.estimated_days_min != null) {\n eta = formatShippingEstimate(\n option.estimated_days_min,\n option.estimated_days_max ?? option.estimated_days_min\n );\n }\n return {\n title: option.display_name,\n carrierName: option.carrier_name\n ? [option.carrier_name, option.carrier_service_name]\n .filter(Boolean)\n .join(\" · \")\n : null,\n carrierLogoUrl: safeHttpUrl(option.carrier_logo_url),\n eta,\n };\n}\n"],"mappings":"AACA,SAAS,mBAA2C;AACpD,SAAS,8BAA8B;AAOhC,SAAS,mBAAmB,QAAyB;AAC1D,SAAO,WAAW;AACpB;AAUO,SAAS,qBACd,QACA,WACA,QACA,UACQ;AACR,SAAO,mBAAmB,MAAM,IAC5B,YACA,YAAY,QAAQ,QAAQ,QAAQ;AAC1C;AAUA,SAAS,YAAY,KAA+C;AAClE,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,EAAE,SAAS,IAAI,IAAI,IAAI,GAAG;AAChC,WAAO,aAAa,WAAW,aAAa,WAAW,MAAM;AAAA,EAC/D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAOO,SAAS,uBACd,QACuB;AACvB,MAAI,MAAqB;AACzB,MAAI,OAAO,iBAAiB;AAC1B,UAAM,OAAO;AAAA,EACf,WAAW,OAAO,sBAAsB,MAAM;AAC5C,UAAM;AAAA,MACJ,OAAO;AAAA,MACP,OAAO,sBAAsB,OAAO;AAAA,IACtC;AAAA,EACF;AACA,SAAO;AAAA,IACL,OAAO,OAAO;AAAA,IACd,aAAa,OAAO,eAChB,CAAC,OAAO,cAAc,OAAO,oBAAoB,EAC9C,OAAO,OAAO,EACd,KAAK,QAAK,IACb;AAAA,IACJ,gBAAgB,YAAY,OAAO,gBAAgB;AAAA,IACnD;AAAA,EACF;AACF;","names":[]}
@@ -7,6 +7,8 @@ const SHIPPING_MESSAGES = Object.freeze({
7
7
  failedHint: "K\u1EBFt n\u1ED1i c\xF3 th\u1EC3 \u0111ang gi\xE1n \u0111o\u1EA1n. Vui l\xF2ng th\u1EED l\u1EA1i.",
8
8
  retry: "Th\u1EED l\u1EA1i",
9
9
  free: "Mi\u1EC5n ph\xED",
10
+ quoteChanged: "Ph\xED v\u1EADn chuy\u1EC3n \u0111\xE3 thay \u0111\u1ED5i",
11
+ quoteChangedHint: "Vui l\xF2ng ki\u1EC3m tra l\u1EA1i ph\xED v\u1EADn chuy\u1EC3n m\u1EDBi r\u1ED3i \u0111\u1EB7t h\xE0ng.",
10
12
  estimate: "D\u1EF1 ki\u1EBFn giao: {min} \u0111\u1EBFn {max} ng\xE0y"
11
13
  });
12
14
  function formatShippingEstimate(min, max) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/messages.ts"],"sourcesContent":["/**\n * Checkout shipping strings, extracted from the components that used to\n * hardcode them inline. This is NOT an i18n layer -- the storefront has no\n * i18n infrastructure (no next-intl, no locale routing, no message\n * catalog), and bootstrapping one is out of scope for a shipping-vocabulary\n * change. This just gets every shipping string into one place so a real\n * i18n task can source from here later instead of hunting through JSX.\n *\n * `estimate` is a template: interpolate `{min}` and `{max}` yourself.\n */\nexport const SHIPPING_MESSAGES = Object.freeze({\n title: \"Phương thức vận chuyển\",\n prompt: \"Vui lòng nhập địa chỉ giao hàng để xem phương thức vận chuyển\",\n empty: \"Không có phương thức vận chuyển phù hợp\",\n emptyHint:\n \"Vui lòng kiểm tra lại địa chỉ giao hàng hoặc liên hệ với cửa hàng.\",\n failed: \"Không thể tính phí vận chuyển\",\n failedHint: \"Kết nối có thể đang gián đoạn. Vui lòng thử lại.\",\n retry: \"Thử lại\",\n free: \"Miễn phí\",\n estimate: \"Dự kiến giao: {min} đến {max} ngày\",\n});\n\n/** Fills in the `{min}`/`{max}` placeholders in `SHIPPING_MESSAGES.estimate`. */\nexport function formatShippingEstimate(min: number, max: number): string {\n return SHIPPING_MESSAGES.estimate\n .replace(\"{min}\", String(min))\n .replace(\"{max}\", String(max));\n}\n"],"mappings":"AAUO,MAAM,oBAAoB,OAAO,OAAO;AAAA,EAC7C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WACE;AAAA,EACF,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAM;AAAA,EACN,UAAU;AACZ,CAAC;AAGM,SAAS,uBAAuB,KAAa,KAAqB;AACvE,SAAO,kBAAkB,SACtB,QAAQ,SAAS,OAAO,GAAG,CAAC,EAC5B,QAAQ,SAAS,OAAO,GAAG,CAAC;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/messages.ts"],"sourcesContent":["/**\n * Checkout shipping strings, extracted from the components that used to\n * hardcode them inline. This is NOT an i18n layer -- the storefront has no\n * i18n infrastructure (no next-intl, no locale routing, no message\n * catalog), and bootstrapping one is out of scope for a shipping-vocabulary\n * change. This just gets every shipping string into one place so a real\n * i18n task can source from here later instead of hunting through JSX.\n *\n * `estimate` is a template: interpolate `{min}` and `{max}` yourself.\n */\nexport const SHIPPING_MESSAGES = Object.freeze({\n title: \"Phương thức vận chuyển\",\n prompt: \"Vui lòng nhập địa chỉ giao hàng để xem phương thức vận chuyển\",\n empty: \"Không có phương thức vận chuyển phù hợp\",\n emptyHint:\n \"Vui lòng kiểm tra lại địa chỉ giao hàng hoặc liên hệ với cửa hàng.\",\n failed: \"Không thể tính phí vận chuyển\",\n failedHint: \"Kết nối có thể đang gián đoạn. Vui lòng thử lại.\",\n retry: \"Thử lại\",\n free: \"Miễn phí\",\n quoteChanged: \"Phí vận chuyển đã thay đổi\",\n quoteChangedHint: \"Vui lòng kiểm tra lại phí vận chuyển mới rồi đặt hàng.\",\n estimate: \"Dự kiến giao: {min} đến {max} ngày\",\n});\n\n/** Fills in the `{min}`/`{max}` placeholders in `SHIPPING_MESSAGES.estimate`. */\nexport function formatShippingEstimate(min: number, max: number): string {\n return SHIPPING_MESSAGES.estimate\n .replace(\"{min}\", String(min))\n .replace(\"{max}\", String(max));\n}\n"],"mappings":"AAUO,MAAM,oBAAoB,OAAO,OAAO;AAAA,EAC7C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WACE;AAAA,EACF,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAM;AAAA,EACN,cAAc;AAAA,EACd,kBAAkB;AAAA,EAClB,UAAU;AACZ,CAAC;AAGM,SAAS,uBAAuB,KAAa,KAAqB;AACvE,SAAO,kBAAkB,SACtB,QAAQ,SAAS,OAAO,GAAG,CAAC,EAC5B,QAAQ,SAAS,OAAO,GAAG,CAAC;AACjC;","names":[]}
@@ -0,0 +1,7 @@
1
+ function optionIdOf(option) {
2
+ return option.option_id ?? String(option.rate_id);
3
+ }
4
+ export {
5
+ optionIdOf
6
+ };
7
+ //# sourceMappingURL=option-id.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shipping/option-id.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * The stable identity of a shipping option. Carrier-backed rates can offer\n * several options under one `rate_id`, so the API sends `option_id`; older\n * APIs don't, and `rate_id` alone is unique there.\n */\nexport function optionIdOf(option: ShippingOption): string {\n return option.option_id ?? String(option.rate_id);\n}\n"],"mappings":"AAOO,SAAS,WAAW,QAAgC;AACzD,SAAO,OAAO,aAAa,OAAO,OAAO,OAAO;AAClD;","names":[]}
@@ -1,12 +1,26 @@
1
+ import { optionIdOf } from "./option-id.js";
1
2
  const initialShippingCalculationState = {
2
3
  shippingFee: 0,
3
4
  isCalculatingShipping: false,
4
5
  hasCalculatedShipping: false,
5
6
  shippingOptions: [],
6
7
  selectedShippingRate: null,
8
+ selectedOptionId: null,
7
9
  requestId: 0,
8
10
  calculationFailed: false
9
11
  };
12
+ function selectFrom(options, preferId) {
13
+ const preferred = preferId === null ? void 0 : options.find((option) => optionIdOf(option) === preferId);
14
+ const chosen = preferred ?? options.reduce(
15
+ (best, option) => !best || option.amount < best.amount ? option : best,
16
+ null
17
+ );
18
+ return chosen ? {
19
+ optionId: optionIdOf(chosen),
20
+ rateId: chosen.rate_id,
21
+ fee: chosen.amount
22
+ } : { optionId: null, rateId: null, fee: 0 };
23
+ }
10
24
  function shippingCalculationReducer(state, action) {
11
25
  switch (action.type) {
12
26
  case "RESET":
@@ -24,10 +38,7 @@ function shippingCalculationReducer(state, action) {
24
38
  case "CALCULATION_SUCCEEDED": {
25
39
  if (action.requestId !== state.requestId) return state;
26
40
  const { options } = action;
27
- const cheapest = options.reduce(
28
- (best, option) => !best || option.amount < best.amount ? option : best,
29
- null
30
- );
41
+ const picked = selectFrom(options, null);
31
42
  return {
32
43
  ...state,
33
44
  shippingOptions: options,
@@ -35,10 +46,36 @@ function shippingCalculationReducer(state, action) {
35
46
  isCalculatingShipping: false,
36
47
  // Auto-select the cheapest option. This also revalidates the
37
48
  // selection on every successful recalculation: it is always
38
- // replaced with a rate_id guaranteed to belong to THIS response,
39
- // so a stale rate from an earlier quote can never linger.
40
- selectedShippingRate: cheapest ? cheapest.rate_id : null,
41
- shippingFee: cheapest ? cheapest.amount : 0,
49
+ // replaced with an option guaranteed to belong to THIS response,
50
+ // so a stale selection from an earlier quote can never linger.
51
+ selectedOptionId: picked.optionId,
52
+ selectedShippingRate: picked.rateId,
53
+ shippingFee: picked.fee,
54
+ calculationFailed: false
55
+ };
56
+ }
57
+ case "QUOTE_REPLACED": {
58
+ if (action.requestId !== state.requestId) return state;
59
+ const incoming = new Map(action.options.map((o) => [optionIdOf(o), o]));
60
+ const merged = state.shippingOptions.map(
61
+ (o) => incoming.get(optionIdOf(o)) ?? o
62
+ );
63
+ const known = new Set(state.shippingOptions.map(optionIdOf));
64
+ for (const o of action.options) {
65
+ if (!known.has(optionIdOf(o))) {
66
+ known.add(optionIdOf(o));
67
+ merged.push(o);
68
+ }
69
+ }
70
+ const picked = selectFrom(merged, action.preferOptionId);
71
+ return {
72
+ ...state,
73
+ shippingOptions: merged,
74
+ hasCalculatedShipping: true,
75
+ isCalculatingShipping: false,
76
+ selectedOptionId: picked.optionId,
77
+ selectedShippingRate: picked.rateId,
78
+ shippingFee: picked.fee,
42
79
  calculationFailed: false
43
80
  };
44
81
  }
@@ -49,10 +86,23 @@ function shippingCalculationReducer(state, action) {
49
86
  shippingFee: 0,
50
87
  shippingOptions: [],
51
88
  selectedShippingRate: null,
89
+ selectedOptionId: null,
52
90
  hasCalculatedShipping: false,
53
91
  isCalculatingShipping: false,
54
92
  calculationFailed: true
55
93
  };
94
+ case "OPTION_SELECTED": {
95
+ const option = state.shippingOptions.find(
96
+ (opt) => optionIdOf(opt) === action.optionId
97
+ );
98
+ if (!option) return state;
99
+ return {
100
+ ...state,
101
+ selectedOptionId: optionIdOf(option),
102
+ selectedShippingRate: option.rate_id,
103
+ shippingFee: option.amount
104
+ };
105
+ }
56
106
  case "RATE_SELECTED": {
57
107
  const option = state.shippingOptions.find(
58
108
  (opt) => opt.rate_id === action.rateId
@@ -60,10 +110,8 @@ function shippingCalculationReducer(state, action) {
60
110
  return {
61
111
  ...state,
62
112
  selectedShippingRate: action.rateId,
63
- // Preserves the previous fee if the id doesn't match a known
64
- // option -- shouldn't happen in practice (the UI only ever
65
- // dispatches a rate_id it just rendered from shippingOptions),
66
- // kept explicit rather than silently coercing the fee to 0.
113
+ selectedOptionId: option ? optionIdOf(option) : state.selectedOptionId,
114
+ // Preserves the previous fee if the id doesn't match a known option.
67
115
  shippingFee: option ? option.amount : state.shippingFee
68
116
  };
69
117
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n selectedShippingRate: number | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | {\n type: \"CALCULATION_SUCCEEDED\";\n options: ShippingOption[];\n requestId: number;\n }\n | { type: \"CALCULATION_FAILED\"; requestId: number }\n /** The shopper picked a specific option out of the current quote. */\n | { type: \"RATE_SELECTED\"; rateId: number };\n\nexport function shippingCalculationReducer(\n state: ShippingCalculationState,\n action: ShippingCalculationAction\n): ShippingCalculationState {\n switch (action.type) {\n case \"RESET\":\n // Keep counting up: a response from before the reset must still be\n // recognisable as stale.\n return {\n ...initialShippingCalculationState,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_STARTED\":\n return {\n ...state,\n isCalculatingShipping: true,\n calculationFailed: false,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_SUCCEEDED\": {\n if (action.requestId !== state.requestId) return state;\n const { options } = action;\n // The cheapest option (the API's order breaks ties), as shoppers\n // expect: a free rate is never passed over for a paid one.\n const cheapest = options.reduce<(typeof options)[number] | null>(\n (best, option) =>\n !best || option.amount < best.amount ? option : best,\n null\n );\n return {\n ...state,\n shippingOptions: options,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n // Auto-select the cheapest option. This also revalidates the\n // selection on every successful recalculation: it is always\n // replaced with a rate_id guaranteed to belong to THIS response,\n // so a stale rate from an earlier quote can never linger.\n selectedShippingRate: cheapest ? cheapest.rate_id : null,\n shippingFee: cheapest ? cheapest.amount : 0,\n calculationFailed: false,\n };\n }\n\n case \"CALCULATION_FAILED\":\n if (action.requestId !== state.requestId) return state;\n return {\n ...state,\n shippingFee: 0,\n shippingOptions: [],\n selectedShippingRate: null,\n hasCalculatedShipping: false,\n isCalculatingShipping: false,\n calculationFailed: true,\n };\n\n case \"RATE_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => opt.rate_id === action.rateId\n );\n return {\n ...state,\n selectedShippingRate: action.rateId,\n // Preserves the previous fee if the id doesn't match a known\n // option -- shouldn't happen in practice (the UI only ever\n // dispatches a rate_id it just rendered from shippingOptions),\n // kept explicit rather than silently coercing the fee to 0.\n shippingFee: option ? option.amount : state.shippingFee,\n };\n }\n\n default:\n return state;\n }\n}\n"],"mappings":"AA+BO,MAAM,kCAA4D;AAAA,EACvE,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,iBAAiB,CAAC;AAAA,EAClB,sBAAsB;AAAA,EACtB,WAAW;AAAA,EACX,mBAAmB;AACrB;AAsBO,SAAS,2BACd,OACA,QAC0B;AAC1B,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AAGH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,QACnB,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK,yBAAyB;AAC5B,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,YAAM,EAAE,QAAQ,IAAI;AAGpB,YAAM,WAAW,QAAQ;AAAA,QACvB,CAAC,MAAM,WACL,CAAC,QAAQ,OAAO,SAAS,KAAK,SAAS,SAAS;AAAA,QAClD;AAAA,MACF;AACA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,iBAAiB;AAAA,QACjB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA,QAKvB,sBAAsB,WAAW,SAAS,UAAU;AAAA,QACpD,aAAa,WAAW,SAAS,SAAS;AAAA,QAC1C,mBAAmB;AAAA,MACrB;AAAA,IACF;AAAA,IAEA,KAAK;AACH,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,aAAO;AAAA,QACL,GAAG;AAAA,QACH,aAAa;AAAA,QACb,iBAAiB,CAAC;AAAA,QAClB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,MACrB;AAAA,IAEF,KAAK,iBAAiB;AACpB,YAAM,SAAS,MAAM,gBAAgB;AAAA,QACnC,SAAO,IAAI,YAAY,OAAO;AAAA,MAChC;AACA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,sBAAsB,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,QAK7B,aAAa,SAAS,OAAO,SAAS,MAAM;AAAA,MAC9C;AAAA,IACF;AAAA,IAEA;AACE,aAAO;AAAA,EACX;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\nimport { optionIdOf } from \"./option-id\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n /** The `rate_id` of the selected option; kept for existing callers. */\n selectedShippingRate: number | null;\n /**\n * The selected option's identity (`optionIdOf`). Several carrier options\n * can share one `rate_id`, so this, not the rate id, picks the option.\n */\n selectedOptionId: string | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n selectedOptionId: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | {\n type: \"CALCULATION_SUCCEEDED\";\n options: ShippingOption[];\n requestId: number;\n }\n | { type: \"CALCULATION_FAILED\"; requestId: number }\n /**\n * The current quote was re-priced (e.g. the API reported a changed\n * quote). Judged against the current `requestId` like\n * CALCULATION_SUCCEEDED, and does not bump it. MERGES by option id: the\n * given options replace matching entries, other existing options are\n * kept (the API re-checks their amounts at placement), and new ones are\n * appended. Keeps `preferOptionId` selected when it is still offered, else\n * the cheapest option.\n */\n | {\n type: \"QUOTE_REPLACED\";\n options: ShippingOption[];\n requestId: number;\n preferOptionId: string | null;\n }\n /** The shopper picked a specific option out of the current quote. */\n | { type: \"OPTION_SELECTED\"; optionId: string }\n /** @deprecated Use OPTION_SELECTED. Selects the first option with this rate_id. */\n | { type: \"RATE_SELECTED\"; rateId: number };\n\ninterface Selection {\n optionId: string | null;\n rateId: number | null;\n fee: number;\n}\n\n/**\n * Picks `preferId` when it is among `options`, else the cheapest option\n * (the API's order breaks ties), as shoppers expect: a free rate is never\n * passed over for a paid one.\n */\nfunction selectFrom(\n options: ShippingOption[],\n preferId: string | null\n): Selection {\n const preferred =\n preferId === null\n ? undefined\n : options.find(option => optionIdOf(option) === preferId);\n const chosen =\n preferred ??\n options.reduce<ShippingOption | null>(\n (best, option) => (!best || option.amount < best.amount ? option : best),\n null\n );\n return chosen\n ? {\n optionId: optionIdOf(chosen),\n rateId: chosen.rate_id,\n fee: chosen.amount,\n }\n : { optionId: null, rateId: null, fee: 0 };\n}\n\nexport function shippingCalculationReducer(\n state: ShippingCalculationState,\n action: ShippingCalculationAction\n): ShippingCalculationState {\n switch (action.type) {\n case \"RESET\":\n // Keep counting up: a response from before the reset must still be\n // recognisable as stale.\n return {\n ...initialShippingCalculationState,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_STARTED\":\n return {\n ...state,\n isCalculatingShipping: true,\n calculationFailed: false,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_SUCCEEDED\": {\n if (action.requestId !== state.requestId) return state;\n const { options } = action;\n const picked = selectFrom(options, null);\n return {\n ...state,\n shippingOptions: options,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n // Auto-select the cheapest option. This also revalidates the\n // selection on every successful recalculation: it is always\n // replaced with an option guaranteed to belong to THIS response,\n // so a stale selection from an earlier quote can never linger.\n selectedOptionId: picked.optionId,\n selectedShippingRate: picked.rateId,\n shippingFee: picked.fee,\n calculationFailed: false,\n };\n }\n\n case \"QUOTE_REPLACED\": {\n if (action.requestId !== state.requestId) return state;\n const incoming = new Map(action.options.map(o => [optionIdOf(o), o]));\n const merged = state.shippingOptions.map(\n o => incoming.get(optionIdOf(o)) ?? o\n );\n const known = new Set(state.shippingOptions.map(optionIdOf));\n for (const o of action.options) {\n if (!known.has(optionIdOf(o))) {\n known.add(optionIdOf(o));\n merged.push(o);\n }\n }\n const picked = selectFrom(merged, action.preferOptionId);\n return {\n ...state,\n shippingOptions: merged,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n selectedOptionId: picked.optionId,\n selectedShippingRate: picked.rateId,\n shippingFee: picked.fee,\n calculationFailed: false,\n };\n }\n\n case \"CALCULATION_FAILED\":\n if (action.requestId !== state.requestId) return state;\n return {\n ...state,\n shippingFee: 0,\n shippingOptions: [],\n selectedShippingRate: null,\n selectedOptionId: null,\n hasCalculatedShipping: false,\n isCalculatingShipping: false,\n calculationFailed: true,\n };\n\n case \"OPTION_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => optionIdOf(opt) === action.optionId\n );\n // An id that isn't in the current quote is ignored: the UI only\n // dispatches ids it just rendered from shippingOptions.\n if (!option) return state;\n return {\n ...state,\n selectedOptionId: optionIdOf(option),\n selectedShippingRate: option.rate_id,\n shippingFee: option.amount,\n };\n }\n\n case \"RATE_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => opt.rate_id === action.rateId\n );\n return {\n ...state,\n selectedShippingRate: action.rateId,\n selectedOptionId: option ? optionIdOf(option) : state.selectedOptionId,\n // Preserves the previous fee if the id doesn't match a known option.\n shippingFee: option ? option.amount : state.shippingFee,\n };\n }\n\n default:\n return state;\n }\n}\n"],"mappings":"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","names":[]}
@@ -1,7 +1,8 @@
1
1
  import { sdk } from "../sdk.js";
2
- import { useReducer, useEffect, useCallback, useRef } from "react";
2
+ import { useReducer, useEffect, useCallback, useRef, useMemo } from "react";
3
3
  import { SHIPPING_MESSAGES } from "./messages.js";
4
4
  import { useNotify } from "../notices.js";
5
+ import { optionIdOf } from "./option-id.js";
5
6
  import {
6
7
  shippingCalculationReducer,
7
8
  initialShippingCalculationState
@@ -12,7 +13,8 @@ function useShippingCalculation({
12
13
  ward,
13
14
  subtotal,
14
15
  totalWeight,
15
- itemsCount
16
+ itemsCount,
17
+ includeCarrierOptions = false
16
18
  }) {
17
19
  const [state, dispatch] = useReducer(
18
20
  shippingCalculationReducer,
@@ -23,7 +25,7 @@ function useShippingCalculation({
23
25
  stateRef.current = state;
24
26
  useEffect(() => {
25
27
  dispatch({ type: "RESET" });
26
- }, [city, ward, subtotal, totalWeight]);
28
+ }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);
27
29
  const calculateShippingFee = useCallback(async () => {
28
30
  if (!city || !ward || itemsCount === 0) {
29
31
  dispatch({ type: "RESET" });
@@ -37,7 +39,8 @@ function useShippingCalculation({
37
39
  ward_id: ward,
38
40
  subtotal,
39
41
  currency: "VND",
40
- weight_gr: totalWeight
42
+ weight_gr: totalWeight,
43
+ ...includeCarrierOptions && { include_carrier_options: true }
41
44
  });
42
45
  dispatch({ type: "CALCULATION_SUCCEEDED", options, requestId: next });
43
46
  } catch (error) {
@@ -51,7 +54,16 @@ function useShippingCalculation({
51
54
  description: SHIPPING_MESSAGES.failedHint
52
55
  });
53
56
  }
54
- }, [city, ward, itemsCount, storeRef, subtotal, totalWeight, notify]);
57
+ }, [
58
+ city,
59
+ ward,
60
+ itemsCount,
61
+ storeRef,
62
+ subtotal,
63
+ totalWeight,
64
+ includeCarrierOptions,
65
+ notify
66
+ ]);
55
67
  useEffect(() => {
56
68
  const timeoutId = setTimeout(() => {
57
69
  calculateShippingFee();
@@ -61,6 +73,22 @@ function useShippingCalculation({
61
73
  const handleShippingRateSelect = useCallback((rateId) => {
62
74
  dispatch({ type: "RATE_SELECTED", rateId });
63
75
  }, []);
76
+ const handleShippingOptionSelect = useCallback((optionId) => {
77
+ dispatch({ type: "OPTION_SELECTED", optionId });
78
+ }, []);
79
+ const replaceOptions = useCallback(
80
+ (options, preferOptionId, requestId) => {
81
+ dispatch({ type: "QUOTE_REPLACED", options, requestId, preferOptionId });
82
+ },
83
+ []
84
+ );
85
+ const currentRequestId = useCallback(() => stateRef.current.requestId, []);
86
+ const selectedOption = useMemo(
87
+ () => state.selectedOptionId === null ? null : state.shippingOptions.find(
88
+ (o) => optionIdOf(o) === state.selectedOptionId
89
+ ) ?? null,
90
+ [state.shippingOptions, state.selectedOptionId]
91
+ );
64
92
  return {
65
93
  shippingFee: state.shippingFee,
66
94
  isCalculatingShipping: state.isCalculatingShipping,
@@ -68,6 +96,11 @@ function useShippingCalculation({
68
96
  shippingOptions: state.shippingOptions,
69
97
  selectedShippingRate: state.selectedShippingRate,
70
98
  calculationFailed: state.calculationFailed,
99
+ selectedOptionId: state.selectedOptionId,
100
+ selectedOption,
101
+ handleShippingOptionSelect,
102
+ replaceOptions,
103
+ currentRequestId,
71
104
  handleShippingRateSelect,
72
105
  /**
73
106
  * Re-run the quote with the inputs unchanged. The debounced effect only
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef } from \"react\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [city, ward, itemsCount, storeRef, subtotal, totalWeight, notify]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,cAAc;AAC3D,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAWA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgC;AAC9B,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACA,QAAM,SAAS,UAAU;AAIzB,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAanB,YAAU,MAAM;AACd,aAAS,EAAE,MAAM,QAAQ,CAAC;AAAA,EAC5B,GAAG,CAAC,MAAM,MAAM,UAAU,WAAW,CAAC;AAEtC,QAAM,uBAAuB,YAAY,YAAY;AACnD,QAAI,CAAC,QAAQ,CAAC,QAAQ,eAAe,GAAG;AACtC,eAAS,EAAE,MAAM,QAAQ,CAAC;AAC1B;AAAA,IACF;AAKA,UAAM,OAAO,SAAS,QAAQ,YAAY;AAC1C,aAAS,EAAE,MAAM,sBAAsB,CAAC;AAExC,QAAI;AACF,YAAM,UAAU,MAAM,IAAI,SAAS,UAAU,UAAU;AAAA,QACrD,aAAa;AAAA,QACb,SAAS;AAAA,QACT;AAAA,QACA,UAAU;AAAA,QACV,WAAW;AAAA,MACb,CAAC;AAED,eAAS,EAAE,MAAM,yBAAyB,SAAS,WAAW,KAAK,CAAC;AAAA,IACtE,SAAS,OAAO;AAMd,UAAI,SAAS,SAAS,QAAQ,UAAW;AAEzC,cAAQ,MAAM,qCAAqC,KAAK;AACxD,eAAS,EAAE,MAAM,sBAAsB,WAAW,KAAK,CAAC;AACxD,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO,kBAAkB;AAAA,QACzB,aAAa,kBAAkB;AAAA,MACjC,CAAC;AAAA,IACH;AAAA,EACF,GAAG,CAAC,MAAM,MAAM,YAAY,UAAU,UAAU,aAAa,MAAM,CAAC;AAGpE,YAAU,MAAM;AACd,UAAM,YAAY,WAAW,MAAM;AACjC,2BAAqB;AAAA,IACvB,GAAG,GAAG;AAEN,WAAO,MAAM,aAAa,SAAS;AAAA,EACrC,GAAG,CAAC,oBAAoB,CAAC;AAGzB,QAAM,2BAA2B,YAAY,CAAC,WAAmB;AAC/D,aAAS,EAAE,MAAM,iBAAiB,OAAO,CAAC;AAAA,EAC5C,GAAG,CAAC,CAAC;AAEL,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,uBAAuB,MAAM;AAAA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"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","names":[]}
@@ -1,5 +1,13 @@
1
1
  import { sdk } from "../sdk.js";
2
2
  import { isStoreSuspendedError } from "./store-suspension.js";
3
+ import {
4
+ comingSoonStoreNameOf,
5
+ isStoreComingSoonError
6
+ } from "./store-coming-soon.js";
7
+ import {
8
+ SKIP_STORE_PREVIEW,
9
+ STORE_PREVIEW_HEADER
10
+ } from "./store-preview-cookie.js";
3
11
  import { publicConfig } from "../config.js";
4
12
  import { TtlCache } from "./ttl-cache.js";
5
13
  const FOUND_TTL_MS = 3e4;
@@ -15,7 +23,7 @@ function platformSubdomain(hostname, platformDomain) {
15
23
  const label = hostname.slice(0, -suffix.length);
16
24
  return label && !label.includes(".") ? label : null;
17
25
  }
18
- async function getStoreByHost(host) {
26
+ async function getStoreByHost(host, options) {
19
27
  if (host.includes("localhost") || host.includes("127.0.0.1")) {
20
28
  return {
21
29
  storeRef: null,
@@ -23,17 +31,26 @@ async function getStoreByHost(host) {
23
31
  isSubDomain: false,
24
32
  suspended: false,
25
33
  externalUrl: null,
26
- previewSlug: null
34
+ previewSlug: null,
35
+ comingSoon: false,
36
+ comingSoonName: null,
37
+ storePreviewToken: null
27
38
  };
28
39
  }
40
+ const previewToken = options?.previewToken || null;
29
41
  const key = host.toLowerCase();
30
- const cached = byHost.get(key);
31
- if (cached) return cached;
42
+ if (!previewToken) {
43
+ const cached = byHost.get(key);
44
+ if (cached) return cached;
45
+ }
32
46
  let storeRef = null;
33
47
  let domain = null;
34
48
  let suspended = false;
35
49
  let externalUrl = null;
36
50
  let previewSlug = null;
51
+ let comingSoon = false;
52
+ let comingSoonName = null;
53
+ let storePreviewToken = null;
37
54
  let failed = false;
38
55
  const hostname = key.split(":")[0];
39
56
  const platformDomain = (publicConfig().platformDomainSuffix ?? "ecomsite.app").toLowerCase();
@@ -41,16 +58,23 @@ async function getStoreByHost(host) {
41
58
  const isSubDomain = subdomain !== null;
42
59
  try {
43
60
  const lookupValue = subdomain ?? host;
44
- const foundStore = await sdk.stores.getByDomain(lookupValue);
61
+ const foundStore = await sdk.stores.getByDomain(
62
+ lookupValue,
63
+ previewToken ? { headers: { [STORE_PREVIEW_HEADER]: previewToken } } : SKIP_STORE_PREVIEW
64
+ );
45
65
  if (foundStore?.ref) {
46
66
  storeRef = foundStore.ref;
47
67
  domain = foundStore.config?.custom_domain || null;
48
68
  externalUrl = foundStore.storefront_url || null;
49
69
  previewSlug = foundStore.preview_slug || null;
70
+ storePreviewToken = previewSlug ? foundStore.store_preview_token || null : null;
50
71
  }
51
72
  } catch (error) {
52
73
  if (isStoreSuspendedError(error)) {
53
74
  suspended = true;
75
+ } else if (isStoreComingSoonError(error)) {
76
+ comingSoon = true;
77
+ comingSoonName = comingSoonStoreNameOf(error);
54
78
  } else {
55
79
  failed = true;
56
80
  console.error("Store not found for host:", host);
@@ -62,9 +86,12 @@ async function getStoreByHost(host) {
62
86
  isSubDomain,
63
87
  suspended,
64
88
  externalUrl,
65
- previewSlug
89
+ previewSlug,
90
+ comingSoon,
91
+ comingSoonName,
92
+ storePreviewToken
66
93
  };
67
- if (!failed) {
94
+ if (!failed && !previewToken) {
68
95
  byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);
69
96
  }
70
97
  return result;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport { publicConfig } from \"../config\";\nimport { TtlCache } from \"./ttl-cache\";\n\ntype StoreByHost = Awaited<ReturnType<typeof getStoreByHost>>;\n\n/**\n * How long a lookup is reused in this process. A merchant's change (custom\n * domain, external theme, suspension) reaches shoppers within this window on\n * top of the API's own Redis cache. Misses and suspensions expire sooner so\n * a new or re-enabled store shows up quickly. A failed lookup (API down) is\n * never cached: it would turn a blip into a run of 404s.\n */\nconst FOUND_TTL_MS = 30_000;\nconst NOT_FOUND_TTL_MS = 10_000;\nconst MAX_HOSTS = 10_000;\n\nconst byHost = new TtlCache<StoreByHost>(MAX_HOSTS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreByHostCache(): void {\n byHost.clear();\n}\n\n/**\n * The store's subdomain label when `hostname` is `<label>.<platformDomain>`\n * (a single label, so `www.shop.<platform>` and `shop.evil<platform>` are\n * not subdomains), else null.\n */\nfunction platformSubdomain(\n hostname: string,\n platformDomain: string\n): string | null {\n const suffix = `.${platformDomain}`;\n if (!hostname.endsWith(suffix)) return null;\n const label = hostname.slice(0, -suffix.length);\n return label && !label.includes(\".\") ? label : null;\n}\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n */\nexport async function getStoreByHost(host: string): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n // A theme's preview host, p-<slug> (theme preview hosts): its slug.\n previewSlug: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n previewSlug: null,\n };\n }\n\n const key = host.toLowerCase();\n const cached = byHost.get(key);\n if (cached) return cached;\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n let externalUrl: string | null = null;\n let previewSlug: string | null = null;\n\n let failed = false;\n\n const hostname = key.split(\":\")[0]!;\n const platformDomain = (\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\"\n ).toLowerCase();\n const subdomain = platformSubdomain(hostname, platformDomain);\n const isSubDomain = subdomain !== null;\n\n try {\n const lookupValue = subdomain ?? host;\n const foundStore = await sdk.stores.getByDomain(lookupValue);\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n domain = foundStore.config?.custom_domain || null;\n externalUrl = foundStore.storefront_url || null;\n previewSlug = foundStore.preview_slug || null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else {\n failed = true;\n console.error(\"Store not found for host:\", host);\n }\n }\n\n const result = {\n storeRef,\n domain,\n isSubDomain,\n suspended,\n externalUrl,\n previewSlug,\n };\n if (!failed) {\n byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);\n }\n return result;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AAWzB,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,YAAY;AAElB,MAAM,SAAS,IAAI,SAAsB,SAAS;AAG3C,SAAS,wBAA8B;AAC5C,SAAO,MAAM;AACf;AAOA,SAAS,kBACP,UACA,gBACe;AACf,QAAM,SAAS,IAAI,cAAc;AACjC,MAAI,CAAC,SAAS,SAAS,MAAM,EAAG,QAAO;AACvC,QAAM,QAAQ,SAAS,MAAM,GAAG,CAAC,OAAO,MAAM;AAC9C,SAAO,SAAS,CAAC,MAAM,SAAS,GAAG,IAAI,QAAQ;AACjD;AAMA,eAAsB,eAAe,MAelC;AACD,MAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,WAAW,GAAG;AAC5D,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,WAAW;AAAA,MACX,aAAa;AAAA,MACb,aAAa;AAAA,IACf;AAAA,EACF;AAEA,QAAM,MAAM,KAAK,YAAY;AAC7B,QAAM,SAAS,OAAO,IAAI,GAAG;AAC7B,MAAI,OAAQ,QAAO;AAEnB,MAAI,WAA0B;AAC9B,MAAI,SAAwB;AAC5B,MAAI,YAAY;AAChB,MAAI,cAA6B;AACjC,MAAI,cAA6B;AAEjC,MAAI,SAAS;AAEb,QAAM,WAAW,IAAI,MAAM,GAAG,EAAE,CAAC;AACjC,QAAM,kBACJ,aAAa,EAAE,wBAAwB,gBACvC,YAAY;AACd,QAAM,YAAY,kBAAkB,UAAU,cAAc;AAC5D,QAAM,cAAc,cAAc;AAElC,MAAI;AACF,UAAM,cAAc,aAAa;AACjC,UAAM,aAAa,MAAM,IAAI,OAAO,YAAY,WAAW;AAE3D,QAAI,YAAY,KAAK;AACnB,iBAAW,WAAW;AACtB,eAAS,WAAW,QAAQ,iBAAiB;AAC7C,oBAAc,WAAW,kBAAkB;AAC3C,oBAAc,WAAW,gBAAgB;AAAA,IAC3C;AAAA,EACF,SAAS,OAAO;AACd,QAAI,sBAAsB,KAAK,GAAG;AAChC,kBAAY;AAAA,IACd,OAAO;AACL,eAAS;AACT,cAAQ,MAAM,6BAA6B,IAAI;AAAA,IACjD;AAAA,EACF;AAEA,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,QAAQ;AACX,WAAO,IAAI,KAAK,QAAQ,WAAW,eAAe,gBAAgB;AAAA,EACpE;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/stores/get-store-by-host.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { isStoreSuspendedError } from \"./store-suspension\";\nimport {\n comingSoonStoreNameOf,\n isStoreComingSoonError,\n} from \"./store-coming-soon\";\nimport {\n SKIP_STORE_PREVIEW,\n STORE_PREVIEW_HEADER,\n} from \"./store-preview-cookie\";\nimport { publicConfig } from \"../config\";\nimport { TtlCache } from \"./ttl-cache\";\n\ntype StoreByHost = Awaited<ReturnType<typeof getStoreByHost>>;\n\n/**\n * How long a lookup is reused in this process. A merchant's change (custom\n * domain, external theme, suspension) reaches shoppers within this window on\n * top of the API's own Redis cache. Misses and suspensions expire sooner so\n * a new or re-enabled store shows up quickly. A failed lookup (API down) is\n * never cached: it would turn a blip into a run of 404s. Neither is a lookup\n * made with a preview token: its answer is that previewer's, not the public's.\n */\nconst FOUND_TTL_MS = 30_000;\nconst NOT_FOUND_TTL_MS = 10_000;\nconst MAX_HOSTS = 10_000;\n\nconst byHost = new TtlCache<StoreByHost>(MAX_HOSTS);\n\n/** Tests only: forget every cached lookup. */\nexport function clearStoreByHostCache(): void {\n byHost.clear();\n}\n\n/**\n * The store's subdomain label when `hostname` is `<label>.<platformDomain>`\n * (a single label, so `www.shop.<platform>` and `shop.evil<platform>` are\n * not subdomains), else null.\n */\nfunction platformSubdomain(\n hostname: string,\n platformDomain: string\n): string | null {\n const suffix = `.${platformDomain}`;\n if (!hostname.endsWith(suffix)) return null;\n const label = hostname.slice(0, -suffix.length);\n return label && !label.includes(\".\") ? label : null;\n}\n\n/**\n * Get store ref and domain info from host\n * Used by middleware and API routes to determine which store is being accessed\n *\n * With `previewToken` (a store or theme preview token), the token is sent as\n * `X-Store-Preview`, which opens a coming soon store, and the cache is\n * neither read nor written. Without one the lookup is the public answer for\n * the host: it is cached, and it carries `SKIP_STORE_PREVIEW` so the API\n * client never attaches the request's ambient preview token to it.\n */\nexport async function getStoreByHost(\n host: string,\n options?: { previewToken?: string | null }\n): Promise<{\n storeRef: string | null;\n domain: string | null;\n isSubDomain: boolean;\n // True when the backend identified a store for this host but rejected it\n // with STORE_SUSPENDED. There is no `ref` to route on in that case — the\n // 403 response carries no store-identifying payload — so the caller must\n // handle this without a storeRef (see proxy.ts, which rewrites to a\n // platform-level suspended page rather than `/store/<ref>`).\n suspended: boolean;\n // The live theme's URL when it is external (`storefront_url`), else null.\n // Null too when the API predates external themes.\n externalUrl: string | null;\n // A theme's preview host, p-<slug> (theme preview hosts): its slug.\n previewSlug: string | null;\n // True when the backend identified a store for this host but rejected it\n // with STORE_COMING_SOON: the merchant has not opened it yet. Like\n // `suspended`, there is no `ref` to route on, because the 403 carries only\n // `details.name`; the caller handles it without a storeRef (proxy.ts\n // rewrites to the platform-level coming soon page). A lookup with a valid\n // preview token gets the store instead.\n comingSoon: boolean;\n // The store's name from that 403's `details.name`, else null.\n comingSoonName: string | null;\n // On a theme's preview host only (previewSlug set): the API's short-lived\n // store preview token for a coming soon store, sent as X-Store-Preview in\n // place of the cookie on that host. Null everywhere else. It is cached\n // with the lookup, because the p-<slug> host is itself the capability, and\n // 30 s is far inside the token's 1 h.\n storePreviewToken: string | null;\n}> {\n if (host.includes(\"localhost\") || host.includes(\"127.0.0.1\")) {\n return {\n storeRef: null,\n domain: null,\n isSubDomain: false,\n suspended: false,\n externalUrl: null,\n previewSlug: null,\n comingSoon: false,\n comingSoonName: null,\n storePreviewToken: null,\n };\n }\n\n const previewToken = options?.previewToken || null;\n const key = host.toLowerCase();\n if (!previewToken) {\n const cached = byHost.get(key);\n if (cached) return cached;\n }\n\n let storeRef: string | null = null;\n let domain: string | null = null;\n let suspended = false;\n let externalUrl: string | null = null;\n let previewSlug: string | null = null;\n let comingSoon = false;\n let comingSoonName: string | null = null;\n let storePreviewToken: string | null = null;\n\n let failed = false;\n\n const hostname = key.split(\":\")[0]!;\n const platformDomain = (\n publicConfig().platformDomainSuffix ?? \"ecomsite.app\"\n ).toLowerCase();\n const subdomain = platformSubdomain(hostname, platformDomain);\n const isSubDomain = subdomain !== null;\n\n try {\n const lookupValue = subdomain ?? host;\n const foundStore = await sdk.stores.getByDomain(\n lookupValue,\n previewToken\n ? { headers: { [STORE_PREVIEW_HEADER]: previewToken } }\n : SKIP_STORE_PREVIEW\n );\n\n if (foundStore?.ref) {\n storeRef = foundStore.ref;\n domain = foundStore.config?.custom_domain || null;\n externalUrl = foundStore.storefront_url || null;\n previewSlug = foundStore.preview_slug || null;\n // Never taken from a non-preview host.\n storePreviewToken = previewSlug\n ? foundStore.store_preview_token || null\n : null;\n }\n } catch (error) {\n if (isStoreSuspendedError(error)) {\n suspended = true;\n } else if (isStoreComingSoonError(error)) {\n comingSoon = true;\n comingSoonName = comingSoonStoreNameOf(error);\n } else {\n failed = true;\n console.error(\"Store not found for host:\", host);\n }\n }\n\n const result = {\n storeRef,\n domain,\n isSubDomain,\n suspended,\n externalUrl,\n previewSlug,\n comingSoon,\n comingSoonName,\n storePreviewToken,\n };\n if (!failed && !previewToken) {\n byHost.set(key, result, storeRef ? FOUND_TTL_MS : NOT_FOUND_TTL_MS);\n }\n return result;\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB;AAYzB,MAAM,eAAe;AACrB,MAAM,mBAAmB;AACzB,MAAM,YAAY;AAElB,MAAM,SAAS,IAAI,SAAsB,SAAS;AAG3C,SAAS,wBAA8B;AAC5C,SAAO,MAAM;AACf;AAOA,SAAS,kBACP,UACA,gBACe;AACf,QAAM,SAAS,IAAI,cAAc;AACjC,MAAI,CAAC,SAAS,SAAS,MAAM,EAAG,QAAO;AACvC,QAAM,QAAQ,SAAS,MAAM,GAAG,CAAC,OAAO,MAAM;AAC9C,SAAO,SAAS,CAAC,MAAM,SAAS,GAAG,IAAI,QAAQ;AACjD;AAYA,eAAsB,eACpB,MACA,SA+BC;AACD,MAAI,KAAK,SAAS,WAAW,KAAK,KAAK,SAAS,WAAW,GAAG;AAC5D,WAAO;AAAA,MACL,UAAU;AAAA,MACV,QAAQ;AAAA,MACR,aAAa;AAAA,MACb,WAAW;AAAA,MACX,aAAa;AAAA,MACb,aAAa;AAAA,MACb,YAAY;AAAA,MACZ,gBAAgB;AAAA,MAChB,mBAAmB;AAAA,IACrB;AAAA,EACF;AAEA,QAAM,eAAe,SAAS,gBAAgB;AAC9C,QAAM,MAAM,KAAK,YAAY;AAC7B,MAAI,CAAC,cAAc;AACjB,UAAM,SAAS,OAAO,IAAI,GAAG;AAC7B,QAAI,OAAQ,QAAO;AAAA,EACrB;AAEA,MAAI,WAA0B;AAC9B,MAAI,SAAwB;AAC5B,MAAI,YAAY;AAChB,MAAI,cAA6B;AACjC,MAAI,cAA6B;AACjC,MAAI,aAAa;AACjB,MAAI,iBAAgC;AACpC,MAAI,oBAAmC;AAEvC,MAAI,SAAS;AAEb,QAAM,WAAW,IAAI,MAAM,GAAG,EAAE,CAAC;AACjC,QAAM,kBACJ,aAAa,EAAE,wBAAwB,gBACvC,YAAY;AACd,QAAM,YAAY,kBAAkB,UAAU,cAAc;AAC5D,QAAM,cAAc,cAAc;AAElC,MAAI;AACF,UAAM,cAAc,aAAa;AACjC,UAAM,aAAa,MAAM,IAAI,OAAO;AAAA,MAClC;AAAA,MACA,eACI,EAAE,SAAS,EAAE,CAAC,oBAAoB,GAAG,aAAa,EAAE,IACpD;AAAA,IACN;AAEA,QAAI,YAAY,KAAK;AACnB,iBAAW,WAAW;AACtB,eAAS,WAAW,QAAQ,iBAAiB;AAC7C,oBAAc,WAAW,kBAAkB;AAC3C,oBAAc,WAAW,gBAAgB;AAEzC,0BAAoB,cAChB,WAAW,uBAAuB,OAClC;AAAA,IACN;AAAA,EACF,SAAS,OAAO;AACd,QAAI,sBAAsB,KAAK,GAAG;AAChC,kBAAY;AAAA,IACd,WAAW,uBAAuB,KAAK,GAAG;AACxC,mBAAa;AACb,uBAAiB,sBAAsB,KAAK;AAAA,IAC9C,OAAO;AACL,eAAS;AACT,cAAQ,MAAM,6BAA6B,IAAI;AAAA,IACjD;AAAA,EACF;AAEA,QAAM,SAAS;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,MAAI,CAAC,UAAU,CAAC,cAAc;AAC5B,WAAO,IAAI,KAAK,QAAQ,WAAW,eAAe,gBAAgB;AAAA,EACpE;AACA,SAAO;AACT;","names":[]}