@ecomweb/storefront-kit 0.10.0 → 0.12.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 (51) hide show
  1. package/README.md +57 -2
  2. package/dist/api/client.js +32 -1
  3. package/dist/api/client.js.map +1 -1
  4. package/dist/api/proxy.js +29 -4
  5. package/dist/api/proxy.js.map +1 -1
  6. package/dist/api/store-preview-header.js +42 -0
  7. package/dist/api/store-preview-header.js.map +1 -0
  8. package/dist/auth/error-copy.js +7 -1
  9. package/dist/auth/error-copy.js.map +1 -1
  10. package/dist/auth/session-refresh.js +2 -0
  11. package/dist/auth/session-refresh.js.map +1 -1
  12. package/dist/cart/server-context.js +26 -0
  13. package/dist/cart/server-context.js.map +1 -1
  14. package/dist/checkout/use-checkout.js +10 -1
  15. package/dist/checkout/use-checkout.js.map +1 -1
  16. package/dist/index.d.ts +111 -11
  17. package/dist/index.js +22 -0
  18. package/dist/index.js.map +1 -1
  19. package/dist/metafields/rich-text.js.map +1 -1
  20. package/dist/middleware/create-storefront-middleware.js +78 -18
  21. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  22. package/dist/middleware.d.ts +5 -2
  23. package/dist/orders/bank-transfer.js +58 -0
  24. package/dist/orders/bank-transfer.js.map +1 -0
  25. package/dist/orders/use-order-status.js +3 -28
  26. package/dist/orders/use-order-status.js.map +1 -1
  27. package/dist/provider.js +22 -0
  28. package/dist/provider.js.map +1 -1
  29. package/dist/redirects/lookup-redirect.js +2 -1
  30. package/dist/redirects/lookup-redirect.js.map +1 -1
  31. package/dist/server.d.ts +20 -1
  32. package/dist/server.js +4 -0
  33. package/dist/server.js.map +1 -1
  34. package/dist/stores/cached.js.map +1 -1
  35. package/dist/stores/get-store-by-host.js +35 -8
  36. package/dist/stores/get-store-by-host.js.map +1 -1
  37. package/dist/stores/metadata.js +17 -0
  38. package/dist/stores/metadata.js.map +1 -1
  39. package/dist/stores/read-store-preview-token.js +10 -0
  40. package/dist/stores/read-store-preview-token.js.map +1 -0
  41. package/dist/stores/resolve-coming-soon.js +30 -0
  42. package/dist/stores/resolve-coming-soon.js.map +1 -0
  43. package/dist/stores/store-coming-soon.js +21 -0
  44. package/dist/stores/store-coming-soon.js.map +1 -0
  45. package/dist/stores/store-preview-cookie.js +64 -0
  46. package/dist/stores/store-preview-cookie.js.map +1 -0
  47. package/dist/stores/store-preview-guard.js +12 -0
  48. package/dist/stores/store-preview-guard.js.map +1 -0
  49. package/dist/stores/store-subdomain.js +10 -5
  50. package/dist/stores/store-subdomain.js.map +1 -1
  51. package/package.json +2 -2
@@ -3,7 +3,8 @@ import { REQUEST_PATH_HEADER } from "../request/request-path.js";
3
3
  import {
4
4
  applyThemePreview,
5
5
  hasThemePreview,
6
- THEME_PREVIEW_PARAM
6
+ THEME_PREVIEW_PARAM,
7
+ themePreviewCookieName
7
8
  } from "../theme/preview-cookie.js";
