@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
package/dist/server.js ADDED
@@ -0,0 +1,19 @@
1
+ import "server-only";
2
+ import {
3
+ createAuthRoutes,
4
+ createBackendProxy,
5
+ requireSession
6
+ } from "./server/routes.js";
7
+ import { hasCustomerSession } from "./auth/session.js";
8
+ import { parseServerConfig, serverConfig } from "./config/server.js";
9
+ import { resolveRootStoreRef } from "./store-scope/root.js";
10
+ export {
11
+ createAuthRoutes,
12
+ createBackendProxy,
13
+ hasCustomerSession,
14
+ parseServerConfig,
15
+ requireSession,
16
+ resolveRootStoreRef,
17
+ serverConfig
18
+ };
19
+ //# sourceMappingURL=server.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;","names":[]}
@@ -0,0 +1,12 @@
1
+ import { formatPrice } from "../currency.js";
2
+ function isFreeShippingRate(amount) {
3
+ return amount === 0;
4
+ }
5
+ function formatShippingAmount(amount, freeLabel, locale, currency) {
6
+ return isFreeShippingRate(amount) ? freeLabel : formatPrice(amount, locale, currency);
7
+ }
8
+ export {
9
+ formatShippingAmount,
10
+ isFreeShippingRate
11
+ };
12
+ //# sourceMappingURL=format-shipping-option.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shipping/format-shipping-option.ts"],"sourcesContent":["import { formatPrice, type SupportedCurrency } from \"../currency\";\n\n/**\n * A free shipping rate is a VALUE comparison (amount === 0), not a rate\n * type the API tags for us. There is no \"FREE\" rate_type in the shipping\n * vocabulary on purpose — see @ecomweb/sdk's shipping types.\n */\nexport function isFreeShippingRate(amount: number): boolean {\n return amount === 0;\n}\n\n/**\n * Renders a shipping option's price for display: the free label when the\n * rate is free, the house money format otherwise.\n *\n * `freeLabel` is passed in (see lib/shipping/messages.ts) rather than\n * hardcoded here, so this stays a pure, generic function reachable from a\n * plain vitest spec.\n */\nexport function formatShippingAmount(\n amount: number,\n freeLabel: string,\n locale: string,\n currency: SupportedCurrency | string\n): string {\n return isFreeShippingRate(amount)\n ? freeLabel\n : formatPrice(amount, locale, currency);\n}\n"],"mappings":"AAAA,SAAS,mBAA2C;AAO7C,SAAS,mBAAmB,QAAyB;AAC1D,SAAO,WAAW;AACpB;AAUO,SAAS,qBACd,QACA,WACA,QACA,UACQ;AACR,SAAO,mBAAmB,MAAM,IAC5B,YACA,YAAY,QAAQ,QAAQ,QAAQ;AAC1C;","names":[]}
@@ -0,0 +1,104 @@
1
+ "use client";
2
+ import { useEffect, useMemo, useState } from "react";
3
+ import { LEVEL_PROVINCE } from "@ecomweb/sdk";
4
+ import { sdk } from "../sdk.js";
5
+ const defaultFetcher = (storeRef, query) => sdk.shipping.listLocationAreas(storeRef, query);
6
+ const provinceCache = /* @__PURE__ */ new Map();
7
+ const wardCache = /* @__PURE__ */ new Map();
8
+ function __resetLocationCaches() {
9
+ provinceCache.clear();
10
+ wardCache.clear();
11
+ }
12
+ function loadProvinces(storeRef, fetcher = defaultFetcher) {
13
+ let pending = provinceCache.get(storeRef);
14
+ if (!pending) {
15
+ pending = fetcher(storeRef, { level: LEVEL_PROVINCE }).then((r) => r.areas).catch((error) => {
16
+ provinceCache.delete(storeRef);
17
+ throw error;
18
+ });
19
+ provinceCache.set(storeRef, pending);
20
+ }
21
+ return pending;
22
+ }
23
+ function loadWards(storeRef, provinceCode, fetcher = defaultFetcher) {
24
+ if (!provinceCode) return Promise.resolve([]);
25
+ const key = `${storeRef}:${provinceCode}`;
26
+ let pending = wardCache.get(key);
27
+ if (!pending) {
28
+ pending = fetcher(storeRef, { parent_code: provinceCode }).then((r) => r.areas).catch((error) => {
29
+ wardCache.delete(key);
30
+ throw error;
31
+ });
32
+ wardCache.set(key, pending);
33
+ }
34
+ return pending;
35
+ }
36
+ function useProvinces(storeRef) {
37
+ const [provinces, setProvinces] = useState([]);
38
+ const [loading, setLoading] = useState(true);
39
+ useEffect(() => {
40
+ let cancelled = false;
41
+ loadProvinces(storeRef).then((areas) => {
42
+ if (!cancelled) setProvinces(areas);
43
+ }).catch((error) => {
44
+ console.error("Failed to load provinces:", error);
45
+ }).finally(() => {
46
+ if (!cancelled) setLoading(false);
47
+ });
48
+ return () => {
49
+ cancelled = true;
50
+ };
51
+ }, [storeRef]);
52
+ return { provinces, loading };
53
+ }
54
+ function useWards(storeRef, provinceCode) {
55
+ const [wards, setWards] = useState([]);
56
+ const [loading, setLoading] = useState(false);
57
+ useEffect(() => {
58
+ setWards([]);
59
+ if (!provinceCode) {
60
+ setLoading(false);
61
+ return;
62
+ }
63
+ let cancelled = false;
64
+ setLoading(true);
65
+ loadWards(storeRef, provinceCode).then((areas) => {
66
+ if (!cancelled) setWards(areas);
67
+ }).catch((error) => {
68
+ if (!cancelled) setWards([]);
69
+ console.error("Failed to load wards:", error);
70
+ }).finally(() => {
71
+ if (!cancelled) setLoading(false);
72
+ });
73
+ return () => {
74
+ cancelled = true;
75
+ };
76
+ }, [storeRef, provinceCode]);
77
+ return { wards, loading };
78
+ }
79
+ function searchTextFor(area) {
80
+ return [
81
+ area.name_with_type,
82
+ area.name,
83
+ (area.slug || "").replace(/-/g, " "),
84
+ area.code
85
+ ].filter(Boolean).join(" ");
86
+ }
87
+ function byCode(areas, code) {
88
+ if (!code) return void 0;
89
+ return areas.find((area) => area.code === code);
90
+ }
91
+ function useAreaLabel(areas, code) {
92
+ return useMemo(() => byCode(areas, code), [areas, code]);
93
+ }
94
+ export {
95
+ __resetLocationCaches,
96
+ byCode,
97
+ loadProvinces,
98
+ loadWards,
99
+ searchTextFor,
100
+ useAreaLabel,
101
+ useProvinces,
102
+ useWards
103
+ };
104
+ //# sourceMappingURL=location-areas.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shipping/location-areas.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport type { LocationArea, LocationAreasResponse } from \"@ecomweb/sdk\";\nimport { LEVEL_PROVINCE } from \"@ecomweb/sdk\";\nimport { sdk } from \"../sdk\";\n\n/**\n * Location data is fetched in two steps rather than all at once: the 34\n * provinces up front, then one province's wards when something actually\n * needs them. Fetching everything cost 751 KB and every ward in the\n * country on a page that shows at most one province's worth.\n *\n * Caches hold the in-flight promise, not just the result, so concurrent\n * callers (a checkout page mounts several) share one request. A failure\n * is evicted so it is never cached.\n */\ntype Fetcher = (\n storeRef: string,\n query: { level?: number; parent_code?: string }\n) => Promise<LocationAreasResponse>;\n\nconst defaultFetcher: Fetcher = (storeRef, query) =>\n sdk.shipping.listLocationAreas(storeRef, query);\n\nconst provinceCache = new Map<string, Promise<LocationArea[]>>();\nconst wardCache = new Map<string, Promise<LocationArea[]>>();\n\n/** Test seam. Never called by application code. */\nexport function __resetLocationCaches() {\n provinceCache.clear();\n wardCache.clear();\n}\n\nexport function loadProvinces(\n storeRef: string,\n fetcher: Fetcher = defaultFetcher\n): Promise<LocationArea[]> {\n let pending = provinceCache.get(storeRef);\n if (!pending) {\n pending = fetcher(storeRef, { level: LEVEL_PROVINCE })\n .then(r => r.areas)\n .catch(error => {\n provinceCache.delete(storeRef);\n throw error;\n });\n provinceCache.set(storeRef, pending);\n }\n return pending;\n}\n\nexport function loadWards(\n storeRef: string,\n provinceCode: string | undefined,\n fetcher: Fetcher = defaultFetcher\n): Promise<LocationArea[]> {\n if (!provinceCode) return Promise.resolve([]);\n\n const key = `${storeRef}:${provinceCode}`;\n let pending = wardCache.get(key);\n if (!pending) {\n pending = fetcher(storeRef, { parent_code: provinceCode })\n .then(r => r.areas)\n .catch(error => {\n wardCache.delete(key);\n throw error;\n });\n wardCache.set(key, pending);\n }\n return pending;\n}\n\nexport function useProvinces(storeRef: string) {\n const [provinces, setProvinces] = useState<LocationArea[]>([]);\n const [loading, setLoading] = useState(true);\n\n useEffect(() => {\n let cancelled = false;\n loadProvinces(storeRef)\n .then(areas => {\n if (!cancelled) setProvinces(areas);\n })\n .catch(error => {\n // eslint-disable-next-line no-console\n console.error(\"Failed to load provinces:\", error);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [storeRef]);\n\n return { provinces, loading };\n}\n\nexport function useWards(storeRef: string, provinceCode: string | undefined) {\n const [wards, setWards] = useState<LocationArea[]>([]);\n const [loading, setLoading] = useState(false);\n\n useEffect(() => {\n // Drop the previous province's wards up front. Keeping them until the\n // new list arrives leaves wards from the wrong province selectable,\n // and on a failed request it leaves them there for good.\n setWards([]);\n\n if (!provinceCode) {\n setLoading(false);\n return;\n }\n let cancelled = false;\n setLoading(true);\n loadWards(storeRef, provinceCode)\n .then(areas => {\n if (!cancelled) setWards(areas);\n })\n .catch(error => {\n if (!cancelled) setWards([]);\n // eslint-disable-next-line no-console\n console.error(\"Failed to load wards:\", error);\n })\n .finally(() => {\n if (!cancelled) setLoading(false);\n });\n return () => {\n cancelled = true;\n };\n }, [storeRef, provinceCode]);\n\n return { wards, loading };\n}\n\n/**\n * The string a combobox filters on. cmdk matches against a CommandItem's\n * `value`, so putting the code there alone meant a shopper had to type\n * \"12\" to find Hồ Chí Minh. This puts the names in, plus the slug with\n * its hyphens spaced out so typing without accents (\"ho chi minh\") still\n * matches. The code stays searchable for anyone who knows it.\n */\nexport function searchTextFor(area: LocationArea): string {\n return [\n area.name_with_type,\n area.name,\n (area.slug || \"\").replace(/-/g, \" \"),\n area.code,\n ]\n .filter(Boolean)\n .join(\" \");\n}\n\n/** Look up one area by code within a list, for display labels. */\nexport function byCode(areas: LocationArea[], code: string | undefined) {\n if (!code) return undefined;\n return areas.find(area => area.code === code);\n}\n\nexport function useAreaLabel(areas: LocationArea[], code: string | undefined) {\n return useMemo(() => byCode(areas, code), [areas, code]);\n}\n"],"mappings":";AAEA,SAAS,WAAW,SAAS,gBAAgB;AAE7C,SAAS,sBAAsB;AAC/B,SAAS,WAAW;AAiB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,MAAM,OAAO,OAAO,IAAI,GAAG,CAAC,OAAO,IAAI,CAAC;AACzD;","names":[]}
@@ -0,0 +1,19 @@
1
+ const SHIPPING_MESSAGES = Object.freeze({
2
+ title: "Ph\u01B0\u01A1ng th\u1EE9c v\u1EADn chuy\u1EC3n",
3
+ prompt: "Vui l\xF2ng nh\u1EADp \u0111\u1ECBa ch\u1EC9 giao h\xE0ng \u0111\u1EC3 xem ph\u01B0\u01A1ng th\u1EE9c v\u1EADn chuy\u1EC3n",
4
+ empty: "Kh\xF4ng c\xF3 ph\u01B0\u01A1ng th\u1EE9c v\u1EADn chuy\u1EC3n ph\xF9 h\u1EE3p",
5
+ emptyHint: "Vui l\xF2ng ki\u1EC3m tra l\u1EA1i \u0111\u1ECBa ch\u1EC9 giao h\xE0ng ho\u1EB7c li\xEAn h\u1EC7 v\u1EDBi c\u1EEDa h\xE0ng.",
6
+ failed: "Kh\xF4ng th\u1EC3 t\xEDnh ph\xED v\u1EADn chuy\u1EC3n",
7
+ failedHint: "K\u1EBFt n\u1ED1i c\xF3 th\u1EC3 \u0111ang gi\xE1n \u0111o\u1EA1n. Vui l\xF2ng th\u1EED l\u1EA1i.",
8
+ retry: "Th\u1EED l\u1EA1i",
9
+ free: "Mi\u1EC5n ph\xED",
10
+ estimate: "D\u1EF1 ki\u1EBFn giao: {min} \u0111\u1EBFn {max} ng\xE0y"
11
+ });
12
+ function formatShippingEstimate(min, max) {
13
+ return SHIPPING_MESSAGES.estimate.replace("{min}", String(min)).replace("{max}", String(max));
14
+ }
15
+ export {
16
+ SHIPPING_MESSAGES,
17
+ formatShippingEstimate
18
+ };
19
+ //# sourceMappingURL=messages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shipping/messages.ts"],"sourcesContent":["/**\n * Checkout shipping strings, extracted from the components that used to\n * hardcode them inline. This is NOT an i18n layer -- the storefront has no\n * i18n infrastructure (no next-intl, no locale routing, no message\n * catalog), and bootstrapping one is out of scope for a shipping-vocabulary\n * change. This just gets every shipping string into one place so a real\n * i18n task can source from here later instead of hunting through JSX.\n *\n * `estimate` is a template: interpolate `{min}` and `{max}` yourself.\n */\nexport const SHIPPING_MESSAGES = Object.freeze({\n title: \"Phương thức vận chuyển\",\n prompt: \"Vui lòng nhập địa chỉ giao hàng để xem phương thức vận chuyển\",\n empty: \"Không có phương thức vận chuyển phù hợp\",\n emptyHint:\n \"Vui lòng kiểm tra lại địa chỉ giao hàng hoặc liên hệ với cửa hàng.\",\n failed: \"Không thể tính phí vận chuyển\",\n failedHint: \"Kết nối có thể đang gián đoạn. Vui lòng thử lại.\",\n retry: \"Thử lại\",\n free: \"Miễn phí\",\n estimate: \"Dự kiến giao: {min} đến {max} ngày\",\n});\n\n/** Fills in the `{min}`/`{max}` placeholders in `SHIPPING_MESSAGES.estimate`. */\nexport function formatShippingEstimate(min: number, max: number): string {\n return SHIPPING_MESSAGES.estimate\n .replace(\"{min}\", String(min))\n .replace(\"{max}\", String(max));\n}\n"],"mappings":"AAUO,MAAM,oBAAoB,OAAO,OAAO;AAAA,EAC7C,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WACE;AAAA,EACF,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,OAAO;AAAA,EACP,MAAM;AAAA,EACN,UAAU;AACZ,CAAC;AAGM,SAAS,uBAAuB,KAAa,KAAqB;AACvE,SAAO,kBAAkB,SACtB,QAAQ,SAAS,OAAO,GAAG,CAAC,EAC5B,QAAQ,SAAS,OAAO,GAAG,CAAC;AACjC;","names":[]}
@@ -0,0 +1,75 @@
1
+ const initialShippingCalculationState = {
2
+ shippingFee: 0,
3
+ isCalculatingShipping: false,
4
+ hasCalculatedShipping: false,
5
+ shippingOptions: [],
6
+ selectedShippingRate: null,
7
+ requestId: 0,
8
+ calculationFailed: false
9
+ };
10
+ function shippingCalculationReducer(state, action) {
11
+ switch (action.type) {
12
+ case "RESET":
13
+ return {
14
+ ...initialShippingCalculationState,
15
+ requestId: state.requestId + 1
16
+ };
17
+ case "CALCULATION_STARTED":
18
+ return {
19
+ ...state,
20
+ isCalculatingShipping: true,
21
+ calculationFailed: false,
22
+ requestId: state.requestId + 1
23
+ };
24
+ case "CALCULATION_SUCCEEDED": {
25
+ if (action.requestId !== state.requestId) return state;
26
+ const { options } = action;
27
+ const first = options.length > 0 ? options[0] : null;
28
+ return {
29
+ ...state,
30
+ shippingOptions: options,
31
+ hasCalculatedShipping: true,
32
+ isCalculatingShipping: false,
33
+ // Auto-select the first option. This also revalidates the
34
+ // selection on every successful recalculation: it is always
35
+ // replaced with a rate_id guaranteed to belong to THIS response,
36
+ // so a stale rate from an earlier quote can never linger.
37
+ selectedShippingRate: first ? first.rate_id : null,
38
+ shippingFee: first ? first.amount : 0,
39
+ calculationFailed: false
40
+ };
41
+ }
42
+ case "CALCULATION_FAILED":
43
+ if (action.requestId !== state.requestId) return state;
44
+ return {
45
+ ...state,
46
+ shippingFee: 0,
47
+ shippingOptions: [],
48
+ selectedShippingRate: null,
49
+ hasCalculatedShipping: false,
50
+ isCalculatingShipping: false,
51
+ calculationFailed: true
52
+ };
53
+ case "RATE_SELECTED": {
54
+ const option = state.shippingOptions.find(
55
+ (opt) => opt.rate_id === action.rateId
56
+ );
57
+ return {
58
+ ...state,
59
+ selectedShippingRate: action.rateId,
60
+ // Preserves the previous fee if the id doesn't match a known
61
+ // option -- shouldn't happen in practice (the UI only ever
62
+ // dispatches a rate_id it just rendered from shippingOptions),
63
+ // kept explicit rather than silently coercing the fee to 0.
64
+ shippingFee: option ? option.amount : state.shippingFee
65
+ };
66
+ }
67
+ default:
68
+ return state;
69
+ }
70
+ }
71
+ export {
72
+ initialShippingCalculationState,
73
+ shippingCalculationReducer
74
+ };
75
+ //# sourceMappingURL=shipping-calculation-reducer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n selectedShippingRate: number | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | { type: \"CALCULATION_SUCCEEDED\"; options: ShippingOption[]; requestId: number }\n | { type: \"CALCULATION_FAILED\"; requestId: number }\n /** The shopper picked a specific option out of the current quote. */\n | { type: \"RATE_SELECTED\"; rateId: number };\n\nexport function shippingCalculationReducer(\n state: ShippingCalculationState,\n action: ShippingCalculationAction\n): ShippingCalculationState {\n switch (action.type) {\n case \"RESET\":\n // Keep counting up: a response from before the reset must still be\n // recognisable as stale.\n return {\n ...initialShippingCalculationState,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_STARTED\":\n return {\n ...state,\n isCalculatingShipping: true,\n calculationFailed: false,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_SUCCEEDED\": {\n if (action.requestId !== state.requestId) return state;\n const { options } = action;\n const first = options.length > 0 ? options[0] : null;\n return {\n ...state,\n shippingOptions: options,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n // Auto-select the first option. This also revalidates the\n // selection on every successful recalculation: it is always\n // replaced with a rate_id guaranteed to belong to THIS response,\n // so a stale rate from an earlier quote can never linger.\n selectedShippingRate: first ? first.rate_id : null,\n shippingFee: first ? first.amount : 0,\n calculationFailed: false,\n };\n }\n\n case \"CALCULATION_FAILED\":\n if (action.requestId !== state.requestId) return state;\n return {\n ...state,\n shippingFee: 0,\n shippingOptions: [],\n selectedShippingRate: null,\n hasCalculatedShipping: false,\n isCalculatingShipping: false,\n calculationFailed: true,\n };\n\n case \"RATE_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => opt.rate_id === action.rateId\n );\n return {\n ...state,\n selectedShippingRate: action.rateId,\n // Preserves the previous fee if the id doesn't match a known\n // option -- shouldn't happen in practice (the UI only ever\n // dispatches a rate_id it just rendered from shippingOptions),\n // kept explicit rather than silently coercing the fee to 0.\n shippingFee: option ? option.amount : state.shippingFee,\n };\n }\n\n default:\n return state;\n }\n}\n"],"mappings":"AA+BO,MAAM,kCAA4D;AAAA,EACvE,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,iBAAiB,CAAC;AAAA,EAClB,sBAAsB;AAAA,EACtB,WAAW;AAAA,EACX,mBAAmB;AACrB;AAkBO,SAAS,2BACd,OACA,QAC0B;AAC1B,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AAGH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,QACnB,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK,yBAAyB;AAC5B,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,YAAM,EAAE,QAAQ,IAAI;AACpB,YAAM,QAAQ,QAAQ,SAAS,IAAI,QAAQ,CAAC,IAAI;AAChD,aAAO;AAAA,QACL,GAAG;AAAA,QACH,iBAAiB;AAAA,QACjB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA,QAKvB,sBAAsB,QAAQ,MAAM,UAAU;AAAA,QAC9C,aAAa,QAAQ,MAAM,SAAS;AAAA,QACpC,mBAAmB;AAAA,MACrB;AAAA,IACF;AAAA,IAEA,KAAK;AACH,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,aAAO;AAAA,QACL,GAAG;AAAA,QACH,aAAa;AAAA,QACb,iBAAiB,CAAC;AAAA,QAClB,sBAAsB;AAAA,QACtB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,MACrB;AAAA,IAEF,KAAK,iBAAiB;AACpB,YAAM,SAAS,MAAM,gBAAgB;AAAA,QACnC,SAAO,IAAI,YAAY,OAAO;AAAA,MAChC;AACA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,sBAAsB,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA,QAK7B,aAAa,SAAS,OAAO,SAAS,MAAM;AAAA,MAC9C;AAAA,IACF;AAAA,IAEA;AACE,aAAO;AAAA,EACX;AACF;","names":[]}
@@ -0,0 +1,84 @@
1
+ import { sdk } from "../sdk.js";
2
+ import { useReducer, useEffect, useCallback, useRef } from "react";
3
+ import { SHIPPING_MESSAGES } from "./messages.js";
4
+ import { useNotify } from "../notices.js";
5
+ import {
6
+ shippingCalculationReducer,
7
+ initialShippingCalculationState
8
+ } from "./shipping-calculation-reducer.js";
9
+ function useShippingCalculation({
10
+ storeRef,
11
+ city,
12
+ ward,
13
+ subtotal,
14
+ totalWeight,
15
+ itemsCount
16
+ }) {
17
+ const [state, dispatch] = useReducer(
18
+ shippingCalculationReducer,
19
+ initialShippingCalculationState
20
+ );
21
+ const notify = useNotify();
22
+ const stateRef = useRef(state);
23
+ stateRef.current = state;
24
+ useEffect(() => {
25
+ dispatch({ type: "RESET" });
26
+ }, [city, ward, subtotal, totalWeight]);
27
+ const calculateShippingFee = useCallback(async () => {
28
+ if (!city || !ward || itemsCount === 0) {
29
+ dispatch({ type: "RESET" });
30
+ return;
31
+ }
32
+ const next = stateRef.current.requestId + 1;
33
+ dispatch({ type: "CALCULATION_STARTED" });
34
+ try {
35
+ const options = await sdk.shipping.calculate(storeRef, {
36
+ province_id: city,
37
+ ward_id: ward,
38
+ subtotal,
39
+ currency: "VND",
40
+ weight_gr: totalWeight
41
+ });
42
+ dispatch({ type: "CALCULATION_SUCCEEDED", options, requestId: next });
43
+ } catch (error) {
44
+ if (next !== stateRef.current.requestId) return;
45
+ console.error("Failed to calculate shipping fee:", error);
46
+ dispatch({ type: "CALCULATION_FAILED", requestId: next });
47
+ notify({
48
+ kind: "error",
49
+ code: "shipping.quote_failed",
50
+ title: SHIPPING_MESSAGES.failed,
51
+ description: SHIPPING_MESSAGES.failedHint
52
+ });
53
+ }
54
+ }, [city, ward, itemsCount, storeRef, subtotal, totalWeight, notify]);
55
+ useEffect(() => {
56
+ const timeoutId = setTimeout(() => {
57
+ calculateShippingFee();
58
+ }, 500);
59
+ return () => clearTimeout(timeoutId);
60
+ }, [calculateShippingFee]);
61
+ const handleShippingRateSelect = useCallback((rateId) => {
62
+ dispatch({ type: "RATE_SELECTED", rateId });
63
+ }, []);
64
+ return {
65
+ shippingFee: state.shippingFee,
66
+ isCalculatingShipping: state.isCalculatingShipping,
67
+ hasCalculatedShipping: state.hasCalculatedShipping,
68
+ shippingOptions: state.shippingOptions,
69
+ selectedShippingRate: state.selectedShippingRate,
70
+ calculationFailed: state.calculationFailed,
71
+ handleShippingRateSelect,
72
+ /**
73
+ * Re-run the quote with the inputs unchanged. The debounced effect only
74
+ * fires when an input dependency changes, so after a transient failure
75
+ * there was otherwise no way back: the shopper had to edit the address
76
+ * or reload the page.
77
+ */
78
+ retryCalculation: calculateShippingFee
79
+ };
80
+ }
81
+ export {
82
+ useShippingCalculation
83
+ };
84
+ //# sourceMappingURL=use-shipping-calculation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef } from \"react\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [city, ward, itemsCount, storeRef, subtotal, totalWeight, notify]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,cAAc;AAC3D,SA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,WAAW,MAAM;AACjC,2BAAqB;AAAA,IACvB,GAAG,GAAG;AAEN,WAAO,MAAM,aAAa,SAAS;AAAA,EACrC,GAAG,CAAC,oBAAoB,CAAC;AAGzB,QAAM,2BAA2B,YAAY,CAAC,WAAmB;AAC/D,aAAS,EAAE,MAAM,iBAAiB,OAAO,CAAC;AAAA,EAC5C,GAAG,CAAC,CAAC;AAEL,SAAO;AAAA,IACL,aAAa,MAAM;AAAA,IACnB,uBAAuB,MAAM;AAAA,IAC7B,uBAAuB,MAAM;AAAA,IAC7B,iBAAiB,MAAM;AAAA,IACvB,sBAAsB,MAAM;AAAA,IAC5B,mBAAmB,MAAM;AAAA,IACzB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
@@ -0,0 +1,18 @@
1
+ function findProvinceByCodeOrName(identifier, provinces) {
2
+ if (!identifier) return void 0;
3
+ return provinces.find(
4
+ (province) => province.code === identifier || province.name === identifier || province.name_with_type === identifier
5
+ );
6
+ }
7
+ function findWardByCodeOrName(identifier, wards, provinceCode) {
8
+ if (!identifier) return void 0;
9
+ const filteredWards = provinceCode ? wards.filter((ward) => ward.parent_code === provinceCode) : wards;
10
+ return filteredWards.find(
11
+ (ward) => ward.code === identifier || ward.name === identifier || ward.name_with_type === identifier || ward.path?.includes(identifier) || ward.path_with_type?.includes(identifier)
12
+ );
13
+ }
14
+ export {
15
+ findProvinceByCodeOrName,
16
+ findWardByCodeOrName
17
+ };
18
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/shipping/utils.ts"],"sourcesContent":["import type { LocationArea } from \"@ecomweb/sdk\";\n\n/**\n * Find an area by code or name, for values stored before codes were used\n * consistently. The old `id` match arm is gone with the field itself: it\n * was the source JSON object's own key, never a stable identifier.\n * @param identifier - Area code, name, or name_with_type\n * @param provinces - Areas to search\n * @returns The area if found, undefined otherwise\n */\nexport function findProvinceByCodeOrName(\n identifier: string | undefined,\n provinces: LocationArea[]\n): LocationArea | undefined {\n if (!identifier) return undefined;\n return provinces.find(\n province =>\n province.code === identifier ||\n province.name === identifier ||\n province.name_with_type === identifier\n );\n}\n\n/**\n * Find a ward by code or name, optionally restricted to one province.\n * @param identifier - Area code, name, name_with_type, or a path fragment\n * @param wards - Areas to search\n * @param provinceCode - Optional province code to filter wards\n * @returns The area if found, undefined otherwise\n */\nexport function findWardByCodeOrName(\n identifier: string | undefined,\n wards: LocationArea[],\n provinceCode?: string\n): LocationArea | undefined {\n if (!identifier) return undefined;\n // Filter wards by province first if provinceCode is provided\n const filteredWards = provinceCode\n ? wards.filter(ward => ward.parent_code === provinceCode)\n : wards;\n\n return filteredWards.find(\n ward =>\n ward.code === identifier ||\n ward.name === identifier ||\n ward.name_with_type === identifier ||\n ward.path?.includes(identifier) ||\n ward.path_with_type?.includes(identifier)\n );\n}\n"],"mappings":"AAUO,SAAS,yBACd,YACA,WAC0B;AAC1B,MAAI,CAAC,WAAY,QAAO;AACxB,SAAO,UAAU;AAAA,IACf,cACE,SAAS,SAAS,cAClB,SAAS,SAAS,cAClB,SAAS,mBAAmB;AAAA,EAChC;AACF;AASO,SAAS,qBACd,YACA,OACA,cAC0B;AAC1B,MAAI,CAAC,WAAY,QAAO;AAExB,QAAM,gBAAgB,eAClB,MAAM,OAAO,UAAQ,KAAK,gBAAgB,YAAY,IACtD;AAEJ,SAAO,cAAc;AAAA,IACnB,UACE,KAAK,SAAS,cACd,KAAK,SAAS,cACd,KAAK,mBAAmB,cACxB,KAAK,MAAM,SAAS,UAAU,KAC9B,KAAK,gBAAgB,SAAS,UAAU;AAAA,EAC5C;AACF;","names":[]}
@@ -0,0 +1,116 @@
1
+ const OBJECT_PREFIX = "/storage/v1/object/public/";
2
+ import { publicConfig } from "./config.js";
3
+ const RENDER_PREFIX = "/storage/v1/render/image/public/";
4
+ const DEFAULT_BUCKET = "public-cdn";
5
+ function assetBaseUrl() {
6
+ return publicConfig().assetBaseUrl;
7
+ }
8
+ function transformationsEnabled() {
9
+ const flag = publicConfig().imageTransformationsFlag;
10
+ if (typeof flag === "string" && flag !== "") {
11
+ return ["1", "true", "yes", "on"].includes(flag.toLowerCase());
12
+ }
13
+ return !/localhost|127\.0\.0\.1/.test(assetBaseUrl());
14
+ }
15
+ function buildTransformQuery(opts) {
16
+ if (!opts) return "";
17
+ const params = new URLSearchParams();
18
+ if (opts.width && Number.isFinite(opts.width))
19
+ params.set("width", String(opts.width));
20
+ if (opts.height && Number.isFinite(opts.height))
21
+ params.set("height", String(opts.height));
22
+ if (opts.resize) params.set("resize", opts.resize);
23
+ if (opts.quality && Number.isFinite(opts.quality))
24
+ params.set("quality", String(opts.quality));
25
+ if (opts.format) params.set("format", opts.format);
26
+ const qs = params.toString();
27
+ return qs ? `?${qs}` : "";
28
+ }
29
+ function parseStorageUrl(url) {
30
+ try {
31
+ const { pathname } = new URL(url);
32
+ const prefix = [OBJECT_PREFIX, RENDER_PREFIX].find(
33
+ (p) => pathname.includes(p)
34
+ );
35
+ if (!prefix) return null;
36
+ const parts = pathname.split(prefix)[1].split("/");
37
+ const bucket = parts.shift();
38
+ if (!bucket || parts.length === 0) return null;
39
+ return { bucket, path: parts.join("/") };
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+ function buildAssetUrl(bucket, path, opts) {
45
+ const base = assetBaseUrl();
46
+ if (!base) {
47
+ if (process.env.NODE_ENV !== "production") {
48
+ console.warn(
49
+ "[storage] NEXT_PUBLIC_ASSET_BASE_URL is not set \u2014 image URLs cannot be resolved."
50
+ );
51
+ }
52
+ return null;
53
+ }
54
+ const normalizedPath = path.replace(/^\//, "");
55
+ if (transformationsEnabled()) {
56
+ const query = buildTransformQuery({ resize: "cover", quality: 80, ...opts });
57
+ return `${base}${RENDER_PREFIX}${bucket}/${normalizedPath}${query}`;
58
+ }
59
+ return `${base}${OBJECT_PREFIX}${bucket}/${normalizedPath}`;
60
+ }
61
+ function resolveTransformedImageUrl(imagePathOrUrl, opts, defaultBucket = DEFAULT_BUCKET) {
62
+ if (!imagePathOrUrl) return null;
63
+ if (/^https?:\/\//i.test(imagePathOrUrl)) {
64
+ const parsed = parseStorageUrl(imagePathOrUrl);
65
+ if (!parsed) return imagePathOrUrl;
66
+ return buildAssetUrl(parsed.bucket, parsed.path, opts) ?? imagePathOrUrl;
67
+ }
68
+ if (imagePathOrUrl.startsWith("/")) {
69
+ return imagePathOrUrl;
70
+ }
71
+ return buildAssetUrl(defaultBucket, imagePathOrUrl, opts);
72
+ }
73
+ function resolveObjectUrl(imagePath) {
74
+ if (!imagePath) return null;
75
+ if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
76
+ const parsed = parseStorageUrl(imagePath);
77
+ if (!parsed) return imagePath;
78
+ const base2 = assetBaseUrl();
79
+ return base2 ? `${base2}${OBJECT_PREFIX}${parsed.bucket}/${parsed.path}` : imagePath;
80
+ }
81
+ if (imagePath.startsWith("/")) return imagePath;
82
+ const base = assetBaseUrl();
83
+ return base ? `${base}${OBJECT_PREFIX}${DEFAULT_BUCKET}/${imagePath}` : null;
84
+ }
85
+ function resolvePublicUrl(imagePath) {
86
+ return resolveObjectUrl(imagePath);
87
+ }
88
+ function resolveStoreLogoUrl(logoPath) {
89
+ return resolveObjectUrl(logoPath);
90
+ }
91
+ function resolveBlogUrl(imagePath) {
92
+ return resolveObjectUrl(imagePath);
93
+ }
94
+ function resolveTransformedProductImageUrl(imagePathOrUrl, opts) {
95
+ return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);
96
+ }
97
+ function resolveTransformedStoreLogoUrl(imagePathOrUrl, opts) {
98
+ return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);
99
+ }
100
+ function resolveTransformedBlogUrl(imagePathOrUrl, opts) {
101
+ return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);
102
+ }
103
+ function resolveAssetSrc(url, opts) {
104
+ return resolveTransformedImageUrl(url, opts) ?? "";
105
+ }
106
+ export {
107
+ resolveAssetSrc,
108
+ resolveBlogUrl,
109
+ resolvePublicUrl,
110
+ resolveStoreLogoUrl,
111
+ resolveTransformedBlogUrl,
112
+ resolveTransformedImageUrl,
113
+ resolveTransformedProductImageUrl,
114
+ resolveTransformedStoreLogoUrl
115
+ };
116
+ //# sourceMappingURL=storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["// ---------------------------------------------\n// Image URL helpers\n// ---------------------------------------------\n//\n// The storefront does not talk to a storage SDK. Object URLs are plain strings,\n// so there was nothing here a client library was needed for: getPublicUrl()\n// only ever concatenated base + bucket + path.\n//\n// Everything is built against NEXT_PUBLIC_ASSET_BASE_URL, which points at our\n// own API (e.g. https://apibase.ecomweb.app). The path shapes below are the\n// ones the API serves and the ones already stored in the database.\n//\n// Crucially, a stored URL's ORIGIN is ignored and rebuilt. Rows written before\n// the storage migration carry whatever host was configured at the time —\n// locally that is Kong on :8000, or an older Supabase on :54321 — and those\n// hosts no longer serve anything. Rebuilding is what lets old and new rows\n// resolve identically with no database backfill.\n//\n// The browser-side upload/delete helpers that used to live here wrote directly\n// to supabase/storage-api, which has been retired. They had no callers and were\n// removed; uploads go through the API's asset endpoints.\n\nconst OBJECT_PREFIX = \"/storage/v1/object/public/\";\nimport { publicConfig } from \"./config\";\nconst RENDER_PREFIX = \"/storage/v1/render/image/public/\";\n\nconst DEFAULT_BUCKET = \"public-cdn\";\n\ntype ResizeMode = \"cover\" | \"contain\" | \"inside\" | \"outside\";\ntype ImageFormat = \"origin\" | \"avif\" | \"webp\" | \"png\" | \"jpeg\";\n\nexport interface ImageTransformOptions {\n width?: number;\n height?: number;\n resize?: ResizeMode; // default: cover\n quality?: number; // 1..100, default: 80\n format?: ImageFormat; // default: origin\n}\n\nfunction assetBaseUrl(): string {\n return publicConfig().assetBaseUrl;\n}\n\nfunction transformationsEnabled(): boolean {\n const flag = publicConfig().imageTransformationsFlag;\n if (typeof flag === \"string\" && flag !== \"\") {\n return [\"1\", \"true\", \"yes\", \"on\"].includes(flag.toLowerCase());\n }\n // Local stacks may not run the image renderer, so serve originals.\n return !/localhost|127\\.0\\.0\\.1/.test(assetBaseUrl());\n}\n\nfunction buildTransformQuery(opts?: ImageTransformOptions): string {\n if (!opts) return \"\";\n const params = new URLSearchParams();\n if (opts.width && Number.isFinite(opts.width))\n params.set(\"width\", String(opts.width));\n if (opts.height && Number.isFinite(opts.height))\n params.set(\"height\", String(opts.height));\n if (opts.resize) params.set(\"resize\", opts.resize);\n if (opts.quality && Number.isFinite(opts.quality))\n params.set(\"quality\", String(opts.quality));\n if (opts.format) params.set(\"format\", opts.format);\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n}\n\n/**\n * Pull bucket + object path out of a storage URL, whatever host it names.\n * Accepts both the object and render path shapes.\n */\nfunction parseStorageUrl(\n url: string\n): { bucket: string; path: string } | null {\n try {\n const { pathname } = new URL(url);\n const prefix = [OBJECT_PREFIX, RENDER_PREFIX].find((p) =>\n pathname.includes(p)\n );\n if (!prefix) return null;\n\n const parts = pathname.split(prefix)[1].split(\"/\");\n const bucket = parts.shift();\n if (!bucket || parts.length === 0) return null;\n\n return { bucket, path: parts.join(\"/\") };\n } catch {\n return null;\n }\n}\n\nfunction buildAssetUrl(\n bucket: string,\n path: string,\n opts?: ImageTransformOptions\n): string | null {\n const base = assetBaseUrl();\n if (!base) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[storage] NEXT_PUBLIC_ASSET_BASE_URL is not set — image URLs cannot be resolved.\"\n );\n }\n return null;\n }\n\n const normalizedPath = path.replace(/^\\//, \"\");\n\n if (transformationsEnabled()) {\n const query = buildTransformQuery({ resize: \"cover\", quality: 80, ...opts });\n return `${base}${RENDER_PREFIX}${bucket}/${normalizedPath}${query}`;\n }\n\n return `${base}${OBJECT_PREFIX}${bucket}/${normalizedPath}`;\n}\n\n/**\n * Resolve any image reference (full URL or bare storage object path) into a\n * URL, applying transformation params when enabled.\n *\n * - A full http(s) URL that is not a storage URL is returned as-is.\n * - A storage URL is rebuilt against the configured base, ignoring its host.\n * - A bare object path is resolved within `defaultBucket`.\n */\nexport function resolveTransformedImageUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions,\n defaultBucket: \"public-cdn\" = DEFAULT_BUCKET\n): string | null {\n if (!imagePathOrUrl) return null;\n\n if (/^https?:\\/\\//i.test(imagePathOrUrl)) {\n const parsed = parseStorageUrl(imagePathOrUrl);\n if (!parsed) return imagePathOrUrl;\n return buildAssetUrl(parsed.bucket, parsed.path, opts) ?? imagePathOrUrl;\n }\n\n // Starts with / -> a local app asset, not storage. Leave untouched.\n if (imagePathOrUrl.startsWith(\"/\")) {\n return imagePathOrUrl;\n }\n\n return buildAssetUrl(defaultBucket, imagePathOrUrl, opts);\n}\n\n/** Object URL without any transformation. */\nfunction resolveObjectUrl(\n imagePath: string | null | undefined\n): string | null {\n if (!imagePath) return null;\n\n if (imagePath.startsWith(\"http://\") || imagePath.startsWith(\"https://\")) {\n const parsed = parseStorageUrl(imagePath);\n if (!parsed) return imagePath;\n const base = assetBaseUrl();\n return base\n ? `${base}${OBJECT_PREFIX}${parsed.bucket}/${parsed.path}`\n : imagePath;\n }\n\n if (imagePath.startsWith(\"/\")) return imagePath;\n\n const base = assetBaseUrl();\n return base ? `${base}${OBJECT_PREFIX}${DEFAULT_BUCKET}/${imagePath}` : null;\n}\n\nexport function resolvePublicUrl(\n imagePath: string | null | undefined\n): string | null {\n return resolveObjectUrl(imagePath);\n}\n\nexport function resolveStoreLogoUrl(\n logoPath: string | null | undefined\n): string | null {\n return resolveObjectUrl(logoPath);\n}\n\nexport function resolveBlogUrl(\n imagePath: string | null | undefined\n): string | null {\n return resolveObjectUrl(imagePath);\n}\n\n// Convenience wrappers with sensible defaults per bucket\nexport function resolveTransformedProductImageUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\nexport function resolveTransformedStoreLogoUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\nexport function resolveTransformedBlogUrl(\n imagePathOrUrl: string | null | undefined,\n opts?: ImageTransformOptions\n): string | null {\n return resolveTransformedImageUrl(imagePathOrUrl, opts, DEFAULT_BUCKET);\n}\n\n/**\n * Null-safe wrapper for use directly in `src={...}`.\n *\n * Rebuilds against the current NEXT_PUBLIC_ASSET_BASE_URL regardless of the\n * stored host, and passes non-storage URLs through untouched.\n */\nexport function resolveAssetSrc(\n url: string | null | undefined,\n opts?: ImageTransformOptions\n): string {\n return resolveTransformedImageUrl(url, opts) ?? \"\";\n}\n"],"mappings":"AAsBA,MAAM,gBAAgB;AACtB,SAAS,oBAAoB;AAC7B,MAAM,gBAAgB;AAEtB,MAAM,iBAAiB;AAavB,SAAS,eAAuB;AAC9B,SAAO,aAAa,EAAE;AACxB;AAEA,SAAS,yBAAkC;AACzC,QAAM,OAAO,aAAa,EAAE;AAC5B,MAAI,OAAO,SAAS,YAAY,SAAS,IAAI;AAC3C,WAAO,CAAC,KAAK,QAAQ,OAAO,IAAI,EAAE,SAAS,KAAK,YAAY,CAAC;AAAA,EAC/D;AAEA,SAAO,CAAC,yBAAyB,KAAK,aAAa,CAAC;AACtD;AAEA,SAAS,oBAAoB,MAAsC;AACjE,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,SAAS,IAAI,gBAAgB;AACnC,MAAI,KAAK,SAAS,OAAO,SAAS,KAAK,KAAK;AAC1C,WAAO,IAAI,SAAS,OAAO,KAAK,KAAK,CAAC;AACxC,MAAI,KAAK,UAAU,OAAO,SAAS,KAAK,MAAM;AAC5C,WAAO,IAAI,UAAU,OAAO,KAAK,MAAM,CAAC;AAC1C,MAAI,KAAK,OAAQ,QAAO,IAAI,UAAU,KAAK,MAAM;AAC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"use client";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { createContext, useContext } from "react";
4
+ import {
5
+ getDefaultLocale,
6
+ isSupportedCurrency
7
+ } from "../currency.js";
8
+ const StoreContext = createContext(void 0);
9
+ function StoreProvider({ children, store }) {
10
+ const value = {
11
+ store
12
+ };
13
+ return /* @__PURE__ */ jsx(StoreContext.Provider, { value, children });
14
+ }
15
+ function useStore() {
16
+ const context = useContext(StoreContext);
17
+ if (!context) {
18
+ throw new Error("useStore must be used within a StoreProvider");
19
+ }
20
+ return context;
21
+ }
22
+ function useStoreData() {
23
+ const { store } = useStore();
24
+ return store;
25
+ }
26
+ function useOptionalStoreId() {
27
+ return useContext(StoreContext)?.store.ref ?? null;
28
+ }
29
+ function useStoreId() {
30
+ const { store } = useStore();
31
+ return store.ref;
32
+ }
33
+ function useStoreSettings() {
34
+ const { store } = useStore();
35
+ return store.settings;
36
+ }
37
+ function useStoreConfig() {
38
+ const { store } = useStore();
39
+ return store.config;
40
+ }
41
+ function useBlogSettings() {
42
+ const { store } = useStore();
43
+ return {
44
+ blogEnabled: store.settings?.is_blog_enabled ?? false,
45
+ blogTitle: store.settings?.blog_title ?? "Blog"
46
+ };
47
+ }
48
+ function useStoreCurrency() {
49
+ const { store } = useStore();
50
+ const currencyCode = store.settings?.currency_code;
51
+ if (!currencyCode || !isSupportedCurrency(currencyCode)) {
52
+ return "VND";
53
+ }
54
+ return currencyCode;
55
+ }
56
+ function useStoreLocale() {
57
+ const currency = useStoreCurrency();
58
+ return getDefaultLocale(currency);
59
+ }
60
+ export {
61
+ StoreProvider,
62
+ useBlogSettings,
63
+ useOptionalStoreId,
64
+ useStore,
65
+ useStoreConfig,
66
+ useStoreCurrency,
67
+ useStoreData,
68
+ useStoreId,
69
+ useStoreLocale,
70
+ useStoreSettings
71
+ };
72
+ //# sourceMappingURL=store-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/store/store-context.tsx"],"sourcesContent":["\"use client\";\n\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { createContext, useContext, ReactNode } from \"react\";\n\nimport {\n SupportedCurrency,\n getDefaultLocale,\n isSupportedCurrency,\n} from \"../currency\";\n\ninterface StoreContextData {\n store: StoreConfigurationInfo;\n}\n\ninterface StoreProviderProps {\n children: ReactNode;\n store: StoreConfigurationInfo;\n}\n\nconst StoreContext = createContext<StoreContextData | undefined>(undefined);\n\nexport function StoreProvider({ children, store }: StoreProviderProps) {\n const value: StoreContextData = {\n store,\n };\n\n return (\n <StoreContext.Provider value={value}>{children}</StoreContext.Provider>\n );\n}\n\nexport function useStore() {\n const context = useContext(StoreContext);\n if (!context) {\n throw new Error(\"useStore must be used within a StoreProvider\");\n }\n return context;\n}\n\n// Export specific hooks for convenience\nexport function useStoreData() {\n const { store } = useStore();\n return store;\n}\n\n/** The store ref, or null outside a StoreProvider (e.g. a store-level 404). */\nexport function useOptionalStoreId(): string | null {\n return useContext(StoreContext)?.store.ref ?? null;\n}\n\nexport function useStoreId() {\n const { store } = useStore();\n return store.ref;\n}\n\nexport function useStoreSettings() {\n const { store } = useStore();\n return store.settings;\n}\n\nexport function useStoreConfig() {\n const { store } = useStore();\n return store.config;\n}\n\nexport function useBlogSettings() {\n const { store } = useStore();\n\n // Blog settings are now in settings, not theme_config\n return {\n blogEnabled: store.settings?.is_blog_enabled ?? false,\n blogTitle: store.settings?.blog_title ?? \"Blog\",\n };\n}\n\nexport function useStoreCurrency(): SupportedCurrency {\n const { store } = useStore();\n const currencyCode = store.settings?.currency_code;\n\n // Default to VND for anything we cannot price in.\n if (!currencyCode || !isSupportedCurrency(currencyCode)) {\n return \"VND\";\n }\n\n return currencyCode;\n}\n\nexport function useStoreLocale(): string {\n const currency = useStoreCurrency();\n return getDefaultLocale(currency);\n}\n"],"mappings":";AA4BI;AAzBJ,SAAS,eAAe,kBAA6B;AAErD;AAAA,EAEE;AAAA,EACA;AAAA,OACK;AAWP,MAAM,eAAe,cAA4C,MAAS;AAEnE,SAAS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