@ecomweb/storefront-kit 0.5.0 → 0.9.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 (64) hide show
  1. package/dist/api/proxy.js +5 -1
  2. package/dist/api/proxy.js.map +1 -1
  3. package/dist/api/server-client.js +7 -4
  4. package/dist/api/server-client.js.map +1 -1
  5. package/dist/auth/cookies.js +51 -33
  6. package/dist/auth/cookies.js.map +1 -1
  7. package/dist/auth/error-copy.js +2 -1
  8. package/dist/auth/error-copy.js.map +1 -1
  9. package/dist/auth/route-handlers.js +2 -2
  10. package/dist/auth/route-handlers.js.map +1 -1
  11. package/dist/auth/session-refresh.js +11 -5
  12. package/dist/auth/session-refresh.js.map +1 -1
  13. package/dist/auth/session.js +8 -4
  14. package/dist/auth/session.js.map +1 -1
  15. package/dist/checkout/get-payment-state.js.map +1 -1
  16. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  17. package/dist/checkout/order-handoff.js +10 -1
  18. package/dist/checkout/order-handoff.js.map +1 -1
  19. package/dist/checkout/use-checkout.js +8 -2
  20. package/dist/checkout/use-checkout.js.map +1 -1
  21. package/dist/config/schema.js +12 -1
  22. package/dist/config/schema.js.map +1 -1
  23. package/dist/config/server.js +9 -2
  24. package/dist/config/server.js.map +1 -1
  25. package/dist/config.d.ts +3 -3
  26. package/dist/index.d.ts +84 -24
  27. package/dist/index.js +12 -0
  28. package/dist/index.js.map +1 -1
  29. package/dist/middleware/create-storefront-middleware.js +62 -26
  30. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  31. package/dist/middleware.d.ts +2 -2
  32. package/dist/{mode-YNx2aOtQ.d.ts → mode-Lm9t4qzX.d.ts} +1 -1
  33. package/dist/promotions/use-promotion-validation.js +19 -16
  34. package/dist/promotions/use-promotion-validation.js.map +1 -1
  35. package/dist/{schema-Tc0qRs-Q.d.ts → schema-Dg0ZflMW.d.ts} +1 -0
  36. package/dist/server.d.ts +8 -2
  37. package/dist/server.js +2 -0
  38. package/dist/server.js.map +1 -1
  39. package/dist/shipping/shipping-calculation-reducer.js +7 -4
  40. package/dist/shipping/shipping-calculation-reducer.js.map +1 -1
  41. package/dist/stores/get-store-by-host.js +41 -6
  42. package/dist/stores/get-store-by-host.js.map +1 -1
  43. package/dist/stores/store-subdomain.js +25 -0
  44. package/dist/stores/store-subdomain.js.map +1 -0
  45. package/dist/stores/store-traffic.js +50 -0
  46. package/dist/stores/store-traffic.js.map +1 -0
  47. package/dist/stores/ttl-cache.js +34 -0
  48. package/dist/stores/ttl-cache.js.map +1 -0
  49. package/dist/theme/define.js.map +1 -1
  50. package/dist/theme/index.js.map +1 -1
  51. package/dist/theme/preview-bridge.js +33 -0
  52. package/dist/theme/preview-bridge.js.map +1 -0
  53. package/dist/theme/preview-cookie.js +13 -6
  54. package/dist/theme/preview-cookie.js.map +1 -1
  55. package/dist/theme/preview-host.js +7 -0
  56. package/dist/theme/preview-host.js.map +1 -0
  57. package/dist/theme/read-preview-host.js +10 -0
  58. package/dist/theme/read-preview-host.js.map +1 -0
  59. package/dist/theme/read-preview-token.js +5 -3
  60. package/dist/theme/read-preview-token.js.map +1 -1
  61. package/dist/theme/settings-context.js +14 -1
  62. package/dist/theme/settings-context.js.map +1 -1
  63. package/dist/theme.d.ts +65 -5
  64. package/package.json +2 -2
@@ -1,15 +1,19 @@
1
1
  import "server-only";
2
2
  import { cache } from "react";
3
3
  import { cookies, headers } from "next/headers";
4
- import { readAuthCookies } from "./cookies.js";
4
+ import { authCookiePathFor, readAuthCookies } from "./cookies.js";
5
5
  import { clientIpFrom } from "./client-ip.js";
6
6
  import { createAuthApi } from "./sdk.js";
