@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
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type { OrderHandoff } from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport { formatShippingAmount } from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,uBAAuB;AAChC,SAAS,QAAQ,oBAAoB;AACrC,SAAS,eAAe;AACxB,SAAS,WAAW,oBAAoB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB,wBAAwB;AACnD,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAEjC,SAAS,wBAAwB;AACjC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;AAC/B,SAAS,+BAA+B;AACxC,SAAS,gBAAgB,WAAW;AACpC,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,mBAAmB,8BAA8B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB,cAAc,iBAAiB;AACzD,SAAS,qBAAqB;AAC9B,SAAS,mBAAmB,wBAAwB;AACpD,SAAS,cAAc,mBAAmB;AAY1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,WAAW,uBAAuB;AAC3C,SAAS,eAAe,sBAAsB;AAC9C,SAAS,gBAAgB;AAEzB,SAAS,YAAY,qBAAqB;AAC1C,SAAS,sBAAsB;AAC/B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,6BAA6B;AACtC,SAAS,oBAAoB,aAAa,iBAAiB;","names":[]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// @ecomweb/storefront-kit: client-safe hooks, providers and helpers.\nexport { StorefrontKitProvider } from \"./provider\";\nexport type { StorefrontKitProviderProps } from \"./provider\";\nexport { useNotify } from \"./notices\";\nexport { useCheckout } from \"./checkout/use-checkout\";\nexport { useOrderLookup, useOrderStatus } from \"./orders/use-order-status\";\nexport type { BankAccountView } from \"./orders/use-order-status\";\nexport type {\n PlacedOrder,\n PlaceOrderInput,\n PlaceOrderResult,\n UseCheckoutOptions,\n} from \"./checkout/use-checkout\";\nexport type { Notice, NoticeHandler, NoticeKind } from \"./notices\";\nexport {\n useOptionalStoreId,\n useStore,\n useStoreCurrency,\n useStoreData,\n useStoreId,\n useStoreLocale,\n} from \"./store/store-context\";\nexport { usePublicAuthConfig } from \"./auth/use-public-auth-config\";\nexport { publicApiClient } from \"./api/client\";\nexport { unwrap, unwrapOrNull } from \"./api/response\";\nexport { useAuth } from \"./auth/context\";\nexport { errorCopy, errorCopyFor } from \"./auth/error-copy\";\nexport {\n getPasswordPolicyHints,\n validatePasswordAgainstPolicy,\n} from \"./auth/password-policy\";\nexport { DEFAULT_REDIRECT, safeRedirectPath } from \"./auth/safe-redirect\";\nexport { useCart } from \"./cart/server-context\";\nexport { getPaymentState } from \"./checkout/get-payment-state\";\nexport { readOrderHandoff } from \"./checkout/order-handoff\";\nexport type {\n OrderHandoff,\n OrderHandoffSummary,\n} from \"./checkout/order-handoff\";\nexport { pollPaymentState } from \"./checkout/payment-state-poll\";\nexport { STOCK_ISSUE_TOAST_DESCRIPTION } from \"./checkout/stock-issues\";\nexport {\n resolveInitialState,\n shouldPollForConfirmation,\n} from \"./checkout/success-state\";\nexport type { PaymentConfirmationState } from \"./checkout/success-state\";\nexport type { OrderSuccessInfo } from \"./checkout/types\";\nexport {\n formatNumber,\n formatPrice,\n formatPriceRange,\n formatPriceWithoutSymbol,\n getDefaultLocale,\n money,\n} from \"./currency\";\nexport type { SupportedCurrency } from \"./currency\";\nexport {\n ORDER_PROGRESS_STEPS,\n deriveOrderProgress,\n} from \"./orders/derive-progress\";\nexport { STATUS_OPTIONS } from \"./orders/types\";\nexport { getPromotionDescription } from \"./promotions/utils\";\nexport { createStoreSdk, sdk } from \"./sdk\";\nexport { formatShippingAmount } from \"./shipping/format-shipping-option\";\nexport {\n loadWards,\n searchTextFor,\n useProvinces,\n useWards,\n} from \"./shipping/location-areas\";\nexport { SHIPPING_MESSAGES, formatShippingEstimate } from \"./shipping/messages\";\nexport {\n findProvinceByCodeOrName,\n findWardByCodeOrName,\n} from \"./shipping/utils\";\nexport {\n resolveAssetSrc,\n resolveTransformedImageUrl,\n resolveTransformedProductImageUrl,\n resolveTransformedStoreLogoUrl,\n} from \"./storage\";\nexport { resolveStoreRef, storeApiPath, storePath } from \"./store-scope\";\nexport { buildStoreUrl } from \"./store-scope/store-url\";\nexport { readBasicSettings, resolveLegalHref } from \"./stores/basic-settings\";\nexport { defineSchema, defineTheme } from \"./theme/define\";\nexport type {\n AnyThemeDefinition,\n BlogIndexSlotProps,\n BlogPostSlotProps,\n CollectionPageSlotProps,\n CollectionSearchParams,\n ContentPageSlotProps,\n NotFoundProps,\n ProductCardProps,\n ProductPageSlotProps,\n ThemeClientComponents,\n HomePageSlotProps,\n LayoutSlotProps,\n ThemeComponents,\n ThemeDefinition,\n ThemeInfo,\n ThemeSlot,\n ThemeSlotName,\n ThemeSlotProps,\n} from \"./theme/define\";\nexport {\n ThemeSettingsProvider,\n useOptionalThemeId,\n useOptionalThemeKey,\n useThemeId,\n useThemeSettings,\n} from \"./theme/settings-context\";\nexport { metafield, metaobjectField } from \"./metafields/readers\";\nexport { getMetaobject, getMetaobjects } from \"./metafields/metaobjects\";\nexport { RichText } from \"./metafields/rich-text\";\nexport type { RichTextProps } from \"./metafields/rich-text\";\nexport { ThemeStyle, themeStyleCss } from \"./theme/style\";\nexport {\n THEME_PREVIEW_FRAME_ATTR,\n THEME_PREVIEW_MESSAGE,\n ThemePreviewBridge,\n} from \"./theme/preview-bridge\";\nexport { getCachedStore } from \"./stores/cached\";\nexport {\n SUSPENDED_STORE_METADATA,\n withSuspendedStoreMetadataFallback,\n} from \"./stores/metadata\";\nexport { refFromPathname } from \"./stores/store-path\";\nexport { isStoreSuspendedError } from \"./stores/store-suspension\";\nexport { applyConsoleFilter, getLogLevel, shouldLog } from \"./logging\";\n"],"mappings":"AACA,SAAS,6BAA6B;AAEtC,SAAS,iBAAiB;AAC1B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB,sBAAsB;AAS/C;AAAA,EACE;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B,aAAa,iBAAiB;","names":[]}
@@ -19,6 +19,12 @@ import { publicConfig } from "../config/public.js";
19
19
  import { lookupRedirect } from "../redirects/lookup-redirect.js";
20
20
  import { multiTenantStorePath } from "../store-scope/index.js";
21
21
  import { getStoreByHost } from "../stores/get-store-by-host.js";
22
+ import { getStoreSubdomain } from "../stores/store-subdomain.js";
23
+ import { recordStoreRequest } from "../stores/store-traffic.js";
24
+ import {
25
+ PREVIEW_HOST_ROBOTS,
26
+ THEME_PREVIEW_HOST_HEADER
27
+ } from "../theme/preview-host.js";
22
28
  const METADATA_FILES = [
23
29
  "/robots.txt",
24
30
  "/sitemap.xml",
@@ -32,7 +38,7 @@ const EXTERNAL_METADATA_FILES = ["/robots.txt", "/sitemap.xml"];
32
38
  const DOMAIN_NOT_CONNECTED_PATH = "/domain-not-connected";
33
39
  function externalThemeResponse(req, host, storeRef, externalUrl) {
34
40
  if (!externalUrl) return null;
35
- if (req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) || hasThemePreview(req))
41
+ if (req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) || hasThemePreview(req, authCookiePath(storeRef, true)))
36
42
  return null;
