@ecomweb/storefront-kit 0.12.0 → 0.13.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.
package/dist/api/proxy.js CHANGED
@@ -169,6 +169,7 @@ async function handleBackendProxy(request, storeRef, segments) {
169
169
  return response;
170
170
  }
171
171
  export {
172
- handleBackendProxy
172
+ handleBackendProxy,
173
+ storePreviewTokenFor
173
174
  };
174
175
  //# sourceMappingURL=proxy.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/proxy.ts"],"sourcesContent":["import \"server-only\";\n\nimport { NextResponse, type NextRequest } from \"next/server\";\n\nimport {\n authCookiePathFor,\n readAuthCookies,\n writeAuthCookies,\n} from \"../auth/cookies\";\nimport {\n clientIpFrom,\n FORWARDER_SECRET_HEADER,\n forwardingHeaders,\n} from \"../auth/client-ip\";\nimport { backendBaseUrl, createAuthApi, storefrontApiKey } from \"../auth/sdk\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport {\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewTokenFrom,\n} from \"../stores/store-preview-cookie\";\n\n/**\n * Same-origin server proxy for the storefront's authenticated backend calls.\n *\n * Session tokens live in httpOnly, store-scoped cookies (`lib/auth/cookies.ts`)\n * that browser JS cannot read, and the backend runs on a different origin, so a\n * direct browser->backend call carries neither cookie nor bearer token. The\n * browser therefore calls `/store/<storeRef>/api/backend/<path>` — same origin,\n * so the cookie is sent — and this handler, running on the server, attaches the\n * bearer token and the storefront API key before forwarding.\n *\n * This is the same shape as `lib/auth/route-handlers.ts`, which is why this\n * module is the third (and last) place allowed to touch auth cookies. It still\n * goes through `lib/auth/cookies.ts` rather than naming cookies itself.\n */\n\n/**\n * Never forwarded upstream:\n * - hop-by-hop headers (RFC 9110 s7.6.1) are per-connection by definition;\n * - `host`/`content-length`/`accept-encoding` are owned by `fetch`;\n * - `origin` describes the browser->proxy hop, not the proxy->backend one;\n * - `authorization` and `cookie` because the httpOnly cookie is the ONLY\n * trusted source of identity here — a browser-supplied `Authorization`\n * header must never reach the backend through this route;\n * - `x-storefront-api-key` because the server attaches its own;\n * - `x-forwarded-for` and `x-real-ip` because neither is a Fetch-forbidden\n * header name, so browser JS can set them — and the backend derives the\n * client IP from exactly those, for the auth throttle key and for API-key IP\n * allowlisting. They are dropped here and re-set below from the value the\n * platform edge gave *this* server. Block first, then set: the reverse order\n * would hand the choice back to the caller;\n * - `x-ecomweb-forwarder-secret` because it is what makes the backend trust\n * `x-forwarded-for`. Only this server attaches it, from a server-only env\n * var; a browser-supplied one must never pass through, least of all when\n * the var is unset here and nothing would overwrite it;\n * - `x-store-preview` and the middleware's internal store preview token\n * header, because the token sent upstream comes only from this request's\n * cookie or the middleware's stamp (`storePreviewTokenFor` below).\n */\nconst BLOCKED_REQUEST_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"authorization\",\n \"cookie\",\n \"x-storefront-api-key\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"cf-connecting-ip\",\n FORWARDER_SECRET_HEADER,\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n]);\n\nconst METHODS_WITH_BODY = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nfunction jsonError(status: number, message: string, code: string) {\n return NextResponse.json({ code, message }, { status });\n}\n\n/**\n * Rebuilds the upstream URL from the catch-all segments. Next has already\n * percent-decoded them, so `..` arrives literally and is rejected here; the\n * origin/prefix check afterwards is the backstop that keeps this route from\n * becoming an open forward proxy.\n */\nfunction resolveTarget(segments: string[], search: string): URL | null {\n if (segments.length === 0) return null;\n\n for (const segment of segments) {\n if (\n segment === \"\" ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\")\n ) {\n return null;\n }\n }\n\n const base = new URL(backendBaseUrl());\n const prefix = base.pathname.replace(/\\/$/, \"\");\n const target = new URL(\n `${prefix}/${segments.map(encodeURIComponent).join(\"/\")}`,\n base\n );\n\n if (target.origin !== base.origin) return null;\n if (!target.pathname.startsWith(`${prefix}/`)) return null;\n\n target.search = search;\n return target;\n}\n\n/**\n * The store preview token to send upstream as `X-Store-Preview`, or null:\n * a preview host's token the middleware stamped, else the store preview\n * cookie, else the theme preview cookie (`storePreviewTokenFrom`).\n *\n * The stamp is trusted only under `/store/<ref>/`: the middleware's matcher\n * covers that path, and every response there that reaches this route drops\n * a client's copy of the header first. Root `/api/*` (the single-store\n * proxy) is outside the matcher, so the header there is whatever the client\n * sent, and only the cookies count.\n */\nfunction storePreviewTokenFor(\n request: NextRequest,\n storeRef: string\n): string | null {\n const stamped = request.nextUrl.pathname.startsWith(\n `${multiTenantStorePath(storeRef)}/`\n );\n return storePreviewTokenFrom(\n request.cookies,\n stamped\n ? request\n : {\n headers: {\n get: name =>\n name.toLowerCase() === STORE_PREVIEW_TOKEN_HEADER\n ? null\n : request.headers.get(name),\n },\n }\n );\n}\n\nfunction forwardedHeaders(\n request: NextRequest,\n storeRef: string,\n accessToken?: string\n) {\n const headers = new Headers();\n\n request.headers.forEach((value, key) => {\n if (!BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n headers.set(\"x-storefront-api-key\", storefrontApiKey());\n\n // Set only after the blocklist has stripped whatever the browser sent.\n for (const [key, value] of Object.entries(\n forwardingHeaders(clientIpFrom(request.headers))\n )) {\n headers.set(key, value);\n }\n\n // Set only after the blocklist has dropped whatever the browser sent.\n const previewToken = storePreviewTokenFor(request, storeRef);\n if (previewToken) headers.set(STORE_PREVIEW_HEADER, previewToken);\n\n if (accessToken) headers.set(\"authorization\", `Bearer ${accessToken}`);\n\n return headers;\n}\n\ninterface UpstreamResult {\n status: number;\n body: string;\n contentType: string | null;\n}\n\nasync function callUpstream(\n request: NextRequest,\n storeRef: string,\n target: URL,\n body: string | undefined,\n accessToken?: string\n): Promise<UpstreamResult> {\n const response = await fetch(target, {\n method: request.method,\n headers: forwardedHeaders(request, storeRef, accessToken),\n body,\n cache: \"no-store\",\n redirect: \"manual\",\n });\n\n return {\n status: response.status,\n body: await response.text(),\n contentType: response.headers.get(\"content-type\"),\n };\n}\n\n/**\n * Passes the backend's status and body through untouched — callers read\n * `{ code, message }` off the body, so rewriting it would break their error\n * handling.\n */\nfunction respond(result: UpstreamResult): NextResponse {\n return new NextResponse(result.body || null, {\n status: result.status,\n headers: result.contentType\n ? { \"content-type\": result.contentType }\n : undefined,\n });\n}\n\nexport async function handleBackendProxy(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const target = resolveTarget(segments, request.nextUrl.search);\n\n if (!target) {\n return jsonError(400, \"Invalid proxy path\", \"PROXY_INVALID_PATH\");\n }\n\n // Buffered once so the 401 retry below can replay it.\n const body = METHODS_WITH_BODY.has(request.method)\n ? await request.text()\n : undefined;\n\n const tokens = readAuthCookies(\n request.cookies,\n storeRef,\n authCookiePathFor(request, storeRef)\n );\n\n let result: UpstreamResult;\n\n try {\n result = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n tokens?.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n // Anonymous callers and non-401 answers are done: public endpoints must keep\n // working through this proxy.\n if (result.status !== 401 || !tokens) return respond(result);\n\n // Exactly one refresh + retry. Never a loop.\n const refreshed = await createAuthApi(\n storeRef,\n clientIpFrom(request.headers)\n ).refresh(tokens.refresh_token);\n\n // A failed refresh does NOT clear the cookies, because \"failed\" and \"the\n // session is dead\" are not the same thing here. `SessionService.rotate()`\n // revokes the presented refresh token before issuing its replacement, so a\n // token can be rejected simply for having lost a race: `proxy.ts` refreshes\n // near-expiry tokens on every matched request, this route refreshes again on\n // a 401, and a page load fires several of both at once. Each of those reads\n // the refresh token from its own request snapshot, so whichever rotation\n // lands second presents an already-revoked token through no fault of the\n // shopper. Clearing here would log them out mid-page.\n //\n // Leaving stale cookies in place is safe: the `(protected)` layout resolves\n // the session server-side on the next navigation and redirects to /login if\n // it really is gone, and signing in overwrites them.\n if (\n !refreshed.success ||\n !refreshed.data?.access_token ||\n !refreshed.data.refresh_token\n ) {\n return respond(result);\n }\n\n let retry: UpstreamResult;\n\n try {\n retry = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n refreshed.data.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n const response = respond(retry);\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: refreshed.data.access_token,\n refresh_token: refreshed.data.refresh_token,\n },\n authCookiePathFor(request, storeRef)\n );\n\n return response;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,oBAAsC;AAE/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,eAAe,wBAAwB;AAChE,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAwCP,MAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,MAAM,oBAAoB,oBAAI,IAAI,CAAC,QAAQ,OAAO,SAAS,QAAQ,CAAC;AAEpE,SAAS,UAAU,QAAgB,SAAiB,MAAc;AAChE,SAAO,aAAa,KAAK,EAAE,MAAM,QAAQ,GAAG,EA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IACV;AAAA,EACF,QAAQ;AACN,WAAO,UAAU,KAAK,2BAA2B,sBAAsB;AAAA,EACzE;AAIA,MAAI,OAAO,WAAW,OAAO,CAAC,OAAQ,QAAO,QAAQ,MAAM;AAG3D,QAAM,YAAY,MAAM;AAAA,IACtB;AAAA,IACA,aAAa,QAAQ,OAAO;AAAA,EAC9B,EAAE,QAAQ,OAAO,aAAa;AAe9B,MACE,CAAC,UAAU,WACX,CAAC,UAAU,MAAM,gBACjB,CAAC,UAAU,KAAK,eAChB;AACA,WAAO,QAAQ,MAAM;AAAA,EACvB;AAEA,MAAI;AAEJ,MAAI;AACF,YAAQ,MAAM;AAAA,MACZ;AAAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,MACR,UAAU,KAAK;AAAA,IACjB;AAAA,EACF,QAAQ;AACN,WAAO,UAAU,KAAK,2BAA2B,sBAAsB;AAAA,EACzE;AAEA,QAAM,WAAW,QAAQ,KAAK;AAE9B;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,MACE,cAAc,UAAU,KAAK;AAAA,MAC7B,eAAe,UAAU,KAAK;AAAA,IAChC;AAAA,IACA,kBAAkB,SAAS,QAAQ;AAAA,EACrC;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/api/proxy.ts"],"sourcesContent":["import \"server-only\";\n\nimport { NextResponse, type NextRequest } from \"next/server\";\n\nimport {\n authCookiePathFor,\n readAuthCookies,\n writeAuthCookies,\n} from \"../auth/cookies\";\nimport {\n clientIpFrom,\n FORWARDER_SECRET_HEADER,\n forwardingHeaders,\n} from \"../auth/client-ip\";\nimport { backendBaseUrl, createAuthApi, storefrontApiKey } from \"../auth/sdk\";\nimport { multiTenantStorePath } from \"../store-scope\";\nimport {\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n storePreviewTokenFrom,\n} from \"../stores/store-preview-cookie\";\n\n/**\n * Same-origin server proxy for the storefront's authenticated backend calls.\n *\n * Session tokens live in httpOnly, store-scoped cookies (`lib/auth/cookies.ts`)\n * that browser JS cannot read, and the backend runs on a different origin, so a\n * direct browser->backend call carries neither cookie nor bearer token. The\n * browser therefore calls `/store/<storeRef>/api/backend/<path>` — same origin,\n * so the cookie is sent — and this handler, running on the server, attaches the\n * bearer token and the storefront API key before forwarding.\n *\n * This is the same shape as `lib/auth/route-handlers.ts`, which is why this\n * module is the third (and last) place allowed to touch auth cookies. It still\n * goes through `lib/auth/cookies.ts` rather than naming cookies itself.\n */\n\n/**\n * Never forwarded upstream:\n * - hop-by-hop headers (RFC 9110 s7.6.1) are per-connection by definition;\n * - `host`/`content-length`/`accept-encoding` are owned by `fetch`;\n * - `origin` describes the browser->proxy hop, not the proxy->backend one;\n * - `authorization` and `cookie` because the httpOnly cookie is the ONLY\n * trusted source of identity here — a browser-supplied `Authorization`\n * header must never reach the backend through this route;\n * - `x-storefront-api-key` because the server attaches its own;\n * - `x-forwarded-for` and `x-real-ip` because neither is a Fetch-forbidden\n * header name, so browser JS can set them — and the backend derives the\n * client IP from exactly those, for the auth throttle key and for API-key IP\n * allowlisting. They are dropped here and re-set below from the value the\n * platform edge gave *this* server. Block first, then set: the reverse order\n * would hand the choice back to the caller;\n * - `x-ecomweb-forwarder-secret` because it is what makes the backend trust\n * `x-forwarded-for`. Only this server attaches it, from a server-only env\n * var; a browser-supplied one must never pass through, least of all when\n * the var is unset here and nothing would overwrite it;\n * - `x-store-preview` and the middleware's internal store preview token\n * header, because the token sent upstream comes only from this request's\n * cookie or the middleware's stamp (`storePreviewTokenFor` below).\n */\nconst BLOCKED_REQUEST_HEADERS = new Set([\n \"connection\",\n \"keep-alive\",\n \"proxy-authenticate\",\n \"proxy-authorization\",\n \"te\",\n \"trailer\",\n \"transfer-encoding\",\n \"upgrade\",\n \"host\",\n \"content-length\",\n \"accept-encoding\",\n \"origin\",\n \"authorization\",\n \"cookie\",\n \"x-storefront-api-key\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"cf-connecting-ip\",\n FORWARDER_SECRET_HEADER,\n STORE_PREVIEW_HEADER,\n STORE_PREVIEW_TOKEN_HEADER,\n]);\n\nconst METHODS_WITH_BODY = new Set([\"POST\", \"PUT\", \"PATCH\", \"DELETE\"]);\n\nfunction jsonError(status: number, message: string, code: string) {\n return NextResponse.json({ code, message }, { status });\n}\n\n/**\n * Rebuilds the upstream URL from the catch-all segments. Next has already\n * percent-decoded them, so `..` arrives literally and is rejected here; the\n * origin/prefix check afterwards is the backstop that keeps this route from\n * becoming an open forward proxy.\n */\nfunction resolveTarget(segments: string[], search: string): URL | null {\n if (segments.length === 0) return null;\n\n for (const segment of segments) {\n if (\n segment === \"\" ||\n segment === \".\" ||\n segment === \"..\" ||\n segment.includes(\"/\") ||\n segment.includes(\"\\\\\")\n ) {\n return null;\n }\n }\n\n const base = new URL(backendBaseUrl());\n const prefix = base.pathname.replace(/\\/$/, \"\");\n const target = new URL(\n `${prefix}/${segments.map(encodeURIComponent).join(\"/\")}`,\n base\n );\n\n if (target.origin !== base.origin) return null;\n if (!target.pathname.startsWith(`${prefix}/`)) return null;\n\n target.search = search;\n return target;\n}\n\n/**\n * The store preview token to send upstream as `X-Store-Preview`, or null:\n * a preview host's token the middleware stamped, else the store preview\n * cookie, else the theme preview cookie (`storePreviewTokenFrom`).\n *\n * The stamp is trusted only under `/store/<ref>/`: the middleware's matcher\n * covers that path, and every response there that reaches this route drops\n * a client's copy of the header first. Root `/api/*` (the single-store\n * proxy) is outside the matcher, so the header there is whatever the client\n * sent, and only the cookies count.\n */\nexport function storePreviewTokenFor(\n request: NextRequest,\n storeRef: string\n): string | null {\n const stamped = request.nextUrl.pathname.startsWith(\n `${multiTenantStorePath(storeRef)}/`\n );\n return storePreviewTokenFrom(\n request.cookies,\n stamped\n ? request\n : {\n headers: {\n get: name =>\n name.toLowerCase() === STORE_PREVIEW_TOKEN_HEADER\n ? null\n : request.headers.get(name),\n },\n }\n );\n}\n\nfunction forwardedHeaders(\n request: NextRequest,\n storeRef: string,\n accessToken?: string\n) {\n const headers = new Headers();\n\n request.headers.forEach((value, key) => {\n if (!BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {\n headers.set(key, value);\n }\n });\n\n headers.set(\"x-storefront-api-key\", storefrontApiKey());\n\n // Set only after the blocklist has stripped whatever the browser sent.\n for (const [key, value] of Object.entries(\n forwardingHeaders(clientIpFrom(request.headers))\n )) {\n headers.set(key, value);\n }\n\n // Set only after the blocklist has dropped whatever the browser sent.\n const previewToken = storePreviewTokenFor(request, storeRef);\n if (previewToken) headers.set(STORE_PREVIEW_HEADER, previewToken);\n\n if (accessToken) headers.set(\"authorization\", `Bearer ${accessToken}`);\n\n return headers;\n}\n\ninterface UpstreamResult {\n status: number;\n body: string;\n contentType: string | null;\n}\n\nasync function callUpstream(\n request: NextRequest,\n storeRef: string,\n target: URL,\n body: string | undefined,\n accessToken?: string\n): Promise<UpstreamResult> {\n const response = await fetch(target, {\n method: request.method,\n headers: forwardedHeaders(request, storeRef, accessToken),\n body,\n cache: \"no-store\",\n redirect: \"manual\",\n });\n\n return {\n status: response.status,\n body: await response.text(),\n contentType: response.headers.get(\"content-type\"),\n };\n}\n\n/**\n * Passes the backend's status and body through untouched — callers read\n * `{ code, message }` off the body, so rewriting it would break their error\n * handling.\n */\nfunction respond(result: UpstreamResult): NextResponse {\n return new NextResponse(result.body || null, {\n status: result.status,\n headers: result.contentType\n ? { \"content-type\": result.contentType }\n : undefined,\n });\n}\n\nexport async function handleBackendProxy(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const target = resolveTarget(segments, request.nextUrl.search);\n\n if (!target) {\n return jsonError(400, \"Invalid proxy path\", \"PROXY_INVALID_PATH\");\n }\n\n // Buffered once so the 401 retry below can replay it.\n const body = METHODS_WITH_BODY.has(request.method)\n ? await request.text()\n : undefined;\n\n const tokens = readAuthCookies(\n request.cookies,\n storeRef,\n authCookiePathFor(request, storeRef)\n );\n\n let result: UpstreamResult;\n\n try {\n result = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n tokens?.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n // Anonymous callers and non-401 answers are done: public endpoints must keep\n // working through this proxy.\n if (result.status !== 401 || !tokens) return respond(result);\n\n // Exactly one refresh + retry. Never a loop.\n const refreshed = await createAuthApi(\n storeRef,\n clientIpFrom(request.headers)\n ).refresh(tokens.refresh_token);\n\n // A failed refresh does NOT clear the cookies, because \"failed\" and \"the\n // session is dead\" are not the same thing here. `SessionService.rotate()`\n // revokes the presented refresh token before issuing its replacement, so a\n // token can be rejected simply for having lost a race: `proxy.ts` refreshes\n // near-expiry tokens on every matched request, this route refreshes again on\n // a 401, and a page load fires several of both at once. Each of those reads\n // the refresh token from its own request snapshot, so whichever rotation\n // lands second presents an already-revoked token through no fault of the\n // shopper. Clearing here would log them out mid-page.\n //\n // Leaving stale cookies in place is safe: the `(protected)` layout resolves\n // the session server-side on the next navigation and redirects to /login if\n // it really is gone, and signing in overwrites them.\n if (\n !refreshed.success ||\n !refreshed.data?.access_token ||\n !refreshed.data.refresh_token\n ) {\n return respond(result);\n }\n\n let retry: UpstreamResult;\n\n try {\n retry = await callUpstream(\n request,\n storeRef,\n target,\n body || undefined,\n refreshed.data.access_token\n );\n } catch {\n return jsonError(502, \"Upstream request failed\", \"PROXY_UPSTREAM_ERROR\");\n }\n\n const response = respond(retry);\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: refreshed.data.access_token,\n refresh_token: refreshed.data.refresh_token,\n },\n authCookiePathFor(request, storeRef)\n );\n\n return response;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,oBAAsC;AAE/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gBAAgB,eAAe,wBAAwB;AAChE,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AA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,6 +1,7 @@
