@ecomweb/storefront-kit 0.2.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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -0
  3. package/dist/api/client.js +162 -0
  4. package/dist/api/client.js.map +1 -0
  5. package/dist/api/index.js +7 -0
  6. package/dist/api/index.js.map +1 -0
  7. package/dist/api/proxy.js +145 -0
  8. package/dist/api/proxy.js.map +1 -0
  9. package/dist/api/response.js +55 -0
  10. package/dist/api/response.js.map +1 -0
  11. package/dist/api/server-client.js +159 -0
  12. package/dist/api/server-client.js.map +1 -0
  13. package/dist/auth/client-ip.js +44 -0
  14. package/dist/auth/client-ip.js.map +1 -0
  15. package/dist/auth/context.js +125 -0
  16. package/dist/auth/context.js.map +1 -0
  17. package/dist/auth/cookies.js +97 -0
  18. package/dist/auth/cookies.js.map +1 -0
  19. package/dist/auth/error-copy.js +49 -0
  20. package/dist/auth/error-copy.js.map +1 -0
  21. package/dist/auth/password-policy.js +29 -0
  22. package/dist/auth/password-policy.js.map +1 -0
  23. package/dist/auth/route-handlers.js +337 -0
  24. package/dist/auth/route-handlers.js.map +1 -0
  25. package/dist/auth/safe-redirect.js +20 -0
  26. package/dist/auth/safe-redirect.js.map +1 -0
  27. package/dist/auth/sdk.js +76 -0
  28. package/dist/auth/sdk.js.map +1 -0
  29. package/dist/auth/session-refresh.js +81 -0
  30. package/dist/auth/session-refresh.js.map +1 -0
  31. package/dist/auth/session.js +26 -0
  32. package/dist/auth/session.js.map +1 -0
  33. package/dist/auth/use-public-auth-config.js +29 -0
  34. package/dist/auth/use-public-auth-config.js.map +1 -0
  35. package/dist/cart/api.js +60 -0
  36. package/dist/cart/api.js.map +1 -0
  37. package/dist/cart/server-context.js +279 -0
  38. package/dist/cart/server-context.js.map +1 -0
  39. package/dist/cart/types.js +1 -0
  40. package/dist/cart/types.js.map +1 -0
  41. package/dist/cart/utils.js +49 -0
  42. package/dist/cart/utils.js.map +1 -0
  43. package/dist/checkout/get-payment-state.js +15 -0
  44. package/dist/checkout/get-payment-state.js.map +1 -0
  45. package/dist/checkout/initiate-gateway-payment.js +13 -0
  46. package/dist/checkout/initiate-gateway-payment.js.map +1 -0
  47. package/dist/checkout/order-handoff.js +61 -0
  48. package/dist/checkout/order-handoff.js.map +1 -0
  49. package/dist/checkout/payment-redirect.js +11 -0
  50. package/dist/checkout/payment-redirect.js.map +1 -0
  51. package/dist/checkout/payment-state-poll.js +45 -0
  52. package/dist/checkout/payment-state-poll.js.map +1 -0
  53. package/dist/checkout/start-gateway-redirect.js +16 -0
  54. package/dist/checkout/start-gateway-redirect.js.map +1 -0
  55. package/dist/checkout/stock-issues.js +35 -0
  56. package/dist/checkout/stock-issues.js.map +1 -0
  57. package/dist/checkout/success-state.js +15 -0
  58. package/dist/checkout/success-state.js.map +1 -0
  59. package/dist/checkout/types.js +1 -0
  60. package/dist/checkout/types.js.map +1 -0
  61. package/dist/checkout/use-checkout.js +256 -0
  62. package/dist/checkout/use-checkout.js.map +1 -0
  63. package/dist/checkout/utils.js +7 -0
  64. package/dist/checkout/utils.js.map +1 -0
  65. package/dist/config/index.js +7 -0
  66. package/dist/config/index.js.map +1 -0
  67. package/dist/config/log-level.js +8 -0
  68. package/dist/config/log-level.js.map +1 -0
  69. package/dist/config/mode.js +18 -0
  70. package/dist/config/mode.js.map +1 -0
  71. package/dist/config/public.js +115 -0
  72. package/dist/config/public.js.map +1 -0
  73. package/dist/config/schema.js +70 -0
  74. package/dist/config/schema.js.map +1 -0
  75. package/dist/config/server.js +68 -0
  76. package/dist/config/server.js.map +1 -0
  77. package/dist/config.d.ts +16 -0
  78. package/dist/config.js +15 -0
  79. package/dist/config.js.map +1 -0
  80. package/dist/currency.js +68 -0
  81. package/dist/currency.js.map +1 -0
  82. package/dist/index.d.ts +968 -0
  83. package/dist/index.js +146 -0
  84. package/dist/index.js.map +1 -0
  85. package/dist/interfaces/api.types.js +1 -0
  86. package/dist/interfaces/api.types.js.map +1 -0
  87. package/dist/interfaces/index.js +2 -0
  88. package/dist/interfaces/index.js.map +1 -0
  89. package/dist/logging.js +42 -0
  90. package/dist/logging.js.map +1 -0
  91. package/dist/middleware/create-storefront-middleware.js +175 -0
  92. package/dist/middleware/create-storefront-middleware.js.map +1 -0
  93. package/dist/middleware.d.ts +24 -0
  94. package/dist/middleware.js +9 -0
  95. package/dist/middleware.js.map +1 -0
  96. package/dist/mode-1ZKDELPZ.d.ts +16 -0
  97. package/dist/notices.js +31 -0
  98. package/dist/notices.js.map +1 -0
  99. package/dist/orders/api-client.js +32 -0
  100. package/dist/orders/api-client.js.map +1 -0
  101. package/dist/orders/derive-progress.js +36 -0
  102. package/dist/orders/derive-progress.js.map +1 -0
  103. package/dist/orders/index.js +6 -0
  104. package/dist/orders/index.js.map +1 -0
  105. package/dist/orders/types.js +13 -0
  106. package/dist/orders/types.js.map +1 -0
  107. package/dist/orders/use-order-status.js +137 -0
  108. package/dist/orders/use-order-status.js.map +1 -0
  109. package/dist/promotions/use-promotion-validation.js +106 -0
  110. package/dist/promotions/use-promotion-validation.js.map +1 -0
  111. package/dist/promotions/utils.js +40 -0
  112. package/dist/promotions/utils.js.map +1 -0
  113. package/dist/provider.js +25 -0
  114. package/dist/provider.js.map +1 -0
  115. package/dist/redirects/index.js +2 -0
  116. package/dist/redirects/index.js.map +1 -0
  117. package/dist/redirects/lookup-redirect.js +13 -0
  118. package/dist/redirects/lookup-redirect.js.map +1 -0
  119. package/dist/request/public-url.js +20 -0
  120. package/dist/request/public-url.js.map +1 -0
  121. package/dist/schema-CEMKsCwh.d.ts +52 -0
  122. package/dist/sdk.js +33 -0
  123. package/dist/sdk.js.map +1 -0
  124. package/dist/server/routes.js +56 -0
  125. package/dist/server/routes.js.map +1 -0
  126. package/dist/server.d.ts +58 -0
  127. package/dist/server.js +19 -0
  128. package/dist/server.js.map +1 -0
  129. package/dist/shipping/format-shipping-option.js +12 -0
  130. package/dist/shipping/format-shipping-option.js.map +1 -0
  131. package/dist/shipping/location-areas.js +104 -0
  132. package/dist/shipping/location-areas.js.map +1 -0
  133. package/dist/shipping/messages.js +19 -0
  134. package/dist/shipping/messages.js.map +1 -0
  135. package/dist/shipping/shipping-calculation-reducer.js +75 -0
  136. package/dist/shipping/shipping-calculation-reducer.js.map +1 -0
  137. package/dist/shipping/use-shipping-calculation.js +84 -0
  138. package/dist/shipping/use-shipping-calculation.js.map +1 -0
  139. package/dist/shipping/utils.js +18 -0
  140. package/dist/shipping/utils.js.map +1 -0
  141. package/dist/storage.js +116 -0
  142. package/dist/storage.js.map +1 -0
  143. package/dist/store/store-context.js +72 -0
  144. package/dist/store/store-context.js.map +1 -0
  145. package/dist/store-scope/index.js +33 -0
  146. package/dist/store-scope/index.js.map +1 -0
  147. package/dist/store-scope/root.js +15 -0
  148. package/dist/store-scope/root.js.map +1 -0
  149. package/dist/store-scope/store-url.js +45 -0
  150. package/dist/store-scope/store-url.js.map +1 -0
  151. package/dist/stores/basic-settings.js +67 -0
  152. package/dist/stores/basic-settings.js.map +1 -0
  153. package/dist/stores/cached.js +20 -0
  154. package/dist/stores/cached.js.map +1 -0
  155. package/dist/stores/get-store-by-host.js +38 -0
  156. package/dist/stores/get-store-by-host.js.map +1 -0
  157. package/dist/stores/index.js +7 -0
  158. package/dist/stores/index.js.map +1 -0
  159. package/dist/stores/metadata.js +19 -0
  160. package/dist/stores/metadata.js.map +1 -0
  161. package/dist/stores/store-path.js +9 -0
  162. package/dist/stores/store-path.js.map +1 -0
  163. package/dist/stores/store-suspension.js +14 -0
  164. package/dist/stores/store-suspension.js.map +1 -0
  165. package/package.json +64 -0