8
9
  import {
9
10
  externalStorefrontUrl,
@@ -19,6 +20,13 @@ import { publicConfig } from "../config/public.js";
19
20
  import { lookupRedirect } from "../redirects/lookup-redirect.js";
20
21
  import { multiTenantStorePath } from "../store-scope/index.js";
21
22
  import { getStoreByHost } from "../stores/get-store-by-host.js";
23
+ import { STORE_COMING_SOON_REDIRECT_PATH } from "../stores/store-coming-soon.js";
24
+ import {
25
+ applyStorePreview,
26
+ STORE_PREVIEW_PATH,
27
+ STORE_PREVIEW_TOKEN_HEADER,
28
+ storePreviewCookieName
29
+ } from "../stores/store-preview-cookie.js";
22
30
  import { getStoreSubdomain } from "../stores/store-subdomain.js";
23
31
  import { recordStoreRequest } from "../stores/store-traffic.js";
24
32
  import {
@@ -36,6 +44,7 @@ const METADATA_FILES = [
36
44
  ];
37
45
  const EXTERNAL_METADATA_FILES = ["/robots.txt", "/sitemap.xml"];
38
46
  const DOMAIN_NOT_CONNECTED_PATH = "/domain-not-connected";
47
+ const CUSTOM_DOMAIN_REDIRECT_CACHE = "public, max-age=3600";
39
48
  function externalThemeResponse(req, host, storeRef, externalUrl) {
40
49
  if (!externalUrl) return null;
41
50
  if (req.nextUrl.searchParams.has(THEME_PREVIEW_PARAM) || hasThemePreview(req, authCookiePath(storeRef, true)))
@@ -54,13 +63,25 @@ function externalThemeResponse(req, host, storeRef, externalUrl) {
54
63
  const url = req.nextUrl.clone();
55
64
  url.pathname = DOMAIN_NOT_CONNECTED_PATH;
56
65
  url.search = "";
57
- const res = NextResponse.rewrite(url);
66
+ const res = NextResponse.rewrite(url, withoutInternalHeaders(req));
58
67
  res.headers.set("x-robots-tag", "noindex");
59
68
  return res;
60
69
  }
61
70
  const safe = req.method === "GET" || req.method === "HEAD";
62
71
  return NextResponse.redirect(target, { status: safe ? 302 : 307 });
63
72
  }
73
+ function withoutInternalHeaders(req) {
74
+ const headers = new Headers(req.headers);
75
+ headers.delete(THEME_PREVIEW_HOST_HEADER);
76
+ headers.delete(STORE_PREVIEW_TOKEN_HEADER);
77
+ return { request: { headers } };
78
+ }
79
+ function hasStorePreview(req, cookiePath) {
80
+ return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;
81
+ }
82
+ function hostLookupPreviewToken(req) {
83
+ return req.cookies.get(storePreviewCookieName("/"))?.value || req.cookies.get(themePreviewCookieName("/"))?.value || null;
84
+ }
64
85
  function storeRefFromPath(pathname) {
65
86
  const match = /^\/store\/([^/]+)/.exec(pathname);
66
87
  if (!match) return null;
@@ -70,10 +91,19 @@ function storeRefFromPath(pathname) {
70
91
  return match[1];
71
92
  }
72
93
  }
94
+ function redirectDestinationUrl(req, destination, pathPrefix = "") {
95
+ const url = publicNextUrl(req);
96
+ const parsed = new URL(destination, "http://destination.invalid");
97
+ url.pathname = `${pathPrefix}${parsed.pathname}`;
98
+ if (parsed.search) url.search = parsed.search;
99
+ if (parsed.hash) url.hash = parsed.hash;
100
+ return url;
101
+ }
73
102
  function buildRedirectResponse(req, redirect, pathPrefix = "") {
74
- const redirectUrl = publicNextUrl(req);
75
- redirectUrl.pathname = `${pathPrefix}${redirect.destination_path}`;
76
- return NextResponse.redirect(redirectUrl, { status: redirect.redirect_type });
103
+ return NextResponse.redirect(
104
+ redirectDestinationUrl(req, redirect.destination_path, pathPrefix),
105
+ { status: redirect.redirect_type }
106
+ );
77
107
  }
78
108
  async function apexStoreResponse(req, storeRef, platformDomain) {
79
109
  let subdomain = null;
@@ -86,7 +116,7 @@ async function apexStoreResponse(req, storeRef, platformDomain) {
86
116
  const url = req.nextUrl.clone();
87
117
  url.pathname = "/404";
88
118
  url.search = "";
89
- return NextResponse.rewrite(url);
119
+ return NextResponse.rewrite(url, withoutInternalHeaders(req));
90
120
  }
91
121
  const prefix = multiTenantStorePath(storeRef);
92
122
  const pathname = req.nextUrl.pathname;
@@ -102,7 +132,7 @@ async function multiTenant(req) {
102
132
  const pathname = req.nextUrl.pathname;
103
133
  const isMetadataFile = METADATA_FILES.includes(pathname);
104
134
  if (isMetadataFile && !EXTERNAL_METADATA_FILES.includes(pathname)) {
105
- return NextResponse.next();
135
+ return NextResponse.next(withoutInternalHeaders(req));
106
136
  }
107
137
  const platformDomain = publicConfig().platformDomainSuffix ?? "ecomsite.app";
108
138
  const hostIdentifiesStore = !host.includes("localhost") && !host.includes("127.0.0.1") && host !== platformDomain && host !== `www.${platformDomain}`;
@@ -112,19 +142,28 @@ async function multiTenant(req) {
112
142
  if (apexStoreRef)
113
143
  return apexStoreResponse(req, apexStoreRef, platformDomain);
114
144
  }
145
+ if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {
146
+ return applyStorePreview(req, "/", "/");
147
+ }
115
148
  let hostStoreRef = null;
116
149
  let hostResolved = false;
117
150
  let hostStoreSuspended = false;
151
+ let hostStoreComingSoon = false;
118
152
  let previewSlug = null;
119
- if (isMetadataFile && !hostIdentifiesStore) return NextResponse.next();
153
+ let storePreviewToken = null;
154
+ if (isMetadataFile && !hostIdentifiesStore)
155
+ return NextResponse.next(withoutInternalHeaders(req));
120
156
  if (hostIdentifiesStore) {
121
157
  try {
122
- const lookup = await getStoreByHost(host);
158
+ const previewToken = hostLookupPreviewToken(req);
159
+ const lookup = previewToken ? await getStoreByHost(host, { previewToken }) : await getStoreByHost(host);
123
160
  const { storeRef: storeRef2, domain, isSubDomain, suspended, externalUrl } = lookup;
124
161
  hostResolved = true;
125
162
  hostStoreRef = storeRef2 || null;
126
163
  hostStoreSuspended = suspended;
164
+ hostStoreComingSoon = !storeRef2 && !!lookup.comingSoon;
127
165
  previewSlug = storeRef2 ? lookup.previewSlug : null;
166
+ storePreviewToken = previewSlug ? lookup.storePreviewToken || null : null;
128
167
  if (previewSlug && isMetadataFile) {
129
168
  return pathname === "/robots.txt" ? new NextResponse(PREVIEW_HOST_ROBOTS, {
130
169
  headers: { "content-type": "text/plain" }
@@ -139,14 +178,16 @@ async function multiTenant(req) {
139
178
  );
140
179
  if (external) return external;
141
180
  }
142
- if (isMetadataFile) return NextResponse.next();
181
+ if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));
143
182
  if (storeRef2) {
144
183
  if (isSubDomain && domain && domain !== host && !previewSlug) {
145
184
  const url = publicNextUrl(req);
146
185
  url.hostname = domain;
147
186
  url.protocol = "https:";
148
187
  url.port = "";
149
- return NextResponse.redirect(url, { status: 301 });
188
+ const response2 = NextResponse.redirect(url, { status: 301 });
189
+ response2.headers.set("Cache-Control", CUSTOM_DOMAIN_REDIRECT_CACHE);
190
+ return response2;
150
191
  }
151
192
  if (!pathname.startsWith(multiTenantStorePath(storeRef2))) {
152
193
  const redirect = await lookupRedirect(storeRef2, pathname);
@@ -157,17 +198,24 @@ async function multiTenant(req) {
157
198
  }
158
199
  } catch (error) {
159
200
  console.debug("Middleware error:", error);
160
- if (isMetadataFile) return NextResponse.next();
201
+ if (isMetadataFile) return NextResponse.next(withoutInternalHeaders(req));
161
202
  hostResolved = false;
162
203
  hostStoreRef = null;
163
204
  }
164
205
  }
165
206
  const storeRef = hostStoreRef ?? storeRefFromPath(pathname);
166
207
  if (storeRef) recordStoreRequest(storeRef);
208
+ if (hostStoreComingSoon) {
209
+ const preview = applyThemePreview(req, "/");
210
+ if (preview) return preview;
211
+ }
167
212
  const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;
168
213
  if (storeRef && cookiePath) {
169
214
  const preview = applyThemePreview(req, cookiePath);
170
215
  if (preview) return preview;
216
+ if (!hostIdentifiesStore && pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)) {
217
+ return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));
218
+ }
171
219
  }
172
220
  if (!hostStoreRef && storeRef) {
173
221
  const prefix = multiTenantStorePath(storeRef);
@@ -195,6 +243,8 @@ async function multiTenant(req) {
195
243
  `${req.nextUrl.pathname}${req.nextUrl.search}`
196
244
  );
197
245
  if (previewSlug) downstream.set(THEME_PREVIEW_HOST_HEADER, previewSlug);
246
+ if (previewSlug && storePreviewToken)
247
+ downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);
198
248
  const init = { request: { headers: downstream } };
199
249
  let response;
200
250
  if (hostStoreRef) {
@@ -209,6 +259,11 @@ async function multiTenant(req) {
209
259
  const url = req.nextUrl.clone();
210
260
  url.pathname = "/store-suspended";
211
261
  response = NextResponse.rewrite(url, init);
262
+ } else if (hostStoreComingSoon) {
263
+ const url = req.nextUrl.clone();
264
+ url.pathname = STORE_COMING_SOON_REDIRECT_PATH;
265
+ response = NextResponse.rewrite(url, init);
266
+ response.headers.set("x-robots-tag", "noindex");
212
267
  } else if (hostResolved) {
213
268
  console.debug("Store not found for host:", host);
214
269
  const url = req.nextUrl.clone();
@@ -217,7 +272,8 @@ async function multiTenant(req) {
217
272
  } else {
218
273
  response = NextResponse.next(init);
219
274
  }
220
- if (previewSlug || cookiePath && hasThemePreview(req, cookiePath)) {
275
+ const storePreviewPath = hostIdentifiesStore ? "/" : cookiePath;
276
+ if (previewSlug || cookiePath && hasThemePreview(req, cookiePath) || storePreviewPath && hasStorePreview(req, storePreviewPath)) {
221
277
  response.headers.set("x-robots-tag", "noindex");
222
278
  }
223
279
  if (rotated && storeRef && cookiePath) {
@@ -227,17 +283,21 @@ async function multiTenant(req) {
227
283
  }
228
284
  async function singleStore(req) {
229
285
  const pathname = req.nextUrl.pathname;
230
- if (METADATA_FILES.includes(pathname)) return NextResponse.next();
286
+ if (METADATA_FILES.includes(pathname))
287
+ return NextResponse.next(withoutInternalHeaders(req));
231
288
  const storeRef = publicConfig().storeRef;
232
289
  const cookiePath = authCookiePath(storeRef, true);
290
+ if (pathname === STORE_PREVIEW_PATH)
291
+ return applyStorePreview(req, cookiePath, "/");
233
292
  const preview = applyThemePreview(req, cookiePath);
234
293
  if (preview) return preview;
235
294
  try {
236
295
  const redirect = await lookupRedirect(storeRef, pathname);
237
296
  if (redirect) {
238
- const url = publicNextUrl(req);
239
- url.pathname = redirect.destination_path;
240
- return NextResponse.redirect(url, { status: redirect.redirect_type });
297
+ return NextResponse.redirect(
298
+ redirectDestinationUrl(req, redirect.destination_path),
299
+ { status: redirect.redirect_type }
300
+ );
241
301
  }
242
302
  } catch (error) {
243
303
  console.debug("Redirect lookup error:", error);
@@ -248,7 +308,7 @@ async function singleStore(req) {
248
308
  headers: downstreamRequestHeaders(req, true, storeRef, rotated)
249
309
  }
250
310
  });
251
- if (hasThemePreview(req, cookiePath))
311
+ if (hasThemePreview(req, cookiePath) || hasStorePreview(req, cookiePath))
252
312
  response.headers.set("x-robots-tag", "noindex");
253
313
  if (rotated) {
254
314
  writeAuthCookies(response, storeRef, rotated, cookiePath);
@@ -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\";\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).*)\",\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;AAC/B,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAGP,MAAM,iBAAiB;AAAA,EACrB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,E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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
+ {"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 themePreviewCookieName,\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 { STORE_COMING_SOON_REDIRECT_PATH } from \"../stores/store-coming-soon\";\nimport {\n applyStorePreview,\n STORE_PREVIEW_PATH,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewCookieName,\n} from \"../stores/store-preview-cookie\";\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 * Cache-Control on the subdomain → custom domain 301. An hour keeps the 301\n * for search engines and caps how long browsers follow it after the merchant\n * removes the domain.\n */\nconst CUSTOM_DOMAIN_REDIRECT_CACHE = \"public, max-age=3600\";\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, withoutInternalHeaders(req));\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 init for a response that lets the request through without the full\n * downstream headers (metadata files, the \"domain not connected\" and apex\n * 404 rewrites): the client's headers minus the middleware's internal ones.\n * With it, every request the matcher covers reaches the app with no client\n * copy of them, so a server-side reader can trust them there.\n */\nfunction withoutInternalHeaders(req: NextRequest): {\n request: { headers: Headers };\n} {\n const headers = new Headers(req.headers);\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n return { request: { headers } };\n}\n\n/** True while the store preview cookie at `cookiePath` holds a token. */\nfunction hasStorePreview(req: NextRequest, cookiePath: string): boolean {\n return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;\n}\n\n/**\n * The preview token for the host lookup on a store host: the store preview\n * cookie, else the theme preview cookie (`?preview_theme=` on the store's own\n * host), both at `/`. Read from the cookies only, never through\n * `storePreviewTokenFrom`: that trusts `STORE_PREVIEW_TOKEN_HEADER`, and on\n * the middleware's incoming request that header is whatever the client sent.\n */\nfunction hostLookupPreviewToken(req: NextRequest): string | null {\n return (\n req.cookies.get(storePreviewCookieName(\"/\"))?.value ||\n req.cookies.get(themePreviewCookieName(\"/\"))?.value ||\n null\n );\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 * Where a stored redirect sends this request, on this request's own host.\n *\n * The destination is parsed as a URL rather than assigned to `pathname`,\n * which would percent-encode its `?` and lose the query. A destination with\n * a query (or fragment) keeps its own; one without carries the request's\n * query over, as before. Only the destination's path, query and fragment are\n * used, so the redirect never leaves the store's host.\n */\nfunction redirectDestinationUrl(\n req: NextRequest,\n destination: string,\n pathPrefix = \"\"\n) {\n const url = publicNextUrl(req);\n const parsed = new URL(destination, \"http://destination.invalid\");\n url.pathname = `${pathPrefix}${parsed.pathname}`;\n if (parsed.search) url.search = parsed.search;\n if (parsed.hash) url.hash = parsed.hash;\n return url;\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 return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path, pathPrefix),\n { status: redirect.redirect_type }\n );\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, withoutInternalHeaders(req));\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(withoutInternalHeaders(req));\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 // The dashboard's preview link on the store's own host. Before the lookup:\n // a coming soon store's host resolves to nothing until the cookie is set.\n if (hostIdentifiesStore && pathname === STORE_PREVIEW_PATH) {\n return applyStorePreview(req, \"/\", \"/\");\n }\n\n let hostStoreRef: string | null = null;\n let hostResolved = false;\n\n let hostStoreSuspended = false;\n let hostStoreComingSoon = false;\n // A theme's preview host (theme preview hosts): the theme's slug.\n let previewSlug: string | null = null;\n // A preview host's store preview token for a coming soon store (lookup).\n let storePreviewToken: string | null = null;\n\n if (isMetadataFile && !hostIdentifiesStore)\n return NextResponse.next(withoutInternalHeaders(req));\n\n if (hostIdentifiesStore) {\n try {\n // Without a token, the plain call: its answer is cached for the host.\n const previewToken = hostLookupPreviewToken(req);\n const lookup = previewToken\n ? await getStoreByHost(host, { previewToken })\n : await getStoreByHost(host);\n const { storeRef, domain, isSubDomain, suspended, externalUrl } = lookup;\n hostResolved = true;\n hostStoreRef = storeRef || null;\n hostStoreSuspended = suspended;\n hostStoreComingSoon = !storeRef && !!lookup.comingSoon;\n previewSlug = storeRef ? lookup.previewSlug : null;\n storePreviewToken = previewSlug ? lookup.storePreviewToken || null : 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(withoutInternalHeaders(req));\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 const response = NextResponse.redirect(url, { status: 301 });\n // Browsers keep an uncached 301 forever: if the merchant removes a\n // broken domain, shoppers would never come back to the subdomain.\n response.headers.set(\"Cache-Control\", CUSTOM_DOMAIN_REDIRECT_CACHE);\n return response;\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(withoutInternalHeaders(req));\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). A coming soon store's own host resolves\n // no store until a preview token comes with the lookup, so there the link\n // becomes the host's `/` cookie, the lookup's fallback token\n // (hostLookupPreviewToken).\n if (hostStoreComingSoon) {\n const preview = applyThemePreview(req, \"/\");\n if (preview) return preview;\n }\n const cookiePath = storeRef ? authCookiePath(storeRef, !!hostStoreRef) : null;\n if (storeRef && cookiePath) {\n const preview = applyThemePreview(req, cookiePath);\n if (preview) return preview;\n // The store preview link on the shared path-based host (localhost; the\n // apex already sent /store/<ref>/… to the store's subdomain above). Not\n // on a store host, even one that resolved no store: it takes `/preview`.\n if (\n !hostIdentifiesStore &&\n pathname === multiTenantStorePath(storeRef, STORE_PREVIEW_PATH)\n ) {\n return applyStorePreview(req, cookiePath, multiTenantStorePath(storeRef));\n }\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 // Set after downstreamRequestHeaders deleted any copy the client sent. On\n // every request to the preview host, the backend proxy's included.\n if (previewSlug && storePreviewToken)\n downstream.set(STORE_PREVIEW_TOKEN_HEADER, storePreviewToken);\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 (hostStoreComingSoon) {\n // The merchant has not opened the store, and the request carried no\n // valid preview token (an expired one lands here too). Like the\n // suspended branch, the 403 carries no ref, so a platform-level page.\n // Known limitation: on the shared path-based host (localhost) nothing\n // routes here; a store that turns coming soon mid-session sends the\n // browser to /coming-soon, which resolves no store there and 404s, as\n // the apex's /store/<ref> already does for these stores.\n const url = req.nextUrl.clone();\n url.pathname = STORE_COMING_SOON_REDIRECT_PATH;\n response = NextResponse.rewrite(url, init);\n response.headers.set(\"x-robots-tag\", \"noindex\");\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 // A store preview cookie lives at `/` on a store host, even when the host\n // resolved no store (coming soon), else at the store's path.\n const storePreviewPath = hostIdentifiesStore ? \"/\" : cookiePath;\n if (\n previewSlug ||\n (cookiePath && hasThemePreview(req, cookiePath)) ||\n (storePreviewPath && hasStorePreview(req, storePreviewPath))\n ) {\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))\n return NextResponse.next(withoutInternalHeaders(req));\n\n const storeRef = publicConfig().storeRef as string;\n\n const cookiePath = authCookiePath(storeRef, true);\n if (pathname === STORE_PREVIEW_PATH)\n return applyStorePreview(req, cookiePath, \"/\");\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 return NextResponse.redirect(\n redirectDestinationUrl(req, redirect.destination_path),\n { status: redirect.redirect_type }\n );\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) || hasStorePreview(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, coming soon stores (rewritten to /coming-soon, noindex),\n * redirects, session refresh. The store preview link (`/preview?token=`\n * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a\n * cookie before the lookup, and the lookup carries that token.\n * - single: the `/preview?token=` link, redirects and session refresh.\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,EACA;AA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,IAAI,gBAAgB,SAAS;AAChD,MAAI,SAAS;AACX,qBAAiB,UAAU,UAAU,SAAS,UAAU;AAAA,EAC1D;AACA,SAAO;AACT;AAYO,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","response"]}
@@ -6,8 +6,11 @@ import 'zod';
6
6
  /**
7
7
  * The storefront's proxy.ts (Next middleware).
8
8
  * - multi: host → store lookup, rewrites to /store/<ref>, suspended and
9
- * unknown stores, redirects, session refresh.
10
- * - single: redirects and session refresh only.
9
+ * unknown stores, coming soon stores (rewritten to /coming-soon, noindex),
10
+ * redirects, session refresh. The store preview link (`/preview?token=`
11
+ * on a store host, `/store/<ref>/preview?token=` on localhost) becomes a
12
+ * cookie before the lookup, and the lookup carries that token.
13
+ * - single: the `/preview?token=` link, redirects and session refresh.
11
14
  * Without `mode`, the configured mode (ECOMWEB_MODE) decides per request.
12
15
  */
13
16
  declare function createStorefrontMiddleware(opts?: {
@@ -0,0 +1,58 @@
1
+ "use client";
2
+ import { useEffect, useState } from "react";
3
+ import { publicApiClient } from "../api/client.js";
4
+ import { unwrap } from "../api/response.js";
5
+ import { useStoreId } from "../store/store-context.js";
6
+ function shouldShowBankTransferDetails(order) {
7
+ if (!order) return false;
8
+ return order.payment_method === "bank_transfer" && order.payment_status === "pending" && order.order_status !== "cancelled";
9
+ }
10
+ function pickBankTransfer(methods) {
11
+ const list = Array.isArray(methods) ? methods : [];
12
+ const transfer = list.find((m) => m?.payment_method === "bank_transfer");
13
+ return {
14
+ accounts: Array.isArray(transfer?.bank_accounts) ? transfer.bank_accounts : [],
15
+ // transfer_instruction, not description: description is the
16
+ // choose-a-method text shown at checkout.
17
+ note: transfer?.transfer_instruction || null
18
+ };
19
+ }
20
+ function useBankTransferDetails(enabled) {
21
+ const storeRef = useStoreId();
22
+ const [accounts, setAccounts] = useState([]);
23
+ const [note, setNote] = useState(null);
24
+ const [isLoading, setIsLoading] = useState(false);
25
+ useEffect(() => {
26
+ if (!enabled || !storeRef) return;
27
+ let cancelled = false;
28
+ setIsLoading(true);
29
+ (async () => {
30
+ try {
31
+ const res = await publicApiClient.get(
32
+ `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`
33
+ );
34
+ const picked = pickBankTransfer(unwrap(res));
35
+ if (cancelled) return;
36
+ setAccounts(picked.accounts);
37
+ setNote(picked.note);
38
+ } catch {
39
+ if (!cancelled) {
40
+ setAccounts([]);
41
+ setNote(null);
42
+ }
43
+ } finally {
44
+ if (!cancelled) setIsLoading(false);
45
+ }
46
+ })();
47
+ return () => {
48
+ cancelled = true;
49
+ };
50
+ }, [enabled, storeRef]);
51
+ return { accounts, note, isLoading };
52
+ }
53
+ export {
54
+ pickBankTransfer,
55
+ shouldShowBankTransferDetails,
56
+ useBankTransferDetails
57
+ };
58
+ //# sourceMappingURL=bank-transfer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/orders/bank-transfer.ts"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useState } from \"react\";\nimport { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport { useStoreId } from \"../store/store-context\";\n\n/** The bank_transfer slice of the public payment-methods projection. */\nexport interface BankAccountView {\n id: number;\n bank_name: string;\n bank_code: string;\n account_number: string;\n account_holder: string;\n}\n\ninterface PublicPaymentMethod {\n payment_method: string;\n transfer_instruction?: string | null;\n bank_accounts?: BankAccountView[];\n}\n\n/** What a shopper needs to pay a bank transfer order. */\nexport interface BankTransferDetails {\n accounts: BankAccountView[];\n /** The merchant's transfer instruction, if they wrote one. */\n note: string | null;\n isLoading: boolean;\n}\n\n/**\n * Whether an order page should tell the shopper how to pay by transfer: a\n * bank_transfer order the merchant has not marked paid yet, and that is\n * still live. Order pages read this from the order itself, so they work for\n * any order, long after the checkout handoff has expired.\n */\nexport function shouldShowBankTransferDetails(\n order:\n | {\n payment_method?: string | null;\n payment_status?: string | null;\n order_status?: string | null;\n }\n | null\n | undefined\n): boolean {\n if (!order) return false;\n return (\n order.payment_method === \"bank_transfer\" &&\n order.payment_status === \"pending\" &&\n order.order_status !== \"cancelled\"\n );\n}\n\n/**\n * The bank_transfer method's accounts and instruction out of the public\n * payment-methods response. A store without the method, or a malformed\n * response, yields no accounts.\n */\nexport function pickBankTransfer(methods: unknown): {\n accounts: BankAccountView[];\n note: string | null;\n} {\n const list = Array.isArray(methods) ? (methods as PublicPaymentMethod[]) : [];\n const transfer = list.find(m => m?.payment_method === \"bank_transfer\");\n return {\n accounts: Array.isArray(transfer?.bank_accounts)\n ? transfer.bank_accounts\n : [],\n // transfer_instruction, not description: description is the\n // choose-a-method text shown at checkout.\n note: transfer?.transfer_instruction || null,\n };\n}\n\n/**\n * The store's bank accounts and transfer instruction, fetched from the\n * public payment-methods endpoint while `enabled`. Used by the order-success\n * page and by the order lookup and account order pages.\n */\nexport function useBankTransferDetails(enabled: boolean): BankTransferDetails {\n const storeRef = useStoreId();\n const [accounts, setAccounts] = useState<BankAccountView[]>([]);\n const [note, setNote] = useState<string | null>(null);\n const [isLoading, setIsLoading] = useState(false);\n\n useEffect(() => {\n if (!enabled || !storeRef) return;\n let cancelled = false;\n setIsLoading(true);\n (async () => {\n try {\n const res = await publicApiClient.get<PublicPaymentMethod[]>(\n `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`\n );\n const picked = pickBankTransfer(unwrap(res));\n if (cancelled) return;\n setAccounts(picked.accounts);\n setNote(picked.note);\n } catch {\n // The order exists either way; no accounts renders a \"contact the\n // shop\" fallback rather than an error.\n if (!cancelled) {\n setAccounts([]);\n setNote(null);\n }\n } finally {\n if (!cancelled) setIsLoading(false);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [enab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pC;AAAA,IACF,GAAG;AACH,WAAO,MAAM;AACX,kBAAY;AAAA,IACd;AAAA,EACF,GAAG,CAAC,SAAS,QAAQ,CAAC;AAEtB,SAAO,EAAE,UAAU,MAAM,UAAU;AACrC;","names":[]}
@@ -1,7 +1,5 @@
1
1
  "use client";
2
2
  import { useCallback, useEffect, useState } from "react";
3
- import { publicApiClient } from "../api/client.js";
4
- import { unwrap } from "../api/response.js";
5
3
  import { getPaymentState } from "../checkout/get-payment-state.js";
6
4
  import { readOrderHandoff } from "../checkout/order-handoff.js";
7
5
  import { pollPaymentState } from "../checkout/payment-state-poll.js";
@@ -11,6 +9,7 @@ import {
11
9
  } from "../checkout/success-state.js";
12
10
  import { sdk } from "../sdk.js";
13
11
  import { useStoreId } from "../store/store-context.js";
12
+ import { useBankTransferDetails } from "./bank-transfer.js";
14
13
  const CANCELLED = new Error("order status: unmounted");
15
14
  const timeoutWait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
16
15
  function useOrderStatus({
@@ -24,37 +23,13 @@ function useOrderStatus({
24
23
  () => resolveInitialState(orderCode, null)
25
24
  );
26
25
  const [isPolling, setIsPolling] = useState(false);
27
- const [bankAccounts, setBankAccounts] = useState([]);
28
- const [transferNote, setTransferNote] = useState(null);
29
26
  useEffect(() => {
30
27
  const stored = readOrderHandoff(orderCode);
31
28
  setHandoff(stored);
32
29
  setState(resolveInitialState(orderCode, stored));
33
30
  setHandoffLoaded(true);
34
31
  }, [orderCode]);
35
- useEffect(() => {
36
- if (state !== "awaiting-transfer" || !storeRef) return;
37
- let cancelled = false;
38
- (async () => {
39
- try {
40
- const res = await publicApiClient.get(
41
- `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`
42
- );
43
- const methods = unwrap(res);
44
- const transfer = (Array.isArray(methods) ? methods : []).find(
45
- (m) => m.payment_method === "bank_transfer"
46
- );
47
- if (cancelled) return;
48
- setBankAccounts(transfer?.bank_accounts ?? []);
49
- setTransferNote(transfer?.transfer_instruction ?? null);
50
- } catch {
51
- if (!cancelled) setBankAccounts([]);
52
- }
53
- })();
54
- return () => {
55
- cancelled = true;
56
- };
57
- }, [state, storeRef]);
32
+ const bankTransfer = useBankTransferDetails(state === "awaiting-transfer");
58
33
  useEffect(() => {
59
34
  if (!orderCode) return;
60
35
  if (!handoffLoaded) return;
@@ -87,7 +62,7 @@ function useOrderStatus({
87
62
  return {
88
63
  handoff,
89
64
  payment: { state, isPolling },
90
- bankTransfer: { accounts: bankAccounts, note: transferNote }
65
+ bankTransfer: { accounts: bankTransfer.accounts, note: bankTransfer.note }
91
66
  };
92
67
  }
93
68
  function useOrderLookup({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/use-order-status.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { OrderWithItems } from \"@ecomweb/sdk\";\nimport { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport { getPaymentState } from \"../checkout/get-payment-state\";\nimport { readOrderHandoff, type OrderHandoff } from \"../checkout/order-handoff\";\nimport { pollPaymentState } from \"../checkout/payment-state-poll\";\nimport {\n resolveInitialState,\n shouldPollForConfirmation,\n type PaymentConfirmationState,\n} from \"../checkout/success-state\";\nimport { sdk } from \"../sdk\";\nimport { useStoreId } from \"../store/store-context\";\n\n/** The bank_transfer slice of the public payment-methods projection. */\nexport interface BankAccountView {\n id: number;\n bank_name: string;\n bank_code: string;\n account_number: string;\n account_holder: string;\n}\n\ninterface PublicPaymentMethod {\n payment_method: string;\n transfer_instruction?: string | null;\n bank_accounts?: BankAccountView[];\n}\n\nconst CANCELLED = new Error(\"order status: unmounted\");\n\nconst timeoutWait = (ms: number) =>\n new Promise<void>(resolve => setTimeout(resolve, ms));\n\n/**\n * What the shopper should be told about a just-placed order (the\n * order-success page, which is also the payment gateway's return URL).\n *\n * Arriving back from a gateway proves nothing about the payment: the\n * provider's server-to-server callback usually lands later, so a gateway\n * order polls the API until it is paid or failed. Offline orders read the\n * checkout's handoff and never poll. See checkout/success-state.ts.\n */\nexport function useOrderStatus({\n orderCode,\n wait = timeoutWait,\n}: {\n orderCode: string | null;\n /** Delay between polls; injectable for tests. */\n wait?: (ms: number) => Promise<void>;\n}) {\n const storeRef = useStoreId();\n // Read in an effect, not a useState initialiser: storage does not exist\n // during the server render, and seeding state from it would make the first\n // client render disagree with the server's.\n const [handoff, setHandoff] = useState<OrderHandoff | null>(null);\n const [handoffLoaded, setHandoffLoaded] = useState(false);\n const [state, setState] = useState<PaymentConfirmationState>(() =>\n resolveInitialState(orderCode, null)\n );\n const [isPolling, setIsPolling] = useState(false);\n const [bankAccounts, setBankAccounts] = useState<BankAccountView[]>([]);\n const [transferNote, setTransferNote] = useState<string | null>(null);\n\n useEffect(() => {\n const stored = readOrderHandoff(orderCode);\n setHandoff(stored);\n setState(resolveInitialState(orderCode, stored));\n setHandoffLoaded(true);\n }, [orderCode]);\n\n // A bank transfer order needs the merchant's accounts and transfer\n // instruction, which travel on the public payment-methods endpoint.\n useEffect(() => {\n if (state !== \"awaiting-transfer\" || !storeRef) return;\n let cancelled = false;\n (async () => {\n try {\n const res = await publicApiClient.get<PublicPaymentMethod[]>(\n `/public/stores/${encodeURIComponent(storeRef)}/payment-methods`\n );\n const methods = unwrap(res) as unknown as PublicPaymentMethod[];\n const transfer = (Array.isArray(methods) ? methods : []).find(\n m => m.payment_method === \"bank_transfer\"\n );\n if (cancelled) return;\n setBankAccounts(transfer?.bank_accounts ?? []);\n // transfer_instruction, not description: description is the\n // choose-a-method text shown at checkout.\n setTransferNote(transfer?.transfer_instruction ?? null);\n } catch {\n // The order is placed either way; no accounts renders a \"contact the\n // shop\" fallback rather than an error.\n if (!cancelled) setBankAccounts([]);\n }\n })();\n return () => {\n cancelled = true;\n };\n }, [state, storeRef]);\n\n useEffect(() => {\n if (!orderCode) return; // no gateway return in play, nothing to poll\n // Until the handoff is read every order looks like \"confirming\"; an\n // offline one would start a poll with no callback coming.\n if (!handoffLoaded) return;\n if (!shouldPollForConfirmation(state)) return;\n\n let cancelled = false;\n setIsPolling(true);\n pollPaymentState({\n poll: () => getPaymentState(storeRef, orderCode),\n // Rejecting once unmounted ends the poll loop, not just its result.\n wait: async ms => {\n if (cancelled) throw CANCELLED;\n await wait(ms);\n if (cancelled) throw CANCELLED;\n },\n }).then(\n outcome => {\n if (cancelled) return;\n // \"pending\" (attempts exhausted, or every attempt errored) is\n // \"still-confirming\", never \"failed\": only the API says failed.\n setState(\n outcome.status === \"paid\"\n ? \"paid\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : \"still-confirming\"\n );\n setIsPolling(false);\n },\n () => {}\n );\n\n return () => {\n cancelled = true;\n };\n // state is read once to decide whether to start; re-running on every\n // transition would restart the poll it just resolved.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [orderCode, storeRef, handoffLoaded]);\n\n return {\n handoff,\n payment: { state, isPolling },\n bankTransfer: { accounts: bankAccounts, note: transferNote },\n };\n}\n\n/**\n * A guest's order, looked up by its code plus the email or phone it was\n * placed with (the view-order page).\n */\nexport function useOrderLookup({\n orderCode,\n email,\n phone,\n}: {\n orderCode: string | null;\n email?: string | null;\n phone?: string | null;\n}) {\n const storeRef = useStoreId();\n const [order, setOrder] = useState<OrderWithItems | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchOrder = useCallback(async () => {\n if (!orderCode || (!email && !phone)) {\n setError(\"Thiếu thông tin cần thiết để tra cứu đơn hàng\");\n setIsLoading(false);\n return;\n }\n try {\n setIsLoading(true);\n setError(null);\n const found = await sdk.orders.lookupGuest(storeRef, {\n order_code: orderCode,\n customer_email: email || undefined,\n customer_phone: phone || undefined,\n });\n if (!found) {\n setError(\"Không tìm thấy đơn hàng với thông tin đã cung cấp\");\n return;\n }\n setOrder(found as unknown as OrderWithItems);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Error fetching order:\", err);\n setError(\"Có lỗi xảy ra khi tra cứu đơn hàng\");\n } finally {\n setIsLoading(false);\n }\n }, [storeRef, orderCode, email, phone]);\n\n useEffect(() => {\n fetchOrder();\n }, [fetchOrder]);\n\n return { order, isLoading, error, retry: fetchOrder };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,gBAAgB;AAEjD,SAAS,uBAAuB;AAChC,SAAS,cAAc;AACvB,SAAS,uBAAuB;AAChC,SAAS,wBAA2C;AACpD,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,WAAW;AACpB,SAAS,kBAAkB;AAiB3B,MAAM,YAAY,IAAI,MAAM,yBAAyB;AAErD,MAAM,cAAc,CAAC,OACnB,IAAI,QAAc,aAAW,WAAW,SAAS,EAAE,CAAC;AAW/C,SAAS,eAAe;AAAA,EAC7B;AAAA,EACA,OAAO;AACT,GAIG;AACD,QAAM,WAAW,WAAW;AAI5B,QAAM,CAAC,SAAS,UAAU,IAAI,SAA8B,IAAI;AAChE,QAAM,CAAC,eAAe,gBAAgB,IAAI,SAAS,KAAK;AACxD,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IAAmC,MAC3D,oBAAoB,WAAW,IAAI;AAAA,EACrC;AACA,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,KAAK;AAChD,QAAM,CAAC,cAAc,eAAe,IAAI,SAA4B,CAAC,CAAC;AACtE,QAAM,CAAC,cAAc,eAAe,IAAI,SAAwB,IAAI;AAEpE,YAAU,MAAM;AACd,UAAM,SAAS,iBAAiB,SAAS;AACzC,eAAW,MAAM;AACjB,aAAS,oBAAoB,WAAW,MAAM,CAAC;AAC/C,qBAAiB,IAAI;AAAA,EACvB,GAAG,CAAC,SAAS,CAAC;AAId,YAAU,MAAM;AACd,QAAI,UAAU,uBAAuB,CAAC,SAAU;AAChD,QAAI,YAAY;AAChB,KAAC,YAAY;AACX,UAAI;AACF,cAAM,MAAM,MAAM,gBAAgB;AAAA,UAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,QAChD;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C5B,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAgC,IAAI;AAC9D,QAAM,CAAC,WAAW,YAAY,IAAI,SAAS,IAAI;AAC/C,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAwB,IAAI;AAEtD,QAAM,aAAa,YAAY,YAAY;AACzC,QAAI,CAAC,aAAc,CAAC,SAAS,CAAC,OAAQ;AACpC,eAAS,6FAA+C;AACxD,mBAAa,KAAK;AAClB;AAAA,IACF;AACA,QAAI;AACF,mBAAa,IAAI;AACjB,eAAS,IAAI;AACb,YAAM,QAAQ,MAAM,IAAI,OAAO,YAAY,UAAU;AAAA,QACnD,YAAY;AAAA,QACZ,gBAAgB,SAAS;AAAA,QACzB,gBAAgB,SAAS;AAAA,MAC3B,CAAC;AACD,UAAI,CAAC,OAAO;AACV,iBAAS,gGAAmD;AAC5D;AAAA,MACF;AACA,eAAS,KAAkC;AAAA,IAC7C,SAAS,KAAK;AAEZ,cAAQ,MAAM,yBAAyB,GAAG;AAC1C,eAAS,mEAAoC;AAAA,IAC/C,UAAE;AACA,mBAAa,KAAK;AAAA,IACpB;AAAA,EACF,GAAG,CAAC,UAAU,WAAW,OAAO,KAAK,CAAC;AAEtC,YAAU,MAAM;AACd,eAAW;AAAA,EACb,GAAG,CAAC,UAAU,CAAC;AAEf,SAAO,EAAE,OAAO,WAAW,OAAO,OAAO,WAAW;AACtD;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/use-order-status.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport type { OrderWithItems } from \"@ecomweb/sdk\";\nimport { getPaymentState } from \"../checkout/get-payment-state\";\nimport { readOrderHandoff, type OrderHandoff } from \"../checkout/order-handoff\";\nimport { pollPaymentState } from \"../checkout/payment-state-poll\";\nimport {\n resolveInitialState,\n shouldPollForConfirmation,\n type PaymentConfirmationState,\n} from \"../checkout/success-state\";\nimport { sdk } from \"../sdk\";\nimport { useStoreId } from \"../store/store-context\";\nimport { useBankTransferDetails } from \"./bank-transfer\";\n\nexport type { BankAccountView } from \"./bank-transfer\";\n\nconst CANCELLED = new Error(\"order status: unmounted\");\n\nconst timeoutWait = (ms: number) =>\n new Promise<void>(resolve => setTimeout(resolve, ms));\n\n/**\n * What the shopper should be told about a just-placed order (the\n * order-success page, which is also the payment gateway's return URL).\n *\n * Arriving back from a gateway proves nothing about the payment: the\n * provider's server-to-server callback usually lands later, so a gateway\n * order polls the API until it is paid or failed. Offline orders read the\n * checkout's handoff and never poll. See checkout/success-state.ts.\n */\nexport function useOrderStatus({\n orderCode,\n wait = timeoutWait,\n}: {\n orderCode: string | null;\n /** Delay between polls; injectable for tests. */\n wait?: (ms: number) => Promise<void>;\n}) {\n const storeRef = useStoreId();\n // Read in an effect, not a useState initialiser: storage does not exist\n // during the server render, and seeding state from it would make the first\n // client render disagree with the server's.\n const [handoff, setHandoff] = useState<OrderHandoff | null>(null);\n const [handoffLoaded, setHandoffLoaded] = useState(false);\n const [state, setState] = useState<PaymentConfirmationState>(() =>\n resolveInitialState(orderCode, null)\n );\n const [isPolling, setIsPolling] = useState(false);\n\n useEffect(() => {\n const stored = readOrderHandoff(orderCode);\n setHandoff(stored);\n setState(resolveInitialState(orderCode, stored));\n setHandoffLoaded(true);\n }, [orderCode]);\n\n // A bank transfer order needs the merchant's accounts and transfer\n // instruction, which travel on the public payment-methods endpoint.\n const bankTransfer = useBankTransferDetails(state === \"awaiting-transfer\");\n\n useEffect(() => {\n if (!orderCode) return; // no gateway return in play, nothing to poll\n // Until the handoff is read every order looks like \"confirming\"; an\n // offline one would start a poll with no callback coming.\n if (!handoffLoaded) return;\n if (!shouldPollForConfirmation(state)) return;\n\n let cancelled = false;\n setIsPolling(true);\n pollPaymentState({\n poll: () => getPaymentState(storeRef, orderCode),\n // Rejecting once unmounted ends the poll loop, not just its result.\n wait: async ms => {\n if (cancelled) throw CANCELLED;\n await wait(ms);\n if (cancelled) throw CANCELLED;\n },\n }).then(\n outcome => {\n if (cancelled) return;\n // \"pending\" (attempts exhausted, or every attempt errored) is\n // \"still-confirming\", never \"failed\": only the API says failed.\n setState(\n outcome.status === \"paid\"\n ? \"paid\"\n : outcome.status === \"failed\"\n ? \"failed\"\n : \"still-confirming\"\n );\n setIsPolling(false);\n },\n () => {}\n );\n\n return () => {\n cancelled = true;\n };\n // state is read once to decide whether to start; re-running on every\n // transition would restart the poll it just resolved.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [orderCode, storeRef, handoffLoaded]);\n\n return {\n handoff,\n payment: { state, isPolling },\n bankTransfer: { accounts: bankTransfer.accounts, note: bankTransfer.note },\n };\n}\n\n/**\n * A guest's order, looked up by its code plus the email or phone it was\n * placed with (the view-order page).\n */\nexport function useOrderLookup({\n orderCode,\n email,\n phone,\n}: {\n orderCode: string | null;\n email?: string | null;\n phone?: string | null;\n}) {\n const storeRef = useStoreId();\n const [order, setOrder] = useState<OrderWithItems | null>(null);\n const [isLoading, setIsLoading] = useState(true);\n const [error, setError] = useState<string | null>(null);\n\n const fetchOrder = useCallback(async () => {\n if (!orderCode || (!email && !phone)) {\n setError(\"Thiếu thông tin cần thiết để tra cứu đơn hàng\");\n setIsLoading(false);\n return;\n }\n try {\n setIsLoading(true);\n setError(null);\n const found = await sdk.orders.lookupGuest(storeRef, {\n order_code: orderCode,\n customer_email: email || undefined,\n customer_phone: phone || undefined,\n });\n if (!found) {\n setError(\"Không tìm thấy đơn hàng với thông tin đã cung cấp\");\n return;\n }\n setOrder(found as unknown as OrderWithItems);\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error(\"Error fetching order:\", err);\n setError(\"Có lỗi xảy ra khi tra cứu đơn hàng\");\n } finally {\n setIsLoading(false);\n }\n }, [storeRef, orderCode, email, phone]);\n\n useEffect(() => {\n fetchOrder();\n }, [fetchOrder]);\n\n return { order, isLoading, error, retry: fetchOrder };\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,gBAAgB;AAEjD,SAAS,uBAAuB;AAChC,SAAS,wBAA2C;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ist/provider.js CHANGED
@@ -1,9 +1,15 @@
1
1
  "use client";
2
2
  import { jsx } from "react/jsx-runtime";
3
+ import { useEffect, useRef } from "react";
3
4
  import { AuthProvider, useAuth } from "./auth/context.js";
4
5
  import { CartProvider } from "./cart/server-context.js";
5
6
  import { NoticeProvider } from "./notices.js";
6
7
  import { StoreProvider } from "./store/store-context.js";
8
+ import {
9
+ setBrowserStorePreviewToken,
10
+ setStorePreviewRenewer
11
+ } from "./api/store-preview-header.js";
12
+ const STORE_PREVIEW_RENEW_MS = 30 * 60 * 1e3;
7
13
  function IdentityCart({
8
14
  storeRef,
9
15
  children
@@ -15,8 +21,24 @@ function StorefrontKitProvider({
15
21
  store,
16
22
  storeRef,
17
23
  onNotice,
24
+ storePreviewToken,
25
+ onStorePreviewRenew,
18
26
  children
19
27
  }) {
28
+ setBrowserStorePreviewToken(storePreviewToken ?? null);
29
+ const renewRef = useRef(onStorePreviewRenew);
30
+ renewRef.current = onStorePreviewRenew;
31
+ const renews = !!storePreviewToken && !!onStorePreviewRenew;
32
+ useEffect(() => {
33
+ if (!renews) return;
34
+ const renew = () => renewRef.current?.();
35
+ setStorePreviewRenewer(renew);
36
+ const timer = setInterval(renew, STORE_PREVIEW_RENEW_MS);
37
+ return () => {
38
+ clearInterval(timer);
39
+ setStorePreviewRenewer(null);
40
+ };
41
+ }, [renews]);
20
42
  return /* @__PURE__ */ jsx(StoreProvider, { store, children: /* @__PURE__ */ jsx(NoticeProvider, { onNotice, children: /* @__PURE__ */ jsx(AuthProvider, { children: /* @__PURE__ */ jsx(IdentityCart, { storeRef: storeRef ?? store.ref, children }) }) }) });
21
43
  }
22
44
  export {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport type { ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\n\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n children,\n}: StorefrontKitProviderProps) {\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA2BI;AAvBJ,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAW9B,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAC7B,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/provider.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect, useRef, type ReactNode } from \"react\";\nimport type { StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { AuthProvider, useAuth } from \"./auth/context\";\nimport { CartProvider } from \"./cart/server-context\";\nimport { NoticeProvider, type NoticeHandler } from \"./notices\";\nimport { StoreProvider } from \"./store/store-context\";\nimport {\n setBrowserStorePreviewToken,\n setStorePreviewRenewer,\n} from \"./api/store-preview-header\";\n\n/**\n * How often a preview host's preview token is renewed: half of its 1 h, so\n * a long editor session never sends an expired one.\n */\nconst STORE_PREVIEW_RENEW_MS = 30 * 60 * 1000;\n\nexport interface StorefrontKitProviderProps {\n store: StoreConfigurationInfo;\n /** The ref the cart is scoped to; defaults to `store.ref`. */\n storeRef?: string;\n /** Receives the kit's notices (item added, request failed, …). */\n onNotice?: NoticeHandler;\n /**\n * The store preview token the browser's kit clients send as\n * `X-Store-Preview` (`readStorePreviewToken()` on the server). The layout\n * passes it only while the store is coming soon, else null.\n *\n * Why the browser gets it: the preview cookie stays httpOnly, but without\n * the token the client-side fetches on the home, collection and product\n * pages would get the API's 403 during a preview. It is one of three\n * tokens: the store preview cookie's (the dashboard's preview link), a\n * theme preview host's (`p-<slug>`, from the host lookup), or the theme\n * preview cookie's (`?preview_theme=` on the store's own host). Each is\n * read-only (the API opens GET and HEAD only) and bound to one store.\n * Merchant scripts are off during a store preview, so they never see it.\n */\n storePreviewToken?: string | null;\n /**\n * Fetches a fresh `storePreviewToken`, such as by re-rendering the layout.\n * The app passes it only on a theme preview host, whose token lasts 1 h:\n * the layout does not re-render on client navigation, so the first\n * render's token would run out in a long editor session. While both are\n * set, the kit calls it every 30 minutes, and when a read is refused with\n * `STORE_COMING_SOON` (at most once a minute). A link preview's 24 h\n * cookie is not renewed.\n */\n onStorePreviewRenew?: () => void;\n children: ReactNode;\n}\n\nfunction IdentityCart({\n storeRef,\n children,\n}: {\n storeRef: string;\n children: ReactNode;\n}) {\n const { user } = useAuth();\n return (\n <CartProvider storeRef={storeRef} userId={user?.id}>\n {children}\n </CartProvider>\n );\n}\n\n/**\n * The kit's providers in their required order: auth reads the store, and the\n * cart reads the signed-in identity from auth.\n */\nexport function StorefrontKitProvider({\n store,\n storeRef,\n onNotice,\n storePreviewToken,\n onStorePreviewRenew,\n children,\n}: StorefrontKitProviderProps) {\n // In the render body, not an effect: React renders this before any child\n // effect runs, so the first client fetch already carries the token. A\n // render without one clears it; until then it stays set (store-preview-\n // header.ts). A no-op on the server.\n setBrowserStorePreviewToken(storePreviewToken ?? null);\n\n // The latest callback, so an app that passes a new function on every\n // render does not restart the 30 minute timer each time.\n const renewRef = useRef(onStorePreviewRenew);\n renewRef.current = onStorePreviewRenew;\n const renews = !!storePreviewToken && !!onStorePreviewRenew;\n useEffect(() => {\n if (!renews) return;\n const renew = () => renewRef.current?.();\n setStorePreviewRenewer(renew);\n const timer = setInterval(renew, STORE_PREVIEW_RENEW_MS);\n return () => {\n clearInterval(timer);\n setStorePreviewRenewer(null);\n };\n }, [renews]);\n\n return (\n <StoreProvider store={store}>\n <NoticeProvider onNotice={onNotice}>\n <AuthProvider>\n <IdentityCart storeRef={storeRef ?? store.ref}>\n {children}\n </IdentityCart>\n </AuthProvider>\n </NoticeProvider>\n </StoreProvider>\n );\n}\n"],"mappings":";AA8DI;AA5DJ,SAAS,WAAW,cAA8B;AAElD,SAAS,cAAc,eAAe;AACtC,SAAS,oBAAoB;AAC7B,SAAS,sBAA0C;AACnD,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMP,MAAM,yBAAyB,KAAK,KAAK;AAoCzC,SAAS,aAAa;AAAA,EACpB;AAAA,EACA;AACF,GAGG;AACD,QAAM,EAAE,KAAK,IAAI,QAAQ;AACzB,SACE,oBAAC,gBAAa,UAAoB,QAAQ,MAAM,IAC7C,UACH;AAEJ;AAMO,SAAS,sBAAsB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA+B;AAK7B,8BAA4B,qBAAqB,IAAI;AAIrD,QAAM,WAAW,OAAO,mBAAmB;AAC3C,WAAS,UAAU;AACnB,QAAM,SAAS,CAAC,CAAC,qBAAqB,CAAC,CAAC;AACxC,YAAU,MAAM;AACd,QAAI,CAAC,OAAQ;AACb,UAAM,QAAQ,MAAM,SAAS,UAAU;AACvC,2BAAuB,KAAK;AAC5B,UAAM,QAAQ,YAAY,OAAO,sBAAsB;AACvD,WAAO,MAAM;AACX,oBAAc,KAAK;AACnB,6BAAuB,IAAI;AAAA,IAC7B;AAAA,EACF,GAAG,CAAC,MAAM,CAAC;AAEX,SACE,oBAAC,iBAAc,OACb,8BAAC,kBAAe,UACd,8BAAC,gBACC,8BAAC,gBAAa,UAAU,YAAY,MAAM,KACvC,UACH,GACF,GACF,GACF;AAEJ;","names":[]}