1
1
  import { NextResponse } from "next/server";
2
2
  import { createAuthApi } from "./sdk.js";
3
3
  import { clientIpFrom } from "./client-ip.js";
4
+ import { storePreviewTokenFor } from "../api/proxy.js";
4
5
  import { safeRedirectPath } from "./safe-redirect.js";
5
6
  import { publicNextUrl } from "../request/public-url.js";
6
7
  import {
@@ -73,7 +74,11 @@ async function handleAuthRoute(request, storeRef, segments) {
73
74
  const allowedMethod = AUTH_ACTION_METHOD[action];
74
75
  if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);
75
76
  if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);
76
- const auth = createAuthApi(storeRef, clientIpFrom(request.headers));
77
+ const auth = createAuthApi(
78
+ storeRef,
79
+ clientIpFrom(request.headers),
80
+ storePreviewTokenFor(request, storeRef)
81
+ );
77
82
  const hostMapped = isHostMappedRequest(request);
78
83
  const cookiePath = authCookiePath(storeRef, hostMapped);
79
84
  const tokens = readAuthCookies(request.cookies, storeRef, cookiePath);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/route-handlers.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { createAuthApi } from \"./sdk\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { safeRedirectPath } from \"./safe-redirect\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n authCookiePath,\n clearAuthCookies,\n clearOAuthNonceCookie,\n isHostMappedRequest,\n oauthNonceCookieName,\n readAuthCookies,\n writeAuthCookies,\n storeBasePathFor,\n writeOAuthNonceCookie,\n} from \"./cookies\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangePasswordPayload,\n LoginPayload,\n RegisterPayload,\n ResetPasswordPayload,\n VerifyOtpPayload,\n} from \"@ecomweb/sdk\";\n\n/** Translates the SDK's ApiResponse into a JSON response, preserving the code. */\nfunction fail(status: number, message: string, code?: string) {\n return NextResponse.json(\n { error: { message, code } },\n { status: status || 500 }\n );\n}\n\n/**\n * The HTTP method each action answers on — one entry per action, no defaults.\n *\n * Every one of these used to answer GET as well as POST, and the session\n * cookies are `sameSite: \"lax\"`, which the browser DOES send on a cross-site\n * top-level navigation. A link on any page therefore reached `logout-all`, or\n * `google/complete` with a code of the attacker's choosing. The split is\n * enumerated rather than inferred so that adding an action forces a decision\n * here; an action missing from this map is a 404, not a silent GET.\n *\n * GET is limited to the two reads the client polls (`config`, `session`) and\n * the two halves of the OAuth hand-off: `google/url` is a read, and\n * `google/complete` is the browser's landing spot in a redirect chain, so it\n * cannot be anything else. It carries its own browser binding instead — see\n * the nonce cookie below.\n */\nconst AUTH_ACTION_METHOD = {\n config: \"GET\",\n session: \"GET\",\n \"google/url\": \"GET\",\n \"google/complete\": \"GET\",\n\n register: \"POST\",\n login: \"POST\",\n \"otp/request\": \"POST\",\n \"otp/verify\": \"POST\",\n anonymous: \"POST\",\n logout: \"POST\",\n \"logout-all\": \"POST\",\n \"verify-email\": \"POST\",\n \"resend-verification\": \"POST\",\n \"forgot-password\": \"POST\",\n \"reset-password\": \"POST\",\n \"change-password\": \"POST\",\n \"change-email\": \"POST\",\n \"change-email/confirm\": \"POST\",\n} as const satisfies Record<string, \"GET\" | \"POST\">;\n\ntype AuthAction = keyof typeof AUTH_ACTION_METHOD;\n\n/**\n * The query parameter carrying the OAuth nonce home.\n *\n * `redirect_to` is the only field that survives the round trip through the\n * signed `state` and back out as `next=`, and the backend requires it to be a\n * relative path, so the nonce travels inside it as a query parameter of a\n * path-only URL. The storefront is both the producer and the only consumer of\n * this shape.\n */\nconst OAUTH_NONCE_PARAM = \"sf_oauth\";\nconst OAUTH_NEXT_PARAM = \"next\";\n\n/** Tokens go into cookies and never into the response body. */\nfunction withSession(\n storeRef: string,\n cookiePath: string,\n result: AuthResult,\n body: Record<string, unknown> = {}\n) {\n const response = NextResponse.json({ identity: result.identity, ...body });\n\n if (result.access_token && result.refresh_token) {\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n },\n cookiePath\n );\n }\n\n return response;\n}\n\nfunction methodNotAllowed(allowed: \"GET\" | \"POST\") {\n return NextResponse.json(\n {\n error: {\n message: `This action requires ${allowed}`,\n code: \"METHOD_NOT_ALLOWED\",\n },\n },\n { status: 405, headers: { allow: allowed } }\n );\n}\n\nexport async function handleAuthRoute(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const action = segments.join(\"/\");\n const allowedMethod = AUTH_ACTION_METHOD[action as AuthAction];\n\n if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);\n if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);\n\n // The shopper's address, not this server's: the backend rate-limits per\n // `storeId:clientIp` and every one of these calls is made server-side.\n const auth = createAuthApi(storeRef, clientIpFrom(request.headers));\n const hostMapped = isHostMappedRequest(request);\n const cookiePath = authCookiePath(storeRef, hostMapped);\n const tokens = readAuthCookies(request.cookies, storeRef, cookiePath);\n\n const body: Record<string, any> =\n request.method === \"POST\" ? await request.json().catch(() => ({})) : {};\n\n switch (action) {\n case \"config\": {\n const res = await auth.getAuthConfig();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"register\": {\n // Never trust a browser-supplied `anonymous_identity_id`: the backend\n // only checks store_id / is_anonymous / !deleted_at, not ownership, so\n // forwarding it would let anyone who learns an anonymous UUID register\n // against it and inherit its cart and orders. Whatever the browser sent\n // is dropped and the id is derived from the httpOnly session instead.\n const payload: Record<string, any> = { ...body };\n delete payload.anonymous_identity_id;\n\n let anonymousIdentityId: string | undefined;\n\n if (tokens) {\n const current = await auth.me(tokens.access_token);\n if (current.success && current.data?.is_anonymous) {\n anonymousIdentityId = current.data.id;\n }\n }\n\n const res = await auth.register({\n ...payload,\n anonymous_identity_id: anonymousIdentityId,\n } as RegisterPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Register never returns tokens, by design.\n return NextResponse.json({ registered: true });\n }\n\n case \"login\": {\n const res = await auth.login(body as LoginPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"otp/request\": {\n const res = await auth.requestOtp(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"otp/verify\": {\n const res = await auth.verifyOtp(body as VerifyOtpPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"anonymous\": {\n const res = await auth.anonymous();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"session\": {\n if (!tokens) return NextResponse.json({ identity: null });\n const res = await auth.me(tokens.access_token);\n if (!res.success) return NextResponse.json({ identity: null });\n return NextResponse.json({ identity: res.data });\n }\n\n case \"logout\": {\n // Best-effort revoke: a failed call must still clear the browser's\n // cookies, or the shopper is stuck logged in against a dead session.\n if (tokens) {\n await auth\n .logout(tokens.access_token, tokens.refresh_token)\n .catch(() => undefined);\n }\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"logout-all\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.logoutAll(tokens.access_token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"verify-email\": {\n const res = await auth.verifyEmail(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"resend-verification\": {\n const res = await auth.resendVerification(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"forgot-password\": {\n const res = await auth.forgotPassword(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"reset-password\": {\n const res = await auth.resetPassword(body as ResetPasswordPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"change-password\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changePassword(\n tokens.access_token,\n body as ChangePasswordPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Changing a password revokes sessions server-side; drop the cookies too.\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"change-email\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changeEmail(\n tokens.access_token,\n body as ChangeEmailPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"change-email/confirm\": {\n const res = await auth.confirmEmailChange(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"google/url\": {\n // Proxied rather than called from the browser so the storefront API key\n // stays server-side.\n const base = storeBasePathFor(request, storeRef);\n const wanted = safeRedirectPath(\n request.nextUrl.searchParams.get(\"redirect_to\"),\n publicNextUrl(request).toString()\n );\n\n // The nonce is minted here, remembered in an httpOnly cookie, and rides\n // out inside `redirect_to`. `google/complete` refuses to issue a session\n // unless the two match, which is what makes that GET unforgeable.\n // `globalThis.crypto` rather than a node:crypto import: this module is\n // bundled for whichever runtime the route runs in.\n const nonce = globalThis.crypto.randomUUID();\n const carrier = new URLSearchParams({\n [OAUTH_NONCE_PARAM]: nonce,\n [OAUTH_NEXT_PARAM]: wanted,\n });\n\n const res = await auth.getGoogleUrl(`${base}/?${carrier.toString()}`);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n\n const response = NextResponse.json(res.data);\n writeOAuthNonceCookie(response, storeRef, nonce, cookiePath);\n return response;\n }\n\n case \"google/complete\": {\n // The backend redirects the BROWSER here with a one-time code. It is\n // redeemed server-side so no token ever reaches the URL bar, history,\n // or a Referer header.\n const base = storeBasePathFor(request, storeRef);\n const errorTarget = new URL(\n `${base}/auth/error?error=oauth_failed`,\n publicNextUrl(request).toString()\n );\n\n const code = request.nextUrl.searchParams.get(\"code\");\n\n // Whatever came back in `next` is the carrier this route wrote in\n // `google/url`: a relative path plus the nonce. Both halves are\n // re-validated — the path against the origin, the nonce against the\n // cookie — before anything is issued.\n const carrier = safeRedirectPath(\n request.nextUrl.searchParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;\n const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);\n const expectedNonce = request.cookies.get(\n oauthNonceCookieName(storeRef, cookiePath)\n )?.value;\n\n const nonceMatches =\n !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;\n\n if (!code || !nonceMatches) {\n // A missing or mismatched nonce means this browser did not start the\n // flow: someone else's one-time code is being pushed into it. Refuse\n // before any token is exchanged, and burn the nonce either way.\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const res = await auth.exchangeGoogleCode(code);\n\n if (!res.success || !res.data?.access_token || !res.data.refresh_token) {\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const target = safeRedirectPath(\n carrierParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const response = NextResponse.redirect(\n new URL(target === \"/\" ? `${base}/` : target, publicNextUrl(request).toString())\n );\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: res.data.access_token,\n refresh_token: res.data.refresh_token,\n },\n cookiePath\n );\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n\n return response;\n }\n\n default:\n // Unreachable: AUTH_ACTION_METHOD is checked first, and every key it\n // holds has a case above. Kept so adding a key without a case is a\n // 404 rather than an undefined response.\n return fail(404, `Unknown auth action: ${action}`);\n }\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,SAAS,KAAK,QAAgB,SAAiB,MAAe;AAC5D,SAAO,aAAa;AAAA,IAClB,EAAE,OAAO,EAAE,SAAS,KAAK,EAAE;AAAA,IAC3B,EAAE,QAAQ,UAAU,IAAI;AAAA,EAC1B;AACF;AAkBA,MAAM,qBAAqB;AAAA,EACzB,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,cAAc;AAAA,EACd,mBAAmB;AAAA,EAEnB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,eAAe;AAAA,EACf,cAAc;AAAA,EACd,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,uBAAuB;AAAA,EACvB,mBAAmB;AAAA,EACnB,kBAAkB;AAAA,EAClB,mBAAmB;AAAA,EACnB,gBAAgB;AAAA,EAChB,wBAAwB;AAC1B;AAaA,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AAGzB,SAAS,YACP,UACA,YACA,QACA,OAAgC,CAAC,GACjC;AACA,QAAM,WAAW,aAAa,KAAK,EAAE,UAAU,OAAO,UAAU,GAAG,KAAK,CAAC;AAEzE,MAAI,OAAO,gBAAgB,OAAO,eAAe;AAC/C;AA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EACrD;AACF;","names":["response"]}
1
+ {"version":3,"sources":["../../src/auth/route-handlers.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport { createAuthApi } from \"./sdk\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { storePreviewTokenFor } from \"../api/proxy\";\nimport { safeRedirectPath } from \"./safe-redirect\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n authCookiePath,\n clearAuthCookies,\n clearOAuthNonceCookie,\n isHostMappedRequest,\n oauthNonceCookieName,\n readAuthCookies,\n writeAuthCookies,\n storeBasePathFor,\n writeOAuthNonceCookie,\n} from \"./cookies\";\nimport type {\n AuthResult,\n ChangeEmailPayload,\n ChangePasswordPayload,\n LoginPayload,\n RegisterPayload,\n ResetPasswordPayload,\n VerifyOtpPayload,\n} from \"@ecomweb/sdk\";\n\n/** Translates the SDK's ApiResponse into a JSON response, preserving the code. */\nfunction fail(status: number, message: string, code?: string) {\n return NextResponse.json(\n { error: { message, code } },\n { status: status || 500 }\n );\n}\n\n/**\n * The HTTP method each action answers on — one entry per action, no defaults.\n *\n * Every one of these used to answer GET as well as POST, and the session\n * cookies are `sameSite: \"lax\"`, which the browser DOES send on a cross-site\n * top-level navigation. A link on any page therefore reached `logout-all`, or\n * `google/complete` with a code of the attacker's choosing. The split is\n * enumerated rather than inferred so that adding an action forces a decision\n * here; an action missing from this map is a 404, not a silent GET.\n *\n * GET is limited to the two reads the client polls (`config`, `session`) and\n * the two halves of the OAuth hand-off: `google/url` is a read, and\n * `google/complete` is the browser's landing spot in a redirect chain, so it\n * cannot be anything else. It carries its own browser binding instead — see\n * the nonce cookie below.\n */\nconst AUTH_ACTION_METHOD = {\n config: \"GET\",\n session: \"GET\",\n \"google/url\": \"GET\",\n \"google/complete\": \"GET\",\n\n register: \"POST\",\n login: \"POST\",\n \"otp/request\": \"POST\",\n \"otp/verify\": \"POST\",\n anonymous: \"POST\",\n logout: \"POST\",\n \"logout-all\": \"POST\",\n \"verify-email\": \"POST\",\n \"resend-verification\": \"POST\",\n \"forgot-password\": \"POST\",\n \"reset-password\": \"POST\",\n \"change-password\": \"POST\",\n \"change-email\": \"POST\",\n \"change-email/confirm\": \"POST\",\n} as const satisfies Record<string, \"GET\" | \"POST\">;\n\ntype AuthAction = keyof typeof AUTH_ACTION_METHOD;\n\n/**\n * The query parameter carrying the OAuth nonce home.\n *\n * `redirect_to` is the only field that survives the round trip through the\n * signed `state` and back out as `next=`, and the backend requires it to be a\n * relative path, so the nonce travels inside it as a query parameter of a\n * path-only URL. The storefront is both the producer and the only consumer of\n * this shape.\n */\nconst OAUTH_NONCE_PARAM = \"sf_oauth\";\nconst OAUTH_NEXT_PARAM = \"next\";\n\n/** Tokens go into cookies and never into the response body. */\nfunction withSession(\n storeRef: string,\n cookiePath: string,\n result: AuthResult,\n body: Record<string, unknown> = {}\n) {\n const response = NextResponse.json({ identity: result.identity, ...body });\n\n if (result.access_token && result.refresh_token) {\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: result.access_token,\n refresh_token: result.refresh_token,\n },\n cookiePath\n );\n }\n\n return response;\n}\n\nfunction methodNotAllowed(allowed: \"GET\" | \"POST\") {\n return NextResponse.json(\n {\n error: {\n message: `This action requires ${allowed}`,\n code: \"METHOD_NOT_ALLOWED\",\n },\n },\n { status: 405, headers: { allow: allowed } }\n );\n}\n\nexport async function handleAuthRoute(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const action = segments.join(\"/\");\n const allowedMethod = AUTH_ACTION_METHOD[action as AuthAction];\n\n if (!allowedMethod) return fail(404, `Unknown auth action: ${action}`);\n if (request.method !== allowedMethod) return methodNotAllowed(allowedMethod);\n\n // The shopper's address, not this server's: the backend rate-limits per\n // `storeId:clientIp` and every one of these calls is made server-side.\n const auth = createAuthApi(\n storeRef,\n clientIpFrom(request.headers),\n storePreviewTokenFor(request, storeRef)\n );\n const hostMapped = isHostMappedRequest(request);\n const cookiePath = authCookiePath(storeRef, hostMapped);\n const tokens = readAuthCookies(request.cookies, storeRef, cookiePath);\n\n const body: Record<string, any> =\n request.method === \"POST\" ? await request.json().catch(() => ({})) : {};\n\n switch (action) {\n case \"config\": {\n const res = await auth.getAuthConfig();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"register\": {\n // Never trust a browser-supplied `anonymous_identity_id`: the backend\n // only checks store_id / is_anonymous / !deleted_at, not ownership, so\n // forwarding it would let anyone who learns an anonymous UUID register\n // against it and inherit its cart and orders. Whatever the browser sent\n // is dropped and the id is derived from the httpOnly session instead.\n const payload: Record<string, any> = { ...body };\n delete payload.anonymous_identity_id;\n\n let anonymousIdentityId: string | undefined;\n\n if (tokens) {\n const current = await auth.me(tokens.access_token);\n if (current.success && current.data?.is_anonymous) {\n anonymousIdentityId = current.data.id;\n }\n }\n\n const res = await auth.register({\n ...payload,\n anonymous_identity_id: anonymousIdentityId,\n } as RegisterPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Register never returns tokens, by design.\n return NextResponse.json({ registered: true });\n }\n\n case \"login\": {\n const res = await auth.login(body as LoginPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"otp/request\": {\n const res = await auth.requestOtp(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"otp/verify\": {\n const res = await auth.verifyOtp(body as VerifyOtpPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"anonymous\": {\n const res = await auth.anonymous();\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return withSession(storeRef, cookiePath, res.data!);\n }\n\n case \"session\": {\n if (!tokens) return NextResponse.json({ identity: null });\n const res = await auth.me(tokens.access_token);\n if (!res.success) return NextResponse.json({ identity: null });\n return NextResponse.json({ identity: res.data });\n }\n\n case \"logout\": {\n // Best-effort revoke: a failed call must still clear the browser's\n // cookies, or the shopper is stuck logged in against a dead session.\n if (tokens) {\n await auth\n .logout(tokens.access_token, tokens.refresh_token)\n .catch(() => undefined);\n }\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"logout-all\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.logoutAll(tokens.access_token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"verify-email\": {\n const res = await auth.verifyEmail(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"resend-verification\": {\n const res = await auth.resendVerification(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"forgot-password\": {\n const res = await auth.forgotPassword(body.email);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"reset-password\": {\n const res = await auth.resetPassword(body as ResetPasswordPayload);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"change-password\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changePassword(\n tokens.access_token,\n body as ChangePasswordPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n // Changing a password revokes sessions server-side; drop the cookies too.\n const response = NextResponse.json({ ok: true });\n clearAuthCookies(response, storeRef, cookiePath);\n return response;\n }\n\n case \"change-email\": {\n if (!tokens) return fail(401, \"No session\");\n const res = await auth.changeEmail(\n tokens.access_token,\n body as ChangeEmailPayload\n );\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json({ sent: true });\n }\n\n case \"change-email/confirm\": {\n const res = await auth.confirmEmailChange(body.token);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n return NextResponse.json(res.data);\n }\n\n case \"google/url\": {\n // Proxied rather than called from the browser so the storefront API key\n // stays server-side.\n const base = storeBasePathFor(request, storeRef);\n const wanted = safeRedirectPath(\n request.nextUrl.searchParams.get(\"redirect_to\"),\n publicNextUrl(request).toString()\n );\n\n // The nonce is minted here, remembered in an httpOnly cookie, and rides\n // out inside `redirect_to`. `google/complete` refuses to issue a session\n // unless the two match, which is what makes that GET unforgeable.\n // `globalThis.crypto` rather than a node:crypto import: this module is\n // bundled for whichever runtime the route runs in.\n const nonce = globalThis.crypto.randomUUID();\n const carrier = new URLSearchParams({\n [OAUTH_NONCE_PARAM]: nonce,\n [OAUTH_NEXT_PARAM]: wanted,\n });\n\n const res = await auth.getGoogleUrl(`${base}/?${carrier.toString()}`);\n if (!res.success)\n return fail(\n res.error!.statusCode,\n res.error!.message,\n res.error!.error\n );\n\n const response = NextResponse.json(res.data);\n writeOAuthNonceCookie(response, storeRef, nonce, cookiePath);\n return response;\n }\n\n case \"google/complete\": {\n // The backend redirects the BROWSER here with a one-time code. It is\n // redeemed server-side so no token ever reaches the URL bar, history,\n // or a Referer header.\n const base = storeBasePathFor(request, storeRef);\n const errorTarget = new URL(\n `${base}/auth/error?error=oauth_failed`,\n publicNextUrl(request).toString()\n );\n\n const code = request.nextUrl.searchParams.get(\"code\");\n\n // Whatever came back in `next` is the carrier this route wrote in\n // `google/url`: a relative path plus the nonce. Both halves are\n // re-validated — the path against the origin, the nonce against the\n // cookie — before anything is issued.\n const carrier = safeRedirectPath(\n request.nextUrl.searchParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const carrierParams = new URL(carrier, publicNextUrl(request).toString()).searchParams;\n const presentedNonce = carrierParams.get(OAUTH_NONCE_PARAM);\n const expectedNonce = request.cookies.get(\n oauthNonceCookieName(storeRef, cookiePath)\n )?.value;\n\n const nonceMatches =\n !!presentedNonce && !!expectedNonce && presentedNonce === expectedNonce;\n\n if (!code || !nonceMatches) {\n // A missing or mismatched nonce means this browser did not start the\n // flow: someone else's one-time code is being pushed into it. Refuse\n // before any token is exchanged, and burn the nonce either way.\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const res = await auth.exchangeGoogleCode(code);\n\n if (!res.success || !res.data?.access_token || !res.data.refresh_token) {\n const response = NextResponse.redirect(errorTarget);\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n return response;\n }\n\n const target = safeRedirectPath(\n carrierParams.get(OAUTH_NEXT_PARAM),\n publicNextUrl(request).toString()\n );\n const response = NextResponse.redirect(\n new URL(target === \"/\" ? `${base}/` : target, publicNextUrl(request).toString())\n );\n\n writeAuthCookies(\n response,\n storeRef,\n {\n access_token: res.data.access_token,\n refresh_token: res.data.refresh_token,\n },\n cookiePath\n );\n clearOAuthNonceCookie(response, storeRef, cookiePath);\n\n return response;\n }\n\n default:\n // Unreachable: AUTH_ACTION_METHOD is checked first, and every key it\n // holds has a case above. Kept so adding a key without a case is a\n // 404 rather than an undefined response.\n return fail(404, `Unknown auth action: ${action}`);\n }\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AACrC,SAAS,wBAAwB;AACjC,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAYP,SAAS,KAAK,QAAgB,SAAiB,MAA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AAClD,8BAAsBA,WAAU,UAAU,UAAU;AACpD,eAAOA;AAAA,MACT;AAEA,YAAM,MAAM,MAAM,KAAK,mBAAmB,IAAI;AAE9C,UAAI,CAAC,IAAI,WAAW,CAAC,IAAI,MAAM,gBAAgB,CAAC,IAAI,KAAK,eAAe;AACtE,cAAMA,YAAW,aAAa,SAAS,WAAW;AAClD,8BAAsBA,WAAU,UAAU,UAAU;AACpD,eAAOA;AAAA,MACT;AAEA,YAAM,SAAS;AAAA,QACb,cAAc,IAAI,gBAAgB;AAAA,QAClC,cAAc,OAAO,EAAE,SAAS;AAAA,MAClC;AACA,YAAM,WAAW,aAAa;AAAA,QAC5B,IAAI,IAAI,WAAW,MAAM,GAAG,IAAI,MAAM,QAAQ,cAAc,OAAO,EAAE,SAAS,CAAC;AAAA,MACjF;AAEA;AAAA,QACE;AAAA,QACA;AAAA,QACA;AAAA,UACE,cAAc,IAAI,KAAK;AAAA,UACvB,eAAe,IAAI,KAAK;AAAA,QAC1B;AAAA,QACA;AAAA,MACF;AACA,4BAAsB,UAAU,UAAU,UAAU;AAEpD,aAAO;AAAA,IACT;AAAA,IAEA;AAIE,aAAO,KAAK,KAAK,wBAAwB,MAAM,EAAE;AAAA,EACrD;AACF;","names":["response"]}
package/dist/auth/sdk.js CHANGED
@@ -3,19 +3,23 @@ import { AuthApi } from "@ecomweb/sdk";
3
3
  import { forwardingHeaders } from "./client-ip.js";
4
4
  import { publicConfig } from "../config.js";
5
5
  import { serverConfig } from "../config/server.js";
6
+ import { STORE_PREVIEW_HEADER } from "../stores/store-preview-cookie.js";
6
7
  function backendBaseUrl() {
7
8
  return publicConfig().apiUrl;
8
9
  }
9
10
  function storefrontApiKey() {
10
11
  return serverConfig().platformApiKey;
11
12
  }
12
- async function send(method, url, data, options, clientIp) {
13
+ async function send(method, url, data, options, clientIp, previewToken) {
13
14
  try {
14
15
  const response = await fetch(`${backendBaseUrl()}${url}`, {
15
16
  method,
16
17
  headers: {
17
18
  "Content-Type": "application/json",
18
19
  "x-storefront-api-key": storefrontApiKey(),
20
+ // A store preview opens a coming soon store for reads only, so the
21
+ // token rides on GETs (auth config, me) and never on writes.
22
+ ...previewToken && method === "GET" ? { [STORE_PREVIEW_HEADER]: previewToken } : {},
19
23
  ...options?.headers ?? {},
20
24
  // The backend's auth throttler keys on the shopper IP, which it only
21
25
  // reads from `x-forwarded-for` when the forwarder secret rides along.
@@ -55,17 +59,17 @@ async function send(method, url, data, options, clientIp) {
55
59
  };
56
60
  }
57
61
  }
58
- function authHttpClient(clientIp) {
62
+ function authHttpClient(clientIp, previewToken) {
59
63
  return {
60
- get: (url, options) => send("GET", url, void 0, options, clientIp),
64
+ get: (url, options) => send("GET", url, void 0, options, clientIp, previewToken),
61
65
  post: (url, data, options) => send("POST", url, data, options, clientIp),
62
66
  put: (url, data, options) => send("PUT", url, data, options, clientIp),
63
67
  patch: (url, data, options) => send("PATCH", url, data, options, clientIp),
64
68
  delete: (url, options) => send("DELETE", url, void 0, options, clientIp)
65
69
  };
66
70
  }
67
- function createAuthApi(storeRef, clientIp) {
68
- return new AuthApi(authHttpClient(clientIp), storeRef);
71
+ function createAuthApi(storeRef, clientIp, previewToken) {
72
+ return new AuthApi(authHttpClient(clientIp, previewToken), storeRef);
69
73
  }
70
74
  export {
71
75
  authHttpClient,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(clientIp?: string): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n */\nexport function createAuthApi(storeRef: string, clientIp?: string): AuthApi {\n return new AuthApi(authHttpClient(clientIp), storeRef);\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,eAAe;AAExB,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAQtB,SAAS,iBAAyB;AACvC,SAAO,aAAa,EAAE;AACxB;AAWO,SAAS,mBAA2B;AACzC,SAAO,aAAa,EAAE;AACxB;AAEA,eAAe,KACb,QACA,KACA,MACA,SACA,UACyB;AACzB,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,GAAG,IAAI;AAAA,MACxD;AAAA,MACA,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,wBAAwB,iBAAiB;AAAA,QACzC,GAAI,SAAS,WAAW,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAMzB,GAAG,kBAAkB,QAAQ;AAAA,MAC/B;AAAA,MACA,MAAM,SAAS,SAAY,SAAY,KAAK,UAAU,IAAI;AAAA,MAC1D,QAAQ,SAAS;AAAA,MACjB,OAAO;AAAA,IACT,CAAC;AAED,UAAM,OAAO,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,IAAI;AAEnD,QAAI,CAAC,SAAS,IAAI;AAChB,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO;AAAA,UACL,SAAS,MAAM,WAAW,SAAS;AAAA,UACnC,YAAY,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAMrB,OAAO,MAAM,QAAQ,MAAM;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAEA,WAAO,EAAE,SAAS,MAAM,MAAM,KAAU;AAAA,EAC1C,SAAS,OAAO;AACd,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO;AAAA,QACL,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,QAClD,YAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,eAAe,UAAgC;AAC7D,SAAO;AAAA,IACL,KAAK,CAAI,KAAa,YACpB,KAAQ,OAAO,KAAK,QAAW,SAAS,QAAQ;AAAA,IAClD,MAAM,CAAI,KAAa,MAAgB,YACrC,KAAQ,QAAQ,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC9C,KAAK,CAAI,KAAa,MAAgB,YACpC,KAAQ,OAAO,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC7C,OAAO,CAAI,KAAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AAMO,SAAS,cAAc,UAAkB,UAA4B;AAC1E,SAAO,IAAI,QAAQ,eAAe,QAAQ,GAAG,QAAQ;AACvD;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\n\n\n/**\n * The one server-side resolution of the backend origin. `lib/api/proxy.ts`\n * uses this too so the proxy and the auth routes can never disagree about\n * where the backend is.\n */\nexport function backendBaseUrl(): string {\n return publicConfig().apiUrl;\n}\n\n/**\n * StorefrontApiKeyGuard fronts every customer-auth route and also resolves\n * :storeRef into request.storeId, so a missing key fails before auth runs.\n *\n * Only NEXT_PUBLIC_PLATFORM_API_KEY exists in this repo today (see .env /\n * .env.example, lib/api/client.ts, lib/api/server-client.ts). PLATFORM_API_KEY\n * is checked first so a server-only key can be introduced later without\n * another code change.\n */\nexport function storefrontApiKey(): string {\n return serverConfig().platformApiKey;\n}\n\nasync function send<T>(\n method: string,\n url: string,\n data?: unknown,\n options?: RequestOptions,\n clientIp?: string,\n previewToken?: string | null\n): Promise<ApiResponse<T>> {\n try {\n const response = await fetch(`${backendBaseUrl()}${url}`, {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontApiKey(),\n // A store preview opens a coming soon store for reads only, so the\n // token rides on GETs (auth config, me) and never on writes.\n ...(previewToken && method === \"GET\"\n ? { [STORE_PREVIEW_HEADER]: previewToken }\n : {}),\n ...(options?.headers ?? {}),\n // The backend's auth throttler keys on the shopper IP, which it only\n // reads from `x-forwarded-for` when the forwarder secret rides along.\n // Without both, every shopper of a store shares one bucket, because\n // the only client the backend ever sees is this server. Spread last\n // so nothing an SDK call passes can replace the validated values.\n ...forwardingHeaders(clientIp),\n },\n body: data === undefined ? undefined : JSON.stringify(data),\n signal: options?.signal,\n cache: \"no-store\",\n });\n\n const body = await response.json().catch(() => null);\n\n if (!response.ok) {\n return {\n success: false,\n error: {\n message: body?.message ?? response.statusText,\n statusCode: response.status,\n // BusinessException serialises as { code, message, details,\n // timestamp } with no global exception filter rewriting the\n // shape (verified against src/common/exceptions/business.exception.ts\n // in the api repo), so the stable AUTH_* code lands in `code`.\n // `error` is checked too in case a future filter renames it.\n error: body?.code ?? body?.error,\n },\n };\n }\n\n return { success: true, data: body as T };\n } catch (error) {\n return {\n success: false,\n error: {\n message: error instanceof Error ? error.message : \"Network error\",\n statusCode: 0,\n },\n };\n }\n}\n\nexport function authHttpClient(\n clientIp?: string,\n previewToken?: string | null\n): IHttpClient {\n return {\n get: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"GET\", url, undefined, options, clientIp, previewToken),\n post: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"POST\", url, data, options, clientIp),\n put: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PUT\", url, data, options, clientIp),\n patch: <T>(url: string, data?: unknown, options?: RequestOptions) =>\n send<T>(\"PATCH\", url, data, options, clientIp),\n delete: <T>(url: string, options?: RequestOptions) =>\n send<T>(\"DELETE\", url, undefined, options, clientIp),\n };\n}\n\n/**\n * @param clientIp the shopper's address, from `clientIpFrom(request.headers)`.\n * Omit it only where there is genuinely no incoming request to read.\n * @param previewToken the request's store preview token\n * (`storePreviewTokenFrom`), sent as `X-Store-Preview` on GETs so a\n * previewer of a coming soon store still gets the auth config and `me`.\n */\nexport function createAuthApi(\n storeRef: string,\n clientIp?: string,\n previewToken?: string | null\n): AuthApi {\n return new AuthApi(authHttpClient(clientIp, previewToken), storeRef);\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,eAAe;AAExB,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAQ9B,SAAS,iBAAyB;AACvC,SAAO,aAAa,EAAE;AACxB;AAWO,SAAS,mBAA2B;AACzC,SAAO,aAAa,EAAE;AACxB;AAEA,eAAe,KACb,QACA,KACA,MACA,SACA,UACA,cACyB;AACzB,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,GAAG,eAAe,CAAC,GAAG,GAAG,IAAI;AAAA,MACxD;AAAA,MACA,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,wBAAwB,iBAAiB;AAAA;AAAA;AAAA,QAGzC,GAAI,gBAAgB,WAAW,QAC3B,EAAE,CAAC,oBAAoB,GAAG,aAAa,IACvC,CAAC;AAAA,QACL,GAAI,SAAS,WAAW,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAMzB,GAAG,kBAAkB,QAAQ;AAAA,MAC/B;AAAA,MACA,MAAM,SAAS,SAAY,SAAY,KAAK,UAAU,IAAI;AAAA,MAC1D,QAAQ,SAAS;AAAA,MACjB,OAAO;AAAA,IACT,CAAC;AAED,UAAM,OAAO,MAAM,SAAS,KAAK,EAAE,MAAM,MAAM,IAAI;AAEnD,QAAI,CAAC,SAAS,IAAI;AAChB,aAAO;AAAA,QACL,SAAS;AAAA,QACT,OAAO;AAAA,UACL,SAAS,MAAM,WAAW,SAAS;AAAA,UACnC,YAAY,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAMrB,OAAO,MAAM,QAAQ,MAAM;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAEA,WAAO,EAAE,SAAS,MAAM,MAAM,KAAU;AAAA,EAC1C,SAAS,OAAO;AACd,WAAO;AAAA,MACL,SAAS;AAAA,MACT,OAAO;AAAA,QACL,SAAS,iBAAiB,QAAQ,MAAM,UAAU;AAAA,QAClD,YAAY;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACF;AAEO,SAAS,eACd,UACA,cACa;AACb,SAAO;AAAA,IACL,KAAK,CAAI,KAAa,YACpB,KAAQ,OAAO,KAAK,QAAW,SAAS,UAAU,YAAY;AAAA,IAChE,MAAM,CAAI,KAAa,MAAgB,YACrC,KAAQ,QAAQ,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC9C,KAAK,CAAI,KAAa,MAAgB,YACpC,KAAQ,OAAO,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC7C,OAAO,CAAI,KAAa,MAAgB,YACtC,KAAQ,SAAS,KAAK,MAAM,SAAS,QAAQ;AAAA,IAC/C,QAAQ,CAAI,KAAa,YACvB,KAAQ,UAAU,KAAK,QAAW,SAAS,QAAQ;AAAA,EACvD;AACF;AASO,SAAS,cACd,UACA,UACA,cACS;AACT,SAAO,IAAI,QAAQ,eAAe,UAAU,YAAY,GAAG,QAAQ;AACrE;","names":[]}
@@ -4,6 +4,7 @@ import { cookies, headers } from "next/headers";
4
4
  import { authCookiePathFor, readAuthCookies } from "./cookies.js";
5
5
  import { clientIpFrom } from "./client-ip.js";
6
6
  import { createAuthApi } from "./sdk.js";
7
+ import { storePreviewTokenFrom } from "../stores/store-preview-cookie.js";
7
8
  const getServerIdentity = cache(
8
9
  async (storeRef) => {
9
10
  const requestHeaders = await headers();
@@ -13,9 +14,11 @@ const getServerIdentity = cache(
13
14
  authCookiePathFor({ headers: requestHeaders }, storeRef)
14
15
  );
15
16
  if (!tokens) return null;
16
- const me = await createAuthApi(storeRef, clientIpFrom(requestHeaders)).me(
17
- tokens.access_token
18
- );
17
+ const me = await createAuthApi(
18
+ storeRef,
19
+ clientIpFrom(requestHeaders),
20
+ storePreviewTokenFrom(await cookies(), { headers: requestHeaders })
21
+ ).me(tokens.access_token);
19
22
  return me.success ? me.data ?? null : null;
20
23
  }
21
24
  );
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { authCookiePathFor, readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable: they name the cookie path, and\n // the backend rate-limits this call per `storeId:clientIp`, so it has to\n // carry the shopper's address like every other server-side auth call does.\n const requestHeaders = await headers();\n const tokens = readAuthCookies(\n await cookies(),\n storeRef,\n authCookiePathFor({ headers: requestHeaders }, storeRef)\n );\n if (!tokens) return null;\n\n const me = await createAuthApi(storeRef, clientIpFrom(requestHeaders)).me(\n tokens.access_token\n );\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,mBAAmB,uBAAuB;AACnD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AASvB,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAK3D,UAAM,iBAAiB,MAAM,QAAQ;AACrC,UAAM,SAAS;AAAA,MACb,MAAM,QAAQ;AAAA,MACd;AAAA,MACA,kBAAkB,EAAE,SAAS,eAAe,GAAG,QAAQ;AAAA,IACzD;AACA,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,KAAK,MAAM,cAAc,UAAU,aAAa,cAAc,CAAC,EAAE;AAAA,MACrE,OAAO;AAAA,IACT;AACA,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/session.ts"],"sourcesContent":["import \"server-only\";\n\nimport { cache } from \"react\";\nimport { cookies, headers } from \"next/headers\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { authCookiePathFor, readAuthCookies } from \"./cookies\";\nimport { clientIpFrom } from \"./client-ip\";\nimport { createAuthApi } from \"./sdk\";\nimport { storePreviewTokenFrom } from \"../stores/store-preview-cookie\";\n\n/**\n * The one server-side \"who is this request?\" read.\n *\n * Wrapped in React `cache()` so several server components in the same render\n * share a single `me()` round trip — `lib/auth/sdk.ts` sends `cache: \"no-store\"`,\n * so without this every layout and page would issue its own.\n */\nexport const getServerIdentity = cache(\n async (storeRef: string): Promise<CurrentIdentity | null> => {\n // There is no NextRequest in a server component, but the incoming\n // request's headers are still reachable: they name the cookie path, and\n // the backend rate-limits this call per `storeId:clientIp`, so it has to\n // carry the shopper's address like every other server-side auth call does.\n const requestHeaders = await headers();\n const tokens = readAuthCookies(\n await cookies(),\n storeRef,\n authCookiePathFor({ headers: requestHeaders }, storeRef)\n );\n if (!tokens) return null;\n\n const me = await createAuthApi(\n storeRef,\n clientIpFrom(requestHeaders),\n storePreviewTokenFrom(await cookies(), { headers: requestHeaders })\n ).me(tokens.access_token);\n return me.success ? (me.data ?? null) : null;\n }\n);\n\n/**\n * Whether the request carries a real, logged-in shopper session.\n *\n * An **anonymous** identity (the guest-cart session the backend issues) has a\n * perfectly valid token but is not a logged-in shopper: it has no\n * `customer_id`, no name and no email. Treating it as authenticated admits it\n * to `/account/*` — where every page is empty or errors — and, worse, bounces\n * it away from `/login`, so a guest with a cart could never sign in.\n */\nexport async function hasCustomerSession(storeRef: string): Promise<boolean> {\n const identity = await getServerIdentity(storeRef);\n return !!identity && !identity.is_anonymous;\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,aAAa;AACtB,SAAS,SAAS,eAAe;AAEjC,SAAS,mBAAmB,uBAAuB;AACnD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,6BAA6B;AAS/B,MAAM,oBAAoB;AAAA,EAC/B,OAAO,aAAsD;AAK3D,UAAM,iBAAiB,MAAM,QAAQ;AACrC,UAAM,SAAS;AAAA,MACb,MAAM,QAAQ;AAAA,MACd;AAAA,MACA,kBAAkB,EAAE,SAAS,eAAe,GAAG,QAAQ;AAAA,IACzD;AACA,QAAI,CAAC,OAAQ,QAAO;AAEpB,UAAM,KAAK,MAAM;AAAA,MACf;AAAA,MACA,aAAa,cAAc;AAAA,MAC3B,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,eAAe,CAAC;AAAA,IACpE,EAAE,GAAG,OAAO,YAAY;AACxB,WAAO,GAAG,UAAW,GAAG,QAAQ,OAAQ;AAAA,EAC1C;AACF;AAWA,eAAsB,mBAAmB,UAAoC;AAC3E,QAAM,WAAW,MAAM,kBAAkB,QAAQ;AACjD,SAAO,CAAC,CAAC,YAAY,CAAC,SAAS;AACjC;","names":[]}
@@ -5,7 +5,8 @@ import {
5
5
  useContext,
6
6
  useReducer,
7
7
  useEffect,
8
- useCallback
8
+ useCallback,
9
+ useRef
9
10
  } from "react";
10
11
  import { useNotify } from "../notices.js";
11
12
  import { isBrowserStorePreview } from "../api/store-preview-header.js";
@@ -20,7 +21,10 @@ const cartReducer = (state, action) => {
20
21
  };
21
22
  case "LOAD_CART": {
22
23
  const cart = action.payload;
23
- const items = cart.items.map((item) => ({
24
+ const inAddedOrder = [...cart.items].sort(
25
+ (a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)
26
+ );
27
+ const items = inAddedOrder.map((item) => ({
24
28
  id: item.id,
25
29
  productId: item.product_id,
26
30
  variantId: item.variant_id ?? void 0,
@@ -101,6 +105,7 @@ function CartProvider({
101
105
  if (cart) {
102
106
  dispatch({ type: "LOAD_CART", payload: cart });
103
107
  } else {
108
+ dispatch({ type: "CLEAR_CART" });
104
109
  dispatch({ type: "SET_LOADING", payload: false });
105
110
  }
106
111
  } catch (error) {
@@ -108,9 +113,45 @@ function CartProvider({
108
113
  dispatch({ type: "SET_LOADING", payload: false });
109
114
  }
110
115
  }, [storeRef, isAuth]);
116
+ const movingGuestCart = useRef(null);
117
+ const moveGuestCartToAccount = useCallback(() => {
118
+ if (!movingGuestCart.current) {
119
+ movingGuestCart.current = (async () => {
120
+ try {
121
+ const guestCart = await cartApiService.getCart(storeRef, false);
122
+ for (const item of guestCart?.items ?? []) {
123
+ try {
124
+ await cartApiService.addToCart(
125
+ storeRef,
126
+ {
127
+ product_id: item.product_id,
128
+ variant_id: item.variant_id ?? void 0,
129
+ quantity: item.quantity
130
+ },
131
+ true
132
+ );
133
+ await cartApiService.removeFromCart(storeRef, item.id, false);
134
+ } catch (error) {
135
+ console.error("Could not move a guest cart line:", error);
136
+ }
137
+ }
138
+ } catch (error) {
139
+ console.error("Could not read the guest cart:", error);
140
+ } finally {
141
+ movingGuestCart.current = null;
142
+ }
143
+ })();
144
+ }
145
+ return movingGuestCart.current;
146
+ }, [storeRef]);
111
147
  useEffect(() => {
112
- loadCart();
113
- }, [loadCart]);
148
+ if (!storeRef || !isAuth || isBrowserStorePreview()) {
149
+ loadCart();
150
+ return;
151
+ }
152
+ dispatch({ type: "SET_LOADING", payload: true });
153
+ moveGuestCartToAccount().then(loadCart);
154
+ }, [storeRef, isAuth, loadCart, moveGuestCartToAccount]);
114
155
  const addItem = async (item) => {
115
156
  if (isBrowserStorePreview()) {
116
157
  notify(STORE_PREVIEW_READ_ONLY_NOTICE);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n const items: CartItem[] = cart.items.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n loadCart();\n }, [loadCart]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return { added: 0, total: items.length };\n }\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;\n}\n"],"mappings":";AA2XI;AAzXJ;AAAA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L,MAAM;AAAA,UACN,MAAM;AAAA,UACN,OAAO;AAAA,UACP,aAAa;AAAA,QACf,CAAC;AAAA,MACH;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,MAAM,yBAAyB,KAAK;AAC5C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,QAAM,cAAc,YAAY;AAC9B,UAAM,SAAS;AAAA,EACjB;AAEA,QAAM,aAAa,OAAO,YAAoB;AAC5C,QAAI,sBAAsB,GAAG;AAC3B,aAAO,8BAA8B;AACrC;AAAA,IACF;AACA,QAAI,CAAC,YAAY,CAAC,MAAM,UAAW;AAEnC,QAAI;AACF,YAAM,eAAe,WAAW,QAAQ;AAGxC,YAAM,SAAS;AAEf,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH,SAAS,OAAO;AACd,cAAQ,MAAM,0BAA0B,KAAK;AAC7C,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,QACN,OAAO;AAAA,QACP,aAAa;AAAA,MACf,CAAC;AAAA,IACH;AAAA,EACF;AAEA,SACE;AAAA,IAAC,YAAY;AAAA,IAAZ;AAAA,MACC,OAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MAEC;AAAA;AAAA,EACH;AAEJ;AAEO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
1
+ {"version":3,"sources":["../../src/cart/server-context.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n createContext,\n useContext,\n useReducer,\n useEffect,\n useCallback,\n useRef,\n type ReactNode,\n} from \"react\";\nimport { useNotify } from \"../notices\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { CartItem } from \"./types\";\nimport { cartApiService, CartApiResponse, CartApiItem } from \"./api\";\n\ninterface CartState {\n items: CartItem[];\n total: number;\n subtotal: number;\n originalSubtotal: number;\n discountAmount: number;\n shippingFee: number;\n itemCount: number;\n isLoading: boolean;\n cartId?: string;\n sessionId?: string;\n}\n\ntype CartAction =\n | { type: \"SET_LOADING\"; payload: boolean }\n | { type: \"LOAD_CART\"; payload: CartApiResponse }\n | { type: \"SET_SESSION_ID\"; payload: string }\n | { type: \"CLEAR_CART\" };\n\nconst cartReducer = (state: CartState, action: CartAction): CartState => {\n switch (action.type) {\n case \"SET_LOADING\":\n return {\n ...state,\n isLoading: action.payload,\n };\n\n case \"LOAD_CART\": {\n const cart = action.payload;\n // The API returns lines in no fixed order, and an updated line moves.\n // Without this, the row under the shopper's finger swaps mid-tap.\n const inAddedOrder = [...cart.items].sort(\n (a, b) => Date.parse(a.created_at) - Date.parse(b.created_at)\n );\n const items: CartItem[] = inAddedOrder.map((item: CartApiItem) => ({\n id: item.id,\n productId: item.product_id,\n variantId: item.variant_id ?? undefined,\n name: item.product_name,\n price: item.price,\n originalPrice: item.original_price,\n image: item.product_image,\n quantity: item.quantity,\n variantName: item.variant_name,\n variantOptions: item.variant_options,\n promotions: item.promotions,\n bestPromotion: item.best_promotion,\n }));\n\n return {\n ...state,\n items,\n total: cart.total,\n subtotal: cart.subtotal,\n originalSubtotal: cart.original_subtotal,\n discountAmount: cart.discount_amount,\n shippingFee: cart.shipping_fee,\n itemCount: cart.item_count,\n cartId: cart.id,\n isLoading: false,\n };\n }\n\n case \"SET_SESSION_ID\":\n return {\n ...state,\n sessionId: action.payload,\n };\n\n case \"CLEAR_CART\":\n return {\n ...state,\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n cartId: undefined,\n };\n\n default:\n return state;\n }\n};\n\ninterface CartContextType extends CartState {\n addItem: (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => Promise<void>;\n removeItem: (id: string) => Promise<void>;\n updateQuantity: (id: string, quantity: number) => Promise<void>;\n /** Pass false to skip the \"cart cleared\" notice (e.g. after checkout). */\n clearCart: (notifyCleared?: boolean) => Promise<void>;\n refreshCart: () => Promise<void>;\n mergeCarts: (userId: string) => Promise<void>;\n reorderItems: (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ) => Promise<{ added: number; total: number }>;\n}\n\nconst CartContext = createContext<CartContextType | undefined>(undefined);\n\ninterface CartProviderProps {\n children: ReactNode;\n storeRef: string;\n userId?: string;\n}\n\nexport function CartProvider({\n children,\n storeRef,\n userId,\n}: CartProviderProps) {\n // A signed-in shopper gets the identity-scoped cart; everyone else gets the\n // session-id cart. `userId` comes from the auth context one level up\n // (StoreCartProvider) — this module can never read the httpOnly cookie itself.\n const isAuth = !!userId;\n const notify = useNotify();\n const [state, dispatch] = useReducer(cartReducer, {\n items: [],\n total: 0,\n subtotal: 0,\n originalSubtotal: 0,\n discountAmount: 0,\n shippingFee: 0,\n itemCount: 0,\n isLoading: true, // Start with loading true to show loading state on initial render\n });\n\n // Generate session ID for anonymous users\n useEffect(() => {\n if (!userId && !state.sessionId) {\n const sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n dispatch({ type: \"SET_SESSION_ID\", payload: sessionId });\n }\n }, [userId, state.sessionId]);\n\n // Load cart from server\n const loadCart = useCallback(async () => {\n if (!storeRef) return;\n\n dispatch({ type: \"SET_LOADING\", payload: true });\n try {\n const cart = await cartApiService.getCart(storeRef, isAuth);\n\n if (cart) {\n dispatch({ type: \"LOAD_CART\", payload: cart });\n } else {\n // No cart for this identity. Keeping the state would show the\n // previous identity's items (guest before sign-in, account after\n // sign-out) as if they could be bought.\n dispatch({ type: \"CLEAR_CART\" });\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n } catch (error) {\n console.error(\"Failed to load cart:\", error);\n dispatch({ type: \"SET_LOADING\", payload: false });\n }\n }, [storeRef, isAuth]);\n\n // Shared while running: the provider's effect can fire twice for one sign-in.\n const movingGuestCart = useRef<Promise<void> | null>(null);\n\n /**\n * Signing in switches to the account's cart, so without this whatever the\n * shopper added as a guest disappears, even on checkout's own \"sign in and\n * come back\" link. Each line is added before it is removed, and a line that\n * cannot be added stays in the guest cart, so nothing is lost on a failure.\n */\n const moveGuestCartToAccount = useCallback(() => {\n if (!movingGuestCart.current) {\n movingGuestCart.current = (async () => {\n try {\n const guestCart = await cartApiService.getCart(storeRef, false);\n for (const item of guestCart?.items ?? []) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id ?? undefined,\n quantity: item.quantity,\n },\n true\n );\n await cartApiService.removeFromCart(storeRef, item.id, false);\n } catch (error) {\n console.error(\"Could not move a guest cart line:\", error);\n }\n }\n } catch (error) {\n console.error(\"Could not read the guest cart:\", error);\n } finally {\n movingGuestCart.current = null;\n }\n })();\n }\n return movingGuestCart.current;\n }, [storeRef]);\n\n // Load cart on mount and when dependencies change\n useEffect(() => {\n if (!storeRef || !isAuth || isBrowserStorePreview()) {\n loadCart();\n return;\n }\n dispatch({ type: \"SET_LOADING\", payload: true });\n moveGuestCartToAccount().then(loadCart);\n }, [storeRef, isAuth, loadCart, moveGuestCartToAccount]);\n\n const addItem = async (\n item: Omit<CartItem, \"quantity\"> & { quantity?: number }\n ) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.productId,\n variant_id: item.variantId,\n quantity: item.quantity || 1,\n },\n isAuth\n );\n\n // Refresh cart after adding item\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.item_added\",\n title: \"Đã thêm vào giỏ hàng\",\n description: `${item.name} đã được thêm vào giỏ hàng của bạn`,\n data: { productName: item.name },\n });\n } catch (error) {\n console.error(\"Failed to add item to cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.add_failed\",\n title: \"Lỗi\",\n description: \"Không thể thêm sản phẩm vào giỏ hàng\",\n });\n }\n };\n\n /**\n * Add every line of a past order back to the cart.\n *\n * Deliberately not a loop over addItem: that notifies per item and swallows\n * its errors, so a reorder would fire one notice per line and the caller\n * could never report a shortfall. This refreshes once and returns counts.\n */\n const reorderItems = async (\n items: { product_id: number; variant_id?: number; quantity: number }[]\n ): Promise<{ added: number; total: number }> => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return { added: 0, total: items.length };\n }\n if (!storeRef) return { added: 0, total: items.length };\n\n let added = 0;\n for (const item of items) {\n try {\n await cartApiService.addToCart(\n storeRef,\n {\n product_id: item.product_id,\n variant_id: item.variant_id,\n quantity: item.quantity,\n },\n isAuth\n );\n added += 1;\n } catch (error) {\n // Product deleted, out of stock, or repriced since purchase. Skip it —\n // the caller reports the shortfall rather than failing the reorder.\n console.error(\"Reorder skipped an item:\", error);\n }\n }\n\n await loadCart();\n return { added, total: items.length };\n };\n\n const removeItem = async (id: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n const item = state.items.find(item => item.id === id);\n\n try {\n await cartApiService.removeFromCart(storeRef, id, isAuth);\n\n // Refresh cart after removing item\n await loadCart();\n\n if (item) {\n notify({\n kind: \"success\",\n code: \"cart.item_removed\",\n title: \"Đã xóa khỏi giỏ hàng\",\n description: `${item.name} đã được xóa khỏi giỏ hàng`,\n data: { productName: item.name },\n });\n }\n } catch (error) {\n console.error(\"Failed to remove item from cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.remove_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa sản phẩm khỏi giỏ hàng\",\n });\n }\n };\n\n const updateQuantity = async (id: string, quantity: number) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.updateCartItem(storeRef, id, { quantity }, isAuth);\n\n // Refresh cart after updating quantity\n await loadCart();\n } catch (error) {\n console.error(\"Failed to update item quantity:\", error);\n notify({\n kind: \"error\",\n code: \"cart.update_failed\",\n title: \"Lỗi\",\n description: \"Không thể cập nhật số lượng sản phẩm\",\n });\n }\n };\n\n const clearCart = async (notifyCleared: boolean = true) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef) return;\n\n try {\n await cartApiService.clearCart(storeRef, isAuth);\n\n dispatch({ type: \"CLEAR_CART\" });\n\n if (notifyCleared) {\n notify({\n kind: \"success\",\n code: \"cart.cleared\",\n title: \"Đã xóa giỏ hàng\",\n description: \"Tất cả sản phẩm đã được xóa khỏi giỏ hàng\",\n });\n }\n } catch (error) {\n console.error(\"Failed to clear cart:\", error);\n notify({\n kind: \"error\",\n code: \"cart.clear_failed\",\n title: \"Lỗi\",\n description: \"Không thể xóa giỏ hàng\",\n });\n }\n };\n\n const refreshCart = async () => {\n await loadCart();\n };\n\n const mergeCarts = async (_userId: string) => {\n if (isBrowserStorePreview()) {\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n if (!storeRef || !state.sessionId) return;\n\n try {\n await cartApiService.mergeCarts(storeRef);\n\n // Refresh cart after merging\n await loadCart();\n\n notify({\n kind: \"success\",\n code: \"cart.merged\",\n title: \"Đã đồng bộ giỏ hàng\",\n description: \"Giỏ hàng đã được đồng bộ với tài khoản của bạn\",\n });\n } catch (error) {\n console.error(\"Failed to merge carts:\", error);\n notify({\n kind: \"error\",\n code: \"cart.merge_failed\",\n title: \"Lỗi\",\n description: \"Không thể đồng bộ giỏ hàng\",\n });\n }\n };\n\n return (\n <CartContext.Provider\n value={{\n ...state,\n addItem,\n removeItem,\n updateQuantity,\n clearCart,\n refreshCart,\n mergeCarts,\n reorderItems,\n }}\n >\n {children}\n </CartContext.Provider>\n );\n}\n\nexport function useCart() {\n const context = useContext(CartContext);\n if (context === undefined) {\n throw new Error(\"useCart must be used within a CartProvider\");\n }\n return context;\n}\n"],"mappings":";AAkbI;AAhbJ;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,iBAAiB;AAC1B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAE/C,SAAS,sBAAoD;AAqB7D,MAAM,cAAc,CAAC,OAAkB,WAAkC;AACvE,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO;AAAA,QACL,GAAG;AAAA,QACH,WAAW,OAAO;AAAA,MACpB;AAAA,IAEF,KAAK,aAAa;AAChB,YAAM,OAAO,OAAO;AAGpB,YAAM,eAAe,CAAC,GAAG,KAAK,KAAK,EAAE;AAAA,QACnC,CAAC,GAAG,MAAM,KAAK,MAAM,EAAE,UAAU,IAAI,KAAK,MAAM,EAAE,UAAU;AAAA,MAC9D;AACA,YAAM,QAAoB,aAAa,IAAI,CAAC,UAAuB;AAAA,QACjE,IAAI,KAAK;AAAA,QACT,WAAW,KAAK;AAAA,QAChB,WAAW,KAAK,cAAc;AAAA,QAC9B,MAAM,KAAK;AAAA,QACX,OAAO,KAAK;AAAA,QACZ,eAAe,KAAK;AAAA,QACpB,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,aAAa,KAAK;AAAA,QAClB,gBAAgB,KAAK;AAAA,QACrB,YAAY,KAAK;AAAA,QACjB,eAAe,KAAK;AAAA,MACtB,EAAE;AAEF,aAAO;AAAA,QACL,GAAG;AAAA,QACH;AAAA,QACA,OAAO,KAAK;AAAA,QACZ,UAAU,KAAK;AAAA,QACf,kBAAkB,KAAK;AAAA,QACvB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AACT;","names":["item"]}
@@ -23,6 +23,7 @@ import { getStoreByHost } from "../stores/get-store-by-host.js";
23
23
  import { STORE_COMING_SOON_REDIRECT_PATH } from "../stores/store-coming-soon.js";
24
24
  import {
25
25
  applyStorePreview,
26
+ firstLivePreviewToken,
26
27
  STORE_PREVIEW_PATH,
27
28
  STORE_PREVIEW_TOKEN_HEADER,
28
29
  storePreviewCookieName
@@ -80,7 +81,10 @@ function hasStorePreview(req, cookiePath) {
80
81
  return !!req.cookies.get(storePreviewCookieName(cookiePath))?.value;
81
82
  }
82
83
  function hostLookupPreviewToken(req) {
83
- return req.cookies.get(storePreviewCookieName("/"))?.value || req.cookies.get(themePreviewCookieName("/"))?.value || null;
84
+ return firstLivePreviewToken(
85
+ req.cookies.get(storePreviewCookieName("/"))?.value,
86
+ req.cookies.get(themePreviewCookieName("/"))?.value
87
+ );
84
88
  }
85
89
  function storeRefFromPath(pathname) {
86
90
  const match = /^\/store\/([^/]+)/.exec(pathname);
@@ -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 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;AAA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B,KAAK,UAAU;AACrE,aAAS,QAAQ,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"]}
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 firstLivePreviewToken,\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 `/`; an expired one yields to the other. 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 firstLivePreviewToken(\n req.cookies.get(storePreviewCookieName(\"/\"))?.value,\n req.cookies.get(themePreviewCookieName(\"/\"))?.value\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;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;AAC7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kC,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,7 +6,7 @@ const publicOrdersApi = {
6
6
  customer_email: contactInfo.email,
7
7
  customer_phone: contactInfo.phone
8
8
  });
9
- return result.found ? result.order : null;
9
+ return result;
10
10
  },
11
11
  /**
12
12
  * `isAuth` comes from the caller's auth context — this module is not a
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/orders/api-client.ts"],"sourcesContent":["import { createStoreSdk, sdk } from \"../sdk\";\nimport type { CreateOrderRequest, Order, OrderWithItems } from \"@ecomweb/sdk\";\n\nexport const publicOrdersApi = {\n async getPublicOrderStatus(\n storeRef: string,\n orderNumber: number,\n contactInfo: { email?: string; phone?: string }\n ): Promise<Order | null> {\n const result = await sdk.orders.lookupGuest(storeRef, {\n order_number: orderNumber,\n customer_email: contactInfo.email,\n customer_phone: contactInfo.phone,\n });\n return result.found ? result.order : null;\n },\n\n /**\n * `isAuth` comes from the caller's auth context — this module is not a\n * component and must not read context or an httpOnly cookie itself.\n *\n * When true the SDK posts to `/tenant/stores/:ref/customers/orders`, which\n * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`\n * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no\n * such fields to carry them in. The request reaches that guarded route\n * through the same-origin proxy, which attaches the bearer token.\n */\n async createStoreOrder(\n storeRef: string,\n data: Omit<CreateOrderRequest, \"store_id\">,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n return createStoreSdk(storeRef).orders.create(\n storeRef,\n data as CreateOrderRequest,\n isAuth\n );\n },\n};\n\nexport type { CreateOrderRequest, CreateOrderItemRequest } from \"@ecomweb/sdk\";\n"],"mappings":"AAAA,SAAS,gBAAgB,WAAW;AAG7B,MAAM,kBAAkB;AAAA,EAC7B,MAAM,qBACJ,UACA,aACA,aACuB;AACvB,UAAM,SAAS,MAAM,IAAI,OAAO,YAAY,UAAU;AAAA,MACpD,cAAc;AAAA,MACd,gBAAgB,YAAY;AAAA,MAC5B,gBAAgB,YAAY;AAAA,IAC9B,CAAC;AACD,WAAO,OAAO,QAAQ,OAAO,QAAQ;AAAA,EACvC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,iBACJ,UACA,MACA,QACyB;AACzB,WAAO,eAAe,QAAQ,EAAE,OAAO;AAAA,MACrC;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/orders/api-client.ts"],"sourcesContent":["import { createStoreSdk, sdk } from \"../sdk\";\nimport type { CreateOrderRequest, Order, OrderWithItems } from \"@ecomweb/sdk\";\n\nexport const publicOrdersApi = {\n async getPublicOrderStatus(\n storeRef: string,\n orderNumber: number,\n contactInfo: { email?: string; phone?: string }\n ): Promise<Order | null> {\n const result = await sdk.orders.lookupGuest(storeRef, {\n order_number: orderNumber,\n customer_email: contactInfo.email,\n customer_phone: contactInfo.phone,\n });\n return result;\n },\n\n /**\n * `isAuth` comes from the caller's auth context — this module is not a\n * component and must not read context or an httpOnly cookie itself.\n *\n * When true the SDK posts to `/tenant/stores/:ref/customers/orders`, which\n * derives BOTH `customer_id` (ResolveCustomerInterceptor) and `user_id`\n * (JWT) server-side; the payload carries neither, and `CreateOrderDto` has no\n * such fields to carry them in. The request reaches that guarded route\n * through the same-origin proxy, which attaches the bearer token.\n */\n async createStoreOrder(\n storeRef: string,\n data: Omit<CreateOrderRequest, \"store_id\">,\n isAuth: boolean\n ): Promise<OrderWithItems> {\n return createStoreSdk(storeRef).orders.create(\n storeRef,\n data as CreateOrderRequest,\n isAuth\n );\n },\n};\n\nexport type { CreateOrderRequest, CreateOrderItemRequest } from \"@ecomweb/sdk\";\n"],"mappings":"AAAA,SAAS,gBAAgB,WAAW;AAG7B,MAAM,kBAAkB;AAAA,EAC7B,MAAM,qBACJ,UACA,aACA,aACuB;AACvB,UAAM,SAAS,MAAM,IAAI,OAAO,YAAY,UAAU;AAAA,MACpD,cAAc;AAAA,MACd,gBAAgB,YAAY;AAAA,MAC5B,gBAAgB,YAAY;AAAA,IAC9B,CAAC;AACD,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,iBACJ,UACA,MACA,QACyB;AACzB,WAAO,eAAe,QAAQ,EAAE,OAAO;AAAA,MACrC;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -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 { 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;AACpD,SAAS,wBAAwB;AACjC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,WAAW;AACpB,SAAS,kBAAkB;AAC3B,SAAS,8BAA8B;AAIvC,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,SA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W,WAAW;AAC5B,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);\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;AACp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+3,9 @@ import { useReducer, useEffect, useCallback, useRef, useMemo } from "react";
3
3
  import { SHIPPING_MESSAGES } from "./messages.js";
4
4
  import { useNotify } from "../notices.js";
5
5
  import { optionIdOf } from "./option-id.js";
6
+ import { isBrowserStorePreview } from "../api/store-preview-header.js";
7
+ import { STORE_PREVIEW_READ_ONLY_NOTICE } from "../stores/store-preview-guard.js";
8
+ import { isStoreComingSoonError } from "../stores/store-coming-soon.js";
6
9
  import {
7
10
  shippingCalculationReducer,
8
11
  initialShippingCalculationState
@@ -31,6 +34,11 @@ function useShippingCalculation({
31
34
  dispatch({ type: "RESET" });
32
35
  return;
33
36
  }
37
+ if (isBrowserStorePreview()) {
38
+ dispatch({ type: "RESET" });
39
+ notify(STORE_PREVIEW_READ_ONLY_NOTICE);
40
+ return;
41
+ }
34
42
  const next = stateRef.current.requestId + 1;
35
43
  dispatch({ type: "CALCULATION_STARTED" });
36
44
  try {
@@ -45,6 +53,11 @@ function useShippingCalculation({
45
53
  dispatch({ type: "CALCULATION_SUCCEEDED", options, requestId: next });
46
54
  } catch (error) {
47
55
  if (next !== stateRef.current.requestId) return;
56
+ if (isStoreComingSoonError(error)) {
57
+ dispatch({ type: "RESET" });
58
+ notify(STORE_PREVIEW_READ_ONLY_NOTICE);
59
+ return;
60
+ }
48
61
  console.error("Failed to calculate shipping fee:", error);
49
62
  dispatch({ type: "CALCULATION_FAILED", requestId: next });
50
63
  notify({
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,QAAQ,eAAe;AAEpE,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAgBA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,wBAAwB;AAC1B,GAAgC;AAC9B,QAAM,CAAC,OAAO,QAAQ,IAAI;AAAA,IACxB;AAAA,IACA;AAAA,EACF;AACA,QAAM,SAAS,UAAU;AAIzB,QAAM,WAAW,OAAO,KAAK;AAC7B,WAAS,UAAU;AAanB,YAAU,MAAM;AACd,aAAS,EAAE,MAAM,QAAQ,CAAC;AAAA,EAC5B,GAAG,CAAC,MAAM,MAAM,UAAU,aAAa,qBAAqB,CAAC;AAE7D,QAAM,uBAAuB,YAAY,YAAY;AACnD,QAAI,CAAC,QAAQ,CAAC,QAAQ,eAAe,GAAG;AACtC,eAAS,EAAE,MAAM,QAAQ,CAAC;AAC1B;AAAA,IACF;AAKA,UAAM,OAAO,SAAS,QAAQ,YAAY;AAC1C,aAAS,EAAE,MAAM,sBAAsB,CAAC;AAExC,QAAI;AACF,YAAM,UAAU,MAAM,IAAI,SAAS,UAAU,UAAU;AAAA,QACrD,aAAa;AAAA,QACb,SAAS;AAAA,QACT;AAAA,QACA,UAAU;AAAA,QACV,WAAW;AAAA,QACX,GAAI,yBAAyB,EAAE,yBAAyB,KAAK;AAAA,MAC/D,CAAC;AAED,eAAS,EAAE,MAAM,yBAAyB,SAAS,WAAW,KAAK,CAAC;AAAA,IACtE,SAAS,OAAO;AAMd,UAAI,SAAS,SAAS,QAAQ,UAAW;AAEzC,cAAQ,MAAM,qCAAqC,KAAK;AACxD,eAAS,EAAE,MAAM,sBAAsB,WAAW,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ACzB,kBAAkB,MAAM;AAAA,IACxB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/shipping/use-shipping-calculation.ts"],"sourcesContent":["import { sdk } from \"../sdk\";\nimport { useReducer, useEffect, useCallback, useRef, useMemo } from \"react\";\nimport type { ShippingOption } from \"@ecomweb/sdk\";\nimport { SHIPPING_MESSAGES } from \"./messages\";\nimport { useNotify } from \"../notices\";\nimport { optionIdOf } from \"./option-id\";\nimport { isBrowserStorePreview } from \"../api/store-preview-header\";\nimport { STORE_PREVIEW_READ_ONLY_NOTICE } from \"../stores/store-preview-guard\";\nimport { isStoreComingSoonError } from \"../stores/store-coming-soon\";\nimport {\n shippingCalculationReducer,\n initialShippingCalculationState,\n} from \"./shipping-calculation-reducer\";\n\ninterface UseShippingCalculationProps {\n storeRef: string;\n city: string;\n ward: string;\n subtotal: number;\n totalWeight: number;\n itemsCount: number;\n /**\n * Ask the API for carrier-quoted options too. Off by default so stores\n * that have not updated send exactly the body they always did.\n */\n includeCarrierOptions?: boolean;\n}\n\nexport function useShippingCalculation({\n storeRef,\n city,\n ward,\n subtotal,\n totalWeight,\n itemsCount,\n includeCarrierOptions = false,\n}: UseShippingCalculationProps) {\n const [state, dispatch] = useReducer(\n shippingCalculationReducer,\n initialShippingCalculationState\n );\n const notify = useNotify();\n\n // The callback below is memoised, so it must not close over a stale\n // `state`. This ref always holds the latest.\n const stateRef = useRef(state);\n stateRef.current = state;\n\n // Clear stale shipping state the instant an input that affects pricing\n // changes -- BEFORE the debounce below even starts a timer, let alone\n // before the network round-trip it eventually kicks off. Gating on\n // isCalculatingShipping (see checkout-page-client's isSubmitDisabled)\n // only closes the network window; it's still false for the full 500ms\n // debounce, so without this a shopper editing their address and\n // submitting inside that window would send the PREVIOUS quote's\n // rate_id against the NEW address -- exactly what the API's rate_id\n // match now rejects. Clearing here means the worst case during that\n // window is no rate_id at all (the API falls back to picking the best\n // option), never a stale, mismatched one.\n useEffect(() => {\n dispatch({ type: \"RESET\" });\n }, [city, ward, subtotal, totalWeight, includeCarrierOptions]);\n\n const calculateShippingFee = useCallback(async () => {\n if (!city || !ward || itemsCount === 0) {\n dispatch({ type: \"RESET\" });\n return;\n }\n\n // A store preview is read-only and the API refuses this POST with\n // STORE_COMING_SOON, which would show as a shipping error. Say it is a\n // preview instead, like the cart and checkout writes do.\n if (isBrowserStorePreview()) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n // The id this request will be judged against. CALCULATION_STARTED\n // bumps the counter, so the request in flight owns `next`; anything\n // that resets or starts after this makes the response stale.\n const next = stateRef.current.requestId + 1;\n dispatch({ type: \"CALCULATION_STARTED\" });\n\n try {\n const options = await sdk.shipping.calculate(storeRef, {\n province_id: city,\n ward_id: ward,\n subtotal: subtotal,\n currency: \"VND\",\n weight_gr: totalWeight,\n ...(includeCarrierOptions && { include_carrier_options: true }),\n });\n\n dispatch({ type: \"CALCULATION_SUCCEEDED\", options, requestId: next });\n } catch (error) {\n // eslint-disable-next-line no-console\n // The reducer already discards a stale failure, but the notice is\n // outside it: an older request failing after a newer one succeeded\n // would show an error over perfectly good options. Only the request\n // that still owns the quote may report anything.\n if (next !== stateRef.current.requestId) return;\n\n if (isStoreComingSoonError(error)) {\n dispatch({ type: \"RESET\" });\n notify(STORE_PREVIEW_READ_ONLY_NOTICE);\n return;\n }\n\n console.error(\"Failed to calculate shipping fee:\", error);\n dispatch({ type: \"CALCULATION_FAILED\", requestId: next });\n notify({\n kind: \"error\",\n code: \"shipping.quote_failed\",\n title: SHIPPING_MESSAGES.failed,\n description: SHIPPING_MESSAGES.failedHint,\n });\n }\n }, [\n city,\n ward,\n itemsCount,\n storeRef,\n subtotal,\n totalWeight,\n includeCarrierOptions,\n notify,\n ]);\n\n // Debounced effect to prevent too many API calls\n useEffect(() => {\n const timeoutId = setTimeout(() => {\n calculateShippingFee();\n }, 500); // 500ms debounce\n\n return () => clearTimeout(timeoutId);\n }, [calculateShippingFee]);\n\n // Handle shipping rate selection\n const handleShippingRateSelect = useCallback((rateId: number) => {\n dispatch({ type: \"RATE_SELECTED\", rateId });\n }, []);\n\n const handleShippingOptionSelect = useCallback((optionId: string) => {\n dispatch({ type: \"OPTION_SELECTED\", optionId });\n }, []);\n\n const replaceOptions = useCallback(\n (\n options: ShippingOption[],\n preferOptionId: string | null,\n requestId: number\n ) => {\n dispatch({ type: \"QUOTE_REPLACED\", options, requestId, preferOptionId });\n },\n []\n );\n\n const currentRequestId = useCallback(() => stateRef.current.requestId, []);\n\n const selectedOption = useMemo(\n () =>\n state.selectedOptionId === null\n ? null\n : (state.shippingOptions.find(\n o => optionIdOf(o) === state.selectedOptionId\n ) ?? null),\n [state.shippingOptions, state.selectedOptionId]\n );\n\n return {\n shippingFee: state.shippingFee,\n isCalculatingShipping: state.isCalculatingShipping,\n hasCalculatedShipping: state.hasCalculatedShipping,\n shippingOptions: state.shippingOptions,\n selectedShippingRate: state.selectedShippingRate,\n calculationFailed: state.calculationFailed,\n selectedOptionId: state.selectedOptionId,\n selectedOption,\n handleShippingOptionSelect,\n replaceOptions,\n currentRequestId,\n handleShippingRateSelect,\n /**\n * Re-run the quote with the inputs unchanged. The debounced effect only\n * fires when an input dependency changes, so after a transient failure\n * there was otherwise no way back: the shopper had to edit the address\n * or reload the page.\n */\n retryCalculation: calculateShippingFee,\n };\n}\n"],"mappings":"AAAA,SAAS,WAAW;AACpB,SAAS,YAAY,WAAW,aAAa,QAAQ,eAAe;AAEpE,SAAS,yBAAyB;AAClC,SAAS,iBAAiB;AAC1B,SAAS,kBAAkB;AAC3B,SAAS,6BAA6B;AACtC,SAAS,sCAAsC;AAC/C,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAgBA,SAAS,uBAAuB;AAAA,EACrC;AAAA,EACA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A,IACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAOA,kBAAkB;AAAA,EACpB;AACF;","names":[]}
@@ -5,6 +5,7 @@ function buildStoreUrl(store, path) {
5
5
  if (!path) return config.appUrl;
6
6
  return `${config.appUrl}/${path.replace(/^\/+/, "")}`;
7
7
  }
8
+ const subpath = (path ?? "").replace(/^\/+/, "");
8
9
  const isLocal = config.appBaseUrlFlag === "local";
9
10
  let subdomain = "";
10
11
  let custom_domain = "";
@@ -25,19 +26,19 @@ function buildStoreUrl(store, path) {
25
26
  if (isLocal) {
26
27
  const origin = typeof window === "undefined" && process.env.APP_BASE_URL?.trim() || "http://localhost:3002";
27
28
  const baseUrl2 = `${origin}/store/${store_ref}`;
28
- return path ? `${baseUrl2}/${path}` : baseUrl2;
29
+ return subpath ? `${baseUrl2}/${subpath}` : baseUrl2;
29
30
  }
30
31
  if (custom_domain) {
31
32
  const baseUrl2 = `https://${custom_domain}`;
32
- return path ? `${baseUrl2}/${path}` : baseUrl2;
33
+ return subpath ? `${baseUrl2}/${subpath}` : baseUrl2;
33
34
  }
34
35
  if (subdomain) {
35
36
  const platformDomain = config.platformDomainSuffix ?? "ecomsite.app";
36
37
  const baseUrl2 = `https://${subdomain}.${platformDomain}`;
37
- return path ? `${baseUrl2}/${path}` : baseUrl2;
38
+ return subpath ? `${baseUrl2}/${subpath}` : baseUrl2;
38
39
  }
39
40
  const baseUrl = `/store/${store_ref}`;
40
- return path ? `${baseUrl}/${path}` : baseUrl;
41
+ return subpath ? `${baseUrl}/${subpath}` : baseUrl;
41
42
  }
42
43
  export {
43
44
  buildStoreUrl
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/store-scope/store-url.ts"],"sourcesContent":["import type { StoreConfig, StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { publicConfig } from \"../config/public\";\n\n/**\n * Build store URL based on environment and store configuration\n * @param store - Store object with subdomain and custom_domain\n * @param path - Optional path to append to the store URL\n * @returns Complete store URL\n *\n * @example\n * // Local development\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null })\n * // Returns: 'http://localhost:3000/store/1'\n *\n * // Production with subdomain\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null })\n * // Returns: 'https://mystore.{NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX}'\n *\n * // Production with custom domain\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: 'mystore.com' })\n * // Returns: 'https://mystore.com'\n *\n * // With path\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null }, 'about')\n * // Returns: 'https://mystore.{NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX}/about'\n */\nexport function buildStoreUrl(\n store:\n | { ref: string; subdomain: string | null; custom_domain: string | null }\n | StoreConfig\n | StoreConfigurationInfo,\n path?: string\n): string {\n const config = publicConfig();\n // Single-store: an absolute URL on this site; `store` is ignored.\n if (config.mode === \"single\") {\n if (!path) return config.appUrl;\n return `${config.appUrl}/${path.replace(/^\\/+/, \"\")}`;\n }\n\n const isLocal = config.appBaseUrlFlag === \"local\";\n let subdomain = \"\";\n let custom_domain = \"\";\n let store_ref = \"\";\n\n if (\"ref\" in store && \"subdomain\" in store && \"custom_domain\" in store) {\n subdomain = store.subdomain || \"\";\n custom_domain = store.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n } else if (\"config\" in store && store.config) {\n subdomain = store.config.subdomain || \"\";\n custom_domain = store.config.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n } else if (\"subdomain\" in store && \"custom_domain\" in store) {\n subdomain = store.subdomain || \"\";\n custom_domain = store.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n }\n\n if (isLocal) {\n // Server-only var, so the browser always gets the dev default (as before).\n const origin =\n (typeof window === \"undefined\" && process.env.APP_BASE_URL?.trim()) ||\n \"http://localhost:3002\";\n const baseUrl = `${origin}/store/${store_ref}`;\n return path ? `${baseUrl}/${path}` : baseUrl;\n }\n\n if (custom_domain) {\n const baseUrl = `https://${custom_domain}`;\n return path ? `${baseUrl}/${path}` : baseUrl;\n }\n\n if (subdomain) {\n const platformDomain = config.platformDomainSuffix ?? \"ecomsite.app\";\n const baseUrl = `https://${subdomain}.${platformDomain}`;\n return path ? `${baseUrl}/${path}` : baseUrl;\n }\n\n // Fallback: use store ref format\n const baseUrl = `/store/${store_ref}`;\n return path ? `${baseUrl}/${path}` : baseUrl;\n}\n"],"mappings":"AACA,SAAS,oBAAoB;AAyBtB,SAAS,cACd,OAIA,MACQ;AACR,QAAM,SAAS,aAAa;AAE5B,MAAI,OAAO,SAAS,UAAU;AAC5B,QAAI,CAAC,KAAM,QAAO,OAAO;AACzB,WAAO,GAAG,OAAO,MAAM,IAAI,KAAK,QAAQ,QAAQ,EAAE,CAAC;AAAA,EACrD;AAEA,QAAM,UAAU,OAAO,mBAAmB;AAC1C,MAAI,YAAY;AAChB,MAAI,gBAAgB;AACpB,MAAI,YAAY;AAEhB,MAAI,SAAS,SAAS,eAAe,SAAS,mBAAmB,OAAO;AACtE,gBAAY,MAAM,aAAa;AAC/B,oBAAgB,MAAM,iBAAiB;AACvC,gBAAa,MAAc,OAAO;AAAA,EACpC,WAAW,YAAY,SAAS,MAAM,QAAQ;AAC5C,gBAAY,MAAM,OAAO,aAAa;AACtC,oBAAgB,MAAM,OAAO,iBAAiB;AAC9C,gBAAa,MAAc,OAAO;AAAA,EACpC,WAAW,eAAe,SAAS,mBAAmB,OAAO;AAC3D,gBAAY,MAAM,aAAa;AAC/B,oBAAgB,MAAM,iBAAiB;AACvC,gBAAa,MAAc,OAAO;AAAA,EACpC;AAEA,MAAI,SAAS;AAEX,UAAM,SACH,OAAO,WAAW,eAAe,QAAQ,IAAI,cAAc,KAAK,KACjE;AACF,UAAMA,WAAU,GAAG,MAAM,UAAU,SAAS;AAC5C,WAAO,OAAO,GAAGA,QAAO,IAAI,IAAI,KAAKA;AAAA,EACvC;AAEA,MAAI,eAAe;AACjB,UAAMA,WAAU,WAAW,aAAa;AACxC,WAAO,OAAO,GAAGA,QAAO,IAAI,IAAI,KAAKA;AAAA,EACvC;AAEA,MAAI,WAAW;AACb,UAAM,iBAAiB,OAAO,wBAAwB;AACtD,UAAMA,WAAU,WAAW,SAAS,IAAI,cAAc;AACtD,WAAO,OAAO,GAAGA,QAAO,IAAI,IAAI,KAAKA;AAAA,EACvC;AAGA,QAAM,UAAU,UAAU,SAAS;AACnC,SAAO,OAAO,GAAG,OAAO,IAAI,IAAI,KAAK;AACvC;","names":["baseUrl"]}
1
+ {"version":3,"sources":["../../src/store-scope/store-url.ts"],"sourcesContent":["import type { StoreConfig, StoreConfigurationInfo } from \"@ecomweb/sdk\";\nimport { publicConfig } from \"../config/public\";\n\n/**\n * Build store URL based on environment and store configuration\n * @param store - Store object with subdomain and custom_domain\n * @param path - Optional path to append to the store URL\n * @returns Complete store URL\n *\n * @example\n * // Local development\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null })\n * // Returns: 'http://localhost:3000/store/1'\n *\n * // Production with subdomain\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null })\n * // Returns: 'https://mystore.{NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX}'\n *\n * // Production with custom domain\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: 'mystore.com' })\n * // Returns: 'https://mystore.com'\n *\n * // With path\n * buildStoreUrl({ id: 1, subdomain: 'mystore', custom_domain: null }, 'about')\n * // Returns: 'https://mystore.{NEXT_PUBLIC_PLATFORM_DOMAIN_SUFFIX}/about'\n */\nexport function buildStoreUrl(\n store:\n | { ref: string; subdomain: string | null; custom_domain: string | null }\n | StoreConfig\n | StoreConfigurationInfo,\n path?: string\n): string {\n const config = publicConfig();\n // Single-store: an absolute URL on this site; `store` is ignored.\n if (config.mode === \"single\") {\n if (!path) return config.appUrl;\n return `${config.appUrl}/${path.replace(/^\\/+/, \"\")}`;\n }\n\n // Callers pass both \"login\" and \"/login\"; the base never ends in a slash.\n const subpath = (path ?? \"\").replace(/^\\/+/, \"\");\n\n const isLocal = config.appBaseUrlFlag === \"local\";\n let subdomain = \"\";\n let custom_domain = \"\";\n let store_ref = \"\";\n\n if (\"ref\" in store && \"subdomain\" in store && \"custom_domain\" in store) {\n subdomain = store.subdomain || \"\";\n custom_domain = store.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n } else if (\"config\" in store && store.config) {\n subdomain = store.config.subdomain || \"\";\n custom_domain = store.config.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n } else if (\"subdomain\" in store && \"custom_domain\" in store) {\n subdomain = store.subdomain || \"\";\n custom_domain = store.custom_domain || \"\";\n store_ref = (store as any).ref || \"\";\n }\n\n if (isLocal) {\n // Server-only var, so the browser always gets the dev default (as before).\n const origin =\n (typeof window === \"undefined\" && process.env.APP_BASE_URL?.trim()) ||\n \"http://localhost:3002\";\n const baseUrl = `${origin}/store/${store_ref}`;\n return subpath ? `${baseUrl}/${subpath}` : baseUrl;\n }\n\n if (custom_domain) {\n const baseUrl = `https://${custom_domain}`;\n return subpath ? `${baseUrl}/${subpath}` : baseUrl;\n }\n\n if (subdomain) {\n const platformDomain = config.platformDomainSuffix ?? \"ecomsite.app\";\n const baseUrl = `https://${subdomain}.${platformDomain}`;\n return subpath ? `${baseUrl}/${subpath}` : baseUrl;\n }\n\n // Fallback: use store ref format\n const baseUrl = `/store/${store_ref}`;\n return subpath ? `${baseUrl}/${subpath}` : baseUrl;\n}\n"],"mappings":"AACA,SAAS,oBAAoB;AAyBtB,SAAS,cACd,OAIA,MACQ;AACR,QAAM,SAAS,aAAa;AAE5B,MAAI,OAAO,SAAS,UAAU;AAC5B,QAAI,CAAC,KAAM,QAAO,OAAO;AACzB,WAAO,GAAG,OAAO,MAAM,IAAI,KAAK,QAAQ,QAAQ,EAAE,CAAC;AAAA,EACrD;AAGA,QAAM,WAAW,QAAQ,IAAI,QAAQ,QAAQ,EAAE;AAE/C,QAAM,UAAU,OAAO,mBAAmB;AAC1C,MAAI,YAAY;AAChB,MAAI,gBAAgB;AACpB,MAAI,YAAY;AAEhB,MAAI,SAAS,SAAS,eAAe,SAAS,mBAAmB,OAAO;AACtE,gBAAY,MAAM,aAAa;AAC/B,oBAAgB,MAAM,iBAAiB;AACvC,gBAAa,MAAc,OAAO;AAAA,EACpC,WAAW,YAAY,SAAS,MAAM,QAAQ;AAC5C,gBAAY,MAAM,OAAO,aAAa;AACtC,oBAAgB,MAAM,OAAO,iBAAiB;AAC9C,gBAAa,MAAc,OAAO;AAAA,EACpC,WAAW,eAAe,SAAS,mBAAmB,OAAO;AAC3D,gBAAY,MAAM,aAAa;AAC/B,oBAAgB,MAAM,iBAAiB;AACvC,gBAAa,MAAc,OAAO;AAAA,EACpC;AAEA,MAAI,SAAS;AAEX,UAAM,SACH,OAAO,WAAW,eAAe,QAAQ,IAAI,cAAc,KAAK,KACjE;AACF,UAAMA,WAAU,GAAG,MAAM,UAAU,SAAS;AAC5C,WAAO,UAAU,GAAGA,QAAO,IAAI,OAAO,KAAKA;AAAA,EAC7C;AAEA,MAAI,eAAe;AACjB,UAAMA,WAAU,WAAW,aAAa;AACxC,WAAO,UAAU,GAAGA,QAAO,IAAI,OAAO,KAAKA;AAAA,EAC7C;AAEA,MAAI,WAAW;AACb,UAAM,iBAAiB,OAAO,wBAAwB;AACtD,UAAMA,WAAU,WAAW,SAAS,IAAI,cAAc;AACtD,WAAO,UAAU,GAAGA,QAAO,IAAI,OAAO,KAAKA;AAAA,EAC7C;AAGA,QAAM,UAAU,UAAU,SAAS;AACnC,SAAO,UAAU,GAAG,OAAO,IAAI,OAAO,KAAK;AAC7C;","names":["baseUrl"]}
@@ -35,13 +35,31 @@ function applyStorePreview(req, cookiePath, storeRoot) {
35
35
  });
36
36
  return res;
37
37
  }
38
+ function previewTokenUnexpired(token, now = Date.now()) {
39
+ try {
40
+ const payload = token.split(".")[0] ?? "";
41
+ const json = JSON.parse(
42
+ atob(payload.replace(/-/g, "+").replace(/_/g, "/"))
43
+ );
44
+ return typeof json.exp !== "number" || json.exp >= now;
45
+ } catch {
46
+ return true;
47
+ }
48
+ }
49
+ function firstLivePreviewToken(...candidates) {
50
+ const present = candidates.filter((c) => !!c);
51
+ return present.find((t) => previewTokenUnexpired(t)) ?? present[0] ?? null;
52
+ }
38
53
  function storePreviewTokenFrom(jar, request) {
39
54
  const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);
40
- if (stamped) return stamped;
41
55
  const hostMapped = isHostMappedRequest(request);
42
56
  const storeCookie = hostMapped ? storePreviewCookieName("/") : STORE_PREVIEW_COOKIE;
43
57
  const themeCookie = hostMapped ? themePreviewCookieName("/") : THEME_PREVIEW_COOKIE;
44
- return jar.get(storeCookie)?.value || jar.get(themeCookie)?.value || null;
58
+ return firstLivePreviewToken(
59
+ stamped,
60
+ jar.get(storeCookie)?.value,
61
+ jar.get(themeCookie)?.value
62
+ );
45
63
  }
46
64
  const SKIP_STORE_PREVIEW = Object.freeze({
47
65
  skipStorePreview: true
@@ -57,6 +75,8 @@ export {
57
75
  STORE_PREVIEW_PATH,
58
76
  STORE_PREVIEW_TOKEN_HEADER,
59
77
  applyStorePreview,
78
+ firstLivePreviewToken,
79
+ previewTokenUnexpired,
60
80
  skipsStorePreview,
61
81
  storePreviewCookieName,
62
82
  storePreviewTokenFrom
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/store-preview-cookie.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport {\n hostOnlyCookieName,\n isHostMappedRequest,\n secureCookies,\n} from \"../auth/cookies\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n THEME_PREVIEW_COOKIE,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\n\n// No `next/headers` here: the browser bundle reaches this module (through\n// the API client), so readers take the jar and the request as arguments.\n\n/** Holds a coming soon store's preview token (the dashboard's preview link). */\nexport const STORE_PREVIEW_COOKIE = \"ecw_store_preview\";\n/** The preview link's route under the store's root. */\nexport const STORE_PREVIEW_PATH = \"/preview\";\n/** The preview link's query param carrying the token. */\nexport const STORE_PREVIEW_PARAM = \"token\";\n/** The API's request header (`X-Store-Preview`) that opens a coming soon store. */\nexport const STORE_PREVIEW_HEADER = \"x-store-preview\";\n/**\n * Internal request header carrying a theme preview host's (`p-<slug>`) store\n * preview token from the host lookup to the render, in place of the cookie.\n * Only the middleware sets it, and it deletes any value the client sent on\n * every request it lets through, as it does for `THEME_PREVIEW_HOST_HEADER`,\n * so a reader can trust it on any path the matcher covers. Root `/api/*` is\n * outside the matcher; the backend proxy ignores it there.\n */\nexport const STORE_PREVIEW_TOKEN_HEADER = \"x-ecomweb-store-preview-token\";\n\nconst MAX_TOKEN_LENGTH = 2048;\nconst MAX_AGE_SECONDS = 24 * 60 * 60;\n\n/** The store preview cookie's name at `cookiePath` (see hostOnlyCookieName). */\nexport function storePreviewCookieName(cookiePath: string): string {\n return hostOnlyCookieName(STORE_PREVIEW_COOKIE, cookiePath);\n}\n\n/**\n * The dashboard's preview link (`<store root>/preview?token=<t>`) becomes an\n * httpOnly cookie scoped to the store, then a 307 to the store's home, so the\n * token never stays in the address bar or in shared links. A missing, empty\n * or oversized token clears the cookie instead. The API validates the token\n * on every request. SameSite=Lax: the link is a top-level navigation and the\n * store is never framed during a store preview.\n */\nexport function applyStorePreview(\n req: NextRequest,\n cookiePath: string,\n storeRoot: string\n): NextResponse {\n const token = req.nextUrl.searchParams.get(STORE_PREVIEW_PARAM) ?? \"\";\n const url = publicNextUrl(req);\n url.pathname = storeRoot;\n url.search = \"\";\n const res = NextResponse.redirect(url, 307);\n const valid = token.length > 0 && token.length <= MAX_TOKEN_LENGTH;\n res.cookies.set(storePreviewCookieName(cookiePath), valid ? token : \"\", {\n httpOnly: true,\n secure: secureCookies(),\n sameSite: \"lax\",\n path: cookiePath,\n maxAge: valid ? MAX_AGE_SECONDS : 0,\n });\n return res;\n}\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `headers()`-backed requests and `NextRequest`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\n/**\n * The token to send as `X-Store-Preview` for this request, or null. In order:\n * the preview host's token the middleware stamped (`STORE_PREVIEW_TOKEN_HEADER`),\n * the store preview cookie, then the theme preview cookie (`?preview_theme=`\n * on the store's own host), which the API accepts too. Cookies are read under\n * the name their writer used: `/` on a host-mapped request (the `__Host-` name\n * in production, never the bare one a sibling store could plant), else the\n * bare path-scoped name. An empty value counts as none at every step.\n *\n * Trusts `STORE_PREVIEW_TOKEN_HEADER`, so call it only on a request that went\n * through the middleware (server components, route handlers), never on the\n * middleware's own incoming request.\n */\nexport function storePreviewTokenFrom(\n jar: CookieReader,\n request: HeaderReader\n): string | null {\n const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);\n if (stamped) return stamped;\n const hostMapped = isHostMappedRequest(request);\n const storeCookie = hostMapped\n ? storePreviewCookieName(\"/\")\n : STORE_PREVIEW_COOKIE;\n const themeCookie = hostMapped\n ? themePreviewCookieName(\"/\")\n : THEME_PREVIEW_COOKIE;\n return jar.get(storeCookie)?.value || jar.get(themeCookie)?.value || null;\n}\n\n/**\n * Request option that forbids the kit's API client from attaching the\n * request's ambient preview token (`storePreviewTokenFrom`) as\n * `X-Store-Preview`. Spread it into the SDK call's options (the SDK's\n * `RequestOptions` takes extra keys and the kit's ApiClient hands them to\n * axios unchanged). A plain `getStoreByHost(host)` sets it, because its\n * result is cached per host for every visitor and must be the public answer.\n * An explicit `X-Store-Preview` header in the same options still goes out.\n */\nexport const SKIP_STORE_PREVIEW = Object.freeze({\n skipStorePreview: true,\n} as const);\n\n/** True when request options (or an axios config) carry SKIP_STORE_PREVIEW. */\nexport function skipsStorePreview(options: object | undefined): boolean {\n return (\n (options as { skipStorePreview?: unknown } | undefined)\n ?.skipStorePreview === true\n );\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C;AAAA,EAC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,"sources":["../../src/stores/store-preview-cookie.ts"],"sourcesContent":["import { NextResponse, type NextRequest } from \"next/server\";\nimport {\n hostOnlyCookieName,\n isHostMappedRequest,\n secureCookies,\n} from \"../auth/cookies\";\nimport { publicNextUrl } from \"../request/public-url\";\nimport {\n THEME_PREVIEW_COOKIE,\n themePreviewCookieName,\n} from \"../theme/preview-cookie\";\n\n// No `next/headers` here: the browser bundle reaches this module (through\n// the API client), so readers take the jar and the request as arguments.\n\n/** Holds a coming soon store's preview token (the dashboard's preview link). */\nexport const STORE_PREVIEW_COOKIE = \"ecw_store_preview\";\n/** The preview link's route under the store's root. */\nexport const STORE_PREVIEW_PATH = \"/preview\";\n/** The preview link's query param carrying the token. */\nexport const STORE_PREVIEW_PARAM = \"token\";\n/** The API's request header (`X-Store-Preview`) that opens a coming soon store. */\nexport const STORE_PREVIEW_HEADER = \"x-store-preview\";\n/**\n * Internal request header carrying a theme preview host's (`p-<slug>`) store\n * preview token from the host lookup to the render, in place of the cookie.\n * Only the middleware sets it, and it deletes any value the client sent on\n * every request it lets through, as it does for `THEME_PREVIEW_HOST_HEADER`,\n * so a reader can trust it on any path the matcher covers. Root `/api/*` is\n * outside the matcher; the backend proxy ignores it there.\n */\nexport const STORE_PREVIEW_TOKEN_HEADER = \"x-ecomweb-store-preview-token\";\n\nconst MAX_TOKEN_LENGTH = 2048;\nconst MAX_AGE_SECONDS = 24 * 60 * 60;\n\n/** The store preview cookie's name at `cookiePath` (see hostOnlyCookieName). */\nexport function storePreviewCookieName(cookiePath: string): string {\n return hostOnlyCookieName(STORE_PREVIEW_COOKIE, cookiePath);\n}\n\n/**\n * The dashboard's preview link (`<store root>/preview?token=<t>`) becomes an\n * httpOnly cookie scoped to the store, then a 307 to the store's home, so the\n * token never stays in the address bar or in shared links. A missing, empty\n * or oversized token clears the cookie instead. The API validates the token\n * on every request. SameSite=Lax: the link is a top-level navigation and the\n * store is never framed during a store preview.\n */\nexport function applyStorePreview(\n req: NextRequest,\n cookiePath: string,\n storeRoot: string\n): NextResponse {\n const token = req.nextUrl.searchParams.get(STORE_PREVIEW_PARAM) ?? \"\";\n const url = publicNextUrl(req);\n url.pathname = storeRoot;\n url.search = \"\";\n const res = NextResponse.redirect(url, 307);\n const valid = token.length > 0 && token.length <= MAX_TOKEN_LENGTH;\n res.cookies.set(storePreviewCookieName(cookiePath), valid ? token : \"\", {\n httpOnly: true,\n secure: secureCookies(),\n sameSite: \"lax\",\n path: cookiePath,\n maxAge: valid ? MAX_AGE_SECONDS : 0,\n });\n return res;\n}\n\n/** Minimal shape shared by `cookies()` and `request.cookies`. */\ninterface CookieReader {\n get(name: string): { value: string } | undefined;\n}\n\n/** Minimal shape shared by `headers()`-backed requests and `NextRequest`. */\ninterface HeaderReader {\n headers: { get(name: string): string | null };\n}\n\n/**\n * True unless the token's own payload says it has expired. Preview tokens are\n * `<base64url(json)>.<signature>` with `exp` (ms) in the payload; the\n * signature can only be checked by the API, so this only drops tokens that\n * are certainly dead. A token it cannot read counts as live: the API decides.\n */\nexport function previewTokenUnexpired(\n token: string,\n now: number = Date.now()\n): boolean {\n try {\n const payload = token.split(\".\")[0] ?? \"\";\n const json = JSON.parse(\n atob(payload.replace(/-/g, \"+\").replace(/_/g, \"/\"))\n ) as { exp?: unknown };\n return typeof json.exp !== \"number\" || json.exp >= now;\n } catch {\n return true;\n }\n}\n\n/**\n * The first candidate that is present and not expired. When every candidate\n * is expired, the first present one: sending a dead token and getting the\n * API's refusal beats sending none.\n */\nexport function firstLivePreviewToken(\n ...candidates: Array<string | null | undefined>\n): string | null {\n const present = candidates.filter((c): c is string => !!c);\n return present.find(t => previewTokenUnexpired(t)) ?? present[0] ?? null;\n}\n\n/**\n * The token to send as `X-Store-Preview` for this request, or null. In order:\n * the preview host's token the middleware stamped (`STORE_PREVIEW_TOKEN_HEADER`),\n * the store preview cookie, then the theme preview cookie (`?preview_theme=`\n * on the store's own host), which the API accepts too. Cookies are read under\n * the name their writer used: `/` on a host-mapped request (the `__Host-` name\n * in production, never the bare one a sibling store could plant), else the\n * bare path-scoped name. An empty value counts as none at every step, and so\n * does an expired one: a stale store cookie no longer hides a valid theme\n * cookie behind it.\n *\n * Trusts `STORE_PREVIEW_TOKEN_HEADER`, so call it only on a request that went\n * through the middleware (server components, route handlers), never on the\n * middleware's own incoming request.\n */\nexport function storePreviewTokenFrom(\n jar: CookieReader,\n request: HeaderReader\n): string | null {\n const stamped = request.headers.get(STORE_PREVIEW_TOKEN_HEADER);\n const hostMapped = isHostMappedRequest(request);\n const storeCookie = hostMapped\n ? storePreviewCookieName(\"/\")\n : STORE_PREVIEW_COOKIE;\n const themeCookie = hostMapped\n ? themePreviewCookieName(\"/\")\n : THEME_PREVIEW_COOKIE;\n return firstLivePreviewToken(\n stamped,\n jar.get(storeCookie)?.value,\n jar.get(themeCookie)?.value\n );\n}\n\n/**\n * Request option that forbids the kit's API client from attaching the\n * request's ambient preview token (`storePreviewTokenFrom`) as\n * `X-Store-Preview`. Spread it into the SDK call's options (the SDK's\n * `RequestOptions` takes extra keys and the kit's ApiClient hands them to\n * axios unchanged). A plain `getStoreByHost(host)` sets it, because its\n * result is cached per host for every visitor and must be the public answer.\n * An explicit `X-Store-Preview` header in the same options still goes out.\n */\nexport const SKIP_STORE_PREVIEW = Object.freeze({\n skipStorePreview: true,\n} as const);\n\n/** True when request options (or an axios config) carry SKIP_STORE_PREVIEW. */\nexport function skipsStorePreview(options: object | undefined): boolean {\n return (\n (options as { skipStorePreview?: unknown } | undefined)\n ?.skipStorePreview === true\n );\n}\n"],"mappings":"AAAA,SAAS,oBAAsC;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAMA,MAAM,uBAAuB;AAE7B,MAAM,qBAAqB;AAE3B,MAAM,sBAAsB;AAE5B,MAAM,uBAAuB;AAS7B,MAAM,6BAA6B;AAE1C,MAAM,mBAAmB;AACzB,MAAM,kBAAk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,SAAO;AAAA,IACL;AAAA,IACA,IAAI,IAAI,WAAW,GAAG;AAAA,IACtB,IAAI,IAAI,WAAW,GAAG;AAAA,EACxB;AACF;AAWO,MAAM,qBAAqB,OAAO,OAAO;AAAA,EAC9C,kBAAkB;AACpB,CAAU;AAGH,SAAS,kBAAkB,SAAsC;AACtE,SACG,SACG,qBAAqB;AAE7B;","names":[]}
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@ecomweb/storefront-kit",
3
- "version": "0.12.0",
3
+ "version": "0.13.0",
4
4
  "description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "sideEffects": false,
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "https://github.com/travistech20/ecomweb-storefront.git",
10
+ "url": "https://github.com/ecomwebai/ecomweb-storefront.git",
11
11
  "directory": "packages/storefront-kit"
12
12
  },
13
13
  "main": "./dist/index.js",
@@ -47,7 +47,7 @@
47
47
  "currency.js": "^2.0.4",
48
48
  "server-only": "^0.0.1",
49
49
  "zod": "^4.1.12",
50
- "@ecomweb/sdk": "^0.12.0"
50
+ "@ecomweb/sdk": "^0.13.0"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "next": ">=16",