37
43
  const pathname = req.nextUrl.pathname;
38
44
  const prefix = multiTenantStorePath(storeRef);
@@ -69,6 +75,28 @@ function buildRedirectResponse(req, redirect, pathPrefix = "") {
69
75
  redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;
70
76
  return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });
71
77
  }
78
+ async function apexStoreResponse(req, storeRef, platformDomain) {
79
+ let subdomain = null;
80
+ try {
81
+ subdomain = await getStoreSubdomain(storeRef);
82
+ } catch (error) {
83
+ console.error("Store lookup failed for apex path:", storeRef, error);
84
+ }
85
+ if (!subdomain) {
86
+ const url = req.nextUrl.clone();
87
+ url.pathname = "/404";
88
+ url.search = "";
89
+ return NextResponse.rewrite(url);
90
+ }
91
+ const prefix = multiTenantStorePath(storeRef);
92
+ const pathname = req.nextUrl.pathname;
93
+ const target = publicNextUrl(req);
94
+ target.hostname = `${subdomain}.${platformDomain}`;
95
+ target.port = "";
96
+ target.pathname = pathname.startsWith(`${prefix}/`) ? pathname.slice(prefix.length) : "/";
97
+ const safe = req.method === "GET" || req.method === "HEAD";
98
+ return NextResponse.redirect(target, { status: safe ? 302 : 307 });
99
+ }
72
100
  async function multiTenant(req) {
73
101
  const host = req.headers.get("host") || "";
74
102
  const pathname = req.nextUrl.pathname;
@@ -78,16 +106,30 @@ async function multiTenant(req) {
78
106
  }
79
107
  const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
80
108
  const hostIdentifiesStore = !host.includes("localhost") && !host.includes("127.0.0.1") && host !== platformDomain && host !== `www.${platformDomain}`;
109
+ const isPlatformApex = host === platformDomain || host === `www.${platformDomain}`;
110
+ if (isPlatformApex) {
111
+ const apexStoreRef = storeRefFromPath(pathname);
112
+ if (apexStoreRef)
113
+ return apexStoreResponse(req, apexStoreRef, platformDomain);
114
+ }
81
115
  let hostStoreRef = null;
82
116
  let hostResolved = false;
83
117
  let hostStoreSuspended = false;
118
+ let previewSlug = null;
84
119
  if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();
85
120
  if (hostIdentifiesStore) {
86
121
  try {
87
- const { storeRef: storeRef2, domain, isSubDomain, suspended, externalUrl } = await getStoreByHost(host);
122
+ const lookup = await getStoreByHost(host);
123
+ const { storeRef: storeRef2, domain, isSubDomain, suspended, externalUrl } = lookup;
88
124
  hostResolved = true;
89
125
  hostStoreRef = storeRef2 || null;
90
126
  hostStoreSuspended = suspended;
127
+ previewSlug = storeRef2 ? lookup.previewSlug : null;
128
+ if (previewSlug && isMetadataFile) {
129
+ return pathname === "/robots.txt" ? new NextResponse(PREVIEW_HOST_ROBOTS, {
130
+ headers: { "content-type": "text/plain" }
131
+ }) : new NextResponse(null, { status: 404 });
132
+ }
91
133
  if (storeRef2) {
92
134
  const external = externalThemeResponse(
93
135
  req,
@@ -99,7 +141,7 @@ async function multiTenant(req) {
99
141
  }
100
142
  if (isMetadataFile) return NextResponse.next();
101
143
  if (storeRef2) {
102
- if (isSubDomain && domain && domain !== host) {
144
+ if (isSubDomain && domain && domain !== host && !previewSlug) {
103
145
  const url = publicNextUrl(req);
104
146
  url.hostname = domain;
105
147
  url.protocol = "https:";
@@ -121,11 +163,10 @@ async function multiTenant(req) {
121
163
  }
122
164
  }
123
165
  const storeRef = hostStoreRef ?? storeRefFromPath(pathname);
124
- if (storeRef) {
125
- const preview = applyThemePreview(
126
- req,
127
- authCookiePath(storeRef, !!hostStoreRef)
128
- );
166
+ if (storeRef) recordStoreRequest(storeRef);
167
+ const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;
168
+ if (storeRef && cookiePath) {
169
+ const preview = applyThemePreview(req, cookiePath);
129
170
  if (preview) return preview;
130
171
  }
131
172
  if (!hostStoreRef && storeRef) {
@@ -142,7 +183,7 @@ async function multiTenant(req) {
142
183
  }
143
184
  }
144
185
  }
145
- const rotated = storeRef ? await refreshIfNearExpiry(req, storeRef) : null;
186
+ const rotated = storeRef && cookiePath ? await refreshIfNearExpiry(req, storeRef, cookiePath) : null;
146
187
  const downstream = downstreamRequestHeaders(
147
188
  req,
148
189
  !!hostStoreRef,
@@ -153,6 +194,7 @@ async function multiTenant(req) {
153
194
  REQUEST_PATH_HEADER,
154
195
  `${req.nextUrl.pathname}${req.nextUrl.search}`
155
196
  );
197
+ if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);
156
198
  const init = { request: { headers: downstream } };
157
199
  let response;
158
200
  if (hostStoreRef) {
@@ -175,14 +217,11 @@ async function multiTenant(req) {
175
217
  } else {
176
218
  response = NextResponse.next(init);
177
219
  }
178
- if (hasThemePreview(req)) response.headers.set("x-robots-tag", "noindex");
179
- if (rotated && storeRef) {
180
- writeAuthCookies(
181
- response,
182
- storeRef,
183
- rotated,
184
- authCookiePath(storeRef, !!hostStoreRef)
185
- );
220
+ if (previewSlug || cookiePath && hasThemePreview(req, cookiePath)) {
221
+ response.headers.set("x-robots-tag", "noindex");
222
+ }
223
+ if (rotated && storeRef && cookiePath) {
224
+ writeAuthCookies(response, storeRef, rotated, cookiePath);
186
225
  }
187
226
  return response;
188
227
  }
@@ -190,7 +229,8 @@ async function singleStore(req) {
190
229
  const pathname = req.nextUrl.pathname;
191
230
  if (METADATA_FILES.includes(pathname)) return NextResponse.next();
192
231
  const storeRef = publicConfig().storeRef;
193
- const preview = applyThemePreview(req, authCookiePath(storeRef, true));
232
+ const cookiePath = authCookiePath(storeRef, true);
233
+ const preview = applyThemePreview(req, cookiePath);
194
234
  if (preview) return preview;
195
235
  try {
196
236
  const redirect = await lookupRedirect(storeRef, pathname);
@@ -202,20 +242,16 @@ async function singleStore(req) {
202
242
  } catch (error) {
203
243
  console.debug("Redirect lookup error:", error);
204
244
  }
205
- const rotated = await refreshIfNearExpiry(req, storeRef);
245
+ const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);
206
246
  const response = NextResponse.next({
207
247
  request: {
208
248
  headers: downstreamRequestHeaders(req, true, storeRef, rotated)
209
249
  }
210
250
  });
211
- if (hasThemePreview(req)) response.headers.set("x-robots-tag", "noindex");
251
+ if (hasThemePreview(req, cookiePath))
252
+ response.headers.set("x-robots-tag", "noindex");
212
253
  if (rotated) {
213
- writeAuthCookies(
214
- response,
215
- storeRef,
216
- rotated,
217
- authCookiePath(storeRef, true)
218
- );
254
+ writeAuthCookies(response, storeRef, rotated, cookiePath);
219
255
  }
220
256
  return response;
221
257
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) || hasThemePreview(req))\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url);\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next();\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n\n if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();\n\n if (hostIdentifiesStore) {\n try {\n const { storeRef, domain, isSubDomain, suspended, externalUrl } =\n await getStoreByHost(host);\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next();\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to custom domain\n if (isSubDomain && domain && domain !== host) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next();\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1).\n if (storeRef) {\n const preview = applyThemePreview(\n req,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n if (preview) return preview;\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated = storeRef ? await refreshIfNearExpiry(req, storeRef) : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n\n if (rotated && storeRef) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, !!hostStoreRef)\n );\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n const preview = applyThemePreview(req, authCookiePath(storeRef, true));\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req)) response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(\n response,\n storeRef,\n rotated,\n authCookiePath(storeRef, true)\n );\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, redirects, session refresh.\n * - single: redirects and session refresh only.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\",\n ],\n};\n"],"mappings":"AAAA,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAsB,oBAAoB;AAE1C,SAAS,gBAAgB,wBAAwB;AACjD;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,4BAA4B;AACrC,SAAS,sBAAsB;AAG/B,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAMA,MAAM,0BAA0B,CAAC,eAAe,cAAc;AAG9D,MAAM,4BAA4B;AAclC,SAAS,sBACP,KACA,MACA,UACA,aACqB;AACrB,MAAI,CAAC,YAAa,QAAO;AACzB,MAAI,IAAI,QAAQ,aAAa,IAAI,mBAAmB,KAAK,gBAAgB,GAAG;AAC1E,WAAO;AAET,QAAM,WAAW,IAAI,QAAQ;AAC7B,QAAM,SAAS,qBAAqB,QAAQ;AAC5C,QAAM,cACJ,aAAa,UAAU,SAAS,WAAW,GAAG,MAAM,GAAG,IACnD,SAAS,MAAM,OAAO,MAAM,KAAK,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,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
1
+ {"version":3,"sources":["../../src/middleware/create-storefront-middleware.ts"],"sourcesContent":["import { publicNextUrl } from \"../request/public-url\";\nimport { REQUEST_PATH_HEADER } from \"../request/request-path\";\nimport {\n applyThemePreview,\n hasThemePreview,\n THEME_PREVIEW_PARAM,\n} from \"../theme/preview-cookie\";\nimport {\n externalStorefrontUrl,\n isSameHost,\n} from \"../theme/external-storefront\";\nimport { NextRequest, NextResponse } from \"next/server\";\nimport type { UrlRedirect } from \"@ecomweb/sdk\";\nimport { authCookiePath, writeAuthCookies } from \"../auth/cookies\";\nimport {\n downstreamRequestHeaders,\n refreshIfNearExpiry,\n} from \"../auth/session-refresh\";\nimport type { StorefrontMode } from \"../config/mode\";\nimport { publicConfig } from \"../config/public\";\nimport { lookupRedirect } from \"../redirects/lookup-redirect\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport { getStoreByHost } from \"../stores/get-store-by-host\";\nimport { getStoreSubdomain } from \"../stores/store-subdomain\";\nimport { recordStoreRequest } from \"../stores/store-traffic\";\nimport {\n PREVIEW_HOST_ROBOTS,\n THEME_PREVIEW_HOST_HEADER,\n} from \"../theme/preview-host\";\n\n/** Served from the app root in both modes; never rewritten or redirected. */\nconst METADATA_FILES = [\n \"/robots.txt\",\n \"/sitemap.xml\",\n \"/favicon.ico\",\n \"/manifest.json\",\n \"/manifest.webmanifest\",\n \"/icon\",\n \"/apple-icon\",\n];\n\n/**\n * Metadata files that follow the store to an external site: crawlers must\n * find the external site's robots.txt and sitemap, not ours.\n */\nconst EXTERNAL_METADATA_FILES = [\"/robots.txt\", \"/sitemap.xml\"];\n\n/** Rewrite target when a store's external URL still points at Ecomweb. */\nconst DOMAIN_NOT_CONNECTED_PATH = \"/domain-not-connected\";\n\n/**\n * The response for a store whose live theme is external, or null to serve\n * the request here (theme anatomy spec, \"Storefront\"):\n * - 302 to the external URL with the same path and query (307 for non-GET,\n * so the method survives); never 301, the merchant may switch back.\n * - never while previewing (`?preview_theme=` or the preview cookie): a\n * preview of an Ecomweb theme must render here.\n * - the external URL is this very host (the domain still points at Ecomweb):\n * a \"domain not connected\" page rather than a redirect loop (robots.txt\n * and the sitemap are still served here).\n * - no usable URL: null (fail open).\n */\nfunction externalThemeResponse(\n req: NextRequest,\n host: string,\n storeRef: string,\n externalUrl: string | null | undefined\n): NextResponse | null {\n if (!externalUrl) return null;\n if (\n req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) ||\n hasThemePreview(req, authCookiePath(storeRef, true))\n )\n return null;\n\n const pathname = req.nextUrl.pathname;\n const prefix = multiTenantStorePath(storeRef);\n const logicalPath =\n pathname === prefix || pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length) || \"/\"\n : pathname;\n const target = externalStorefrontUrl(\n externalUrl,\n logicalPath,\n req.nextUrl.search\n );\n if (!target) return null;\n\n if (isSameHost(host, target.hostname)) {\n // Our own robots.txt and sitemap still describe this host correctly.\n if (EXTERNAL_METADATA_FILES.includes(pathname)) return null;\n const url = req.nextUrl.clone();\n url.pathname = DOMAIN_NOT_CONNECTED_PATH;\n url.search = \"\";\n const res = NextResponse.rewrite(url);\n res.headers.set(\"x-robots-tag\", \"noindex\");\n return res;\n }\n\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\n/**\n * The store a request belongs to, as far as the *path* can say.\n *\n * On localhost and on the platform apex there is no host→store mapping, but\n * the path is `/store/<storeRef>/…` — which is also how the auth cookies are\n * named. `params.storeRef` arrives URL-decoded downstream, so decode here too.\n */\nfunction storeRefFromPath(pathname: string): string | null {\n const match = /^\\/store\\/([^/]+)/.exec(pathname);\n if (!match) return null;\n try {\n return decodeURIComponent(match[1]) || null;\n } catch {\n return match[1];\n }\n}\n\n/**\n * Turns a stored redirect row into the 301/302 response for it.\n *\n * `pathPrefix` re-adds the `/store/<ref>` segment that direct path-based\n * access needs on the destination but a host-mapped request (whose\n * `destination_path` is already store-root-relative) does not.\n */\nfunction buildRedirectResponse(\n req: NextRequest,\n redirect: UrlRedirect,\n pathPrefix = \"\"\n): NextResponse {\n const redirectUrl = publicNextUrl(req);\n redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;\n return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });\n}\n\n/**\n * `/store/<ref>/…` on the platform apex: never served here, sent to the\n * store's own subdomain instead.\n *\n * On the apex every store shares one origin, and a merchant's embedded\n * scripts run there. A cookie's Path is no boundary between pages of one\n * origin: store A's script could fetch `/store/B/api/…` with B's shopper\n * cookies attached, or frame `/store/B` and read it. Each store's subdomain\n * is its own origin. Localhost keeps path-based access (it is not the apex).\n *\n * 302 (307 for non-GET), not 301: the merchant may change the subdomain.\n * The subdomain then sends shoppers on to a custom domain when there is one.\n * No store, no subdomain, or the API unreachable: the 404 page.\n */\nasync function apexStoreResponse(\n req: NextRequest,\n storeRef: string,\n platformDomain: string\n): Promise<NextResponse> {\n let subdomain: string | null = null;\n try {\n subdomain = await getStoreSubdomain(storeRef);\n } catch (error) {\n console.error(\"Store lookup failed for apex path:\", storeRef, error);\n }\n\n if (!subdomain) {\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n url.search = \"\";\n return NextResponse.rewrite(url);\n }\n\n const prefix = multiTenantStorePath(storeRef);\n const pathname = req.nextUrl.pathname;\n const target = publicNextUrl(req);\n target.hostname = `${subdomain}.${platformDomain}`;\n target.port = \"\";\n target.pathname = pathname.startsWith(`${prefix}/`)\n ? pathname.slice(prefix.length)\n : \"/\";\n const safe = req.method === \"GET\" || req.method === \"HEAD\";\n return NextResponse.redirect(target, { status: safe ? 302 : 307 });\n}\n\nasync function multiTenant(req: NextRequest): Promise<NextResponse> {\n const host = req.headers.get(\"host\") || \"\";\n const pathname = req.nextUrl.pathname;\n\n // Skip metadata files - these are served from app root level - except the\n // ones that follow an external theme (checked once the store is known).\n const isMetadataFile = METADATA_FILES.includes(pathname);\n if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {\n return NextResponse.next();\n }\n\n // Store-by-host resolution and redirect lookup genuinely do not apply on\n // localhost or on the platform apex — but the token refresh below does, so\n // these only skip the host-specific work now, not the whole middleware.\n const platformDomain = publicConfig().platformDomainSuffix ?? \"ecomsite.app\";\n const hostIdentifiesStore =\n !host.includes(\"localhost\") &&\n !host.includes(\"127.0.0.1\") &&\n host !== platformDomain &&\n host !== `www.${platformDomain}`;\n\n const isPlatformApex =\n host === platformDomain || host === `www.${platformDomain}`;\n if (isPlatformApex) {\n const apexStoreRef = storeRefFromPath(pathname);\n if (apexStoreRef)\n return apexStoreResponse(req, apexStoreRef, platformDomain);\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();\n\n if (hostIdentifiesStore) {\n try {\n const lookup = await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n previewSlug = storeRef ? lookup.previewSlug : null;\n\n // Nothing on a preview host is for search engines.\n if (previewSlug && isMetadataFile) {\n return pathname === \"/robots.txt\"\n ? new NextResponse(PREVIEW_HOST_ROBOTS, {\n headers: { \"content-type\": \"text/plain\" },\n })\n : new NextResponse(null, { status: 404 });\n }\n\n if (storeRef) {\n // An external theme is live: the shopper belongs on that site. Before\n // the subdomain → custom domain redirect, which would only add a hop.\n const external = externalThemeResponse(\n req,\n host,\n storeRef,\n externalUrl\n );\n if (external) return external;\n }\n\n if (isMetadataFile) return NextResponse.next();\n\n if (storeRef) {\n // If accessing via subdomain but custom domain exists, redirect to\n // custom domain. Not a preview host: it is the theme's, not the store's.\n if (isSubDomain && domain && domain !== host && !previewSlug) {\n const url = publicNextUrl(req);\n url.hostname = domain;\n url.protocol = \"https:\";\n url.port = \"\"; // Remove port for custom domain\n return NextResponse.redirect(url, { status: 301 });\n }\n\n // Check for URL redirects BEFORE rewriting\n // Skip redirect check if path already starts with /store/ (internal rewrite)\n if (!pathname.startsWith(multiTenantStorePath(storeRef))) {\n const redirect = await lookupRedirect(storeRef, pathname);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect);\n }\n }\n }\n } catch (error) {\n console.debug(\"Middleware error:\", error);\n if (isMetadataFile) return NextResponse.next();\n // Fall through: no host mapping, but the refresh below still applies.\n hostResolved = false;\n hostStoreRef = null;\n }\n }\n\n // The host names the store on custom domains and subdomains; everywhere else\n // (localhost, the apex, direct /store/<ref>/… access) the path does.\n const storeRef = hostStoreRef ?? storeRefFromPath(pathname);\n if (storeRef) recordStoreRequest(storeRef);\n\n // A dashboard preview link: store its token in a cookie, then redirect to\n // the clean URL (themes spec §6.1).\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n }\n\n // Direct /store/<ref>/… access never goes through the host-mapped branch\n // above, so it gets no redirect check there. `redirect_source_path` rows\n // are store-root-relative (e.g. \"/old\"), the same shape a host-mapped\n // request already checks against — strip the /store/<ref> prefix to\n // recover that shape, and re-add it on the destination.\n if (!hostStoreRef && storeRef) {\n const prefix = multiTenantStorePath(storeRef);\n if (pathname === prefix || pathname.startsWith(`${prefix}/`)) {\n try {\n const logicalPath = pathname.slice(prefix.length) || \"/\";\n const redirect = await lookupRedirect(storeRef, logicalPath);\n\n if (redirect) {\n return buildRedirectResponse(req, redirect, prefix);\n }\n } catch (error) {\n // Fail open: lookupRedirect already catches internally and never\n // rejects, but this belongs to the caller's contract, not the\n // callee's — a future regression there must not take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n }\n }\n\n const rotated =\n storeRef && cookiePath\n ? await refreshIfNearExpiry(req, storeRef, cookiePath)\n : null;\n const downstream = downstreamRequestHeaders(\n req,\n !!hostStoreRef,\n storeRef,\n rotated\n );\n downstream.set(\n REQUEST_PATH_HEADER,\n `${req.nextUrl.pathname}${req.nextUrl.search}`\n );\n if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);\n const init = { request: { headers: downstream } };\n\n let response: NextResponse;\n\n if (hostStoreRef) {\n const url = req.nextUrl.clone();\n // Only rewrite if the path doesn't already start with /store/\n if (!url.pathname.startsWith(multiTenantStorePath(hostStoreRef))) {\n url.pathname = multiTenantStorePath(hostStoreRef, url.pathname);\n }\n\n response = NextResponse.rewrite(url, init);\n // Add headers to indicate this is a domain-mapped store\n response.headers.set(\"x-store-domain\", \"true\");\n response.headers.set(\"x-store-ref\", hostStoreRef);\n } else if (hostStoreSuspended) {\n // A platform admin suspended this store. The 403 the backend returned\n // for a domain lookup carries no ref/id to route on (see\n // getStoreByHost), so this can't rewrite to `/store/<ref>` the way the\n // resolved-store branch above does — it goes to a platform-level page\n // instead of the not-found path below.\n const url = req.nextUrl.clone();\n url.pathname = \"/store-suspended\";\n response = NextResponse.rewrite(url, init);\n } else if (hostResolved) {\n // The host looked like a store host but resolved to nothing: 404.\n console.debug(\"Store not found for host:\", host);\n const url = req.nextUrl.clone();\n url.pathname = \"/404\";\n response = NextResponse.rewrite(url, init);\n } else {\n response = NextResponse.next(init);\n }\n\n if (previewSlug || (cookiePath && hasThemePreview(req, cookiePath))) {\n response.headers.set(\"x-robots-tag\", \"noindex\");\n }\n\n if (rotated && storeRef && cookiePath) {\n // Same path the auth route handler writes with, from the same signal.\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n\n return response;\n}\n\n/**\n * Single-store middleware: the store is fixed by ECOMWEB_STORE_REF, so there\n * is no host lookup and no rewrite. It applies the store's URL redirects and\n * refreshes a near-expiry session. Requests are stamped host-mapped, so auth\n * cookies use Path=/ (see auth/cookies.ts).\n */\nasync function singleStore(req: NextRequest): Promise<NextResponse> {\n const pathname = req.nextUrl.pathname;\n if (METADATA_FILES.includes(pathname)) return NextResponse.next();\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n\n try {\n const redirect = await lookupRedirect(storeRef, pathname);\n if (redirect) {\n const url = publicNextUrl(req);\n url.pathname = redirect.destination_path;\n return NextResponse.redirect(url, { status: redirect.redirect_type });\n }\n } catch (error) {\n // Fail open: a redirect lookup must never take the page down.\n console.debug(\"Redirect lookup error:\", error);\n }\n\n const rotated = await refreshIfNearExpiry(req, storeRef, cookiePath);\n const response = NextResponse.next({\n request: {\n headers: downstreamRequestHeaders(req, true, storeRef, rotated),\n },\n });\n\n if (hasThemePreview(req, cookiePath))\n response.headers.set(\"x-robots-tag\", \"noindex\");\n if (rotated) {\n writeAuthCookies(response, storeRef, rotated, cookiePath);\n }\n return response;\n}\n\n/**\n * The storefront's proxy.ts (Next middleware).\n * - multi: host → store lookup, rewrites to /store/<ref>, suspended and\n * unknown stores, redirects, session refresh.\n * - single: redirects and session refresh only.\n * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.\n */\nexport function createStorefrontMiddleware(\n opts: { mode?: StorefrontMode } = {}\n): (req: NextRequest) => Promise<NextResponse> {\n return req =>\n (opts.mode ?? publicConfig().mode) === \"multi\"\n ? multiTenant(req)\n : singleStore(req);\n}\n\n/**\n * Next reads `config` from proxy.ts statically, so an app re-exports this as\n * `export const config = { matcher: [...] }` with the same literal.\n */\nexport const storefrontMiddlewareConfig = {\n matcher: [\n /*\n * Match all request paths except for the ones starting with:\n * - api (API routes)\n * - _next/static (static files)\n * - _next/image (image optimization files)\n * - _vercel (Vercel Analytics; off Vercel, a store page render per hit)\n * - favicon.ico (favicon file)\n */\n \"/((?!api|_next/static|_next/image|_vercel|favicon.ico).*)\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WAAW,IAAI,QAAQ;AAC7B,MAAI,eAAe,SAAS,QAAQ,EAAG,QAAO,aAAa,KAAK;AAEhE,QAAM,WAAW,aAAa,EAAE;AAEhC,QAAM,aAAa,eAAe,UAAU,IAAI;AAChD,QAAM,UAAU,kBAAkB,KAAK,UAAU;AACjD,MAAI,QAAS,QAAO;AAEpB,MAAI;AACF,UAAM,WAAW,MAAM,eAAe,UAAU,QAAQ;AACxD,QAAI,UAAU;AACZ,YAAM,MAAM,cAAc,GAAG;AAC7B,UAAI,WAAW,SAAS;AACxB,aAAO,aAAa,SAAS,KAAK,EAAE,QAAQ,SAAS,cAAc,CAAC;AAAA,IACtE;AAAA,EACF,SAAS,OAAO;AAEd,YAAQ,MAAM,0BAA0B,KAAK;AAAA,EAC/C;AAEA,QAAM,UAAU,MAAM,oBAAoB,KAAK,UAAU,UAAU;AACnE,QAAM,WAAW,aAAa,KAAK;AAAA,IACjC,SAAS;AAAA,MACP,SAAS,yBAAyB,KAAK,MAAM,UAAU,OAAO;AAAA,IAChE;AAAA,EACF,CAAC;AAED,MAAI,gBAAgB,KAAK,UAAU;AACjC,aAAS,QAAQ,IAAI,gBAAgB,SAAS;AAChD,MAAI,SAAS;AACX,qBAAiB,UAAU,UAAU,SAAS,UAAU;AAAA,EAC1D;AACA,SAAO;AACT;AASO,SAAS,2BACd,OAAkC,CAAC,GACU;AAC7C,SAAO,UACJ,KAAK,QAAQ,aAAa,EAAE,UAAU,UACnC,YAAY,GAAG,IACf,YAAY,GAAG;AACvB;AAMO,MAAM,6BAA6B;AAAA,EACxC,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASP;AAAA,EACF;AACF;","names":["storeRef"]}
@@ -1,6 +1,6 @@
1
1
  import { NextRequest, NextResponse } from 'next/server';
2
- import { S as StorefrontMode } from './mode-YNx2aOtQ.js';
3
- import './schema-Tc0qRs-Q.js';
2
+ import { S as StorefrontMode } from './mode-Lm9t4qzX.js';
3
+ import './schema-Dg0ZflMW.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -1,4 +1,4 @@
1
- import { E as EnvSource } from './schema-Tc0qRs-Q.js';
1
+ import { E as EnvSource } from './schema-Dg0ZflMW.js';
2
2
 
3
3
  /**
4
4
  * multi: the shared platform storefront, every store under /store/<ref> or
@@ -1,6 +1,8 @@
1
1
  import { sdk } from "../sdk.js";
2
2
  import { useState, useCallback, useEffect, useRef } from "react";
3
3
  import { useNotify } from "../notices.js";
4
+ class PromotionRejected extends Error {
5
+ }
4
6
  function usePromotionValidation({
5
7
  storeRef,
6
8
  items,
@@ -23,22 +25,21 @@ function usePromotionValidation({
23
25
  setIsValidatingPromo(true);
24
26
  setPromoError("");
25
27
  try {
26
- const result = await sdk.promotions.validate(
27
- storeRef,
28
- {
29
- code: codeToValidate.trim(),
30
- items: items.map((item) => ({
31
- product_id: item.productId,
32
- variant_id: item.variantId ?? void 0,
33
- quantity: item.quantity,
34
- price: item.price
35
- })),
36
- subtotal,
37
- shipping_fee: shippingFee
38
- }
39
- );
28
+ const result = await sdk.promotions.validate(storeRef, {
29
+ code: codeToValidate.trim(),
30
+ items: items.map((item) => ({
31
+ product_id: item.productId,
32
+ variant_id: item.variantId ?? void 0,
33
+ quantity: item.quantity,
34
+ price: item.price
35
+ })),
36
+ subtotal,
37
+ shipping_fee: shippingFee
38
+ });
40
39
  if (!result.success) {
41
- throw new Error(result.message || "M\xE3 khuy\u1EBFn m\xE3i kh\xF4ng h\u1EE3p l\u1EC7");
40
+ throw new PromotionRejected(
41
+ result.message || "M\xE3 khuy\u1EBFn m\xE3i kh\xF4ng h\u1EE3p l\u1EC7"
42
+ );
42
43
  }
43
44
  const promotionWithCode = {
44
45
  ...result.promotion,
@@ -53,7 +54,9 @@ function usePromotionValidation({
53
54
  description: `${result.promotion?.name || ""} \u0111\xE3 \u0111\u01B0\u1EE3c \xE1p d\u1EE5ng`
54
55
  });
55
56
  } catch (error) {
56
- console.error("Failed to validate promotion code:", error);
57
+ if (!(error instanceof PromotionRejected)) {
58
+ console.error("Failed to validate promotion code:", error);
59
+ }
57
60
  setPromoError(
58
61
  error instanceof Error ? error.message : "M\xE3 khuy\u1EBFn m\xE3i kh\xF4ng h\u1EE3p l\u1EC7"
59
62
  );
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/promotions/use-promotion-validation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useState, useCallback, useEffect, useRef } from \"react\";\nimport { useNotify } from \"../notices\";\n\ninterface CartItem {\n productId: number;\n variantId: number | null;\n quantity: number;\n price: number;\n}\n\ninterface UsePromotionValidationProps {\n storeRef: string;\n items: CartItem[];\n subtotal: number;\n shippingFee: number;\n}\n\nexport function usePromotionValidation({\n storeRef,\n items,\n subtotal,\n shippingFee,\n}: UsePromotionValidationProps) {\n const [promoCode, setPromoCode] = useState<string>(\"\");\n const [appliedPromotion, setAppliedPromotion] = useState<any>(null);\n // Computed by the API against the shipping fee we sent; the same number the\n // server uses when the order is placed, so we never derive it ourselves.\n const [shippingDiscount, setShippingDiscount] = useState<number>(0);\n const [isValidatingPromo, setIsValidatingPromo] = useState(false);\n const [promoError, setPromoError] = useState<string>(\"\");\n const notify = useNotify();\n\n // Validate promotion code with specific code\n const validatePromoCodeWithCode = useCallback(\n async (code?: string) => {\n const codeToValidate = code || promoCode;\n\n if (!codeToValidate.trim()) {\n setPromoError(\"Vui lòng nhập mã khuyến mãi\");\n return;\n }\n\n setIsValidatingPromo(true);\n setPromoError(\"\");\n\n try {\n const result = await sdk.promotions.validate(\n storeRef,\n {\n code: codeToValidate.trim(),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId ?? undefined,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal: subtotal,\n shipping_fee: shippingFee,\n }\n );\n\n if (!result.success) {\n throw new Error(result.message || \"Mã khuyến mãi không hợp lệ\");\n }\n\n // Add code to promotion object for tracking\n const promotionWithCode = {\n ...result.promotion,\n code: codeToValidate.trim(),\n };\n setAppliedPromotion(promotionWithCode);\n setShippingDiscount(result.shipping_discount ?? 0);\n notify({\n kind: \"success\",\n code: \"promotion.applied\",\n title: \"Áp dụng mã khuyến mãi thành công\",\n description: `${result.promotion?.name || \"\"} đã được áp dụng`,\n });\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to validate promotion code:\", error);\n setPromoError(\n error instanceof Error ? error.message : \"Mã khuyến mãi không hợp lệ\"\n );\n setAppliedPromotion(null);\n setShippingDiscount(0);\n } finally {\n setIsValidatingPromo(false);\n }\n },\n [storeRef, items, subtotal, shippingFee, promoCode, notify]\n );\n\n // The server computes the shipping discount against the shipping fee we sent\n // it, so the number goes stale the moment the fee changes (new address, new\n // method). Re-ask rather than recomputing locally — a local recomputation is\n // exactly the duplicated money logic this hook exists to avoid.\n const revalidateRef = useRef(validatePromoCodeWithCode);\n revalidateRef.current = validatePromoCodeWithCode;\n\n useEffect(() => {\n const code = appliedPromotion?.code;\n if (!code) return;\n void revalidateRef.current(code);\n // Intentionally keyed on the fee alone: including the callback would\n // re-run this on every render, and including appliedPromotion would loop\n // on the state this very effect writes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shippingFee]);\n\n // Validate promotion code\n const validatePromoCode = useCallback(async () => {\n await validatePromoCodeWithCode();\n }, [validatePromoCodeWithCode]);\n\n // Remove applied promotion\n const removePromoCode = useCallback(() => {\n setPromoCode(\"\");\n setAppliedPromotion(null);\n setShippingDiscount(0);\n setPromoError(\"\");\n }, []);\n\n // Apply promotion from suggestion\n const applyPromotionFromSuggestion = useCallback(\n async (code: string) => {\n setPromoCode(code);\n // Use the code directly instead of relying on state\n await validatePromoCodeWithCode(code);\n },\n [validatePromoCodeWithCode]\n );\n\n return {\n promoCode,\n appliedPromotion,\n shippingDiscount,\n isValidatingPromo,\n promoError,\n setPromoCode,\n validatePromoCode,\n removePromoCode,\n applyPromotionFromSuggestion,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,UAAU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QAAQ,EAAE;AAAA,QAC9C,CAAC;AAAA,MACH,SAAS,OAAO;AAEd,gBAAQ,MAAM,sCAAsC,KAAK;AACzD;AAAA,UACE,iBAAiB,QAAQ,MAAM,UAAU;AAAA,QAC3C;AACA,4BAAoB,IAAI;AACxB,4BAAoB,CAAC;AAAA,MACvB,UAAE;AACA,6BAAqB,KAAK;AAAA,MAC5B;AAAA,IACF;AAAA,IACA,CAAC,UAAU,OAAO,UAAU,aAAa,WAAW,MAAM;AAAA,EAC5D;AAMA,QAAM,gBAAgB,OAAO,yBAAyB;AACtD,gBAAc,UAAU;AAExB,YAAU,MAAM;AACd,UAAM,OAAO,kBAAkB;AAC/B,QAAI,CAAC,KAAM;AACX,SAAK,cAAc,QAAQ,IAAI;AAAA,EAKjC,GAAG,CAAC,WAAW,CAAC;AAGhB,QAAM,oBAAoB,YAAY,YAAY;AAChD,UAAM,0BAA0B;AAAA,EAClC,GAAG,CAAC,yBAAyB,CAAC;AAG9B,QAAM,kBAAkB,YAAY,MAAM;AACxC,iBAAa,EAAE;AACf,wBAAoB,IAAI;AACxB,wBAAoB,CAAC;AACrB,kBAAc,EAAE;AAAA,EAClB,GAAG,CAAC,CAAC;AAGL,QAAM,+BAA+B;AAAA,IACnC,OAAO,SAAiB;AACtB,mBAAa,IAAI;AAEjB,YAAM,0BAA0B,IAAI;AAAA,IACtC;AAAA,IACA,CAAC,yBAAyB;AAAA,EAC5B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/promotions/use-promotion-validation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useState, useCallback, useEffect, useRef } from \"react\";\nimport { useNotify } from \"../notices\";\n\ninterface CartItem {\n productId: number;\n variantId: number | null;\n quantity: number;\n price: number;\n}\n\ninterface UsePromotionValidationProps {\n storeRef: string;\n items: CartItem[];\n subtotal: number;\n shippingFee: number;\n}\n\n/** The API answered: this code does not apply (unknown, expired, not eligible). */\nclass PromotionRejected extends Error {}\n\nexport function usePromotionValidation({\n storeRef,\n items,\n subtotal,\n shippingFee,\n}: UsePromotionValidationProps) {\n const [promoCode, setPromoCode] = useState<string>(\"\");\n const [appliedPromotion, setAppliedPromotion] = useState<any>(null);\n // Computed by the API against the shipping fee we sent; the same number the\n // server uses when the order is placed, so we never derive it ourselves.\n const [shippingDiscount, setShippingDiscount] = useState<number>(0);\n const [isValidatingPromo, setIsValidatingPromo] = useState(false);\n const [promoError, setPromoError] = useState<string>(\"\");\n const notify = useNotify();\n\n // Validate promotion code with specific code\n const validatePromoCodeWithCode = useCallback(\n async (code?: string) => {\n const codeToValidate = code || promoCode;\n\n if (!codeToValidate.trim()) {\n setPromoError(\"Vui lòng nhập mã khuyến mãi\");\n return;\n }\n\n setIsValidatingPromo(true);\n setPromoError(\"\");\n\n try {\n const result = await sdk.promotions.validate(storeRef, {\n code: codeToValidate.trim(),\n items: items.map(item => ({\n product_id: item.productId,\n variant_id: item.variantId ?? undefined,\n quantity: item.quantity,\n price: item.price,\n })),\n subtotal: subtotal,\n shipping_fee: shippingFee,\n });\n\n if (!result.success) {\n throw new PromotionRejected(\n result.message || \"Mã khuyến mãi không hợp lệ\"\n );\n }\n\n // Add code to promotion object for tracking\n const promotionWithCode = {\n ...result.promotion,\n code: codeToValidate.trim(),\n };\n setAppliedPromotion(promotionWithCode);\n setShippingDiscount(result.shipping_discount ?? 0);\n notify({\n kind: \"success\",\n code: \"promotion.applied\",\n title: \"Áp dụng mã khuyến mãi thành công\",\n description: `${result.promotion?.name || \"\"} đã được áp dụng`,\n });\n } catch (error) {\n // A rejected code is an ordinary answer, shown to the shopper; only\n // unexpected failures (network, server) are worth logging.\n if (!(error instanceof PromotionRejected)) {\n // eslint-disable-next-line no-console\n console.error(\"Failed to validate promotion code:\", error);\n }\n setPromoError(\n error instanceof Error ? error.message : \"Mã khuyến mãi không hợp lệ\"\n );\n setAppliedPromotion(null);\n setShippingDiscount(0);\n } finally {\n setIsValidatingPromo(false);\n }\n },\n [storeRef, items, subtotal, shippingFee, promoCode, notify]\n );\n\n // The server computes the shipping discount against the shipping fee we sent\n // it, so the number goes stale the moment the fee changes (new address, new\n // method). Re-ask rather than recomputing locally — a local recomputation is\n // exactly the duplicated money logic this hook exists to avoid.\n const revalidateRef = useRef(validatePromoCodeWithCode);\n revalidateRef.current = validatePromoCodeWithCode;\n\n useEffect(() => {\n const code = appliedPromotion?.code;\n if (!code) return;\n void revalidateRef.current(code);\n // Intentionally keyed on the fee alone: including the callback would\n // re-run this on every render, and including appliedPromotion would loop\n // on the state this very effect writes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [shippingFee]);\n\n // Validate promotion code\n const validatePromoCode = useCallback(async () => {\n await validatePromoCodeWithCode();\n }, [validatePromoCodeWithCode]);\n\n // Remove applied promotion\n const removePromoCode = useCallback(() => {\n setPromoCode(\"\");\n setAppliedPromotion(null);\n setShippingDiscount(0);\n setPromoError(\"\");\n }, []);\n\n // Apply promotion from suggestion\n const applyPromotionFromSuggestion = useCallback(\n async (code: string) => {\n setPromoCode(code);\n // Use the code directly instead of relying on state\n await validatePromoCodeWithCode(code);\n },\n [validatePromoCodeWithCode]\n );\n\n return {\n promoCode,\n appliedPromotion,\n shippingDiscount,\n isValidatingPromo,\n promoError,\n setPromoCode,\n validatePromoCode,\n removePromoCode,\n applyPromotionFromSuggestion,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,UAAU,aAAa,WAAW,cAAc;AACzD,SAAS,iBAAiB;AAiB1B,MAAM,0BAA0B,MAAM;AAAC;AAEhC,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAgC;AAC9B,QAAM,CAAC,WAAW,YAAY,IAAI,SAAiB,EAAE;AACrD,QAAM,CAAC,kBAAkB,mBAAmB,IAAI,SAA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BAAoB,CAAC;AAAA,MACvB,UAAE;AACA,6BAAqB,KAAK;AAAA,MAC5B;AAAA,IACF;AAAA,IACA,CAAC,UAAU,OAAO,UAAU,aAAa,WAAW,MAAM;AAAA,EAC5D;AAMA,QAAM,gBAAgB,OAAO,yBAAyB;AACtD,gBAAc,UAAU;AAExB,YAAU,MAAM;AACd,UAAM,OAAO,kBAAkB;AAC/B,QAAI,CAAC,KAAM;AACX,SAAK,cAAc,QAAQ,IAAI;AAAA,EAKjC,GAAG,CAAC,WAAW,CAAC;AAGhB,QAAM,oBAAoB,YAAY,YAAY;AAChD,UAAM,0BAA0B;AAAA,EAClC,GAAG,CAAC,yBAAyB,CAAC;AAG9B,QAAM,kBAAkB,YAAY,MAAM;AACxC,iBAAa,EAAE;AACf,wBAAoB,IAAI;AACxB,wBAAoB,CAAC;AACrB,kBAAc,EAAE;AAAA,EAClB,GAAG,CAAC,CAAC;AAGL,QAAM,+BAA+B;AAAA,IACnC,OAAO,SAAiB;AACtB,mBAAa,IAAI;AAEjB,YAAM,0BAA0B,IAAI;AAAA,IACtC;AAAA,IACA,CAAC,yBAAyB;AAAA,EAC5B;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -43,6 +43,7 @@ declare const serverConfigSchema: z.ZodObject<{
43
43
  "x-forwarded-for": "x-forwarded-for";
44
44
  "cf-connecting-ip": "cf-connecting-ip";
45
45
  }>;
46
+ storeTrafficLogPerMinute: z.ZodNumber;
46
47
  }, z.core.$strip>;
47
48
  type ServerConfig = z.infer<typeof serverConfigSchema>;
48
49
  declare class ConfigError extends Error {
package/dist/server.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { NextRequest } from 'next/server';
2
2
  import { CurrentIdentity } from '@ecomweb/sdk';
3
- import { E as EnvSource, S as ServerConfig } from './schema-Tc0qRs-Q.js';
3
+ import { E as EnvSource, S as ServerConfig } from './schema-Dg0ZflMW.js';
4
4
  import 'zod';
5
5
 
6
6
  /**
@@ -58,6 +58,12 @@ declare function resolveRootStoreRef(): Promise<string | null>;
58
58
  /** The open theme preview's token, if any (server components only). */
59
59
  declare function readThemePreviewToken(): Promise<string | null>;
60
60
 
61
+ /**
62
+ * The theme preview host's slug when this request came in on one (server
63
+ * components only); the middleware sets it, never the client.
64
+ */
65
+ declare function readPreviewHostSlug(): Promise<string | null>;
66
+
61
67
  /**
62
68
  * Where the store layout sends a request when the published theme is
63
69
  * external, else null: the backstop for path-based access
@@ -76,4 +82,4 @@ declare function externalThemeRedirectFor(request: {
76
82
  external_url?: string | null;
77
83
  } | null | undefined, previewOpen: boolean): string | null;
78
84
 
79
- export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readThemePreviewToken, requireSession, resolveRootStoreRef, serverConfig };
85
+ export { type CustomerIdentity, type RouteContext, type RouteHandler, createAuthRoutes, createBackendProxy, externalThemeRedirectFor, hasCustomerSession, parseServerConfig, readPreviewHostSlug, readThemePreviewToken, requireSession, resolveRootStoreRef, serverConfig };
package/dist/server.js CHANGED
@@ -8,6 +8,7 @@ import { hasCustomerSession } from "./auth/session.js";
8
8
  import { parseServerConfig, serverConfig } from "./config/server.js";
9
9
  import { resolveRootStoreRef } from "./store-scope/root.js";
10
10
  import { readThemePreviewToken } from "./theme/read-preview-token.js";
11
+ import { readPreviewHostSlug } from "./theme/read-preview-host.js";
11
12
  import { externalThemeRedirectFor } from "./theme/external-storefront.js";
12
13
  export {
13
14
  createAuthRoutes,
@@ -15,6 +16,7 @@ export {
15
16
  externalThemeRedirectFor,
16
17
  hasCustomerSession,
17
18
  parseServerConfig,
19
+ readPreviewHostSlug,
18
20
  readThemePreviewToken,
19
21
  requireSession,
20
22
  resolveRootStoreRef,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,gCAAgC;","names":[]}
1
+ {"version":3,"sources":["../src/server.ts"],"sourcesContent":["// @ecomweb/storefront-kit/server: server-only handlers and helpers.\nimport \"server-only\";\n\nexport {\n createAuthRoutes,\n createBackendProxy,\n requireSession,\n} from \"./server/routes\";\nexport type {\n CustomerIdentity,\n RouteContext,\n RouteHandler,\n} from \"./server/routes\";\nexport { hasCustomerSession } from \"./auth/session\";\nexport { parseServerConfig, serverConfig } from \"./config/server\";\nexport { resolveRootStoreRef } from \"./store-scope/root\";\nexport { readThemePreviewToken } from \"./theme/read-preview-token\";\nexport { readPreviewHostSlug } from \"./theme/read-preview-host\";\nexport { externalThemeRedirectFor } from \"./theme/external-storefront\";\n"],"mappings":"AACA,OAAO;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAMP,SAAS,0BAA0B;AACnC,SAAS,mBAAmB,oBAAoB;AAChD,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AACtC,SAAS,2BAA2B;AACpC,SAAS,gCAAgC;","names":[]}
@@ -24,18 +24,21 @@ function shippingCalculationReducer(state, action) {
24
24
  case "CALCULATION_SUCCEEDED": {
25
25
  if (action.requestId !== state.requestId) return state;
26
26
  const { options } = action;
27
- const first = options.length > 0 ? options[0] : null;
27
+ const cheapest = options.reduce(
28
+ (best, option) => !best || option.amount < best.amount ? option : best,
29
+ null
30
+ );
28
31
  return {
29
32
  ...state,
30
33
  shippingOptions: options,
31
34
  hasCalculatedShipping: true,
32
35
  isCalculatingShipping: false,
33
- // Auto-select the first option. This also revalidates the
36
+ // Auto-select the cheapest option. This also revalidates the
34
37
  // selection on every successful recalculation: it is always
35
38
  // replaced with a rate_id guaranteed to belong to THIS response,
36
39
  // so a stale rate from an earlier quote can never linger.
37
- selectedShippingRate: first ? first.rate_id : null,
38
- shippingFee: first ? first.amount : 0,
40
+ selectedShippingRate: cheapest ? cheapest.rate_id : null,
41
+ shippingFee: cheapest ? cheapest.amount : 0,
39
42
  calculationFailed: false
40
43
  };
41
44
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n selectedShippingRate: number | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | { 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":[]}
1
+ {"version":3,"sources":["../../src/shipping/shipping-calculation-reducer.ts"],"sourcesContent":["import type { ShippingOption } from \"@ecomweb/sdk\";\n\n/**\n * State backing `useShippingCalculation`. Kept as one object (not five\n * separate `useState`s) so the transitions below are a single pure\n * function -- reachable from a plain vitest spec instead of only being\n * exercisable by rendering the hook.\n */\nexport interface ShippingCalculationState {\n shippingFee: number;\n isCalculatingShipping: boolean;\n hasCalculatedShipping: boolean;\n shippingOptions: ShippingOption[];\n selectedShippingRate: number | null;\n /**\n * Identifies the quote currently considered current. Bumped by RESET and\n * by CALCULATION_STARTED; a response carrying an older id is discarded.\n * Without this, a slow request issued for the PREVIOUS address could land\n * after a newer one and restore its options, its rate id, and an\n * enabled submit button.\n */\n requestId: number;\n /**\n * The last quote attempt failed. Distinct from \"not quoted yet\": submit\n * is blocked in both cases, but only this one should offer a retry.\n * Without it a transient failure left checkout disabled with no way\n * forward short of editing the address or reloading the page.\n */\n calculationFailed: boolean;\n}\n\nexport const initialShippingCalculationState: ShippingCalculationState = {\n shippingFee: 0,\n isCalculatingShipping: false,\n hasCalculatedShipping: false,\n shippingOptions: [],\n selectedShippingRate: null,\n requestId: 0,\n calculationFailed: false,\n};\n\nexport type ShippingCalculationAction =\n /**\n * The address or cart changed. Dispatched synchronously, before the\n * caller's debounce timer even starts -- this is what guarantees a rate\n * id from the PREVIOUS quote can never survive to be submitted against\n * the NEW address: between an input change and the next quote landing,\n * there is no selected rate at all, only ever a stale one or a fresh\n * one. Also covers the \"address/cart incomplete\" early-out.\n */\n | { type: \"RESET\" }\n | { type: \"CALCULATION_STARTED\" }\n | {\n type: \"CALCULATION_SUCCEEDED\";\n options: ShippingOption[];\n requestId: number;\n }\n | { type: \"CALCULATION_FAILED\"; requestId: number }\n /** The shopper picked a specific option out of the current quote. */\n | { type: \"RATE_SELECTED\"; rateId: number };\n\nexport function shippingCalculationReducer(\n state: ShippingCalculationState,\n action: ShippingCalculationAction\n): ShippingCalculationState {\n switch (action.type) {\n case \"RESET\":\n // Keep counting up: a response from before the reset must still be\n // recognisable as stale.\n return {\n ...initialShippingCalculationState,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_STARTED\":\n return {\n ...state,\n isCalculatingShipping: true,\n calculationFailed: false,\n requestId: state.requestId + 1,\n };\n\n case \"CALCULATION_SUCCEEDED\": {\n if (action.requestId !== state.requestId) return state;\n const { options } = action;\n // The cheapest option (the API's order breaks ties), as shoppers\n // expect: a free rate is never passed over for a paid one.\n const cheapest = options.reduce<(typeof options)[number] | null>(\n (best, option) =>\n !best || option.amount < best.amount ? option : best,\n null\n );\n return {\n ...state,\n shippingOptions: options,\n hasCalculatedShipping: true,\n isCalculatingShipping: false,\n // Auto-select the cheapest option. This also revalidates the\n // selection on every successful recalculation: it is always\n // replaced with a rate_id guaranteed to belong to THIS response,\n // so a stale rate from an earlier quote can never linger.\n selectedShippingRate: cheapest ? cheapest.rate_id : null,\n shippingFee: cheapest ? cheapest.amount : 0,\n calculationFailed: false,\n };\n }\n\n case \"CALCULATION_FAILED\":\n if (action.requestId !== state.requestId) return state;\n return {\n ...state,\n shippingFee: 0,\n shippingOptions: [],\n selectedShippingRate: null,\n hasCalculatedShipping: false,\n isCalculatingShipping: false,\n calculationFailed: true,\n };\n\n case \"RATE_SELECTED\": {\n const option = state.shippingOptions.find(\n opt => opt.rate_id === action.rateId\n );\n return {\n ...state,\n selectedShippingRate: action.rateId,\n // Preserves the previous fee if the id doesn't match a known\n // option -- shouldn't happen in practice (the UI only ever\n // dispatches a rate_id it just rendered from shippingOptions),\n // kept explicit rather than silently coercing the fee to 0.\n shippingFee: option ? option.amount : state.shippingFee,\n };\n }\n\n default:\n return state;\n }\n}\n"],"mappings":"AA+BO,MAAM,kCAA4D;AAAA,EACvE,aAAa;AAAA,EACb,uBAAuB;AAAA,EACvB,uBAAuB;AAAA,EACvB,iBAAiB,CAAC;AAAA,EAClB,sBAAsB;AAAA,EACtB,WAAW;AAAA,EACX,mBAAmB;AACrB;AAsBO,SAAS,2BACd,OACA,QAC0B;AAC1B,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AAGH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,uBAAuB;AAAA,QACvB,mBAAmB;AAAA,QACnB,WAAW,MAAM,YAAY;AAAA,MAC/B;AAAA,IAEF,KAAK,yBAAyB;AAC5B,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,YAAM,EAAE,QAAQ,IAAI;AAGpB,YAAM,WAAW,QAAQ;AAAA,QACvB,CAAC,MAAM,WACL,CAAC,QAAQ,OAAO,SAAS,KAAK,SAAS,SAAS;AAAA,QAClD;AAAA,MACF;AACA,aAAO;AAAA,QACL,GAAG;AAAA,QACH,iBAAiB;AAAA,QACjB,uBAAuB;AAAA,QACvB,uBAAuB;AAAA;AAAA;AAAA;AAAA;AAAA,QAKvB,sBAAsB,WAAW,SAAS,UAAU;AAAA,QACpD,aAAa,WAAW,SAAS,SAAS;AAAA,QAC1C,mBAAmB;AAAA,MACrB;AAAA,IACF;AAAA,IAEA,KAAK;AACH,UAAI,OAAO,cAAc,MAAM,UAAW,QAAO;AACjD,aAAO;AAAA,QACL,GAAG;AAAA,QACH,aAAa;AAAA,QACb,iBAAiB,CAAC;AAAA,QAClB,sBAAsB;AAAA,QAC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