7
7
  const getServerIdentity = cache(
8
8
  async (storeRef) => {
9
- const jar = await cookies();
10
- const tokens = readAuthCookies(jar, storeRef);
9
+ const requestHeaders = await headers();
10
+ const tokens = readAuthCookies(
11
+ await cookies(),
12
+ storeRef,
13
+ authCookiePathFor({ headers: requestHeaders }, storeRef)
14
+ );
11
15
  if (!tokens) return null;
12
- const me = await createAuthApi(storeRef, clientIpFrom(await headers())).me(
16
+ const me = await createAuthApi(storeRef, clientIpFrom(requestHeaders)).me(
13
17
  tokens.access_token
14
18
  );
15
19
  return me.success ? me.data ?? null : null;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n const jar = await cookies();\n const tokens = readAuthCookies(jar, storeRef);\n if (!tokens) return null;\n\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable — and the backend rate-limits this\n // call per `storeId:clientIp`, so it has to carry the shopper's address\n // like every other server-side auth call does.\n const me = await createAuthApi(storeRef, clientIpFrom(await headers())).me(\n tokens.access_token\n );\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,uBAAuB;AAChC,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AASvB,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAC3D,UAAM,MAAM,MAAM,QAAQ;AAC1B,UAAM,SAAS,gBAAgB,KAAK,QAAQ;AAC5C,QAAI,CAAC,OAAQ,QAAO;AAMpB,UAAM,KAAK,MAAM,cAAc,UAAU,aAAa,MAAM,QAAQ,CAAC,CAAC,EAAE;AAAA,MACtE,OAAO;AAAA,IACT;AACA,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { authCookiePathFor, readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable: they name the cookie path, and\n // the backend rate-limits this call per `storeId:clientIp`, so it has to\n // carry the shopper's address like every other server-side auth call does.\n const requestHeaders = await headers();\n const tokens = readAuthCookies(\n await cookies(),\n storeRef,\n authCookiePathFor({ headers: requestHeaders }, storeRef)\n );\n if (!tokens) return null;\n\n const me = await createAuthApi(storeRef, clientIpFrom(requestHeaders)).me(\n tokens.access_token\n );\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,mBAAmB,uBAAuB;AACnD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AASvB,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAK3D,UAAM,iBAAiB,MAAM,QAAQ;AACrC,UAAM,SAAS;AAAA,MACb,MAAM,QAAQ;AAAA,MACd;AAAA,MACA,kBAAkB,EAAE,SAAS,eAAe,GAAG,QAAQ;AAAA,IACzD;AACA,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,KAAK,MAAM,cAAc,UAAU,aAAa,cAAc,CAAC,EAAE;AAAA,MACrE,OAAO;AAAA,IACT;AACA,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-sdk` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * — see `lib/checkout/initiate-gateway-payment.ts` for the full story\n * (same pinned commit, same missing module). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.getPaymentState()`'s request/response\n * shape exactly (same path, same result shape) so that once the SDK bump\n * lands, the fix is: delete this file, delete this import in\n * `payment-state-poll`'s caller, and call\n * `sdk.payments.getPaymentState(...)` instead — the call site already reads\n * as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n const res = await publicApiClient.get<PaymentStateResult>(\n // `order_code` carries a `#` prefix by default in this system — left\n // unencoded, it truncates the URL (everything from `#` on is treated\n // as a fragment) and the request silently hits a different route.\n `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AAyBvB,eAAsB,gBACpB,UACA,YAC6B;AAC7B,QAAM,MAAM,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,IAIhC,kBAAkB,mBAAmB,QAAQ,CAAC,WAAW,mBAAmB,UAAU,CAAC;AAAA,EACzF;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * — see `lib/checkout/initiate-gateway-payment.ts` for the full story\n * (same pinned commit, same missing module). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.getPaymentState()`'s request/response\n * shape exactly (same path, same result shape) so that once the SDK bump\n * lands, the fix is: delete this file, delete this import in\n * `payment-state-poll`'s caller, and call\n * `sdk.payments.getPaymentState(...)` instead — the call site already reads\n * as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n const res = await publicApiClient.get<PaymentStateResult>(\n // `order_code` carries a `#` prefix by default in this system — left\n // unencoded, it truncates the URL (everything from `#` on is treated\n // as a fragment) and the request silently hits a different route.\n `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AAyBvB,eAAsB,gBACpB,UACA,YAC6B;AAC7B,QAAM,MAAM,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,IAIhC,kBAAkB,mBAAmB,QAAQ,CAAC,WAAW,mBAAmB,UAAU,CAAC;AAAA,EACzF;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.initiate`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-sdk` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * (confirmed: nothing under `node_modules/@ecomweb/sdk/src` references\n * `payments`, `provider_code`, or `redirect_url`). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.initiate()`'s request/response shape\n * exactly (same path, same body keys, same result shape) so that once the\n * SDK bump lands, the fix is: delete this file, delete this import in\n * `checkout-page-client.tsx`, and call `sdk.payments.initiate(...)` instead\n * — the call site already reads as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.initiate`.\n */\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n const res = await publicApiClient.post<InitiatePaymentResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code }\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AA4BvB,eAAsB,uBACpB,UACA,OACgC;AAChC,QAAM,MAAM,MAAM,gBAAgB;AAAA,IAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,IAC9C,EAAE,YAAY,MAAM,YAAY,eAAe,MAAM,cAAc;AAAA,EACrE;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.initiate`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * (confirmed: nothing under `node_modules/@ecomweb/sdk/src` references\n * `payments`, `provider_code`, or `redirect_url`). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.initiate()`'s request/response shape\n * exactly (same path, same body keys, same result shape) so that once the\n * SDK bump lands, the fix is: delete this file, delete this import in\n * `checkout-page-client.tsx`, and call `sdk.payments.initiate(...)` instead\n * — the call site already reads as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.initiate`.\n */\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n const res = await publicApiClient.post<InitiatePaymentResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code }\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AA4BvB,eAAsB,uBACpB,UACA,OACgC;AAChC,QAAM,MAAM,MAAM,gBAAgB;AAAA,IAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,IAC9C,EAAE,YAAY,MAAM,YAAY,eAAe,MAAM,cAAc;AAAA,EACrE;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
@@ -1,5 +1,12 @@
1
1
  const HANDOFF_KEY = "ecw:order-handoff";
2
2
  const MAX_AGE_MS = 24 * 60 * 60 * 1e3;
3
+ function isSummary(value) {
4
+ if (!value || typeof value !== "object") return false;
5
+ const s = value;
6
+ return typeof s.customer_name === "string" && typeof s.address === "string" && typeof s.payment_label === "string" && typeof s.subtotal === "number" && Array.isArray(s.items) && s.items.every(
7
+ (item) => !!item && typeof item === "object" && typeof item.name === "string" && typeof item.quantity === "number" && typeof item.price === "number"
8
+ );
9
+ }
3
10
  function writeOrderHandoff(handoff) {
4
11
  try {
5
12
  window.localStorage.setItem(
@@ -29,7 +36,8 @@ function readOrderHandoff(order_code) {
29
36
  function matchHandoff(parsed, order_code, now) {
30
37
  if (!parsed || typeof parsed !== "object") return null;
31
38
  const h = parsed;
32
- if (typeof h.order_code !== "string" || h.order_code !== order_code) return null;
39
+ if (typeof h.order_code !== "string" || h.order_code !== order_code)
40
+ return null;
33
41
  if (typeof h.payment_method !== "string" || h.payment_method.length === 0) {
34
42
  return null;
35
43
  }
@@ -43,6 +51,7 @@ function matchHandoff(parsed, order_code, now) {
43
51
  provider_code: typeof h.provider_code === "string" && h.provider_code.length > 0 ? h.provider_code : null,
44
52
  total: h.total,
45
53
  currency_code: typeof h.currency_code === "string" && h.currency_code.length > 0 ? h.currency_code : "VND",
54
+ summary: isSummary(h.summary) ? h.summary : null,
46
55
  written_at: h.written_at
47
56
  };
48
57
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/order-handoff.ts"],"sourcesContent":["/**\n * Carries what the success screen needs from the checkout page that placed\n * the order.\n *\n * Why this exists: gateway methods reach `/order-success` through the\n * provider and the API's return endpoint, so that page knows only the order\n * code. Offline methods (cod, bank_transfer) now navigate there directly, and\n * the screen has to know which method was used and how much to ask for.\n *\n * Why not read it from the API: the obvious candidate,\n * `GET /public/stores/:ref/orders/:code/payment-state`, deliberately\n * allow-lists its response down to two status fields, because it sits behind\n * only the public storefront key and order codes are sequential. Putting an\n * amount there would let anyone enumerate a store's order values. This data\n * never leaves the shopper's own browser instead.\n *\n * Replaces the older \"recent-order\" key, which nothing had written for a long\n * time while the success page still read it, so `orderInfo` there was always\n * null.\n */\nconst HANDOFF_KEY = \"ecw:order-handoff\";\n\n/** Older handoffs are ignored rather than shown against a newer order. */\nconst MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\nexport interface OrderHandoff {\n order_code: string;\n /** `cod`, `bank_transfer`, or a gateway code. */\n payment_method: string;\n /** Non-null only for gateway-backed methods. */\n provider_code: string | null;\n total: number;\n currency_code: string;\n written_at: number;\n}\n\nexport function writeOrderHandoff(\n handoff: Omit<OrderHandoff, \"written_at\">\n): void {\n try {\n window.localStorage.setItem(\n HANDOFF_KEY,\n JSON.stringify({ ...handoff, written_at: Date.now() })\n );\n } catch {\n // Private mode, quota, or storage disabled. The success screen falls back\n // to its order-code-only rendering, so losing this is a degradation and\n // never a failure.\n }\n}\n\n/**\n * Returns the handoff only if it is present, well-formed, fresh, and for the\n * order being shown. Any mismatch yields null: showing one order's amount on\n * another order's screen would be worse than showing no amount at all.\n */\nexport function readOrderHandoff(order_code: string | null): OrderHandoff | null {\n if (!order_code) return null;\n let raw: string | null = null;\n try {\n raw = window.localStorage.getItem(HANDOFF_KEY);\n } catch {\n return null;\n }\n if (!raw) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n return matchHandoff(parsed, order_code, Date.now());\n}\n\n/**\n * The validation half of readOrderHandoff, split out so it can be tested\n * without a DOM or a clock. Exported for that reason only.\n */\nexport function matchHandoff(\n parsed: unknown,\n order_code: string,\n now: number\n): OrderHandoff | null {\n if (!parsed || typeof parsed !== \"object\") return null;\n const h = parsed as Record<string, unknown>;\n\n if (typeof h.order_code !== \"string\" || h.order_code !== order_code) return null;\n if (typeof h.payment_method !== \"string\" || h.payment_method.length === 0) {\n return null;\n }\n if (typeof h.total !== \"number\" || !Number.isFinite(h.total)) return null;\n if (typeof h.written_at !== \"number\" || now - h.written_at > MAX_AGE_MS) {\n return null;\n }\n\n return {\n order_code: h.order_code,\n payment_method: h.payment_method,\n provider_code:\n typeof h.provider_code === \"string\" && h.provider_code.length > 0\n ? h.provider_code\n : null,\n total: h.total,\n currency_code:\n typeof h.currency_code === \"string\" && h.currency_code.length > 0\n ? h.currency_code\n : \"VND\",\n written_at: h.written_at,\n };\n}\n\nexport function clearOrderHandoff(): void {\n try {\n window.localStorage.removeItem(HANDOFF_KEY);\n } catch {\n // Nothing to do; a stale entry expires on its own.\n }\n}\n"],"mappings":"AAoBA,MAAM,cAAc;AAGpB,MAAM,aAAa,KAAK,KAAK,KAAK;AAa3B,SAAS,kBACd,SACM;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AO,aAAa,WAAW,WAAW;AAAA,EAC5C,QAAQ;AAAA,EAER;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/order-handoff.ts"],"sourcesContent":["/**\n * Carries what the success screen needs from the checkout page that placed\n * the order.\n *\n * Why this exists: gateway methods reach `/order-success` through the\n * provider and the API's return endpoint, so that page knows only the order\n * code. Offline methods (cod, bank_transfer) now navigate there directly, and\n * the screen has to know which method was used and how much to ask for.\n *\n * Why not read it from the API: the obvious candidate,\n * `GET /public/stores/:ref/orders/:code/payment-state`, deliberately\n * allow-lists its response down to two status fields, because it sits behind\n * only the public storefront key and order codes are sequential. Putting an\n * amount there would let anyone enumerate a store's order values. This data\n * never leaves the shopper's own browser instead.\n *\n * Replaces the older \"recent-order\" key, which nothing had written for a long\n * time while the success page still read it, so `orderInfo` there was always\n * null.\n */\nconst HANDOFF_KEY = \"ecw:order-handoff\";\n\n/** Older handoffs are ignored rather than shown against a newer order. */\nconst MAX_AGE_MS = 24 * 60 * 60 * 1000;\n\n/**\n * What the thank-you page shows of the order (contact, address, methods,\n * lines, money), built by the storefront when it places the order. Like the\n * rest of the handoff it stays in the shopper's own browser.\n */\nexport interface OrderHandoffSummary {\n customer_name: string;\n phone: string;\n email: string | null;\n /** The delivery address as one display line. */\n address: string;\n shipping_method: string | null;\n shipping_fee: number | null;\n payment_label: string;\n items: {\n name: string;\n variant: string | null;\n quantity: number;\n /** Unit price. */\n price: number;\n image: string | null;\n }[];\n subtotal: number;\n discount: number;\n}\n\nexport interface OrderHandoff {\n order_code: string;\n /** `cod`, `bank_transfer`, or a gateway code. */\n payment_method: string;\n /** Non-null only for gateway-backed methods. */\n provider_code: string | null;\n total: number;\n currency_code: string;\n /** Absent for gateway returns and older handoffs. */\n summary?: OrderHandoffSummary | null;\n written_at: number;\n}\n\nfunction isSummary(value: unknown): value is OrderHandoffSummary {\n if (!value || typeof value !== \"object\") return false;\n const s = value as Record<string, unknown>;\n return (\n typeof s.customer_name === \"string\" &&\n typeof s.address === \"string\" &&\n typeof s.payment_label === \"string\" &&\n typeof s.subtotal === \"number\" &&\n Array.isArray(s.items) &&\n s.items.every(\n item =>\n !!item &&\n typeof item === \"object\" &&\n typeof (item as Record<string, unknown>).name === \"string\" &&\n typeof (item as Record<string, unknown>).quantity === \"number\" &&\n typeof (item as Record<string, unknown>).price === \"number\"\n )\n );\n}\n\nexport function writeOrderHandoff(\n handoff: Omit<OrderHandoff, \"written_at\">\n): void {\n try {\n window.localStorage.setItem(\n HANDOFF_KEY,\n JSON.stringify({ ...handoff, written_at: Date.now() })\n );\n } catch {\n // Private mode, quota, or storage disabled. The success screen falls back\n // to its order-code-only rendering, so losing this is a degradation and\n // never a failure.\n }\n}\n\n/**\n * Returns the handoff only if it is present, well-formed, fresh, and for the\n * order being shown. Any mismatch yields null: showing one order's amount on\n * another order's screen would be worse than showing no amount at all.\n */\nexport function readOrderHandoff(\n order_code: string | null\n): OrderHandoff | null {\n if (!order_code) return null;\n let raw: string | null = null;\n try {\n raw = window.localStorage.getItem(HANDOFF_KEY);\n } catch {\n return null;\n }\n if (!raw) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return null;\n }\n return matchHandoff(parsed, order_code, Date.now());\n}\n\n/**\n * The validation half of readOrderHandoff, split out so it can be tested\n * without a DOM or a clock. Exported for that reason only.\n */\nexport function matchHandoff(\n parsed: unknown,\n order_code: string,\n now: number\n): OrderHandoff | null {\n if (!parsed || typeof parsed !== \"object\") return null;\n const h = parsed as Record<string, unknown>;\n\n if (typeof h.order_code !== \"string\" || h.order_code !== order_code)\n return null;\n if (typeof h.payment_method !== \"string\" || h.payment_method.length === 0) {\n return null;\n }\n if (typeof h.total !== \"number\" || !Number.isFinite(h.total)) return null;\n if (typeof h.written_at !== \"number\" || now - h.written_at > MAX_AGE_MS) {\n return null;\n }\n\n return {\n order_code: h.order_code,\n payment_method: h.payment_method,\n provider_code:\n typeof h.provider_code === \"string\" && h.provider_code.length > 0\n ? h.provider_code\n : null,\n total: h.total,\n currency_code:\n typeof h.currency_code === \"string\" && h.currency_code.length > 0\n ? h.currency_code\n : \"VND\",\n summary: isSummary(h.summary) ? h.summary : null,\n written_at: h.written_at,\n };\n}\n\nexport function clearOrderHandoff(): void {\n try {\n window.localStorage.removeItem(HANDOFF_KEY);\n } catch {\n // Nothing to do; a stale entry expires on its own.\n }\n}\n"],"mappings":"AAoBA,MAAM,cAAc;AAGpB,MAAM,aAAa,KAAK,KAAK,KAAK;AAyClC,SAAS,UAAU,OAA8C;AAC/D,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,IAAI;AACV,SACE,OAAO,EAAE,kBAAkB,YAC3B,OAAO,EAAE,YAAY,YACrB,OAAO,EAAE,kBAAkB,YAC3B,OAAO,EAAE,aAAa,YACtB,MAAM,QAAQ,EAAE,KAAK,KACrB,EAAE,MAAM;AAAA,IACN,UACE,CAAC,CAAC,QACF,OAAO,SAAS,YAChB,OAAQ,KAAiC,SAAS,YAClD,OAAQ,KAAiC,aAAa,YACtD,OAAQ,KAAiC,UAAU;AAAA,EACvD;AAEJ;AAEO,SAAS,kBACd,SACM;AACN,MAAI;AACF,WAAO,aAAa;AAAA,MAClB;AAAA,MACA,KAAK,UAAU,EAAE,GAAG,SAAS,YAAY,KAAK,IAAI,EAAE,CAAC;AAAA,IACvD;AAAA,EACF,QAAQ;AAAA,EAIR;AACF;AAOO,SAAS,iBACd,YACqB;AACrB,MAAI,CAAC,WAAY,QAAO;AACxB,MAAI,MAAqB;AACzB,MAAI;AACF,UAAM,OAAO,aAAa,QAAQ,WAAW;AAAA,EAC/C,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,CAAC,IAAK,QAAO;AAEjB,MAAI;AACJ,MAAI;AACF,aAAS,KAAK,MAAM,GAAG;AAAA,EACzB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,SAAO,aAAa,QAAQ,YAAY,KAAK,IAAI,CAAC;AACpD;AAMO,SAAS,aACd,QACA,YACA,KACqB;AACrB,MAAI,CAAC,UAAU,OAAO,WAAW,SAAU,QAAO;AAClD,QAAM,IAAI;AAEV,MAAI,OAAO,EAAE,eAAe,YAAY,EAAE,eAAe;AACvD,WAAO;AACT,MAAI,OAAO,EAAE,mBAAmB,YAAY,EAAE,eAAe,WAAW,GAAG;AACzE,WAAO;AAAA,EACT;AACA,MAAI,OAAO,EAAE,UAAU,YAAY,CAAC,OAAO,SAAS,EAAE,KAAK,EAAG,QAAO;AACrE,MAAI,OAAO,EAAE,eAAe,YAAY,MAAM,EAAE,aAAa,YAAY;AACvE,WAAO;AAAA,EACT;AAEA,SAAO;AAAA,IACL,YAAY,EAAE;AAAA,IACd,gBAAgB,EAAE;AAAA,IAClB,eACE,OAAO,EAAE,kBAAkB,YAAY,EAAE,cAAc,SAAS,IAC5D,EAAE,gBACF;AAAA,IACN,OAAO,EAAE;AAAA,IACT,eACE,OAAO,EAAE,kBAAkB,YAAY,EAAE,cAAc,SAAS,IAC5D,EAAE,gBACF;AAAA,IACN,SAAS,UAAU,EAAE,OAAO,IAAI,EAAE,UAAU;AAAA,IAC5C,YAAY,EAAE;AAAA,EAChB;AACF;AAEO,SAAS,oBAA0B;AACxC,MAAI;AACF,WAAO,aAAa,WAAW,WAAW;AAAA,EAC5C,QAAQ;AAAA,EAER;AACF;","names":[]}
@@ -167,7 +167,8 @@ function useCheckout({
167
167
  payment_method: input.paymentMethod,
168
168
  provider_code: method?.provider_code ?? null,
169
169
  total: Number(order.total ?? 0),
170
- currency_code: order.currency_code ?? "VND"
170
+ currency_code: order.currency_code ?? "VND",
171
+ summary: input.summary ?? null
171
172
  });
172
173
  clearCart(false);
173
174
  return {
@@ -181,9 +182,14 @@ function useCheckout({
181
182
  setStockIssues(issues);
182
183
  return { kind: "stock_issues", issues };
183
184
  }
185
+ const code = error && typeof error === "object" && "code" in error ? error.code : void 0;
186
+ if (code === "ORDER_PROMOTION_NOT_APPLICABLE") {
187
+ promotionState.removePromoCode();
188
+ }
184
189
  return {
185
190
  kind: "error",
186
- message: error instanceof Error ? error.message : String(error)
191
+ message: error instanceof Error ? error.message : String(error),
192
+ ...typeof code === "string" && { code }
187
193
  };
188
194
  } finally {
189
195
  inFlight.current = false;
@@ -1 +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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,SAAS,cAAc;AAAA,MACvB,cAAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA,MACjC,YAAY,cAAc;AAAA,MAC1B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
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, type OrderHandoffSummary } 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 * What the thank-you page shows of the order; stored with the handoff in\n * this browser only, never sent to the API.\n */\n summary?: OrderHandoffSummary;\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. `code` is the API's error code when it sent\n * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied\n * code has already been removed, so the shopper sees the real total before\n * placing again.\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; code?: 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 summary: input.summary ?? null,\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 const code =\n error && typeof error === \"object\" && \"code\" in error\n ? (error as { code?: unknown }).code\n : undefined;\n // The API refused the order rather than drop the discount the shopper\n // was shown. Keeping the code would fail every retry the same way.\n if (code === \"ORDER_PROMOTION_NOT_APPLICABLE\") {\n promotionState.removePromoCode();\n }\n return {\n kind: \"error\",\n message: error instanceof Error ? error.message : String(error),\n ...(typeof code === \"string\" && { code }),\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":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgB;AAEzD,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,8BAA8B;AACvC,SAAS,WAAW;AACpB,SAAS,8B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AAc,cAAc;AAAA,MAC5B,eAAe,cAAc;AAAA,MAC7B,eAAe,cAAc;AAAA,MAC7B,mBAAmB,cAAc;AAAA,MACjC,YAAY,cAAc;AAAA,MAC1B,OAAO,cAAc;AAAA,IACvB;AAAA,IACA,WAAW;AAAA,MACT,MAAM,eAAe;AAAA,MACrB,SAAS,eAAe;AAAA,MACxB,SAAS,eAAe;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,cAAc,eAAe;AAAA,MAC7B,OAAO,eAAe;AAAA,MACtB,UAAU,eAAe;AAAA,MACzB,QAAQ,eAAe;AAAA,MACvB,iBAAiB,eAAe;AAAA,IAClC;AAAA;AAAA;AAAA,IAGA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA,UAAU;AAAA,MACV,WAAW;AAAA,MACX,UAAU,cAAc;AAAA,MACxB,kBAAkB,eAAe;AAAA,MACjC,OACE,QAAQ,cAAc,cAAc,eAAe;AAAA,IACvD;AAAA,IACA;AAAA,IACA,oBAAoB;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -34,7 +34,13 @@ const serverConfigSchema = z.object({
34
34
  * shopper cannot forge: X-Forwarded-For behind an edge that overwrites it
35
35
  * (Vercel), CF-Connecting-IP behind Cloudflare → proxies that append.
36
36
  */
37
- clientIpHeader: z.enum(["x-forwarded-for", "cf-connecting-ip"])
37
+ clientIpHeader: z.enum(["x-forwarded-for", "cf-connecting-ip"]),
38
+ /**
39
+ * Requests a minute to one store, on one server, above which the
40
+ * multi-tenant middleware logs that store (log only, nothing is refused).
41
+ * 0 turns it off.
42
+ */
43
+ storeTrafficLogPerMinute: z.number().int().min(0)
38
44
  });
39
45
  class ConfigError extends Error {
40
46
  constructor(message) {
@@ -54,12 +60,17 @@ function parseOrThrow(schema, candidate, envNameOf) {
54
60
  ${lines.join("\n")}`
55
61
  );
56
62
  }
63
+ function countOf(v, fallback) {
64
+ const n = Number(v);
65
+ return v !== void 0 && Number.isInteger(n) && n >= 0 ? n : fallback;
66
+ }
57
67
  function sampleRateOf(v, fallback) {
58
68
  const n = Number(v);
59
69
  return v !== void 0 && Number.isFinite(n) && n >= 0 && n <= 1 ? n : fallback;
60
70
  }
61
71
  export {
62
72
  ConfigError,
73
+ countOf,
63
74
  envValue,
64
75
  logLevelOf,
65
76
  parseOrThrow,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/schema.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\nexport type EnvSource = Record<string, string | undefined>;\n\nconst LOG_LEVELS = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n\n/** Blank strings count as unset: a `KEY=` line in .env is a mistake, not a value. */\nexport function envValue(env: EnvSource, key: string): string | undefined {\n const v = env[key]?.trim();\n return v ? v : undefined;\n}\n\nexport function logLevelOf(v: string | undefined): LogLevel | undefined {\n return (LOG_LEVELS as readonly string[]).includes(v ?? \"\")\n ? (v as LogLevel)\n : undefined;\n}\n\n/** http(s) only: bare `localhost:3001` parses as a URL with scheme \"localhost:\". */\nconst httpUrl = z.url({ protocol: /^https?$/ });\n\nexport const publicConfigSchema = z.object({\n mode: z.enum([\"multi\", \"single\"]),\n storeRef: z.string().min(1).nullable(),\n apiUrl: httpUrl,\n assetBaseUrl: z.string(),\n appUrl: httpUrl,\n storefrontApiKey: z.string().min(1),\n platformDomainSuffix: z.string().min(1).nullable(),\n appBaseUrlFlag: z.string().optional(),\n imageTransformationsFlag: z.string().optional(),\n primaryMenuRef: z.string().min(1),\n logLevel: z.enum(LOG_LEVELS).optional(),\n webVitalsSampleRate: z.number().min(0).max(1),\n});\nexport type PublicConfig = z.infer<typeof publicConfigSchema>;\n\nexport const serverConfigSchema = z.object({\n platformApiKey: z.string().min(1),\n clientIpForwarderSecret: z.string().min(1).optional(),\n appBaseUrl: z.string().min(1),\n appEnv: z.string().min(1),\n googleVerification: z.string().optional(),\n logLevel: z.enum(LOG_LEVELS).optional(),\n /**\n * The header carrying the shopper's IP that this server's edge sets and a\n * shopper cannot forge: X-Forwarded-For behind an edge that overwrites it\n * (Vercel), CF-Connecting-IP behind Cloudflare → proxies that append.\n */\n clientIpHeader: z.enum([\"x-forwarded-for\", \"cf-connecting-ip\"]),\n});\nexport type ServerConfig = z.infer<typeof serverConfigSchema>;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\n/**\n * Parses `candidate` and, on failure, throws one error naming the env var\n * behind every bad field, so a misconfigured deploy says what to fix instead\n * of rendering empty pages.\n */\nexport function parseOrThrow<T>(\n schema: z.ZodType<T>,\n candidate: unknown,\n envNameOf: Record<string, string>\n): T {\n const result = schema.safeParse(candidate);\n if (result.success) return result.data;\n const lines = result.error.issues.map(issue => {\n const field = String(issue.path[0] ?? \"\");\n return ` - ${envNameOf[field] ?? field}: ${issue.message}`;\n });\n throw new ConfigError(\n `Invalid storefront configuration:\\n${lines.join(\"\\n\")}`\n );\n}\n\nexport function sampleRateOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isFinite(n) && n >= 0 && n <= 1\n ? n\n : fallback;\n}\n"],"mappings":"AAAA,SAAS,SAAS;AAKlB,MAAM,aAAa,CAAC,UAAU,SAAS,QAAQ,QAAQ,OAAO;AAGvD,SAAS,SAAS,KAAgB,KAAiC;AACxE,QAAM,IAAI,IAAI,GAAG,GAAG,KAAK;AACzB,SAAO,IAAI,IAAI;AACjB;AAEO,SAAS,WAAW,GAA6C;AACtE,SAAQ,WAAiC,SAAS,KAAK,EAAE,IACpD,IACD;AACN;AAGA,MAAM,UAAU,EAAE,IAAI,EAAE,UAAU,WAAW,CAAC;AAEvC,MAAM,qBAAqB,EAAE,OAAO;AAAA,EACzC,MAAM,EAAE,KAAK,CAAC,SAAS,QAAQ,CAAC;AAAA,EAChC,UAAU,EAAE,OAAO,EAAE,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,WAAO,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK,MAAM,OAAO;AAAA,EAC3D,CAAC;AACD,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,MAAM,KAAK,IAAI,CAAC;AAAA,EACxD;AACF;AAEO,SAAS,aAAa,GAAuB,UAA0B;AAC5E,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,SAAS,CAAC,KAAK,KAAK,KAAK,KAAK,IAC3D,IACA;AACN;","names":[]}
1
+ {"version":3,"sources":["../../src/config/schema.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport type LogLevel = \"silent\" | \"error\" | \"warn\" | \"info\" | \"debug\";\nexport type EnvSource = Record<string, string | undefined>;\n\nconst LOG_LEVELS = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n\n/** Blank strings count as unset: a `KEY=` line in .env is a mistake, not a value. */\nexport function envValue(env: EnvSource, key: string): string | undefined {\n const v = env[key]?.trim();\n return v ? v : undefined;\n}\n\nexport function logLevelOf(v: string | undefined): LogLevel | undefined {\n return (LOG_LEVELS as readonly string[]).includes(v ?? \"\")\n ? (v as LogLevel)\n : undefined;\n}\n\n/** http(s) only: bare `localhost:3001` parses as a URL with scheme \"localhost:\". */\nconst httpUrl = z.url({ protocol: /^https?$/ });\n\nexport const publicConfigSchema = z.object({\n mode: z.enum([\"multi\", \"single\"]),\n storeRef: z.string().min(1).nullable(),\n apiUrl: httpUrl,\n assetBaseUrl: z.string(),\n appUrl: httpUrl,\n storefrontApiKey: z.string().min(1),\n platformDomainSuffix: z.string().min(1).nullable(),\n appBaseUrlFlag: z.string().optional(),\n imageTransformationsFlag: z.string().optional(),\n primaryMenuRef: z.string().min(1),\n logLevel: z.enum(LOG_LEVELS).optional(),\n webVitalsSampleRate: z.number().min(0).max(1),\n});\nexport type PublicConfig = z.infer<typeof publicConfigSchema>;\n\nexport const serverConfigSchema = z.object({\n platformApiKey: z.string().min(1),\n clientIpForwarderSecret: z.string().min(1).optional(),\n appBaseUrl: z.string().min(1),\n appEnv: z.string().min(1),\n googleVerification: z.string().optional(),\n logLevel: z.enum(LOG_LEVELS).optional(),\n /**\n * The header carrying the shopper's IP that this server's edge sets and a\n * shopper cannot forge: X-Forwarded-For behind an edge that overwrites it\n * (Vercel), CF-Connecting-IP behind Cloudflare → proxies that append.\n */\n clientIpHeader: z.enum([\"x-forwarded-for\", \"cf-connecting-ip\"]),\n /**\n * Requests a minute to one store, on one server, above which the\n * multi-tenant middleware logs that store (log only, nothing is refused).\n * 0 turns it off.\n */\n storeTrafficLogPerMinute: z.number().int().min(0),\n});\nexport type ServerConfig = z.infer<typeof serverConfigSchema>;\n\nexport class ConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigError\";\n }\n}\n\n/**\n * Parses `candidate` and, on failure, throws one error naming the env var\n * behind every bad field, so a misconfigured deploy says what to fix instead\n * of rendering empty pages.\n */\nexport function parseOrThrow<T>(\n schema: z.ZodType<T>,\n candidate: unknown,\n envNameOf: Record<string, string>\n): T {\n const result = schema.safeParse(candidate);\n if (result.success) return result.data;\n const lines = result.error.issues.map(issue => {\n const field = String(issue.path[0] ?? \"\");\n return ` - ${envNameOf[field] ?? field}: ${issue.message}`;\n });\n throw new ConfigError(\n `Invalid storefront configuration:\\n${lines.join(\"\\n\")}`\n );\n}\n\n/** A non-negative integer from `v`, else `fallback`. */\nexport function countOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isInteger(n) && n >= 0 ? n : fallback;\n}\n\nexport function sampleRateOf(v: string | undefined, fallback: number): number {\n const n = Number(v);\n return v !== undefined && Number.isFinite(n) && n >= 0 && n <= 1\n ? n\n : fallback;\n}\n"],"mappings":"AAAA,SAAS,SAAS;AAKlB,MAAM,aAAa,CAAC,UAAU,SAAS,QAAQ,QAAQ,OAAO;AAGvD,SAAS,SAAS,KAAgB,KAAiC;AACxE,QAAM,IAAI,IAAI,GAAG,GAAG,KAAK;AACzB,SAAO,I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AAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAClD,CAAC;AAGM,MAAM,oBAAoB,MAAM;AAAA,EACrC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAOO,SAAS,aACd,QACA,WACA,WACG;AACH,QAAM,SAAS,OAAO,UAAU,SAAS;AACzC,MAAI,OAAO,QAAS,QAAO,OAAO;AAClC,QAAM,QAAQ,OAAO,MAAM,OAAO,IAAI,WAAS;AAC7C,UAAM,QAAQ,OAAO,MAAM,KAAK,CAAC,KAAK,EAAE;AACxC,WAAO,OAAO,UAAU,KAAK,KAAK,KAAK,KAAK,MAAM,OAAO;AAAA,EAC3D,CAAC;AACD,QAAM,IAAI;AAAA,IACR;AAAA,EAAsC,MAAM,KAAK,IAAI,CAAC;AAAA,EACxD;AACF;AAGO,SAAS,QAAQ,GAAuB,UAA0B;AACvE,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,UAAU,CAAC,KAAK,KAAK,IAAI,IAAI;AAChE;AAEO,SAAS,aAAa,GAAuB,UAA0B;AAC5E,QAAM,IAAI,OAAO,CAAC;AAClB,SAAO,MAAM,UAAa,OAAO,SAAS,CAAC,KAAK,KAAK,KAAK,KAAK,IAC3D,IACA;AACN;","names":[]}
@@ -1,6 +1,7 @@
1
1
  import "server-only";
2
2
  import { resolveMode } from "./mode.js";
3
3
  import {
4
+ countOf,
4
5
  envValue,
5
6
  logLevelOf,
6
7
  parseOrThrow,
@@ -16,7 +17,11 @@ function parseMulti(env) {
16
17
  appEnv: envValue(env, "APP_ENV") ?? "unknown",
17
18
  googleVerification: envValue(env, "GOOGLE_VERIFICATION"),
18
19
  logLevel: logLevelOf(envValue(env, "LOG_LEVEL")),
19
- clientIpHeader: envValue(env, "CLIENT_IP_HEADER") ?? "x-forwarded-for"
20
+ clientIpHeader: envValue(env, "CLIENT_IP_HEADER") ?? "x-forwarded-for",
21
+ storeTrafficLogPerMinute: countOf(
22
+ envValue(env, "STORE_TRAFFIC_LOG_PER_MINUTE"),
23
+ 600
24
+ )
20
25
  },
21
26
  {
22
27
  platformApiKey: "PLATFORM_API_KEY or NEXT_PUBLIC_PLATFORM_API_KEY",
@@ -37,7 +42,9 @@ function parseSingle(env) {
37
42
  appEnv: envValue(env, "APP_ENV") ?? "production",
38
43
  googleVerification: envValue(env, "GOOGLE_VERIFICATION"),
39
44
  logLevel: logLevelOf(envValue(env, "LOG_LEVEL")),
40
- clientIpHeader: envValue(env, "CLIENT_IP_HEADER") ?? "x-forwarded-for"
45
+ clientIpHeader: envValue(env, "CLIENT_IP_HEADER") ?? "x-forwarded-for",
46
+ // One store per site: there are no neighbours to watch.
47
+ storeTrafficLogPerMinute: 0
41
48
  },
42
49
  {
43
50
  platformApiKey: "ECOMWEB_PUBLISHABLE_KEY",
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport {\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n platformApiKey:\n envValue(env, \"PLATFORM_API_KEY\") ??\n envValue(env, \"NEXT_PUBLIC_PLATFORM_API_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"APP_BASE_URL\") ?? \"http://localhost:3002\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"unknown\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n },\n {\n platformApiKey: \"PLATFORM_API_KEY or NEXT_PUBLIC_PLATFORM_API_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\nfunction parseSingle(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n // The key is publishable, and next.config inlines it at build time as\n // NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY: an image built with --build-arg\n // still runs when the runtime env does not repeat it.\n platformApiKey:\n envValue(env, \"ECOMWEB_PUBLISHABLE_KEY\") ??\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"SITE_URL\") ?? \"http://localhost:3000\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"production\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n },\n {\n platformApiKey: \"ECOMWEB_PUBLISHABLE_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parseServerConfig(env: EnvSource): ServerConfig {\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: ServerConfig | undefined;\n\nexport function resetServerConfigForTests(): void {\n cached = undefined;\n}\n\nexport function serverConfig(): ServerConfig {\n return (cached ??= parseServerConfig({\n ...process.env,\n // Literal reads so Next inlines the build-time values.\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n }));\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,WAAW,KAA8B;AAChD,SAAO;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AAAA,EAChB,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../../src/config/server.ts"],"sourcesContent":["import \"server-only\";\nimport { resolveMode } from \"./mode\";\nimport {\n countOf,\n envValue,\n logLevelOf,\n parseOrThrow,\n serverConfigSchema,\n type EnvSource,\n type ServerConfig,\n} from \"./schema\";\n\nfunction parseMulti(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n platformApiKey:\n envValue(env, \"PLATFORM_API_KEY\") ??\n envValue(env, \"NEXT_PUBLIC_PLATFORM_API_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"APP_BASE_URL\") ?? \"http://localhost:3002\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"unknown\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n storeTrafficLogPerMinute: countOf(\n envValue(env, \"STORE_TRAFFIC_LOG_PER_MINUTE\"),\n 600\n ),\n },\n {\n platformApiKey: \"PLATFORM_API_KEY or NEXT_PUBLIC_PLATFORM_API_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\nfunction parseSingle(env: EnvSource): ServerConfig {\n return parseOrThrow(\n serverConfigSchema,\n {\n // The key is publishable, and next.config inlines it at build time as\n // NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY: an image built with --build-arg\n // still runs when the runtime env does not repeat it.\n platformApiKey:\n envValue(env, \"ECOMWEB_PUBLISHABLE_KEY\") ??\n envValue(env, \"NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY\"),\n clientIpForwarderSecret: envValue(env, \"CLIENT_IP_FORWARDER_SECRET\"),\n appBaseUrl: envValue(env, \"SITE_URL\") ?? \"http://localhost:3000\",\n appEnv: envValue(env, \"APP_ENV\") ?? \"production\",\n googleVerification: envValue(env, \"GOOGLE_VERIFICATION\"),\n logLevel: logLevelOf(envValue(env, \"LOG_LEVEL\")),\n clientIpHeader: envValue(env, \"CLIENT_IP_HEADER\") ?? \"x-forwarded-for\",\n // One store per site: there are no neighbours to watch.\n storeTrafficLogPerMinute: 0,\n },\n {\n platformApiKey: \"ECOMWEB_PUBLISHABLE_KEY\",\n clientIpHeader: \"CLIENT_IP_HEADER\",\n }\n );\n}\n\n/** Parses the variables of the mode `env` selects (see resolveMode). */\nexport function parseServerConfig(env: EnvSource): ServerConfig {\n return resolveMode(env) === \"multi\" ? parseMulti(env) : parseSingle(env);\n}\n\nlet cached: ServerConfig | undefined;\n\nexport function resetServerConfigForTests(): void {\n cached = undefined;\n}\n\nexport function serverConfig(): ServerConfig {\n return (cached ??= parseServerConfig({\n ...process.env,\n // Literal reads so Next inlines the build-time values.\n NEXT_PUBLIC_ECOMWEB_MODE: process.env.NEXT_PUBLIC_ECOMWEB_MODE,\n NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY:\n process.env.NEXT_PUBLIC_ECOMWEB_PUBLISHABLE_KEY,\n }));\n}\n"],"mappings":"AAAA,OAAO;AACP,SAAS,mBAAmB;AAC5B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AAEP,SAAS,WAAW,KAA8B;AAChD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE,gBACE,SAAS,KAAK,kBAAkB,KAChC,SAAS,KAAK,8BAA8B;AAAA,MAC9C,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK,cAAc,KAAK;AAAA,MAC7C,QAAQ,SAAS,KAAK,SAAS,KAAK;AAAA,MACpC,oBAAoB,SAAS,KAAK,qBAAqB;AAAA,MACvD,UAAU,WAAW,SAAS,KAAK,WAAW,CAAC;AAAA,MAC/C,gBAAgB,SAAS,KAAK,kBAAkB,KAAK;AAAA,MACrD,0BAA0B;AAAA,QACxB,SAAS,KAAK,8BAA8B;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,IACA;AAAA,MACE,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAEA,SAAS,YAAY,KAA8B;AACjD,SAAO;AAAA,IACL;AAAA,IACA;AAAA;AAAA;AAAA;AAAA,MAIE,gBACE,SAAS,KAAK,yBAAyB,KACvC,SAAS,KAAK,qCAAqC;AAAA,MACrD,yBAAyB,SAAS,KAAK,4BAA4B;AAAA,MACnE,YAAY,SAAS,KAAK,UAAU,KAAK;AAAA,MACzC,QAAQ,SAAS,KAAK,SAAS,KAAK;AAAA,MACpC,oBAAoB,SAAS,KAAK,qBAAqB;AAAA,MACvD,UAAU,WAAW,SAAS,KAAK,WAAW,CAAC;AAAA,MAC/C,gBAAgB,SAAS,KAAK,kBAAkB,KAAK;AAAA;AAAA,MAErD,0BAA0B;AAAA,IAC5B;AAAA,IACA;AAAA,MACE,gBAAgB;AAAA,MAChB,gBAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAGO,SAAS,kBAAkB,KAA8B;AAC9D,SAAO,YAAY,GAAG,MAAM,UAAU,WAAW,GAAG,IAAI,YAAY,GAAG;AACzE;AAEA,IAAI;AAEG,SAAS,4BAAkC;AAChD,WAAS;AACX;AAEO,SAAS,eAA6B;AAC3C,SAAQ,WAAW,kBAAkB;AAAA,IACnC,GAAG,QAAQ;AAAA;AAAA,IAEX,0BAA0B,QAAQ,IAAI;AAAA,IACtC,qCACE,QAAQ,IAAI;AAAA,EAChB,CAAC;AACH;","names":[]}
package/dist/config.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { E as EnvSource, P as PublicConfig } from './schema-Tc0qRs-Q.js';
2
- export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-Tc0qRs-Q.js';
3
- export { S as StorefrontMode, r as resolveMode } from './mode-YNx2aOtQ.js';
1
+ import { E as EnvSource, P as PublicConfig } from './schema-Dg0ZflMW.js';
2
+ export { C as ConfigError, L as LogLevel, S as ServerConfig } from './schema-Dg0ZflMW.js';
3
+ export { S as StorefrontMode, r as resolveMode } from './mode-Lm9t4qzX.js';
4
4
  import 'zod';
5
5
 
6
6
  /** Parses the variables of the mode `env` selects (see resolveMode). */
package/dist/index.d.ts CHANGED
@@ -5,7 +5,7 @@ import * as _ecomweb_sdk from '@ecomweb/sdk';
5
5
  import { StoreConfigurationInfo, StorePaymentMethod, OrderWithItems, PublicAuthConfig, CurrentIdentity, PasswordPolicy, OrderStatus, Order, CreateOrderRequest, LocationAreasResponse, LocationArea, StoreConfig, ThemeValues, WithMetafields, StorefrontMetafields, ResolvedMetaobjectRef, ResolvedMetaobjectStub, StorefrontMetaobjectEntry, MetaobjectListParams, MetaobjectListResult, RichTextRoot } from '@ecomweb/sdk';
6
6
  import currencyJs from 'currency.js';
7
7
  import { AxiosRequestConfig, AxiosInstance } from 'axios';
8
- export { AnyThemeDefinition, HomePageSlotProps, LayoutSlotProps, ThemeComponents, ThemeDefinition, ThemeInfo, ThemeSlot, ThemeSlotName, ThemeSlotProps, defineSchema, defineTheme } from './theme.js';
8
+ export { AnyThemeDefinition, BlogIndexSlotProps, BlogPostSlotProps, CollectionPageSlotProps, CollectionSearchParams, ContentPageSlotProps, HomePageSlotProps, LayoutSlotProps, NotFoundProps, ProductCardProps, ProductPageSlotProps, ThemeClientComponents, ThemeComponents, ThemeDefinition, ThemeInfo, ThemeSlot, ThemeSlotName, ThemeSlotProps, defineSchema, defineTheme } from './theme.js';
9
9
  import { Metadata } from 'next';
10
10
 
11
11
  type NoticeKind = "success" | "error" | "info";
@@ -73,6 +73,50 @@ interface CartItem {
73
73
  bestPromotion?: any;
74
74
  }
75
75
 
76
+ /**
77
+ * What the thank-you page shows of the order (contact, address, methods,
78
+ * lines, money), built by the storefront when it places the order. Like the
79
+ * rest of the handoff it stays in the shopper's own browser.
80
+ */
81
+ interface OrderHandoffSummary {
82
+ customer_name: string;
83
+ phone: string;
84
+ email: string | null;
85
+ /** The delivery address as one display line. */
86
+ address: string;
87
+ shipping_method: string | null;
88
+ shipping_fee: number | null;
89
+ payment_label: string;
90
+ items: {
91
+ name: string;
92
+ variant: string | null;
93
+ quantity: number;
94
+ /** Unit price. */
95
+ price: number;
96
+ image: string | null;
97
+ }[];
98
+ subtotal: number;
99
+ discount: number;
100
+ }
101
+ interface OrderHandoff {
102
+ order_code: string;
103
+ /** `cod`, `bank_transfer`, or a gateway code. */
104
+ payment_method: string;
105
+ /** Non-null only for gateway-backed methods. */
106
+ provider_code: string | null;
107
+ total: number;
108
+ currency_code: string;
109
+ /** Absent for gateway returns and older handoffs. */
110
+ summary?: OrderHandoffSummary | null;
111
+ written_at: number;
112
+ }
113
+ /**
114
+ * Returns the handoff only if it is present, well-formed, fresh, and for the
115
+ * order being shown. Any mismatch yields null: showing one order's amount on
116
+ * another order's screen would be worse than showing no amount at all.
117
+ */
118
+ declare function readOrderHandoff(order_code: string | null): OrderHandoff | null;
119
+
76
120
  /** What the shopper entered; the app owns the form and its validation. */
77
121
  interface PlaceOrderInput {
78
122
  fullName: string;
@@ -86,6 +130,11 @@ interface PlaceOrderInput {
86
130
  notes?: string;
87
131
  /** A `payment_method` code from `paymentMethods`. */
88
132
  paymentMethod: string;
133
+ /**
134
+ * What the thank-you page shows of the order; stored with the handoff in
135
+ * this browser only, never sent to the API.
136
+ */
137
+ summary?: OrderHandoffSummary;
89
138
  }
90
139
  interface PlacedOrder {
91
140
  order_code: string;
@@ -98,7 +147,10 @@ interface PlacedOrder {
98
147
  * this again instead of creating a second order.
99
148
  * - success: an offline-payment order; show its confirmation.
100
149
  * - stock_issues: nothing was placed; `issues` is copy keyed by cart line id.
101
- * - error: nothing was placed.
150
+ * - error: nothing was placed. `code` is the API's error code when it sent
151
+ * one; pass it to `errorCopy`. On ORDER_PROMOTION_NOT_APPLICABLE the applied
152
+ * code has already been removed, so the shopper sees the real total before
153
+ * placing again.
102
154
  * - busy: an earlier placeOrder is still running; this call did nothing.
103
155
  */
104
156
  type PlaceOrderResult = {
@@ -115,6 +167,7 @@ type PlaceOrderResult = {
115
167
  } | {
116
168
  kind: "error";
117
169
  message: string;
170
+ code?: string;
118
171
  } | {
119
172
  kind: "busy";
120
173
  };
@@ -178,23 +231,6 @@ declare function useCheckout({ province, ward, navigateToGateway, }: UseCheckout
178
231
  retryPaymentRedirect: () => Promise<PlaceOrderResult>;
179
232
  };
180
233
 
181
- interface OrderHandoff {
182
- order_code: string;
183
- /** `cod`, `bank_transfer`, or a gateway code. */
184
- payment_method: string;
185
- /** Non-null only for gateway-backed methods. */
186
- provider_code: string | null;
187
- total: number;
188
- currency_code: string;
189
- written_at: number;
190
- }
191
- /**
192
- * Returns the handoff only if it is present, well-formed, fresh, and for the
193
- * order being shown. Any mismatch yields null: showing one order's amount on
194
- * another order's screen would be worse than showing no amount at all.
195
- */
196
- declare function readOrderHandoff(order_code: string | null): OrderHandoff | null;
197
-
198
234
  /**
199
235
  * Which success screen an order gets.
200
236
  *
@@ -584,7 +620,7 @@ declare function pollPaymentState(options: PollPaymentStateOptions): Promise<Pol
584
620
  * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.
585
621
  *
586
622
  * `sdk.payments` was added by this plan's Task 2
587
- * (`ecomweb-sdk` branch `feat/payment-client-methods`, commit `58c2c76`),
623
+ * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),
588
624
  * but that SDK PR is not yet merged to `main`, and this repo's lockfile
589
625
  * pins an older `@ecomweb/sdk` commit that has no `payments` module at all
590
626
  * — see `lib/checkout/initiate-gateway-payment.ts` for the full story
@@ -691,7 +727,6 @@ declare const sdk: {
691
727
  themes: _ecomweb_sdk.ThemesApi;
692
728
  metaobjects: _ecomweb_sdk.MetaobjectsApi;
693
729
  search: _ecomweb_sdk.SearchApi;
694
- banners: _ecomweb_sdk.BannersApi;
695
730
  shipping: _ecomweb_sdk.ShippingApi;
696
731
  promotions: _ecomweb_sdk.PromotionsApi;
697
732
  paymentMethods: _ecomweb_sdk.PaymentMethodsApi;
@@ -722,7 +757,6 @@ declare function createStoreSdk(storeRef: string): {
722
757
  themes: _ecomweb_sdk.ThemesApi;
723
758
  metaobjects: _ecomweb_sdk.MetaobjectsApi;
724
759
  search: _ecomweb_sdk.SearchApi;
725
- banners: _ecomweb_sdk.BannersApi;
726
760
  shipping: _ecomweb_sdk.ShippingApi;
727
761
  promotions: _ecomweb_sdk.PromotionsApi;
728
762
  paymentMethods: _ecomweb_sdk.PaymentMethodsApi;
@@ -903,15 +937,24 @@ declare function resolveLegalHref(link: string | null, fallbackPath: string | nu
903
937
 
904
938
  interface ThemeSettingsContextValue {
905
939
  themeId: string;
940
+ /** The registry key of the code rendering, e.g. "meridian@1" (theme majors). */
941
+ themeKey?: string;
906
942
  settings: ThemeValues;
907
943
  }
908
944
  /** The published (or previewed) theme's resolved settings, for client components. */
909
- declare function ThemeSettingsProvider({ themeId, settings, children, }: ThemeSettingsContextValue & {
945
+ declare function ThemeSettingsProvider({ themeId, themeKey, settings, children, }: ThemeSettingsContextValue & {
910
946
  children: ReactNode;
911
947
  }): react_jsx_runtime.JSX.Element;
912
948
  /** Pass the theme's settings type: `useThemeSettings<MyThemeSettings>()`. */
913
949
  declare function useThemeSettings<T = ThemeValues>(): T;
914
950
  declare function useThemeId(): string;
951
+ /** The theme id, or null outside a ThemeSettingsProvider (e.g. a store 404). */
952
+ declare function useOptionalThemeId(): string | null;
953
+ /**
954
+ * The registry key of the theme code rendering ("meridian@1"), else its id;
955
+ * null outside a ThemeSettingsProvider. Client registries look up by it.
956
+ */
957
+ declare function useOptionalThemeKey(): string | null;
915
958
 
916
959
  /**
917
960
  * A metafield's resolved value by identifier, e.g.
@@ -968,6 +1011,23 @@ declare function ThemeStyle({ vars, }: {
968
1011
  vars: Record<string, string> | null | undefined;
969
1012
  }): react_jsx_runtime.JSX.Element | null;
970
1013
 
1014
+ /** The messages the dashboard's theme editor and its preview frame trade. */
1015
+ declare const THEME_PREVIEW_MESSAGE = "ecomweb:theme-preview";
1016
+ /** Set on <html> while the preview is inside the theme editor's frame. */
1017
+ declare const THEME_PREVIEW_FRAME_ATTR = "data-theme-preview-frame";
1018
+ /**
1019
+ * The storefront side of the theme editor's live preview. Inside the
1020
+ * editor's frame it says it is ready, then calls onRefresh each time the
1021
+ * editor has sent its unsaved values to the API, which the preview token
1022
+ * reads them back from. The app re-renders the page in place (router.refresh:
1023
+ * server components again, scroll and client state kept); routing is the
1024
+ * app's, not the kit's. Only the frame's parent is listened to; outside a
1025
+ * frame it does nothing.
1026
+ */
1027
+ declare function ThemePreviewBridge({ onRefresh }: {
1028
+ onRefresh: () => void;
1029
+ }): null;
1030
+
971
1031
  declare const getCachedStore: (storeRef: string, options?: {
972
1032
  includeConfig?: boolean;
973
1033
  includeSettings?: boolean;
@@ -1027,4 +1087,4 @@ declare function getLogLevel(): LogLevel;
1027
1087
  declare function shouldLog(currentLevel: LogLevel, messageLevel: LogLevel): boolean;
1028
1088
  declare function applyConsoleFilter(level?: LogLevel): void;
1029
1089
 
1030
- export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, createStoreSdk, deriveOrderProgress, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, pollPaymentState, publicApiClient, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
1090
+ export { type BankAccountView, DEFAULT_REDIRECT, type Notice, type NoticeHandler, type NoticeKind, ORDER_PROGRESS_STEPS, type OrderHandoff, type OrderHandoffSummary, type OrderSuccessInfo, type PaymentConfirmationState, type PlaceOrderInput, type PlaceOrderResult, type PlacedOrder, RichText, type RichTextProps, SHIPPING_MESSAGES, STATUS_OPTIONS, STOCK_ISSUE_TOAST_DESCRIPTION, SUSPENDED_STORE_METADATA, StorefrontKitProvider, type StorefrontKitProviderProps, type SupportedCurrency, THEME_PREVIEW_FRAME_ATTR, THEME_PREVIEW_MESSAGE, ThemePreviewBridge, ThemeSettingsProvider, ThemeStyle, type UseCheckoutOptions, applyConsoleFilter, buildStoreUrl, createStoreSdk, deriveOrderProgress, errorCopy, errorCopyFor, findProvinceByCodeOrName, findWardByCodeOrName, formatNumber, formatPrice, formatPriceRange, formatPriceWithoutSymbol, formatShippingAmount, formatShippingEstimate, getCachedStore, getDefaultLocale, getLogLevel, getMetaobject, getMetaobjects, getPasswordPolicyHints, getPaymentState, getPromotionDescription, isStoreSuspendedError, loadWards, metafield, metaobjectField, money, pollPaymentState, publicApiClient, readBasicSettings, readOrderHandoff, refFromPathname, resolveAssetSrc, resolveInitialState, resolveLegalHref, resolveStoreRef, resolveTransformedImageUrl, resolveTransformedProductImageUrl, resolveTransformedStoreLogoUrl, safeRedirectPath, sdk, searchTextFor, shouldLog, shouldPollForConfirmation, storeApiPath, storePath, themeStyleCss, unwrap, unwrapOrNull, useAuth, useCart, useCheckout, useNotify, useOptionalStoreId, useOptionalThemeId, useOptionalThemeKey, useOrderLookup, useOrderStatus, useProvinces, usePublicAuthConfig, useStore, useStoreCurrency, useStoreData, useStoreId, useStoreLocale, useThemeId, useThemeSettings, useWards, validatePasswordAgainstPolicy, withSuspendedStoreMetadataFallback };
package/dist/index.js CHANGED
@@ -68,6 +68,8 @@ import { readBasicSettings, resolveLegalHref } from "./stores/basic-settings.js"
68
68
  import { defineSchema, defineTheme } from "./theme/define.js";
69
69
  import {
70
70
  ThemeSettingsProvider,
71
+ useOptionalThemeId,
72
+ useOptionalThemeKey,
71
73
  useThemeId,
72
74
  useThemeSettings
73
75
  } from "./theme/settings-context.js";
@@ -75,6 +77,11 @@ import { metafield, metaobjectField } from "./metafields/readers.js";
75
77
  import { getMetaobject, getMetaobjects } from "./metafields/metaobjects.js";
76
78
  import { RichText } from "./metafields/rich-text.js";
77
79
  import { ThemeStyle, themeStyleCss } from "./theme/style.js";
80
+ import {
81
+ THEME_PREVIEW_FRAME_ATTR,
82
+ THEME_PREVIEW_MESSAGE,
83
+ ThemePreviewBridge
84
+ } from "./theme/preview-bridge.js";
78
85
  import { getCachedStore } from "./stores/cached.js";
79
86
  import {
80
87
  SUSPENDED_STORE_METADATA,
@@ -92,6 +99,9 @@ export {
92
99
  STOCK_ISSUE_TOAST_DESCRIPTION,
93
100
  SUSPENDED_STORE_METADATA,
94
101
  StorefrontKitProvider,
102
+ THEME_PREVIEW_FRAME_ATTR,
103
+ THEME_PREVIEW_MESSAGE,
104
+ ThemePreviewBridge,
95
105
  ThemeSettingsProvider,
96
106
  ThemeStyle,
97
107
  applyConsoleFilter,
@@ -150,6 +160,8 @@ export {
150
160
  useCheckout,
151
161
  useNotify,
152
162
  useOptionalStoreId,
163
+ useOptionalThemeId,
164
+ useOptionalThemeKey,
153
165
  useOrderLookup,
154
166
  useOrderStatus,
155
167
  useProvinces,