@@ -0,0 +1,45 @@
1
+ const TERMINAL_STATUSES = /* @__PURE__ */ new Set(["paid", "failed"]);
2
+ function computeBackoffDelay(attemptIndex, baseDelayMs, backoffFactor, maxDelayMs) {
3
+ const delay = baseDelayMs * Math.pow(backoffFactor, attemptIndex);
4
+ return Math.min(delay, maxDelayMs);
5
+ }
6
+ async function pollPaymentState(options) {
7
+ const {
8
+ poll,
9
+ wait,
10
+ maxAttempts = 6,
11
+ baseDelayMs = 2e3,
12
+ backoffFactor = 1.5,
13
+ maxDelayMs = 15e3
14
+ } = options;
15
+ let lastResult = null;
16
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
17
+ try {
18
+ const result = await poll();
19
+ lastResult = result;
20
+ if (TERMINAL_STATUSES.has(result.payment_status)) {
21
+ return {
22
+ status: result.payment_status,
23
+ result
24
+ };
25
+ }
26
+ } catch {
27
+ }
28
+ const isLastAttempt = attempt === maxAttempts - 1;
29
+ if (!isLastAttempt) {
30
+ const delay = computeBackoffDelay(
31
+ attempt,
32
+ baseDelayMs,
33
+ backoffFactor,
34
+ maxDelayMs
35
+ );
36
+ await wait(delay);
37
+ }
38
+ }
39
+ return { status: "pending", result: lastResult };
40
+ }
41
+ export {
42
+ computeBackoffDelay,
43
+ pollPaymentState
44
+ };
45
+ //# sourceMappingURL=payment-state-poll.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checkout/payment-state-poll.ts"],"sourcesContent":["/**\n * Polling policy for confirming a gateway (OnePay/MoMo) payment after the\n * shopper's browser returns from the provider.\n *\n * The browser almost always beats the gateway's server-to-server callback\n * back to us — so the return URL carries no authority of its own; it only\n * decides which page to show. The order's real state comes from the API,\n * which the callback updates asynchronously. This module is the policy that\n * keeps asking the API until that state resolves, or gives up gracefully.\n *\n * A late callback is NORMAL, not exceptional — it is exactly the case the\n * expiry design elsewhere in this system accommodates by expiring an\n * abandoned attempt to reversible `ON_HOLD` rather than terminal\n * `CANCELLED`. So exhausting the attempt budget here must resolve to a\n * \"pending\" outcome, never \"failed\": a shopper who actually paid and is\n * merely waiting on a slow callback must never be told their payment\n * failed.\n *\n * Deliberately pure and timer-free: no `setTimeout`/`setInterval`, no\n * `window`, no React state. The delay mechanism (`wait`) is injected by the\n * caller, so tests can run this to completion synchronously (or nearly so)\n * with a `wait` that resolves immediately and simply records the delay it\n * was asked for — no fake timers required. `computeBackoffDelay` is also\n * exported standalone so the backoff schedule itself can be asserted on\n * without invoking the poll loop at all.\n */\n\n/** The shape mirrored from the intended `sdk.payments.getPaymentState`\n * response — see `lib/checkout/get-payment-state.ts` for the temporary\n * adapter that fetches it. */\nexport interface PaymentStateResult {\n payment_status: string;\n order_status: string;\n}\n\nexport type PollOutcome =\n | { status: \"paid\"; result: PaymentStateResult }\n | { status: \"failed\"; result: PaymentStateResult }\n /** Attempts ran out (or every attempt errored) without a terminal status.\n * `result` is the last successful poll's payload, if any attempt\n * succeeded at all. */\n | { status: \"pending\"; result: PaymentStateResult | null };\n\nconst TERMINAL_STATUSES = new Set([\"paid\", \"failed\"]);\n\nexport interface PollPaymentStateOptions {\n /** Performs one status check against the API. May reject — a single\n * rejection must not abort the sequence. */\n poll: () => Promise<PaymentStateResult>;\n /** Delay mechanism, injected by the caller (e.g. a `setTimeout`-based\n * wait in the page component). Deliberately has no default here so this\n * module never touches a timer API directly. */\n wait: (ms: number) => Promise<void>;\n /** Total number of poll attempts before giving up. Default 6. */\n maxAttempts?: number;\n /** Delay before the 2nd attempt, ms. Default 2000. */\n baseDelayMs?: number;\n /** Multiplier applied to the delay on each subsequent gap. Default 1.5. */\n backoffFactor?: number;\n /** Ceiling on any single delay, ms. Default 15000. */\n maxDelayMs?: number;\n}\n\n/**\n * The exponential backoff schedule, exposed standalone so it can be\n * asserted on directly without running the poll loop.\n *\n * @param attemptIndex 0-based index of the gap being computed — the delay\n * awaited after poll attempt `attemptIndex + 1` and before attempt\n * `attemptIndex + 2`.\n */\nexport function computeBackoffDelay(\n attemptIndex: number,\n baseDelayMs: number,\n backoffFactor: number,\n maxDelayMs: number\n): number {\n const delay = baseDelayMs * Math.pow(backoffFactor, attemptIndex);\n return Math.min(delay, maxDelayMs);\n}\n\n/**\n * Repeatedly polls payment state until it resolves to a terminal status\n * (`paid`, `failed`), or the attempt budget is exhausted — in which case\n * the outcome is `\"pending\"`, never `\"failed\"`. A single poll error is\n * swallowed and counted as a used (non-terminal) attempt so a transient\n * network blip cannot abort the sequence.\n */\nexport async function pollPaymentState(\n options: PollPaymentStateOptions\n): Promise<PollOutcome> {\n const {\n poll,\n wait,\n maxAttempts = 6,\n baseDelayMs = 2000,\n backoffFactor = 1.5,\n maxDelayMs = 15000,\n } = options;\n\n let lastResult: PaymentStateResult | null = null;\n\n for (let attempt = 0; attempt < maxAttempts; attempt++) {\n try {\n const result = await poll();\n lastResult = result;\n if (TERMINAL_STATUSES.has(result.payment_status)) {\n return {\n status: result.payment_status as \"paid\" | \"failed\",\n result,\n };\n }\n } catch {\n // A failed request is not a failed payment. Swallow it and keep\n // polling — the next attempt (or the ones after it) may still land.\n }\n\n const isLastAttempt = attempt === maxAttempts - 1;\n if (!isLastAttempt) {\n const delay = computeBackoffDelay(\n attempt,\n baseDelayMs,\n backoffFactor,\n maxDelayMs\n );\n await wait(delay);\n }\n }\n\n return { status: \"pending\", result: lastResult };\n}\n"],"mappings":"AA2CA,MAAM,oBAAoB,oBAAI,IAAI,CAAC,QAAQ,QAAQ,CAAC;AA4B7C,SAAS,oBACd,cACA,aACA,eACA,YACQ;AACR,QAAM,QAAQ,cAAc,KAAK,IAAI,eAAe,YAAY;AAChE,SAAO,KAAK,IAAI,OAAO,UAAU;AACnC;AASA,eAAsB,iBACpB,SACsB;AACtB,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,cAAc;AAAA,IACd,cAAc;AAAA,IACd,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf,IAAI;AAEJ,MAAI,aAAwC;AAE5C,WAAS,UAAU,GAAG,UAAU,aAAa,WAAW;AACtD,QAAI;AACF,YAAM,SAAS,MAAM,KAAK;AAC1B,mBAAa;AACb,UAAI,kBAAkB,IAAI,OAAO,cAAc,GAAG;AAChD,eAAO;AAAA,UACL,QAAQ,OAAO;AAAA,UACf;AAAA,QACF;AAAA,MACF;AAAA,IACF,QAAQ;AAAA,IAGR;AAEA,UAAM,gBAAgB,YAAY,cAAc;AAChD,QAAI,CAAC,eAAe;AAClB,YAAM,QAAQ;AAAA,QACZ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AACA,YAAM,KAAK,KAAK;AAAA,IAClB;AAAA,EACF;AAEA,SAAO,EAAE,QAAQ,WAAW,QAAQ,WAAW;AACjD;","names":[]}
@@ -0,0 +1,16 @@
1
+ async function startGatewayRedirect({
2
+ initiate,
3
+ clearCart,
4
+ navigate
5
+ }) {
6
+ const { redirect_url } = await initiate();
7
+ try {
8
+ await clearCart();
9
+ } catch {
10
+ }
11
+ navigate(redirect_url);
12
+ }
13
+ export {
14
+ startGatewayRedirect
15
+ };
16
+ //# sourceMappingURL=start-gateway-redirect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checkout/start-gateway-redirect.ts"],"sourcesContent":["/**\n * Sends a shopper whose order is already placed to the payment gateway, and\n * empties their cart on the way out.\n *\n * The cart used to be left full on this path, on the reasoning that a\n * redirect which fails to start must not cost the shopper their cart. That\n * part stands: nothing is cleared until `initiate` has returned a URL. But\n * nothing cleared it afterwards either, so a shopper who paid came back to\n * the same items, and the next checkout ordered them again (in the dev data:\n * NH-990019 paid, then NH-990020 for the same variant; NH-990023 paid, then\n * NH-990024 carrying its product again).\n *\n * The clear is awaited before navigating because the navigation is a full\n * page unload, which can cancel a request still in flight. A failed clear is\n * swallowed: a stale cart is an annoyance, a shopper stranded before paying\n * for an order that already exists is a lost sale.\n *\n * The three effects are injected so the order they happen in can be tested\n * without a page; see start-gateway-redirect.spec.ts.\n */\nexport async function startGatewayRedirect({\n initiate,\n clearCart,\n navigate,\n}: {\n initiate: () => Promise<{ redirect_url: string }>;\n clearCart: () => Promise<void>;\n navigate: (url: string) => void;\n}): Promise<void> {\n const { redirect_url } = await initiate();\n try {\n await clearCart();\n } catch {\n // See above: never block the payment on the cart.\n }\n navigate(redirect_url);\n}\n"],"mappings":"AAoBA,eAAsB,qBAAqB;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AACF,GAIkB;AAChB,QAAM,EAAE,aAAa,IAAI,MAAM,SAAS;AACxC,MAAI;AACF,UAAM,UAAU;AAAA,EAClB,QAAQ;AAAA,EAER;AACA,WAAS,YAAY;AACvB;","names":[]}
@@ -0,0 +1,35 @@
1
+ import {
2
+ INVENTORY_ERROR_CODES
3
+ } from "@ecomweb/sdk";
4
+ const STOCK_ISSUE_TOAST_DESCRIPTION = "Vui l\xF2ng \u0111i\u1EC1u ch\u1EC9nh c\xE1c s\u1EA3n ph\u1EA9m \u0111\u01B0\u1EE3c \u0111\xE1nh d\u1EA5u trong \u0111\u01A1n h\xE0ng r\u1ED3i \u0111\u1EB7t l\u1EA1i.";
5
+ function insufficientItemsFrom(error) {
6
+ if (!error || typeof error !== "object") return null;
7
+ const { code, details } = error;
8
+ if (code !== INVENTORY_ERROR_CODES.INSUFFICIENT_INVENTORY) return null;
9
+ const rawItems = details?.items;
10
+ if (!Array.isArray(rawItems)) return null;
11
+ const valid = rawItems.filter(
12
+ (item) => !!item && typeof item === "object" && typeof item.variant_id === "number" && typeof item.requested === "number" && typeof item.available === "number"
13
+ );
14
+ return valid.length > 0 ? valid : null;
15
+ }
16
+ function stockIssueCopy(item) {
17
+ return item.available <= 0 ? "S\u1EA3n ph\u1EA9m n\xE0y \u0111\xE3 h\u1EBFt h\xE0ng." : `Ch\u1EC9 c\xF2n ${item.available} s\u1EA3n ph\u1EA9m, vui l\xF2ng gi\u1EA3m s\u1ED1 l\u01B0\u1EE3ng.`;
18
+ }
19
+ function stockIssuesByLine(lines, items) {
20
+ const byVariant = new Map(items.map((item) => [item.variant_id, item]));
21
+ const issues = {};
22
+ for (const line of lines) {
23
+ if (line.variantId === void 0) continue;
24
+ const item = byVariant.get(line.variantId);
25
+ if (item) issues[line.id] = stockIssueCopy(item);
26
+ }
27
+ return issues;
28
+ }
29
+ export {
30
+ STOCK_ISSUE_TOAST_DESCRIPTION,
31
+ insufficientItemsFrom,
32
+ stockIssueCopy,
33
+ stockIssuesByLine
34
+ };
35
+ //# sourceMappingURL=stock-issues.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checkout/stock-issues.ts"],"sourcesContent":["import {\n INVENTORY_ERROR_CODES,\n type InsufficientInventoryItem,\n} from \"@ecomweb/sdk\";\n\n/**\n * Turns the API's 409 INSUFFICIENT_INVENTORY into per-line shopper copy.\n *\n * The error's `details.items` names variants, not cart lines, and only\n * variants whose stock is short; lines are matched by `variantId`. Duck-typed\n * rather than `instanceof ApiClientError`: the storefront and the SDK each\n * define an ApiClientError class.\n */\nexport const STOCK_ISSUE_TOAST_DESCRIPTION =\n \"Vui lòng điều chỉnh các sản phẩm được đánh dấu trong đơn hàng rồi đặt lại.\";\n\nexport function insufficientItemsFrom(\n error: unknown\n): InsufficientInventoryItem[] | null {\n if (!error || typeof error !== \"object\") return null;\n const { code, details } = error as { code?: unknown; details?: unknown };\n if (code !== INVENTORY_ERROR_CODES.INSUFFICIENT_INVENTORY) return null;\n\n const rawItems = (details as { items?: unknown } | null | undefined)?.items;\n if (!Array.isArray(rawItems)) return null;\n\n const valid = rawItems.filter(\n (item): item is InsufficientInventoryItem =>\n !!item &&\n typeof item === \"object\" &&\n typeof (item as InsufficientInventoryItem).variant_id === \"number\" &&\n typeof (item as InsufficientInventoryItem).requested === \"number\" &&\n typeof (item as InsufficientInventoryItem).available === \"number\"\n );\n return valid.length > 0 ? valid : null;\n}\n\nexport function stockIssueCopy(item: InsufficientInventoryItem): string {\n return item.available <= 0\n ? \"Sản phẩm này đã hết hàng.\"\n : `Chỉ còn ${item.available} sản phẩm, vui lòng giảm số lượng.`;\n}\n\nexport function stockIssuesByLine(\n lines: ReadonlyArray<{ id: string; variantId?: number }>,\n items: InsufficientInventoryItem[]\n): Record<string, string> {\n const byVariant = new Map(items.map(item => [item.variant_id, item]));\n const issues: Record<string, string> = {};\n for (const line of lines) {\n if (line.variantId === undefined) continue;\n const item = byVariant.get(line.variantId);\n if (item) issues[line.id] = stockIssueCopy(item);\n }\n return issues;\n}\n"],"mappings":"AAAA;AAAA,EACE;AAAA,OAEK;AAUA,MAAM,gCACX;AAEK,SAAS,sBACd,OACoC;AACpC,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,EAAE,MAAM,QAAQ,IAAI;AAC1B,MAAI,SAAS,sBAAsB,uBAAwB,QAAO;AAElE,QAAM,WAAY,SAAoD;AACtE,MAAI,CAAC,MAAM,QAAQ,QAAQ,EAAG,QAAO;AAErC,QAAM,QAAQ,SAAS;AAAA,IACrB,CAAC,SACC,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,OAAQ,KAAmC,eAAe,YAC1D,OAAQ,KAAmC,cAAc,YACzD,OAAQ,KAAmC,cAAc;AAAA,EAC7D;AACA,SAAO,MAAM,SAAS,IAAI,QAAQ;AACpC;AAEO,SAAS,eAAe,MAAyC;AACtE,SAAO,KAAK,aAAa,IACrB,2DACA,mBAAW,KAAK,SAAS;AAC/B;AAEO,SAAS,kBACd,OACA,OACwB;AACxB,QAAM,YAAY,IAAI,IAAI,MAAM,IAAI,UAAQ,CAAC,KAAK,YAAY,IAAI,CAAC,CAAC;AACpE,QAAM,SAAiC,CAAC;AACxC,aAAW,QAAQ,OAAO;AACxB,QAAI,KAAK,cAAc,OAAW;AAClC,UAAM,OAAO,UAAU,IAAI,KAAK,SAAS;AACzC,QAAI,KAAM,QAAO,KAAK,EAAE,IAAI,eAAe,IAAI;AAAA,EACjD;AACA,SAAO;AACT;","names":[]}
@@ -0,0 +1,15 @@
1
+ function resolveInitialState(order_code, handoff) {
2
+ if (!order_code) return "paid";
3
+ if (handoff && !handoff.provider_code) {
4
+ return handoff.payment_method === "bank_transfer" ? "awaiting-transfer" : "placed";
5
+ }
6
+ return "confirming";
7
+ }
8
+ function shouldPollForConfirmation(state) {
9
+ return state === "confirming";
10
+ }
11
+ export {
12
+ resolveInitialState,
13
+ shouldPollForConfirmation
14
+ };
15
+ //# sourceMappingURL=success-state.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checkout/success-state.ts"],"sourcesContent":["import type { OrderHandoff } from \"./order-handoff\";\n\n/**\n * Which success screen an order gets.\n *\n * `confirming` / `still-confirming` / `failed` belong to the gateway return\n * flow, where the browser beats the provider's callback back to us and the\n * page polls until the real state resolves.\n *\n * `placed` and `awaiting-transfer` are the offline methods, which now land\n * here too rather than rendering an inline view on the checkout page. They\n * are terminal on arrival: nothing is in flight, so there is nothing to poll\n * for and the screen must not imply otherwise.\n *\n * `awaiting-transfer` exists because a bank_transfer order stays `pending`\n * until the merchant confirms the money arrived. Without it such an order\n * fell into `still-confirming`, whose copy says confirmation \"is taking\n * longer than usual\" — actively wrong. Nothing is slow; the shopper simply\n * has not paid yet.\n */\nexport type PaymentConfirmationState =\n | \"confirming\"\n | \"paid\"\n | \"placed\"\n | \"awaiting-transfer\"\n | \"still-confirming\"\n | \"failed\";\n\n/**\n * The state to render on arrival, before any polling.\n *\n * `order_code` absent means there is no order to confirm at all, which keeps\n * the historical behaviour of treating the page as an immediate success\n * screen.\n */\nexport function resolveInitialState(\n order_code: string | null,\n handoff: OrderHandoff | null\n): PaymentConfirmationState {\n if (!order_code) return \"paid\";\n\n // A gateway-backed handoff still has a payment in flight: poll.\n if (handoff && !handoff.provider_code) {\n return handoff.payment_method === \"bank_transfer\"\n ? \"awaiting-transfer\"\n : \"placed\";\n }\n\n return \"confirming\";\n}\n\n/**\n * Whether this state should start the gateway confirmation poll.\n *\n * Offline orders must not: there is no callback coming, so polling would burn\n * the whole backoff budget and then downgrade a perfectly good screen to\n * \"still-confirming\".\n */\nexport function shouldPollForConfirmation(\n state: PaymentConfirmationState\n): boolean {\n return state === \"confirming\";\n}\n"],"mappings":"AAmCO,SAAS,oBACd,YACA,SAC0B;AAC1B,MAAI,CAAC,WAAY,QAAO;AAGxB,MAAI,WAAW,CAAC,QAAQ,eAAe;AACrC,WAAO,QAAQ,mBAAmB,kBAC9B,sBACA;AAAA,EACN;AAEA,SAAO;AACT;AASO,SAAS,0BACd,OACS;AACT,SAAO,UAAU;AACnB;","names":[]}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,256 @@
1
+ "use client";
2
+ import { useCallback, useEffect, useRef, useState } from "react";
3
+ import { useAuth } from "../auth/context.js";
4
+ import { useCart } from "../cart/server-context.js";
5
+ import { useNotify } from "../notices.js";
6
+ import { publicOrdersApi } from "../orders/api-client.js";
7
+ import { usePromotionValidation } from "../promotions/use-promotion-validation.js";
8
+ import { sdk } from "../sdk.js";
9
+ import { useShippingCalculation } from "../shipping/use-shipping-calculation.js";
10
+ import { useStoreData } from "../store/store-context.js";
11
+ import { initiateGatewayPayment } from "./initiate-gateway-payment.js";
12
+ import { writeOrderHandoff } from "./order-handoff.js";
13
+ import {
14
+ getPaymentRedirectIntent
15
+ } from "./payment-redirect.js";
16
+ import { startGatewayRedirect } from "./start-gateway-redirect.js";
17
+ import { insufficientItemsFrom, stockIssuesByLine } from "./stock-issues.js";
18
+ import { getPaymentMethod } from "./utils.js";
19
+ const defaultNavigateToGateway = (url) => {
20
+ window.location.href = url;
21
+ };
22
+ function useCheckout({
23
+ province,
24
+ ward,
25
+ navigateToGateway = defaultNavigateToGateway
26
+ }) {
27
+ const store = useStoreData();
28
+ const notify = useNotify();
29
+ const {
30
+ items,
31
+ total,
32
+ subtotal,
33
+ originalSubtotal,
34
+ discountAmount,
35
+ clearCart,
36
+ cartId,
37
+ isLoading: isCartLoading
38
+ } = useCart();
39
+ const { user, isAnonymous } = useAuth();
40
+ const [paymentMethods, setPaymentMethods] = useState(
41
+ []
42
+ );
43
+ const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);
44
+ const [savedAddressId, setSavedAddressId] = useState(
45
+ void 0
46
+ );
47
+ const [isSubmitting, setIsSubmitting] = useState(false);
48
+ const [redirectError, setRedirectError] = useState(null);
49
+ const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);
50
+ const inFlight = useRef(false);
51
+ const [stockIssues, setStockIssues] = useState({});
52
+ const totalWeight = items.reduce(
53
+ (sum, item) => sum + (item.weight_gr || 500) * item.quantity,
54
+ 0
55
+ );
56
+ const shippingQuote = useShippingCalculation({
57
+ storeRef: store.ref,
58
+ city: province,
59
+ ward,
60
+ subtotal,
61
+ totalWeight,
62
+ itemsCount: items.length
63
+ });
64
+ const promotionState = usePromotionValidation({
65
+ storeRef: store.ref,
66
+ items: items.map((item) => ({
67
+ productId: item.productId,
68
+ variantId: item.variantId ?? null,
69
+ quantity: item.quantity,
70
+ price: item.price
71
+ })),
72
+ subtotal,
73
+ shippingFee: shippingQuote.shippingFee
74
+ });
75
+ useEffect(() => {
76
+ const load = async () => {
77
+ try {
78
+ setIsLoadingPaymentMethods(true);
79
+ setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));
80
+ } catch (error) {
81
+ console.error("Failed to load payment methods:", error);
82
+ notify({
83
+ kind: "error",
84
+ code: "checkout.payment_methods_failed",
85
+ title: "Kh\xF4ng th\u1EC3 t\u1EA3i ph\u01B0\u01A1ng th\u1EE9c thanh to\xE1n",
86
+ description: "Vui l\xF2ng th\u1EED l\u1EA1i sau"
87
+ });
88
+ } finally {
89
+ setIsLoadingPaymentMethods(false);
90
+ }
91
+ };
92
+ load();
93
+ }, [store.ref, notify]);
94
+ const redirectTo = useCallback(
95
+ (target) => startGatewayRedirect({
96
+ initiate: () => initiateGatewayPayment(store.ref, target),
97
+ clearCart: () => clearCart(false),
98
+ navigate: navigateToGateway
99
+ }),
100
+ [store.ref, clearCart, navigateToGateway]
101
+ );
102
+ const placeOrder = async (input) => {
103
+ if (redirectError) {
104
+ return { kind: "redirect_failed", orderCode: redirectError.order_code };
105
+ }
106
+ if (inFlight.current) {
107
+ return { kind: "busy" };
108
+ }
109
+ inFlight.current = true;
110
+ setIsSubmitting(true);
111
+ setStockIssues({});
112
+ try {
113
+ const orderData = {
114
+ cart_id: cartId || void 0,
115
+ customer_name: input.fullName,
116
+ customer_phone: input.phone,
117
+ customer_email: input.email || "",
118
+ // Money fields are deliberately not sent: the API recomputes subtotal,
119
+ // shipping, discounts and total from the catalog and its own rules,
120
+ // and ignores anything supplied here.
121
+ shipping_street: input.street,
122
+ shipping_city: input.province,
123
+ shipping_ward: input.ward,
124
+ payment_method: getPaymentMethod(input.paymentMethod),
125
+ // The shopper's choice of rate is real input; the API prices it and
126
+ // rejects a rate_id that isn't one it just quoted for this address
127
+ // and cart. useShippingCalculation clears the selection the moment an
128
+ // input it was quoted against changes, so this is either null
129
+ // (omitted, the API picks) or a rate from the matching quote.
130
+ ...shippingQuote.selectedShippingRate && {
131
+ shipping_rate_id: shippingQuote.selectedShippingRate
132
+ },
133
+ notes: input.notes || void 0,
134
+ promotion_id: promotionState.appliedPromotion?.id || void 0,
135
+ ...savedAddressId && { customer_address_id: savedAddressId },
136
+ items: items.map((item) => ({
137
+ product_id: item.productId,
138
+ variant_id: item.variantId,
139
+ variant_name: item.variantName,
140
+ product_name: item.name,
141
+ product_image: item.image,
142
+ quantity: item.quantity
143
+ // No price/total: the API resolves the unit price from the catalog.
144
+ }))
145
+ };
146
+ const order = await publicOrdersApi.createStoreOrder(
147
+ store.ref,
148
+ orderData,
149
+ !!user && !isAnonymous
150
+ );
151
+ const method = paymentMethods.find(
152
+ (m) => m.payment_method === input.paymentMethod
153
+ );
154
+ const intent = getPaymentRedirectIntent(method, order.order_code);
155
+ if (intent) {
156
+ try {
157
+ await redirectTo(intent);
158
+ return { kind: "redirect" };
159
+ } catch (initiateError) {
160
+ console.error("Failed to initiate gateway payment:", initiateError);
161
+ setRedirectError(intent);
162
+ return { kind: "redirect_failed", orderCode: intent.order_code };
163
+ }
164
+ }
165
+ writeOrderHandoff({
166
+ order_code: order.order_code,
167
+ payment_method: input.paymentMethod,
168
+ provider_code: method?.provider_code ?? null,
169
+ total: Number(order.total ?? 0),
170
+ currency_code: order.currency_code ?? "VND"
171
+ });
172
+ clearCart(false);
173
+ return {
174
+ kind: "success",
175
+ order: { order_code: order.order_code, total: order.total ?? null }
176
+ };
177
+ } catch (error) {
178
+ const shortItems = insufficientItemsFrom(error);
179
+ if (shortItems) {
180
+ const issues = stockIssuesByLine(items, shortItems);
181
+ setStockIssues(issues);
182
+ return { kind: "stock_issues", issues };
183
+ }
184
+ return {
185
+ kind: "error",
186
+ message: error instanceof Error ? error.message : String(error)
187
+ };
188
+ } finally {
189
+ inFlight.current = false;
190
+ setIsSubmitting(false);
191
+ }
192
+ };
193
+ const retryPaymentRedirect = useCallback(async () => {
194
+ if (!redirectError) return { kind: "error", message: "No order to pay" };
195
+ setIsRetryingRedirect(true);
196
+ try {
197
+ await redirectTo(redirectError);
198
+ return { kind: "redirect" };
199
+ } catch (retryError) {
200
+ console.error("Failed to retry gateway payment redirect:", retryError);
201
+ return { kind: "redirect_failed", orderCode: redirectError.order_code };
202
+ } finally {
203
+ setIsRetryingRedirect(false);
204
+ }
205
+ }, [redirectError, redirectTo]);
206
+ return {
207
+ items,
208
+ isCartLoading,
209
+ paymentMethods,
210
+ isLoadingPaymentMethods,
211
+ shipping: {
212
+ fee: shippingQuote.shippingFee,
213
+ options: shippingQuote.shippingOptions,
214
+ selectedRate: shippingQuote.selectedShippingRate,
215
+ isCalculating: shippingQuote.isCalculatingShipping,
216
+ hasCalculated: shippingQuote.hasCalculatedShipping,
217
+ calculationFailed: shippingQuote.calculationFailed,
218
+ selectRate: shippingQuote.handleShippingRateSelect,
219
+ retry: shippingQuote.retryCalculation
220
+ },
221
+ promotion: {
222
+ code: promotionState.promoCode,
223
+ setCode: promotionState.setPromoCode,
224
+ applied: promotionState.appliedPromotion,
225
+ shippingDiscount: promotionState.shippingDiscount,
226
+ isValidating: promotionState.isValidatingPromo,
227
+ error: promotionState.promoError,
228
+ validate: promotionState.validatePromoCode,
229
+ remove: promotionState.removePromoCode,
230
+ applySuggestion: promotionState.applyPromotionFromSuggestion
231
+ },
232
+ // shippingDiscount comes from the API's promotion validation — the same
233
+ // number the server applies when the order is placed.
234
+ totals: {
235
+ subtotal,
236
+ originalSubtotal,
237
+ discount: discountAmount,
238
+ cartTotal: total,
239
+ shipping: shippingQuote.shippingFee,
240
+ shippingDiscount: promotionState.shippingDiscount,
241
+ total: total + shippingQuote.shippingFee - promotionState.shippingDiscount
242
+ },
243
+ savedAddressId,
244
+ selectSavedAddress: setSavedAddressId,
245
+ stockIssues,
246
+ isSubmitting,
247
+ redirectError,
248
+ isRetryingRedirect,
249
+ placeOrder,
250
+ retryPaymentRedirect
251
+ };
252
+ }
253
+ export {
254
+ useCheckout
255
+ };
256
+ //# sourceMappingURL=use-checkout.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checkout/use-checkout.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\nimport type { PaymentMethod, StorePaymentMethod } from \"@ecomweb/sdk\";\nimport { useAuth } from \"../auth/context\";\nimport { useCart } from \"../cart/server-context\";\nimport { useNotify } from \"../notices\";\nimport { publicOrdersApi } from \"../orders/api-client\";\nimport { usePromotionValidation } from \"../promotions/use-promotion-validation\";\nimport { sdk } from \"../sdk\";\nimport { useShippingCalculation } from \"../shipping/use-shipping-calculation\";\nimport { useStoreData } from \"../store/store-context\";\nimport { initiateGatewayPayment } from \"./initiate-gateway-payment\";\nimport { writeOrderHandoff } from \"./order-handoff\";\nimport {\n getPaymentRedirectIntent,\n type PaymentMethodWithProviderCode,\n} from \"./payment-redirect\";\nimport { startGatewayRedirect } from \"./start-gateway-redirect\";\nimport { insufficientItemsFrom, stockIssuesByLine } from \"./stock-issues\";\nimport { getPaymentMethod } from \"./utils\";\n\n/** What the shopper entered; the app owns the form and its validation. */\nexport interface PlaceOrderInput {\n fullName: string;\n phone: string;\n email?: string;\n street: string;\n /** Province code, as quoted for shipping. */\n province: string;\n /** Ward code, as quoted for shipping. */\n ward: string;\n notes?: string;\n /** A `payment_method` code from `paymentMethods`. */\n paymentMethod: string;\n}\n\nexport interface PlacedOrder {\n order_code: string;\n total: number | string | null;\n}\n\n/**\n * - redirect: the shopper is being sent to the payment provider.\n * - redirect_failed: the order exists but the provider hand-off did not\n * start; offer retryPaymentRedirect(). Further placeOrder calls return\n * this again instead of creating a second order.\n * - success: an offline-payment order; show its confirmation.\n * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.\n * - error: nothing was placed.\n * - busy: an earlier placeOrder is still running; this call did nothing.\n */\nexport type PlaceOrderResult =\n | { kind: \"redirect\" }\n | { kind: \"redirect_failed\"; orderCode: string }\n | { kind: \"success\"; order: PlacedOrder }\n | { kind: \"stock_issues\"; issues: Record<string, string> }\n | { kind: \"error\"; message: string }\n | { kind: \"busy\" };\n\nexport interface UseCheckoutOptions {\n /** The address fields shipping is quoted against (codes, may be empty). */\n province: string;\n ward: string;\n /** Leaves for the payment provider; defaults to a full-page navigation. */\n navigateToGateway?: (url: string) => void;\n}\n\nconst defaultNavigateToGateway = (url: string) => {\n window.location.href = url;\n};\n\n/**\n * Checkout without the UI: payment methods, shipping quotes, promotions,\n * totals, placing the order and the payment-provider hand-off. The app\n * renders the form and decides what to show for each PlaceOrderResult.\n */\nexport function useCheckout({\n province,\n ward,\n navigateToGateway = defaultNavigateToGateway,\n}: UseCheckoutOptions) {\n const store = useStoreData();\n const notify = useNotify();\n const {\n items,\n total,\n subtotal,\n originalSubtotal,\n discountAmount,\n clearCart,\n cartId,\n isLoading: isCartLoading,\n } = useCart();\n const { user, isAnonymous } = useAuth();\n\n const [paymentMethods, setPaymentMethods] = useState<StorePaymentMethod[]>(\n []\n );\n const [isLoadingPaymentMethods, setIsLoadingPaymentMethods] = useState(true);\n const [savedAddressId, setSavedAddressId] = useState<number | undefined>(\n undefined\n );\n const [isSubmitting, setIsSubmitting] = useState(false);\n // Set only when the order was placed but the gateway redirect failed to\n // start. The order already exists, so the cart is deliberately left\n // intact until a redirect actually commits — this is what lets the shopper\n // retry payment without resubmitting the order.\n const [redirectError, setRedirectError] = useState<{\n order_code: string;\n provider_code: string;\n } | null>(null);\n const [isRetryingRedirect, setIsRetryingRedirect] = useState(false);\n // Set synchronously, unlike isSubmitting: a double-click lands before the\n // re-render that would disable the button.\n const inFlight = useRef(false);\n // Copy keyed by cart line id when the API rejects the order for short\n // stock. Cleared on the next submit.\n const [stockIssues, setStockIssues] = useState<Record<string, string>>({});\n\n const totalWeight = items.reduce(\n (sum, item) =>\n sum + ((item as { weight_gr?: number }).weight_gr || 500) * item.quantity,\n 0\n );\n\n const shippingQuote = useShippingCalculation({\n storeRef: store.ref,\n city: province,\n ward,\n subtotal,\n totalWeight,\n itemsCount: items.length,\n });\n\n const promotionState = usePromotionValidation({\n storeRef: store.ref,\n items: items.map(item => ({\n productId: item.productId,\n variantId: item.variantId ?? null,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal,\n shippingFee: shippingQuote.shippingFee,\n });\n\n useEffect(() => {\n const load = async () => {\n try {\n setIsLoadingPaymentMethods(true);\n setPaymentMethods(await sdk.paymentMethods.getEnabled(store.ref));\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load payment methods:\", error);\n notify({\n kind: \"error\",\n code: \"checkout.payment_methods_failed\",\n title: \"Không thể tải phương thức thanh toán\",\n description: \"Vui lòng thử lại sau\",\n });\n } finally {\n setIsLoadingPaymentMethods(false);\n }\n };\n load();\n }, [store.ref, notify]);\n\n const redirectTo = useCallback(\n (target: { order_code: string; provider_code: string }) =>\n startGatewayRedirect({\n initiate: () => initiateGatewayPayment(store.ref, target),\n clearCart: () => clearCart(false),\n navigate: navigateToGateway,\n }),\n [store.ref, clearCart, navigateToGateway]\n );\n\n const placeOrder = async (\n input: PlaceOrderInput\n ): Promise<PlaceOrderResult> => {\n // The order from a failed hand-off still exists and the cart is kept for\n // it; placing again would create a second order for the same cart.\n if (redirectError) {\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n }\n if (inFlight.current) {\n return { kind: \"busy\" };\n }\n inFlight.current = true;\n setIsSubmitting(true);\n setStockIssues({});\n\n try {\n const orderData = {\n cart_id: cartId || undefined,\n customer_name: input.fullName,\n customer_phone: input.phone,\n customer_email: input.email || \"\",\n // Money fields are deliberately not sent: the API recomputes subtotal,\n // shipping, discounts and total from the catalog and its own rules,\n // and ignores anything supplied here.\n shipping_street: input.street,\n shipping_city: input.province,\n shipping_ward: input.ward,\n payment_method: getPaymentMethod(input.paymentMethod) as PaymentMethod,\n // The shopper's choice of rate is real input; the API prices it and\n // rejects a rate_id that isn't one it just quoted for this address\n // and cart. useShippingCalculation clears the selection the moment an\n // input it was quoted against changes, so this is either null\n // (omitted, the API picks) or a rate from the matching quote.\n ...(shippingQuote.selectedShippingRate && {\n shipping_rate_id: shippingQuote.selectedShippingRate,\n }),\n notes: input.notes || undefined,\n promotion_id: promotionState.appliedPromotion?.id || undefined,\n ...(savedAddressId && { customer_address_id: savedAddressId }),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId,\n variant_name: item.variantName,\n product_name: item.name,\n product_image: item.image,\n quantity: item.quantity,\n // No price/total: the API resolves the unit price from the catalog.\n })),\n };\n\n // A signed-in (non-anonymous) shopper's order goes to the authenticated\n // route so the backend links it to their customer record; guests and\n // anonymous identities keep the public route.\n const order = await publicOrdersApi.createStoreOrder(\n store.ref,\n orderData,\n !!user && !isAnonymous\n );\n\n // The order now exists no matter what happens below. A gateway-backed\n // method (non-null provider_code) must send the shopper to the provider\n // to pay; offline methods land on the success screen.\n const method = paymentMethods.find(\n m => m.payment_method === input.paymentMethod\n ) as PaymentMethodWithProviderCode | undefined;\n const intent = getPaymentRedirectIntent(method, order.order_code);\n\n if (intent) {\n try {\n await redirectTo(intent);\n return { kind: \"redirect\" };\n } catch (initiateError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to initiate gateway payment:\", initiateError);\n setRedirectError(intent);\n return { kind: \"redirect_failed\", orderCode: intent.order_code };\n }\n }\n\n // The handoff carries what the success screen cannot ask the API for:\n // the amount to transfer (see order-handoff.ts).\n writeOrderHandoff({\n order_code: order.order_code,\n payment_method: input.paymentMethod,\n provider_code: method?.provider_code ?? null,\n total: Number(order.total ?? 0),\n currency_code:\n (order as { currency_code?: string }).currency_code ?? \"VND\",\n });\n clearCart(false);\n return {\n kind: \"success\",\n order: { order_code: order.order_code, total: order.total ?? null },\n };\n } catch (error) {\n const shortItems = insufficientItemsFrom(error);\n if (shortItems) {\n const issues = stockIssuesByLine(items, shortItems);\n setStockIssues(issues);\n return { kind: \"stock_issues\", issues };\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n };\n } finally {\n inFlight.current = false;\n setIsSubmitting(false);\n }\n };\n\n // The order already exists — this only re-attempts starting the gateway\n // charge, never re-submits the order.\n const retryPaymentRedirect =\n useCallback(async (): Promise<PlaceOrderResult> => {\n if (!redirectError) return { kind: \"error\", message: \"No order to pay\" };\n setIsRetryingRedirect(true);\n try {\n await redirectTo(redirectError);\n return { kind: \"redirect\" };\n } catch (retryError) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to retry gateway payment redirect:\", retryError);\n return { kind: \"redirect_failed\", orderCode: redirectError.order_code };\n } finally {\n setIsRetryingRedirect(false);\n }\n }, [redirectError, redirectTo]);\n\n return {\n items,\n isCartLoading,\n paymentMethods,\n isLoadingPaymentMethods,\n shipping: {\n fee: shippingQuote.shippingFee,\n options: shippingQuote.shippingOptions,\n selectedRate: shippingQuote.selectedShippingRate,\n isCalculating: shippingQuote.isCalculatingShipping,\n hasCalculated: shippingQuote.hasCalculatedShipping,\n calculationFailed: shippingQuote.calculationFailed,\n selectRate: shippingQuote.handleShippingRateSelect,\n retry: shippingQuote.retryCalculation,\n },\n promotion: {\n code: promotionState.promoCode,\n setCode: promotionState.setPromoCode,\n applied: promotionState.appliedPromotion,\n shippingDiscount: promotionState.shippingDiscount,\n isValidating: promotionState.isValidatingPromo,\n error: promotionState.promoError,\n validate: promotionState.validatePromoCode,\n remove: promotionState.removePromoCode,\n applySuggestion: promotionState.applyPromotionFromSuggestion,\n },\n // shippingDiscount comes from the API's promotion validation — the same\n // number the server applies when the order is placed.\n totals: {\n subtotal,\n originalSubtotal,\n discount: discountAmount,\n cartTotal: total,\n shipping: shippingQuote.shippingFee,\n shippingDiscount: promotionState.shippingDiscount,\n total:\n total + shippingQuote.shippingFee - promotionState.shippingDiscount,\n },\n savedAddressId,\n selectSavedAddress: setSavedAddressId,\n stockIssues,\n isSubmitting,\n redirectError,\n isRetryingRedirect,\n placeOrder,\n retryPaymentRedirect,\n };\n}\n"],"mappings":"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","names":[]}
@@ -0,0 +1,7 @@
1
+ function getPaymentMethod(method) {
2
+ return method.trim();
3
+ }
4
+ export {
5
+ getPaymentMethod
6
+ };
7
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/checkout/utils.ts"],"sourcesContent":["/**\n * The payment method the shopper selected already came from the store's own\n * enabled list (`sdk.paymentMethods.getEnabled()`), so it is valid by\n * construction -- the store is the sole authority on its payment method\n * vocabulary. Do NOT reinterpret or coerce it here: the API validates the\n * submitted code against that same enabled list and throws\n * PAYMENT_METHOD_NOT_ENABLED if it doesn't match, so silently substituting a\n * different value (e.g. falling back to \"cod\") would turn a valid checkout\n * into either a silently wrong payment method or a checkout-time 400.\n */\nexport function getPaymentMethod(method: string): string {\n return method.trim();\n}\n"],"mappings":"AAUO,SAAS,iBAAiB,QAAwB;AACvD,SAAO,OAAO,KAAK;AACrB;","names":[]}
@@ -0,0 +1,7 @@
1
+ import { publicConfig } from "./public.js";
2
+ import { ConfigError } from "./schema.js";
3
+ export {
4
+ ConfigError,
5
+ publicConfig
6
+ };
7
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/config/index.ts"],"sourcesContent":["export { publicConfig } from \"./public\";\nexport type { PublicConfig, ServerConfig, LogLevel } from \"./schema\";\nexport { ConfigError } from \"./schema\";\n"],"mappings":"AAAA,SAAS,oBAAoB;AAE7B,SAAS,mBAAmB;","names":[]}
@@ -0,0 +1,8 @@
1
+ import { logLevelOf } from "./schema.js";
2
+ function serverLogLevel() {
3
+ return typeof window === "undefined" ? logLevelOf(process.env.LOG_LEVEL?.trim()) : void 0;
4
+ }
5
+ export {
6
+ serverLogLevel
7
+ };
8
+ //# sourceMappingURL=log-level.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/config/log-level.ts"],"sourcesContent":["import { logLevelOf, type LogLevel } from \"./schema\";\n\n/** Server-side LOG_LEVEL. Not behind server-only: logging runs in both runtimes. */\nexport function serverLogLevel(): LogLevel | undefined {\n return typeof window === \"undefined\"\n ? logLevelOf(process.env.LOG_LEVEL?.trim())\n : undefined;\n}\n"],"mappings":"AAAA,SAAS,kBAAiC;AAGnC,SAAS,iBAAuC;AACrD,SAAO,OAAO,WAAW,cACrB,WAAW,QAAQ,IAAI,WAAW,KAAK,CAAC,IACxC;AACN;","names":[]}
@@ -0,0 +1,18 @@
1
+ import { ConfigError, envValue } from "./schema.js";
2
+ const MODES = ["multi", "single"];
3
+ function resolveMode(env) {
4
+ const name = envValue(env, "NEXT_PUBLIC_ECOMWEB_MODE") ? "NEXT_PUBLIC_ECOMWEB_MODE" : "ECOMWEB_MODE";
5
+ const value = envValue(env, name);
6
+ if (value === void 0) return "single";
7
+ if (MODES.includes(value)) {
8
+ return value;
9
+ }
10
+ throw new ConfigError(
11
+ `Invalid storefront configuration:
12
+ - ${name}: expected "multi" or "single", got "${value}"`
13
+ );
14
+ }
15
+ export {
16
+ resolveMode
17
+ };
18
+ //# sourceMappingURL=mode.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/config/mode.ts"],"sourcesContent":["import { ConfigError, envValue, type EnvSource } from \"./schema\";\n\n/**\n * multi: the shared platform storefront, every store under /store/<ref> or\n * its own host. single: one merchant's storefront, the store is the site.\n */\nexport type StorefrontMode = \"multi\" | \"single\";\n\nconst MODES: readonly StorefrontMode[] = [\"multi\", \"single\"];\n\n/**\n * NEXT_PUBLIC_ECOMWEB_MODE is inlined into client bundles, so it wins;\n * ECOMWEB_MODE is the server-side spelling. Unset means single: an ejected\n * storefront needs no extra setting, and the shared app sets multi in\n * next.config.mjs.\n */\nexport function resolveMode(env: EnvSource): StorefrontMode {\n const name = envValue(env, \"NEXT_PUBLIC_ECOMWEB_MODE\")\n ? \"NEXT_PUBLIC_ECOMWEB_MODE\"\n : \"ECOMWEB_MODE\";\n const value = envValue(env, name);\n if (value === undefined) return \"single\";\n if ((MODES as readonly string[]).includes(value)) {\n return value as StorefrontMode;\n }\n throw new ConfigError(\n `Invalid storefront configuration:\\n - ${name}: expected \"multi\" or \"single\", got \"${value}\"`\n );\n}\n"],"mappings":"AAAA,SAAS,aAAa,gBAAgC;AAQtD,MAAM,QAAmC,CAAC,SAAS,QAAQ;AAQpD,SAAS,YAAY,KAAgC;AAC1D,QAAM,OAAO,SAAS,KAAK,0BAA0B,IACjD,6BACA;AACJ,QAAM,QAAQ,SAAS,KAAK,IAAI;AAChC,MAAI,UAAU,OAAW,QAAO;AAChC,MAAK,MAA4B,SAAS,KAAK,GAAG;AAChD,WAAO;AAAA,EACT;AACA,QAAM,IAAI;AAAA,IACR;AAAA,MAA0C,IAAI,wCAAwC,KAAK;AAAA,EAC7F;AACF;","names":[]}
@@ -0,0 +1,115 @@
1
+ import { resolveMode } from "./mode.js";
2
+ import {
3
+ envValue,
4
+ logLevelOf,
5
+ parseOrThrow,
6
+ publicConfigSchema,
7
+ sampleRateOf
8
+ } from "./schema.js";
9
+ const MULTI_ENV_NAME_OF = {
10
+ apiUrl: "NEXT_PUBLIC_API_URL",
11
+ storefrontApiKey: "NEXT_PUBLIC_PLATFORM_API_KEY",
12
+ appUrl: "NEXT_PUBLIC_APP_URL",
13
+ platformDomainSuffix: "NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX",
14
+ primaryMenuRef: "NEXT_PUBLIC_PRIMARY_MENU_REF"
15
+ };
16
+ const SINGLE_ENV_NAME_OF = {
17
+ storeRef: "ECOMWEB_STORE_REF",
18
+ storefrontApiKey: "ECOMWEB_PUBLISHABLE_KEY",
19
+ apiUrl: "ECOMWEB_API_URL",
20
+ appUrl: "SITE_URL"
21
+ };
22
+ const DEFAULT_SINGLE_API_URL = "https://apibase.ecomweb.app";
23
+ function parseMulti(env) {
24
+ return parseOrThrow(
25
+ publicConfigSchema,
26
+ {
27
+ mode: "multi",
28
+ storeRef: null,
29
+ apiUrl: envValue(env, "NEXT_PUBLIC_API_URL")?.replace(/\/$/, ""),
30
+ assetBaseUrl: (envValue(env, "NEXT_PUBLIC_ASSET_BASE_URL") ?? "").replace(
31
+ /\/$/,
32
+ ""
33
+ ),
34
+ appUrl: envValue(env, "NEXT_PUBLIC_APP_URL") ?? "https://ecomweb.app",
35
+ storefrontApiKey: envValue(env, "NEXT_PUBLIC_PLATFORM_API_KEY"),
36
+ platformDomainSuffix: envValue(env, "NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX") ?? "ecomsite.app",
37
+ appBaseUrlFlag: envValue(env, "NEXT_PUBLIC_APP_BASE_URL"),
38
+ imageTransformationsFlag: envValue(
39
+ env,
40
+ "NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS"
41
+ ),
42
+ primaryMenuRef: envValue(env, "NEXT_PUBLIC_PRIMARY_MENU_REF") ?? "main-menu",
43
+ logLevel: logLevelOf(envValue(env, "NEXT_PUBLIC_LOG_LEVEL")),
44
+ webVitalsSampleRate: sampleRateOf(
45
+ envValue(env, "NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE"),
46
+ 0.1
47
+ )
48
+ },
49
+ MULTI_ENV_NAME_OF
50
+ );
51
+ }
52
+ function parseSingle(env) {
53
+ const apiUrl = (envValue(env, "NEXT_PUBLIC_ECOMWEB_API_URL") ?? DEFAULT_SINGLE_API_URL).replace(/\/$/, "");
54
+ return parseOrThrow(
55
+ publicConfigSchema,
56
+ {
57
+ mode: "single",
58
+ storeRef: envValue(env, "NEXT_PUBLIC_ECOMWEB_STORE_REF"),
59
+ apiUrl,
60
+ assetBaseUrl: (envValue(env, "NEXT_PUBLIC_ECOMWEB_ASSET_URL") ?? apiUrl).replace(/\/$/, ""),
61
+ appUrl: envValue(env, "NEXT_PUBLIC_SITE_URL")?.replace(/\/$/, ""),
62
+ storefrontApiKey: envValue(env, "NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY"),
63
+ platformDomainSuffix: null,
64
+ appBaseUrlFlag: void 0,
65
+ imageTransformationsFlag: envValue(
66
+ env,
67
+ "NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS"
68
+ ),
69
+ primaryMenuRef: "main-menu",
70
+ logLevel: logLevelOf(envValue(env, "NEXT_PUBLIC_LOG_LEVEL")),
71
+ webVitalsSampleRate: sampleRateOf(
72
+ envValue(env, "NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE"),
73
+ 0.1
74
+ )
75
+ },
76
+ SINGLE_ENV_NAME_OF
77
+ );
78
+ }
79
+ function parsePublicConfig(env) {
80
+ return resolveMode(env) === "multi" ? parseMulti(env) : parseSingle(env);
81
+ }
82
+ let cached;
83
+ function resetPublicConfigForTests() {
84
+ cached = void 0;
85
+ }
86
+ function publicConfig() {
87
+ return cached ??= parsePublicConfig({
88
+ NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,
89
+ ECOMWEB_MODE: typeof window === "undefined" ? process.env.ECOMWEB_MODE : void 0,
90
+ // multi
91
+ NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,
92
+ NEXT_PUBLIC_ASSET_BASE_URL: process.env.NEXT_PUBLIC_ASSET_BASE_URL,
93
+ NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
94
+ NEXT_PUBLIC_PLATFORM_API_KEY: process.env.NEXT_PUBLIC_PLATFORM_API_KEY,
95
+ NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX: process.env.NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX,
96
+ NEXT_PUBLIC_APP_BASE_URL: process.env.NEXT_PUBLIC_APP_BASE_URL,
97
+ NEXT_PUBLIC_PRIMARY_MENU_REF: process.env.NEXT_PUBLIC_PRIMARY_MENU_REF,
98
+ // single
99
+ NEXT_PUBLIC_ECOMWEB_STORE_REF: process.env.NEXT_PUBLIC_ECOMWEB_STORE_REF,
100
+ NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,
101
+ NEXT_PUBLIC_ECOMWEB_API_URL: process.env.NEXT_PUBLIC_ECOMWEB_API_URL,
102
+ NEXT_PUBLIC_ECOMWEB_ASSET_URL: process.env.NEXT_PUBLIC_ECOMWEB_ASSET_URL,
103
+ NEXT_PUBLIC_SITE_URL: process.env.NEXT_PUBLIC_SITE_URL,
104
+ // both
105
+ NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS: process.env.NEXT_PUBLIC_ENABLE_IMAGE_TRANSFORMATIONS,
106
+ NEXT_PUBLIC_LOG_LEVEL: process.env.NEXT_PUBLIC_LOG_LEVEL,
107
+ NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE: process.env.NEXT_PUBLIC_WEB_VITALS_SAMPLE_RATE
108
+ });
109
+ }
110
+ export {
111
+ parsePublicConfig,
112
+ publicConfig,
113
+ resetPublicConfigForTests
114
+ };
115
+ //# sourceMappingURL=public.js.map