@ecomweb/storefront-kit 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/README.md +25 -1
  2. package/bin/check-client-bundle-lib.d.mts +16 -0
  3. package/bin/check-client-bundle-lib.mjs +58 -0
  4. package/bin/check-client-bundle.d.mts +11 -0
  5. package/bin/check-client-bundle.mjs +8 -0
  6. package/dist/api/client.js +39 -0
  7. package/dist/api/client.js.map +1 -1
  8. package/dist/api/index.js.map +1 -1
  9. package/dist/api/proxy-guard.js +29 -0
  10. package/dist/api/proxy-guard.js.map +1 -0
  11. package/dist/api/proxy-routes.js +126 -0
  12. package/dist/api/proxy-routes.js.map +1 -0
  13. package/dist/api/proxy.js +17 -4
  14. package/dist/api/proxy.js.map +1 -1
  15. package/dist/api/response.js.map +1 -1
  16. package/dist/api/server-sdk.js +41 -0
  17. package/dist/api/server-sdk.js.map +1 -0
  18. package/dist/api/store-preview-header.js.map +1 -1
  19. package/dist/auth/context.js.map +1 -1
  20. package/dist/auth/sdk.js +15 -5
  21. package/dist/auth/sdk.js.map +1 -1
  22. package/dist/auth/session-refresh.js +7 -4
  23. package/dist/auth/session-refresh.js.map +1 -1
  24. package/dist/cart/api.js.map +1 -1
  25. package/dist/cart/server-context.js.map +1 -1
  26. package/dist/checkout/get-payment-state.js +4 -8
  27. package/dist/checkout/get-payment-state.js.map +1 -1
  28. package/dist/checkout/initiate-gateway-payment.js +5 -7
  29. package/dist/checkout/initiate-gateway-payment.js.map +1 -1
  30. package/dist/checkout/order-handoff.js.map +1 -1
  31. package/dist/checkout/payment-redirect.js.map +1 -1
  32. package/dist/checkout/use-checkout.js.map +1 -1
  33. package/dist/client-info.js +1 -1
  34. package/dist/config/public.js +2 -0
  35. package/dist/config/public.js.map +1 -1
  36. package/dist/config/schema.js +16 -4
  37. package/dist/config/schema.js.map +1 -1
  38. package/dist/config/secret-guard.js +20 -0
  39. package/dist/config/secret-guard.js.map +1 -0
  40. package/dist/config/server.js +15 -8
  41. package/dist/config/server.js.map +1 -1
  42. package/dist/config/version-check.js.map +1 -1
  43. package/dist/config.d.ts +22 -4
  44. package/dist/config.js +2 -0
  45. package/dist/config.js.map +1 -1
  46. package/dist/currency.js.map +1 -1
  47. package/dist/index.d.ts +331 -69
  48. package/dist/index.js.map +1 -1
  49. package/dist/logging.js.map +1 -1
  50. package/dist/middleware/create-storefront-middleware.js +14 -3
  51. package/dist/middleware/create-storefront-middleware.js.map +1 -1
  52. package/dist/middleware.d.ts +2 -2
  53. package/dist/middleware.js.map +1 -1
  54. package/dist/{mode-Lm9t4qzX.d.ts → mode-oVZCQxrc.d.ts} +1 -1
  55. package/dist/orders/api-client.js +3 -3
  56. package/dist/orders/api-client.js.map +1 -1
  57. package/dist/orders/bank-transfer.js +1 -1
  58. package/dist/orders/bank-transfer.js.map +1 -1
  59. package/dist/orders/shipment-tracking.js.map +1 -1
  60. package/dist/orders/use-order-status.js +2 -2
  61. package/dist/orders/use-order-status.js.map +1 -1
  62. package/dist/promotions/use-promotion-validation.js +2 -2
  63. package/dist/promotions/use-promotion-validation.js.map +1 -1
  64. package/dist/provider.js.map +1 -1
  65. package/dist/request/served-store.js +5 -0
  66. package/dist/request/served-store.js.map +1 -0
  67. package/dist/{schema-Dg0ZflMW.d.ts → schema-B3nAYiwT.d.ts} +5 -1
  68. package/dist/sdk.js +3 -3
  69. package/dist/sdk.js.map +1 -1
  70. package/dist/server/routes.js +16 -9
  71. package/dist/server/routes.js.map +1 -1
  72. package/dist/server.d.ts +46 -5
  73. package/dist/server.js +2 -0
  74. package/dist/server.js.map +1 -1
  75. package/dist/shipping/location-areas.js.map +1 -1
  76. package/dist/shipping/use-shipping-calculation.js +2 -2
  77. package/dist/shipping/use-shipping-calculation.js.map +1 -1
  78. package/dist/storage.js.map +1 -1
  79. package/dist/store/store-context.js.map +1 -1
  80. package/dist/store-scope/index.js.map +1 -1
  81. package/dist/stores/basic-settings.js.map +1 -1
  82. package/dist/stores/cached.js.map +1 -1
  83. package/dist/theme/define.js.map +1 -1
  84. package/dist/theme/index.js.map +1 -1
  85. package/dist/theme/settings-context.js.map +1 -1
  86. package/dist/theme/style.js.map +1 -1
  87. package/dist/theme.d.ts +33 -0
  88. package/package.json +6 -2
  89. package/dist/api/server-client.js +0 -162
  90. package/dist/api/server-client.js.map +0 -1
@@ -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 */\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;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,EAAE,OAAO,CAAC;AACxD;AAQA,SAAS,cAAc,UAAoB,QAA4B;AACr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AsB;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, storefrontSecretKey } 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\";\nimport { isSameOriginRequest, proxyNotFound } from \"./proxy-guard\";\nimport { matchProxiedRoute } from \"./proxy-routes\";\n\n/**\n * Same-origin server proxy for every private storefront call the browser\n * makes, guest calls included (cart, checkout, orders, payments, review\n * invitations, account), plus the public reads that need the shopper's\n * session.\n *\n * The browser holds only the publishable key, and session tokens live in\n * httpOnly, store-scoped cookies (`lib/auth/cookies.ts`) that browser JS\n * cannot read. So the browser calls `/store/<storeRef>/api/backend/<path>`\n * (same origin, so the cookie is sent) and this handler, on the server,\n * attaches the storefront secret key and the bearer token before forwarding.\n * In the shared app that secret is a platform key valid for every store, so\n * the proxy is locked down: only same-origin callers, only the routes in\n * `PROXIED_STOREFRONT_ROUTES` (closed by default), and only for the store\n * this request serves (the route's store, which `createBackendProxy` has\n * already checked against the middleware's stamp, must equal the store the\n * forwarded API path names). Every refusal is the same 404 `NOT_FOUND`.\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\ntype RefusalReason =\n | \"cross-site\"\n | \"invalid-path\"\n | \"not-proxied\"\n | \"store-mismatch\";\n\n/**\n * Logs the reason, store and method only: never the path (it can carry review\n * tokens and order codes), headers or body.\n */\nfunction refuse(\n reason: RefusalReason,\n storeRef: string,\n method: string\n): NextResponse {\n console.debug(\"backend proxy refused\", { reason, storeRef, method });\n return proxyNotFound();\n}\n\n/**\n * Rebuilds the upstream URL from the catch-all segments, each one passed\n * through `encodeURIComponent`. Next has already percent-decoded them, so\n * `..` arrives literally and is rejected here; the origin/prefix check\n * afterwards is the backstop that keeps this route from becoming an open\n * 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\", storefrontSecretKey());\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\n/**\n * Forwards one browser call to the API under the storefront secret key, or\n * answers 404 `NOT_FOUND` when the caller is not same-origin, the path is\n * malformed or not in `PROXIED_STOREFRONT_ROUTES`, or the path names a store\n * other than `storeRef`. Retries once after a token refresh on a 401.\n */\nexport async function handleBackendProxy(\n request: NextRequest,\n storeRef: string,\n segments: string[]\n): Promise<NextResponse> {\n const method = request.method;\n if (!isSameOriginRequest(request)) {\n return refuse(\"cross-site\", storeRef, method);\n }\n\n const target = resolveTarget(segments, request.nextUrl.search);\n if (!target) return refuse(\"invalid-path\", storeRef, method);\n\n const match = matchProxiedRoute(method, segments);\n if (!match) return refuse(\"not-proxied\", storeRef, method);\n // The API picks the store from the forwarded path, not from this route.\n if (match.storeRef !== storeRef) {\n return refuse(\"store-mismatch\", storeRef, method);\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,2BAA2B;AACnE,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,qBAAqB,qBAAqB;AACnD,SAAS,yBAAyB;AAgDlC,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,QAA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AAEA,SAAO;AACT;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/response.ts"],"sourcesContent":["import { ApiResponse } from \"../interfaces\";\n\nexport class ApiClientError extends Error {\n statusCode: number;\n code?: string;\n /**\n * A business error's structured payload, for example the per-line items of\n * an INSUFFICIENT_INVENTORY rejection. Carried here as well as on the SDK's\n * own error class because this repo has two: checkout's order creation\n * throws the SDK's, while the payment helpers throw this one. Dropping the\n * payload on one of them would lose it silently on whichever path a caller\n * happens to be using.\n */\n details?: unknown;\n constructor(message: string, statusCode = 0, code?: string, details?: unknown) {\n super(message);\n this.name = \"ApiClientError\";\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n}\n\n// Unwraps a successful response, throws if not successful\nexport function unwrap<T>(response: ApiResponse<T>): T {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n\n// Unwraps a response but returns null for specific status codes (default 404)\nexport function unwrapOrNull<T>(\n response: ApiResponse<T>,\n nullStatusCodes: number[] = [404]\n): T | null {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n if (\n !response.success &&\n response.error &&\n nullStatusCodes.includes(response.error.statusCode)\n ) {\n return null;\n }\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n\n// Ensures the response is successful (useful for void endpoints)\nexport function ensureSuccess(response: ApiResponse<any>): void {\n if (response.success) return;\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n"],"mappings":"AAEO,MAAM,uBAAuB,MAAM;AAAA,EACxC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA;AAAA,EACA,YAAY,SAAiB,aAAa,GAAG,MAAe,SAAmB;AAC7E,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAGO,SAAS,OAAU,UAA6B;AACrD,MAAI,SAAS,WAAW,SAAS,SAAS,QAAW;AACnD,WAAO,SAAS;AAAA,EAClB;AACA,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;AAGO,SAAS,aACd,UACA,kBAA4B,CAAC,GAAG,GACtB;AACV,MAAI,SAAS,WAAW,SAAS,SAAS,QAAW;AACnD,WAAO,SAAS;AAAA,EAClB;AACA,MACE,CAAC,SAAS,WACV,SAAS,SACT,gBAAgB,SAAS,SAAS,MAAM,UAAU,GAClD;AACA,WAAO;AAAA,EACT;AACA,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;AAGO,SAAS,cAAc,UAAkC;AAC9D,MAAI,SAAS,QAAS;AACtB,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;","names":[]}
1
+ {"version":3,"sources":["../../src/api/response.ts"],"sourcesContent":["import { ApiResponse } from \"../interfaces\";\n\nexport class ApiClientError extends Error {\n statusCode: number;\n code?: string;\n /**\n * A business error's structured payload, for example the per-line items of\n * an INSUFFICIENT_INVENTORY rejection. Carried here as well as on the SDK's\n * own error class because this repo has two: checkout's order creation\n * throws the SDK's, while the payment helpers throw this one. Dropping the\n * payload on one of them would lose it silently on whichever path a caller\n * happens to be using.\n */\n details?: unknown;\n constructor(message: string, statusCode = 0, code?: string, details?: unknown) {\n super(message);\n this.name = \"ApiClientError\";\n this.statusCode = statusCode;\n this.code = code;\n this.details = details;\n }\n}\n\n// Unwraps a successful response, throws if not successful\n/**\n * Returns the data of a successful API response.\n *\n * @param response - A response from an SDK call.\n * @returns The response data.\n * @throws ApiClientError when the response failed, with the API's message, status code and error code.\n */\nexport function unwrap<T>(response: ApiResponse<T>): T {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n\n// Unwraps a response but returns null for specific status codes (default 404)\n/**\n * Returns the data of a successful API response, or `null` when the API\n * answered with one of the given status codes.\n *\n * @param response - A response from an SDK call.\n * @param nullStatusCodes - Statuses that mean \"nothing there\"; defaults to `[404]`.\n * @returns The response data, or `null` when not found.\n * @throws ApiClientError on any other API error.\n */\nexport function unwrapOrNull<T>(\n response: ApiResponse<T>,\n nullStatusCodes: number[] = [404]\n): T | null {\n if (response.success && response.data !== undefined) {\n return response.data as T;\n }\n if (\n !response.success &&\n response.error &&\n nullStatusCodes.includes(response.error.statusCode)\n ) {\n return null;\n }\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n\n// Ensures the response is successful (useful for void endpoints)\nexport function ensureSuccess(response: ApiResponse<any>): void {\n if (response.success) return;\n const message = response.error?.message || \"Request failed\";\n const status = response.error?.statusCode || 0;\n const code = response.error?.error;\n throw new ApiClientError(message, status, code, response.error?.details);\n}\n"],"mappings":"AAEO,MAAM,uBAAuB,MAAM;AAAA,EACxC;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA;AAAA,EACA,YAAY,SAAiB,aAAa,GAAG,MAAe,SAAmB;AAC7E,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,OAAO;AACZ,SAAK,UAAU;AAAA,EACjB;AACF;AAUO,SAAS,OAAU,UAA6B;AACrD,MAAI,SAAS,WAAW,SAAS,SAAS,QAAW;AACnD,WAAO,SAAS;AAAA,EAClB;AACA,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;AAYO,SAAS,aACd,UACA,kBAA4B,CAAC,GAAG,GACtB;AACV,MAAI,SAAS,WAAW,SAAS,SAAS,QAAW;AACnD,WAAO,SAAS;AAAA,EAClB;AACA,MACE,CAAC,SAAS,WACV,SAAS,SACT,gBAAgB,SAAS,SAAS,MAAM,UAAU,GAClD;AACA,WAAO;AAAA,EACT;AACA,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;AAGO,SAAS,cAAc,UAAkC;AAC9D,MAAI,SAAS,QAAS;AACtB,QAAM,UAAU,SAAS,OAAO,WAAW;AAC3C,QAAM,SAAS,SAAS,OAAO,cAAc;AAC7C,QAAM,OAAO,SAAS,OAAO;AAC7B,QAAM,IAAI,eAAe,SAAS,QAAQ,MAAM,SAAS,OAAO,OAAO;AACzE;","names":[]}
@@ -0,0 +1,41 @@
1
+ import "server-only";
2
+ import { createEcomwebServerSdk } from "@ecomweb/sdk";
3
+ import { clientIpFrom } from "../auth/client-ip.js";
4
+ import { authHttpClient, storefrontSecretKey } from "../auth/sdk.js";
5
+ import { KIT_CLIENT_TOKEN } from "../client-info.js";
6
+ import { readStorePreviewToken } from "../stores/read-store-preview-token.js";
7
+ const SHOPPER_CALL_ON_SERVER = {
8
+ success: false,
9
+ error: {
10
+ statusCode: 401,
11
+ error: "SDK_SHOPPER_CALL_ON_SERVER",
12
+ message: "Shopper calls run in the browser: use createStoreSdk(storeRef)"
13
+ }
14
+ };
15
+ const shopperCallsRefused = {
16
+ get: async () => SHOPPER_CALL_ON_SERVER,
17
+ post: async () => SHOPPER_CALL_ON_SERVER,
18
+ put: async () => SHOPPER_CALL_ON_SERVER,
19
+ patch: async () => SHOPPER_CALL_ON_SERVER,
20
+ delete: async () => SHOPPER_CALL_ON_SERVER
21
+ };
22
+ function serverSdkFor(clientIp, previewToken) {
23
+ return createEcomwebServerSdk({
24
+ publicHttp: authHttpClient(clientIp, previewToken),
25
+ authHttp: shopperCallsRefused,
26
+ secretKey: storefrontSecretKey(),
27
+ clientInfo: KIT_CLIENT_TOKEN
28
+ });
29
+ }
30
+ async function getServerSdk() {
31
+ const { headers } = await import("next/headers");
32
+ return serverSdkFor(
33
+ clientIpFrom(await headers()),
34
+ await readStorePreviewToken()
35
+ );
36
+ }
37
+ export {
38
+ getServerSdk,
39
+ serverSdkFor
40
+ };
41
+ //# sourceMappingURL=server-sdk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/api/server-sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { createEcomwebServerSdk } from \"@ecomweb/sdk\";\nimport type { ApiResponse, EcomwebServerSdk, IHttpClient } from \"@ecomweb/sdk\";\nimport { clientIpFrom } from \"../auth/client-ip\";\nimport { authHttpClient, storefrontSecretKey } from \"../auth/sdk\";\nimport { KIT_CLIENT_TOKEN } from \"../client-info\";\nimport { readStorePreviewToken } from \"../stores/read-store-preview-token\";\n\nconst SHOPPER_CALL_ON_SERVER: ApiResponse<never> = {\n success: false,\n error: {\n statusCode: 401,\n error: \"SDK_SHOPPER_CALL_ON_SERVER\",\n message:\n \"Shopper calls run in the browser: use createStoreSdk(storeRef)\",\n },\n};\n\n/** Answers every shopper-side call with the same 401: a server has no shopper session. */\nconst shopperCallsRefused: IHttpClient = {\n get: async () => SHOPPER_CALL_ON_SERVER,\n post: async () => SHOPPER_CALL_ON_SERVER,\n put: async () => SHOPPER_CALL_ON_SERVER,\n patch: async () => SHOPPER_CALL_ON_SERVER,\n delete: async () => SHOPPER_CALL_ON_SERVER,\n};\n\n/** Internal: builds the server SDK for one request's shopper IP and preview token. */\nexport function serverSdkFor(\n clientIp?: string,\n previewToken?: string | null\n): EcomwebServerSdk {\n return createEcomwebServerSdk({\n publicHttp: authHttpClient(clientIp, previewToken),\n authHttp: shopperCallsRefused,\n secretKey: storefrontSecretKey(),\n clientInfo: KIT_CLIENT_TOKEN,\n });\n}\n\n/**\n * The server SDK for the current request, signed with the storefront secret\n * key, for private reads in server components and route handlers (for example\n * a review invitation by token). The shopper's IP and the store preview token\n * are taken from the request.\n *\n * Shopper-side methods (cart, orders, addresses and the like) do not work\n * here: a server has no shopper session, so they reject with\n * `SDK_SHOPPER_CALL_ON_SERVER`. Use `createStoreSdk(storeRef)` in the browser.\n *\n * @example\n * ```ts\n * import { getServerSdk } from \"@ecomweb/storefront-kit/server\";\n *\n * const sdk = await getServerSdk();\n * const invitation = await sdk.reviews.getReviewInvitation(storeRef, token);\n * ```\n *\n * @returns The server SDK for this request\n * @throws Error when the storefront secret key is not set\n */\nexport async function getServerSdk(): Promise<EcomwebServerSdk> {\n const { headers } = await import(\"next/headers\");\n return serverSdkFor(\n clientIpFrom(await headers()),\n await readStorePreviewToken()\n );\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,8BAA8B;AAEvC,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,2BAA2B;AACpD,SAAS,wBAAwB;AACjC,SAAS,6BAA6B;AAEtC,MAAM,yBAA6C;AAAA,EACjD,SAAS;AAAA,EACT,OAAO;AAAA,IACL,YAAY;AAAA,IACZ,OAAO;AAAA,IACP,SACE;AAAA,EACJ;AACF;AAGA,MAAM,sBAAmC;AAAA,EACvC,KAAK,YAAY;AAAA,EACjB,MAAM,YAAY;AAAA,EAClB,KAAK,YAAY;AAAA,EACjB,OAAO,YAAY;AAAA,EACnB,QAAQ,YAAY;AACtB;AAGO,SAAS,aACd,UACA,cACkB;AAClB,SAAO,uBAAuB;AAAA,IAC5B,YAAY,eAAe,UAAU,YAAY;AAAA,IACjD,UAAU;AAAA,IACV,WAAW,oBAAoB;AAAA,IAC/B,YAAY;AAAA,EACd,CAAC;AACH;AAuBA,eAAsB,eAA0C;AAC9D,QAAM,EAAE,QAAQ,IAAI,MAAM,OAAO,cAAc;AAC/C,SAAO;AAAA,IACL,aAAa,MAAM,QAAQ,CAAC;AAAA,IAC5B,MAAM,sBAAsB;AAAA,EAC9B;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/store-preview-header.ts"],"sourcesContent":["import { storePreviewTokenFrom } from \"../stores/store-preview-cookie\";\n\n/**\n * The browser's store preview token, which the layout hands over through\n * `StorefrontKitProvider` (see `storePreviewToken` there). Module-level: one\n * browser tab is one store. It stays set after the store opens until the\n * next layout render passes null (a reload); accepted: an open store needs\n * no token, so the API's answers do not change, only the kit's preview\n * cues lag in a tab left open across the opening.\n */\nlet browserToken: string | null = null;\n\n/**\n * Sets the token the browser's kit clients send as `X-Store-Preview`. Does\n * nothing on the server: a server module is shared by every request, so a\n * value set there would reach other shoppers.\n */\nexport function setBrowserStorePreviewToken(token: string | null): void {\n if (typeof window === \"undefined\") return;\n browserToken = token;\n}\n\n/**\n * True in the browser while a store preview token is set: the shopper is a\n * previewer, and the API refuses every write. The cart and checkout check\n * this to refuse a write without sending it.\n */\nexport function isBrowserStorePreview(): boolean {\n return typeof window !== \"undefined\" && browserToken !== null;\n}\n\n/**\n * Fetches a fresh preview token, set by `StorefrontKitProvider` only on a\n * theme preview host, whose token lasts 1 h (the app re-renders the layout,\n * which hands the new token over). A link preview's 24 h cookie has none.\n */\nlet renewer: (() => void) | null = null;\nlet lastRenewalAt: number | null = null;\n\n/** The shortest gap between two renewals a 403 asks for. */\nconst RENEWAL_THROTTLE_MS = 60_000;\n\n/** Sets or clears the renewer; a new one may renew at once. */\nexport function setStorePreviewRenewer(renew: (() => void) | null): void {\n renewer = renew;\n lastRenewalAt = null;\n}\n\n/**\n * Asks for a fresh preview token after a read was refused with\n * `STORE_COMING_SOON`. False when there is no renewer: the preview is over.\n * Otherwise true, and the renewer runs at most once per minute, so a page\n * whose reads all fail together renews once.\n */\nexport function requestStorePreviewRenewal(): boolean {\n if (!renewer) return false;\n const now = Date.now();\n if (lastRenewalAt === null || now - lastRenewalAt >= RENEWAL_THROTTLE_MS) {\n lastRenewalAt = now;\n renewer();\n }\n return true;\n}\n\n/**\n * The token this call should send as `X-Store-Preview`, or null. In the\n * browser, the one the layout handed over. On the server, the request's own\n * (`storePreviewTokenFrom`: a preview host's stamped token, else the store\n * preview cookie, else the theme preview cookie). Outside a request scope\n * (build time), `next/headers` throws and this is null.\n *\n * In the middleware it does not throw: Next 16 runs the middleware inside a\n * request store, so `next/headers` is the middleware's own incoming\n * request, before any sanitising, and this returns whatever token the\n * client sent, a forged `STORE_PREVIEW_TOKEN_HEADER` included. So every SDK\n * call the middleware makes must pass `SKIP_STORE_PREVIEW` or an explicit\n * `X-Store-Preview` header (as getStoreByHost, lookupRedirect and\n * getStoreSubdomain do).\n */\nexport async function currentStorePreviewToken(): Promise<string | null> {\n if (typeof window !== \"undefined\") return browserToken;\n try {\n // Imported lazily: this module is in the browser bundle too (as in\n // api/server-client.ts).\n const { cookies, headers } = await import(\"next/headers\");\n return storePreviewTokenFrom(await cookies(), { headers: await headers() });\n } catch {\n return null;\n }\n}\n"],"mappings":"AAAA,SAAS,6BAA6B;AAUtC,IAAI,eAA8B;AAO3B,SAAS,4BAA4B,OAA4B;AACtE,MAAI,OAAO,WAAW,YAAa;AACnC,iBAAe;AACjB;AAOO,SAAS,wBAAiC;AAC/C,SAAO,OAAO,WAAW,eAAe,iBAAiB;AAC3D;AAOA,IAAI,UAA+B;AACnC,IAAI,gBAA+B;AAGnC,MAAM,sBAAsB;AAGrB,SAAS,uBAAuB,OAAkC;AACvE,YAAU;AACV,kBAAgB;AAClB;AAQO,SAAS,6BAAsC;AACpD,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,kBAAkB,QAAQ,MAAM,iBAAiB,qBAAqB;AACxE,oBAAgB;AAChB,YAAQ;AAAA,EACV;AACA,SAAO;AACT;AAiBA,eAAsB,2BAAmD;AACvE,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AAGF,UAAM,EAAE,SAAS,QAAQ,IAAI,MAAM,OAAO,cAAc;AACxD,WAAO,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,MAAM,QAAQ,EAAE,CAAC;AAAA,EAC5E,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/api/store-preview-header.ts"],"sourcesContent":["import { storePreviewTokenFrom } from \"../stores/store-preview-cookie\";\n\n/**\n * The browser's store preview token, which the layout hands over through\n * `StorefrontKitProvider` (see `storePreviewToken` there). Module-level: one\n * browser tab is one store. It stays set after the store opens until the\n * next layout render passes null (a reload); accepted: an open store needs\n * no token, so the API's answers do not change, only the kit's preview\n * cues lag in a tab left open across the opening.\n */\nlet browserToken: string | null = null;\n\n/**\n * Sets the token the browser's kit clients send as `X-Store-Preview`. Does\n * nothing on the server: a server module is shared by every request, so a\n * value set there would reach other shoppers.\n */\nexport function setBrowserStorePreviewToken(token: string | null): void {\n if (typeof window === \"undefined\") return;\n browserToken = token;\n}\n\n/**\n * True in the browser while a store preview token is set: the shopper is a\n * previewer, and the API refuses every write. The cart and checkout check\n * this to refuse a write without sending it.\n */\nexport function isBrowserStorePreview(): boolean {\n return typeof window !== \"undefined\" && browserToken !== null;\n}\n\n/**\n * Fetches a fresh preview token, set by `StorefrontKitProvider` only on a\n * theme preview host, whose token lasts 1 h (the app re-renders the layout,\n * which hands the new token over). A link preview's 24 h cookie has none.\n */\nlet renewer: (() => void) | null = null;\nlet lastRenewalAt: number | null = null;\n\n/** The shortest gap between two renewals a 403 asks for. */\nconst RENEWAL_THROTTLE_MS = 60_000;\n\n/** Sets or clears the renewer; a new one may renew at once. */\nexport function setStorePreviewRenewer(renew: (() => void) | null): void {\n renewer = renew;\n lastRenewalAt = null;\n}\n\n/**\n * Asks for a fresh preview token after a read was refused with\n * `STORE_COMING_SOON`. False when there is no renewer: the preview is over.\n * Otherwise true, and the renewer runs at most once per minute, so a page\n * whose reads all fail together renews once.\n */\nexport function requestStorePreviewRenewal(): boolean {\n if (!renewer) return false;\n const now = Date.now();\n if (lastRenewalAt === null || now - lastRenewalAt >= RENEWAL_THROTTLE_MS) {\n lastRenewalAt = now;\n renewer();\n }\n return true;\n}\n\n/**\n * The token this call should send as `X-Store-Preview`, or null. In the\n * browser, the one the layout handed over. On the server, the request's own\n * (`storePreviewTokenFrom`: a preview host's stamped token, else the store\n * preview cookie, else the theme preview cookie). Outside a request scope\n * (build time), `next/headers` throws and this is null.\n *\n * In the middleware it does not throw: Next 16 runs the middleware inside a\n * request store, so `next/headers` is the middleware's own incoming\n * request, before any sanitising, and this returns whatever token the\n * client sent, a forged `STORE_PREVIEW_TOKEN_HEADER` included. So every SDK\n * call the middleware makes must pass `SKIP_STORE_PREVIEW` or an explicit\n * `X-Store-Preview` header (as getStoreByHost, lookupRedirect and\n * getStoreSubdomain do).\n */\nexport async function currentStorePreviewToken(): Promise<string | null> {\n if (typeof window !== \"undefined\") return browserToken;\n try {\n // Imported lazily: this module is in the browser bundle too (as in\n // api/server-sdk.ts).\n const { cookies, headers } = await import(\"next/headers\");\n return storePreviewTokenFrom(await cookies(), { headers: await headers() });\n } catch {\n return null;\n }\n}\n"],"mappings":"AAAA,SAAS,6BAA6B;AAUtC,IAAI,eAA8B;AAO3B,SAAS,4BAA4B,OAA4B;AACtE,MAAI,OAAO,WAAW,YAAa;AACnC,iBAAe;AACjB;AAOO,SAAS,wBAAiC;AAC/C,SAAO,OAAO,WAAW,eAAe,iBAAiB;AAC3D;AAOA,IAAI,UAA+B;AACnC,IAAI,gBAA+B;AAGnC,MAAM,sBAAsB;AAGrB,SAAS,uBAAuB,OAAkC;AACvE,YAAU;AACV,kBAAgB;AAClB;AAQO,SAAS,6BAAsC;AACpD,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,MAAM,KAAK,IAAI;AACrB,MAAI,kBAAkB,QAAQ,MAAM,iBAAiB,qBAAqB;AACxE,oBAAgB;AAChB,YAAQ;AAAA,EACV;AACA,SAAO;AACT;AAiBA,eAAsB,2BAAmD;AACvE,MAAI,OAAO,WAAW,YAAa,QAAO;AAC1C,MAAI;AAGF,UAAM,EAAE,SAAS,QAAQ,IAAI,MAAM,OAAO,cAAc;AACxD,WAAO,sBAAsB,MAAM,QAAQ,GAAG,EAAE,SAAS,MAAM,QAAQ,EAAE,CAAC;AAAA,EAC5E,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/context.tsx"],"sourcesContent":["\"use client\";\n\nimport type React from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { useStoreData } from \"../store/store-context\";\nimport { storeApiPath } from \"../store-scope\";\n\ninterface AuthError {\n message: string;\n code?: string;\n}\n\ninterface AuthContextType {\n user: CurrentIdentity | null;\n loading: boolean;\n isAnonymous: boolean;\n signIn: (\n email: string,\n password: string\n ) => Promise<{ error: AuthError | null }>;\n signUp: (\n email: string,\n password: string,\n name?: string\n ) => Promise<{ error: AuthError | null }>;\n sendLoginCode: (email: string) => Promise<{ error: AuthError | null }>;\n verifyOtp: (\n email: string,\n code: string\n ) => Promise<{ error: AuthError | null }>;\n signInWithGoogle: (nextPath?: string) => Promise<{ error: AuthError | null }>;\n signInAnonymously: () => Promise<{ error: AuthError | null }>;\n signOut: () => Promise<void>;\n refresh: () => Promise<void>;\n}\n\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\nexport function AuthProvider({ children }: { children: React.ReactNode }) {\n const store = useStoreData();\n const storeRef = store.ref;\n const [user, setUser] = useState<CurrentIdentity | null>(null);\n const [loading, setLoading] = useState(true);\n\n const base = storeApiPath(storeRef, \"auth\");\n\n /** Tokens live in httpOnly cookies, so identity comes from the server. */\n const loadUser = useCallback(async () => {\n try {\n const res = await fetch(storeApiPath(storeRef, \"auth/session\"), {\n cache: \"no-store\",\n });\n setUser(res.ok ? ((await res.json()).identity ?? null) : null);\n } catch {\n setUser(null);\n } finally {\n setLoading(false);\n }\n }, [storeRef]);\n\n useEffect(() => {\n void loadUser();\n }, [loadUser]);\n\n const post = useCallback(\n async (\n action: string,\n body?: unknown\n ): Promise<{ error: AuthError | null }> => {\n const res = await fetch(`${base}/${action}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body ?? {}),\n });\n\n if (!res.ok) {\n const payload = await res.json().catch(() => null);\n return { error: payload?.error ?? { message: \"Request failed\" } };\n }\n\n return { error: null };\n },\n [base]\n );\n\n const signIn = useCallback(\n async (email: string, password: string) => {\n const result = await post(\"login\", { email, password });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signUp = useCallback(\n async (email: string, password: string, name?: string) =>\n // Registration deliberately does not log the caller in. An anonymous\n // identity being upgraded is identified server-side from the session\n // cookie (lib/auth/route-handlers.ts), never from anything sent here.\n post(\"register\", { email, password, name }),\n [post]\n );\n\n const sendLoginCode = useCallback(\n async (email: string) => post(\"otp/request\", { email }),\n [post]\n );\n\n const verifyOtp = useCallback(\n async (email: string, code: string) => {\n const result = await post(\"otp/verify\", { email, code });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signInWithGoogle = useCallback(\n async (nextPath?: string) => {\n const res = await fetch(\n `${base}/google/url?redirect_to=${encodeURIComponent(nextPath || \"/\")}`\n );\n\n if (!res.ok) return { error: { message: \"Google sign-in unavailable\" } };\n\n const { url } = await res.json();\n window.location.href = url;\n return { error: null };\n },\n [base]\n );\n\n const signInAnonymously = useCallback(async () => {\n const result = await post(\"anonymous\");\n if (!result.error) await loadUser();\n return result;\n }, [post, loadUser]);\n\n const signOut = useCallback(async () => {\n await post(\"logout\");\n setUser(null);\n }, [post]);\n\n const value: AuthContextType = {\n user,\n loading,\n isAnonymous: user?.is_anonymous ?? false,\n signIn,\n signUp,\n sendLoginCode,\n verifyOtp,\n signInWithGoogle,\n signInAnonymously,\n signOut,\n refresh: loadUser,\n };\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;\n}\n\nexport function useAuth() {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error(\"useAuth must be used within an AuthProvider\");\n }\n return context;\n}\n"],"mappings":";AAoKS;AAjKT;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AA+B7B,MAAM,cAAc,cAA2C,MAAS;AAEjE,SAAS,aAAa,EAAE,SAAS,GAAkC;AACxE,QAAM,QAAQ,aAAa;AAC3B,QAAM,WAAW,MAAM;AACvB,QAAM,CAAC,MAAM,OAAO,IAAI,SAAiC,IAAI;AAC7D,QAAM,CAAC,SAAS,UAAU,IAAI,SAAS,IAAI;AAE3C,QAAM,OAAO,aAAa,UAAU,MAAM;AAG1C,QAAM,WAAW,YAAY,YAAY;AACvC,QAAI;AACF,YAAM,MAAM,MAAM,MAAM,aAAa,UAAU,cAAc,GAAG;AAAA,QAC9D,OAAO;AAAA,MACT,CAAC;AACD,cAAQ,IAAI,MAAO,MAAM,IAAI,KAAK,GAAG,YAAY,OAAQ,IAAI;AAAA,IAC/D,QAAQ;AACN,cAAQ,IAAI;AAAA,IACd,UAAE;AACA,iBAAW,KAAK;AAAA,IAClB;AAAA,E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ACT;AAAA,IACA,CAAC,MAAM,QAAQ;AAAA,EACjB;AAEA,QAAM,mBAAmB;AAAA,IACvB,OAAO,aAAsB;AAC3B,YAAM,MAAM,MAAM;AAAA,QAChB,GAAG,IAAI,2BAA2B,mBAAmB,YAAY,GAAG,CAAC;AAAA,MACvE;AAEA,UAAI,CAAC,IAAI,GAAI,QAAO,EAAE,OAAO,EAAE,SAAS,6BAA6B,EAAE;AAEvE,YAAM,EAAE,IAAI,IAAI,MAAM,IAAI,KAAK;AAC/B,aAAO,SAAS,OAAO;AACvB,aAAO,EAAE,OAAO,KAAK;AAAA,IACvB;AAAA,IACA,CAAC,IAAI;AAAA,EACP;AAEA,QAAM,oBAAoB,YAAY,YAAY;AAChD,UAAM,SAAS,MAAM,KAAK,WAAW;AACrC,QAAI,CAAC,OAAO,MAAO,OAAM,SAAS;AAClC,WAAO;AAAA,EACT,GAAG,CAAC,MAAM,QAAQ,CAAC;AAEnB,QAAM,UAAU,YAAY,YAAY;AACtC,UAAM,KAAK,QAAQ;AACnB,YAAQ,IAAI;AAAA,EACd,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,QAAyB;AAAA,IAC7B;AAAA,IACA;AAAA,IACA,aAAa,MAAM,gBAAgB;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,EACX;AAEA,SAAO,oBAAC,YAAY,UAAZ,EAAqB,OAAe,UAAS;AACvD;AAEO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AACA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/context.tsx"],"sourcesContent":["\"use client\";\n\nimport type React from \"react\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useState,\n} from \"react\";\nimport type { CurrentIdentity } from \"@ecomweb/sdk\";\nimport { useStoreData } from \"../store/store-context\";\nimport { storeApiPath } from \"../store-scope\";\n\ninterface AuthError {\n message: string;\n code?: string;\n}\n\ninterface AuthContextType {\n user: CurrentIdentity | null;\n loading: boolean;\n isAnonymous: boolean;\n signIn: (\n email: string,\n password: string\n ) => Promise<{ error: AuthError | null }>;\n signUp: (\n email: string,\n password: string,\n name?: string\n ) => Promise<{ error: AuthError | null }>;\n sendLoginCode: (email: string) => Promise<{ error: AuthError | null }>;\n verifyOtp: (\n email: string,\n code: string\n ) => Promise<{ error: AuthError | null }>;\n signInWithGoogle: (nextPath?: string) => Promise<{ error: AuthError | null }>;\n signInAnonymously: () => Promise<{ error: AuthError | null }>;\n signOut: () => Promise<void>;\n refresh: () => Promise<void>;\n}\n\nconst AuthContext = createContext<AuthContextType | undefined>(undefined);\n\nexport function AuthProvider({ children }: { children: React.ReactNode }) {\n const store = useStoreData();\n const storeRef = store.ref;\n const [user, setUser] = useState<CurrentIdentity | null>(null);\n const [loading, setLoading] = useState(true);\n\n const base = storeApiPath(storeRef, \"auth\");\n\n /** Tokens live in httpOnly cookies, so identity comes from the server. */\n const loadUser = useCallback(async () => {\n try {\n const res = await fetch(storeApiPath(storeRef, \"auth/session\"), {\n cache: \"no-store\",\n });\n setUser(res.ok ? ((await res.json()).identity ?? null) : null);\n } catch {\n setUser(null);\n } finally {\n setLoading(false);\n }\n }, [storeRef]);\n\n useEffect(() => {\n void loadUser();\n }, [loadUser]);\n\n const post = useCallback(\n async (\n action: string,\n body?: unknown\n ): Promise<{ error: AuthError | null }> => {\n const res = await fetch(`${base}/${action}`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body ?? {}),\n });\n\n if (!res.ok) {\n const payload = await res.json().catch(() => null);\n return { error: payload?.error ?? { message: \"Request failed\" } };\n }\n\n return { error: null };\n },\n [base]\n );\n\n const signIn = useCallback(\n async (email: string, password: string) => {\n const result = await post(\"login\", { email, password });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signUp = useCallback(\n async (email: string, password: string, name?: string) =>\n // Registration deliberately does not log the caller in. An anonymous\n // identity being upgraded is identified server-side from the session\n // cookie (lib/auth/route-handlers.ts), never from anything sent here.\n post(\"register\", { email, password, name }),\n [post]\n );\n\n const sendLoginCode = useCallback(\n async (email: string) => post(\"otp/request\", { email }),\n [post]\n );\n\n const verifyOtp = useCallback(\n async (email: string, code: string) => {\n const result = await post(\"otp/verify\", { email, code });\n if (!result.error) await loadUser();\n return result;\n },\n [post, loadUser]\n );\n\n const signInWithGoogle = useCallback(\n async (nextPath?: string) => {\n const res = await fetch(\n `${base}/google/url?redirect_to=${encodeURIComponent(nextPath || \"/\")}`\n );\n\n if (!res.ok) return { error: { message: \"Google sign-in unavailable\" } };\n\n const { url } = await res.json();\n window.location.href = url;\n return { error: null };\n },\n [base]\n );\n\n const signInAnonymously = useCallback(async () => {\n const result = await post(\"anonymous\");\n if (!result.error) await loadUser();\n return result;\n }, [post, loadUser]);\n\n const signOut = useCallback(async () => {\n await post(\"logout\");\n setUser(null);\n }, [post]);\n\n const value: AuthContextType = {\n user,\n loading,\n isAnonymous: user?.is_anonymous ?? false,\n signIn,\n signUp,\n sendLoginCode,\n verifyOtp,\n signInWithGoogle,\n signInAnonymously,\n signOut,\n refresh: loadUser,\n };\n\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;\n}\n\n/**\n * The shopper's sign-in state and actions: `user`, `loading`, `isAnonymous`,\n * `signIn`, `signUp`, `sendLoginCode`, `verifyOtp`, `signInWithGoogle`,\n * `signInAnonymously`, `signOut` and `refresh`. The sign-in actions resolve to\n * `{ error }` and do not throw.\n *\n * Must run under {@link StorefrontKitProvider}, which includes the auth provider.\n *\n * @returns The auth context.\n * @throws When used outside the provider.\n */\nexport function useAuth() {\n const context = useContext(AuthContext);\n if (context === undefined) {\n throw new Error(\"useAuth must be used within an AuthProvider\");\n }\n return context;\n}\n"],"mappings":";AAoKS;AAjKT;AAAA,EACE;AA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AM,UAAU,YAAY,YAAY;AACtC,UAAM,KAAK,QAAQ;AACnB,YAAQ,IAAI;AAAA,EACd,GAAG,CAAC,IAAI,CAAC;AAET,QAAM,QAAyB;AAAA,IAC7B;AAAA,IACA;AAAA,IACA,aAAa,MAAM,gBAAgB;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,EACX;AAEA,SAAO,oBAAC,YAAY,UAAZ,EAAqB,OAAe,UAAS;AACvD;AAaO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,6CAA6C;AAAA,EAC/D;AACA,SAAO;AACT;","names":[]}
package/dist/auth/sdk.js CHANGED
@@ -8,16 +8,26 @@ import { STORE_PREVIEW_HEADER } from "../stores/store-preview-cookie.js";
8
8
  function backendBaseUrl() {
9
9
  return publicConfig().apiUrl;
10
10
  }
11
- function storefrontApiKey() {
12
- return serverConfig().platformApiKey;
11
+ function storefrontSecretKey() {
12
+ const key = serverConfig().secretKey;
13
+ if (!key) {
14
+ throw new Error(
15
+ "The storefront secret key is not set (PLATFORM_SECRET_KEY or ECOMWEB_SECRET_KEY)"
16
+ );
17
+ }
18
+ return key;
19
+ }
20
+ function backendUrl(path) {
21
+ const base = backendBaseUrl().replace(/\/+$/, "");
22
+ return `${base}${path.startsWith("/") ? path : `/${path}`}`;
13
23
  }
14
24
  async function send(method, url, data, options, clientIp, previewToken) {
15
25
  try {
16
- const response = await fetch(`${backendBaseUrl()}${url}`, {
26
+ const response = await fetch(backendUrl(url), {
17
27
  method,
18
28
  headers: {
19
29
  "Content-Type": "application/json",
20
- "x-storefront-api-key": storefrontApiKey(),
30
+ "x-storefront-api-key": storefrontSecretKey(),
21
31
  // A store preview opens a coming soon store for reads only, so the
22
32
  // token rides on GETs (auth config, me) and never on writes.
23
33
  ...previewToken && method === "GET" ? { [STORE_PREVIEW_HEADER]: previewToken } : {},
@@ -79,6 +89,6 @@ export {
79
89
  authHttpClient,
80
90
  backendBaseUrl,
81
91
  createAuthApi,
82
- storefrontApiKey
92
+ storefrontSecretKey
83
93
  };
84
94
  //# sourceMappingURL=sdk.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi, withClientHeader } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { KIT_CLIENT_TOKEN } from \"../client-info\";\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(\n withClientHeader(authHttpClient(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ACT,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;AAAA,IACT,iBAAiB,eAAe,UAAU,YAAY,GAAG,gBAAgB;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/sdk.ts"],"sourcesContent":["import \"server-only\";\n\nimport { AuthApi, withClientHeader } from \"@ecomweb/sdk\";\nimport type { ApiResponse, IHttpClient, RequestOptions } from \"@ecomweb/sdk\";\nimport { forwardingHeaders } from \"./client-ip\";\nimport { KIT_CLIENT_TOKEN } from \"../client-info\";\nimport { publicConfig } from \"../config\";\nimport { serverConfig } from \"../config/server\";\nimport { STORE_PREVIEW_HEADER } from \"../stores/store-preview-cookie\";\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 * The key the server signs every backend call with (`x-storefront-api-key`):\n * PLATFORM_SECRET_KEY in the shared app, ECOMWEB_SECRET_KEY in a single-store\n * site. Builds hold none, so an empty one throws here, at use.\n */\nexport function storefrontSecretKey(): string {\n const key = serverConfig().secretKey;\n if (!key) {\n throw new Error(\n \"The storefront secret key is not set (PLATFORM_SECRET_KEY or ECOMWEB_SECRET_KEY)\"\n );\n }\n return key;\n}\n\n/**\n * Joins the backend origin and an SDK path with exactly one slash. Plain\n * string concatenation (unlike axios's baseURL join) turns a path without a\n * leading slash into `.../api/v1public/...`.\n */\nfunction backendUrl(path: string): string {\n const base = backendBaseUrl().replace(/\\/+$/, \"\");\n return `${base}${path.startsWith(\"/\") ? path : `/${path}`}`;\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(backendUrl(url), {\n method,\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontSecretKey(),\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(\n withClientHeader(authHttpClient(clientIp, previewToken), KIT_CLIENT_TOKEN),\n storeRef\n );\n}\n"],"mappings":"AAAA,OAAO;AAEP,SAAS,SAAS,wBAAwB;AAE1C,SAAS,yBAAyB;AAClC,SAAS,wBAAwB;AACjC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,4BAA4B;AAO9B,SAAS,iBAAyB;AACvC,SAAO,aAAa,EAAE;AACxB;AAOO,SAAS,sBAA8B;AAC5C,QAAM,MAAM,aAAa,EAAE;AAC3B,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAOA,SAAS,WAAW,MAAsB;AACxC,QAAM,OAAO,eAAe,EAAE,QAAQ,QAAQ,EAAE;AAChD,SAAO,GAAG,IAAI,GAAG,KAAK,WAAW,G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,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;AAAA,IACT,iBAAiB,eAAe,UAAU,YAAY,GAAG,gBAAgB;AAAA,IACzE;AAAA,EACF;AACF;","names":[]}
@@ -6,8 +6,9 @@ import {
6
6
  } from "./cookies.js";
7
7
  import { forwardedForHeader } from "./client-ip.js";
8
8
  import { publicConfig } from "../config/public.js";
9
- import { serverConfig } from "../config/server.js";
9
+ import { storefrontSecretKey } from "./sdk.js";
10
10
  import { THEME_PREVIEW_HOST_HEADER } from "../theme/preview-host.js";
11
+ import { SERVED_STORE_HEADER } from "../request/served-store.js";
11
12
  import { STORE_PREVIEW_TOKEN_HEADER } from "../stores/store-preview-cookie.js";
12
13
  const REFRESH_WINDOW_SECONDS = 120;
13
14
  const REFRESH_FETCH_TIMEOUT_MS = 2500;
@@ -31,12 +32,12 @@ async function refreshIfNearExpiry(req, storeRef, cookiePath) {
31
32
  if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;
32
33
  try {
33
34
  const res = await fetch(
34
- `${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,
35
+ `${publicConfig().apiUrl}/storefront/stores/${encodeURIComponent(storeRef)}/auth/refresh`,
35
36
  {
36
37
  method: "POST",
37
38
  headers: {
38
39
  "Content-Type": "application/json",
39
- "x-storefront-api-key": serverConfig().platformApiKey,
40
+ "x-storefront-api-key": storefrontSecretKey(),
40
41
  // The backend throttles per `storeId:clientIp`; without this (the
41
42
  // shopper IP plus the forwarder secret that makes the backend
42
43
  // believe it) every shopper's refresh lands in one store-wide bucket.
@@ -64,11 +65,13 @@ async function refreshIfNearExpiry(req, storeRef, cookiePath) {
64
65
  }
65
66
  return null;
66
67
  }
67
- function downstreamRequestHeaders(req, hostMapped, storeRef, rotated) {
68
+ function downstreamRequestHeaders(req, hostMapped, storeRef, rotated, servedStoreRef = null) {
68
69
  const headers = new Headers(req.headers);
69
70
  headers.set(HOST_MAPPED_HEADER, hostMapped ? "1" : "0");
70
71
  headers.delete(THEME_PREVIEW_HOST_HEADER);
71
72
  headers.delete(STORE_PREVIEW_TOKEN_HEADER);
73
+ headers.delete(SERVED_STORE_HEADER);
74
+ if (servedStoreRef) headers.set(SERVED_STORE_HEADER, servedStoreRef);
72
75
  if (rotated && storeRef) {
73
76
  const jar = new Map(req.cookies.getAll().map((c) => [c.name, c.value]));
74
77
  const path = authCookiePath(storeRef, hostMapped);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n authCookiePath,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { serverConfig } from \"../config/server\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"../theme/preview-host\";\nimport { STORE_PREVIEW_TOKEN_HEADER } from \"../stores/store-preview-cookie\";\n\n/**\n * Session upkeep shared by both middleware modes (createStorefrontMiddleware):\n * refresh a near-expiry access token, and pass the downstream render the\n * rotated tokens plus the host-mapped stamp.\n */\n\nconst REFRESH_WINDOW_SECONDS = 120;\nconst REFRESH_FETCH_TIMEOUT_MS = 2500;\n\nexport interface RotatedTokens {\n access_token: string;\n refresh_token: string;\n}\n\n/**\n * Reads `exp` without verifying the signature — the API verifies. This only\n * decides whether to refresh early, so a forged token gains nothing: it still\n * fails at the API.\n */\nexport function expiresWithin(token: string, seconds: number): boolean {\n try {\n const payload = JSON.parse(\n Buffer.from(token.split(\".\")[1], \"base64\").toString(\"utf8\")\n );\n if (typeof payload.exp !== \"number\") return false;\n return payload.exp - Math.floor(Date.now() / 1000) < seconds;\n } catch {\n return false;\n }\n}\n\n/**\n * Proactively refresh a near-expiry access token so requests don't hit a 401\n * on it. Returns the rotated pair, or null if there was nothing to do or the\n * attempt failed — a failed refresh is non-fatal and the request proceeds on\n * the old token, letting the 401 paths handle it.\n *\n * This runs for **every** request the matcher admits, not just host-mapped\n * ones: the server-rendered pages read the session straight off the cookie\n * (`lib/auth/session.ts`) and have no other way to renew it. Part A's backend\n * proxy refreshes on a 401, but that only covers browser-initiated calls.\n * `cookiePath` is the session cookies' path (authCookiePath).\n */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string,\n cookiePath: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef, cookiePath))?.value;\n const refresh = req.cookies.get(\n refreshCookieName(storeRef, cookiePath)\n )?.value;\n\n if (!access || !refresh) return null;\n if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;\n\n try {\n const res = await fetch(\n `${publicConfig().apiUrl}/public/stores/${encodeURIComponent(storeRef)}/auth/refresh`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": serverConfig().platformApiKey,\n // The backend throttles per `storeId:clientIp`; without this (the\n // shopper IP plus the forwarder secret that makes the backend\n // believe it) every shopper's refresh lands in one store-wide bucket.\n ...forwardedForHeader(req.headers),\n },\n body: JSON.stringify({ refresh_token: refresh }),\n // This is a latency budget added to a page load the user did not\n // ask for, not an API call worth waiting out — bound it so a slow\n // (not down) API can't turn a fast page load into a stall. An\n // abort rejects `fetch`, which the surrounding catch below\n // treats the same as any other network failure: non-fatal,\n // the request proceeds on the old token.\n signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS),\n }\n );\n\n if (!res.ok) return null;\n\n const data = await res.json();\n if (data?.access_token && data?.refresh_token) {\n return {\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n };\n }\n } catch {\n // Non-fatal: proceed on the old token, the normal 401 path handles it.\n }\n\n return null;\n}\n\n/**\n * The request headers every downstream render and route handler sees.\n *\n * Two jobs:\n *\n * 1. `HOST_MAPPED_HEADER` records whether the **Host** named the store. This\n * middleware is the only place that resolves Host → store, and the auth\n * route handler needs the answer to choose the cookie `path` and to know\n * where the store's own root is — it cannot tell the deployments apart from\n * the request path, which is `/store/<ref>/api/…` on both. Always set, so a\n * browser-supplied value can never survive.\n * 2. When a token was rotated, the new pair replaces the old one in the cookie\n * header, so the render *this* request triggers already sees the new\n * session. Without it a shopper returning after their access token expired\n * would be bounced to `/login` on the very request that renewed it.\n */\nexport function downstreamRequestHeaders(\n req: NextRequest,\n hostMapped: boolean,\n storeRef: string | null,\n rotated: RotatedTokens | null\n): Headers {\n const headers = new Headers(req.headers);\n headers.set(HOST_MAPPED_HEADER, hostMapped ? \"1\" : \"0\");\n // Only the middleware names a preview host's theme (theme/preview-host).\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n // Only the middleware hands on a preview host's store preview token; a\n // copy the client sent never survives (stores/store-preview-cookie).\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n const path = authCookiePath(storeRef, hostMapped);\n jar.set(accessCookieName(storeRef, path), rotated.access_token);\n jar.set(refreshCookieName(storeRef, path), rotated.refresh_token);\n headers.set(\n \"cookie\",\n [...jar].map(([name, value]) => `${name}=${value}`).join(\"; \")\n );\n }\n\n return headers;\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,iCAAiC;AAC1C,SAAS,kCAAkC;AAQ3C,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AAY1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EACF,QAAQ;AAAA,EAER;AAEA,SAAO;AACT;AAkBO,SAAS,yBACd,KACA,YACA,UACA,SACS;AACT,QAAM,UAAU,IAAI,QAAQ,IAAI,OAAO;AACvC,UAAQ,IAAI,oBAAoB,aAAa,MAAM,GAAG;AAEtD,UAAQ,OAAO,yBAAyB;AAGxC,UAAQ,OAAO,0BAA0B;AAEzC,MAAI,WAAW,UAAU;AACvB,UAAM,MAAM,IAAI,IAAI,IAAI,QAAQ,OAAO,EAAE,IAAI,OAAK,CAAC,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AACpE,UAAM,OAAO,eAAe,UAAU,UAAU;AAChD,QAAI,IAAI,iBAAiB,UAAU,IAAI,GAAG,QAAQ,YAAY;AAC9D,QAAI,IAAI,kBAAkB,UAAU,IAAI,GAAG,QAAQ,aAAa;AAChE,YAAQ;AAAA,MACN;AAAA,MACA,CAAC,GAAG,GAAG,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,IAC/D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/auth/session-refresh.ts"],"sourcesContent":["import type { NextRequest } from \"next/server\";\nimport {\n accessCookieName,\n authCookiePath,\n refreshCookieName,\n HOST_MAPPED_HEADER,\n} from \"./cookies\";\nimport { forwardedForHeader } from \"./client-ip\";\nimport { publicConfig } from \"../config/public\";\nimport { storefrontSecretKey } from \"./sdk\";\nimport { THEME_PREVIEW_HOST_HEADER } from \"../theme/preview-host\";\nimport { SERVED_STORE_HEADER } from \"../request/served-store\";\nimport { STORE_PREVIEW_TOKEN_HEADER } from \"../stores/store-preview-cookie\";\n\n/**\n * Session upkeep shared by both middleware modes (createStorefrontMiddleware):\n * refresh a near-expiry access token, and pass the downstream render the\n * rotated tokens plus the host-mapped stamp.\n */\n\nconst REFRESH_WINDOW_SECONDS = 120;\nconst REFRESH_FETCH_TIMEOUT_MS = 2500;\n\nexport interface RotatedTokens {\n access_token: string;\n refresh_token: string;\n}\n\n/**\n * Reads `exp` without verifying the signature — the API verifies. This only\n * decides whether to refresh early, so a forged token gains nothing: it still\n * fails at the API.\n */\nexport function expiresWithin(token: string, seconds: number): boolean {\n try {\n const payload = JSON.parse(\n Buffer.from(token.split(\".\")[1], \"base64\").toString(\"utf8\")\n );\n if (typeof payload.exp !== \"number\") return false;\n return payload.exp - Math.floor(Date.now() / 1000) < seconds;\n } catch {\n return false;\n }\n}\n\n/**\n * Proactively refresh a near-expiry access token so requests don't hit a 401\n * on it. Returns the rotated pair, or null if there was nothing to do or the\n * attempt failed — a failed refresh is non-fatal and the request proceeds on\n * the old token, letting the 401 paths handle it.\n *\n * This runs for **every** request the matcher admits, not just host-mapped\n * ones: the server-rendered pages read the session straight off the cookie\n * (`lib/auth/session.ts`) and have no other way to renew it. Part A's backend\n * proxy refreshes on a 401, but that only covers browser-initiated calls.\n * `cookiePath` is the session cookies' path (authCookiePath).\n */\nexport async function refreshIfNearExpiry(\n req: NextRequest,\n storeRef: string,\n cookiePath: string\n): Promise<RotatedTokens | null> {\n const access = req.cookies.get(accessCookieName(storeRef, cookiePath))?.value;\n const refresh = req.cookies.get(\n refreshCookieName(storeRef, cookiePath)\n )?.value;\n\n if (!access || !refresh) return null;\n if (!expiresWithin(access, REFRESH_WINDOW_SECONDS)) return null;\n\n try {\n const res = await fetch(\n `${publicConfig().apiUrl}/storefront/stores/${encodeURIComponent(storeRef)}/auth/refresh`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-storefront-api-key\": storefrontSecretKey(),\n // The backend throttles per `storeId:clientIp`; without this (the\n // shopper IP plus the forwarder secret that makes the backend\n // believe it) every shopper's refresh lands in one store-wide bucket.\n ...forwardedForHeader(req.headers),\n },\n body: JSON.stringify({ refresh_token: refresh }),\n // This is a latency budget added to a page load the user did not\n // ask for, not an API call worth waiting out — bound it so a slow\n // (not down) API can't turn a fast page load into a stall. An\n // abort rejects `fetch`, which the surrounding catch below\n // treats the same as any other network failure: non-fatal,\n // the request proceeds on the old token.\n signal: AbortSignal.timeout(REFRESH_FETCH_TIMEOUT_MS),\n }\n );\n\n if (!res.ok) return null;\n\n const data = await res.json();\n if (data?.access_token && data?.refresh_token) {\n return {\n access_token: data.access_token,\n refresh_token: data.refresh_token,\n };\n }\n } catch {\n // Non-fatal: proceed on the old token, the normal 401 path handles it.\n }\n\n return null;\n}\n\n/**\n * The request headers every downstream render and route handler sees.\n *\n * Two jobs:\n *\n * 1. `HOST_MAPPED_HEADER` records whether the **Host** named the store. This\n * middleware is the only place that resolves Host → store, and the auth\n * route handler needs the answer to choose the cookie `path` and to know\n * where the store's own root is — it cannot tell the deployments apart from\n * the request path, which is `/store/<ref>/api/…` on both. Always set, so a\n * browser-supplied value can never survive.\n * 2. `SERVED_STORE_HEADER` names the store this request serves (null: none).\n * 3. When a token was rotated, the new pair replaces the old one in the cookie\n * header, so the render *this* request triggers already sees the new\n * session. Without it a shopper returning after their access token expired\n * would be bounced to `/login` on the very request that renewed it.\n */\nexport function downstreamRequestHeaders(\n req: NextRequest,\n hostMapped: boolean,\n storeRef: string | null,\n rotated: RotatedTokens | null,\n servedStoreRef: string | null = null\n): Headers {\n const headers = new Headers(req.headers);\n headers.set(HOST_MAPPED_HEADER, hostMapped ? \"1\" : \"0\");\n // Only the middleware names a preview host's theme (theme/preview-host).\n headers.delete(THEME_PREVIEW_HOST_HEADER);\n // Only the middleware hands on a preview host's store preview token; a\n // copy the client sent never survives (stores/store-preview-cookie).\n headers.delete(STORE_PREVIEW_TOKEN_HEADER);\n // Only the middleware names the store this request serves; a client copy\n // never survives (request/served-store).\n headers.delete(SERVED_STORE_HEADER);\n if (servedStoreRef) headers.set(SERVED_STORE_HEADER, servedStoreRef);\n\n if (rotated && storeRef) {\n const jar = new Map(req.cookies.getAll().map(c => [c.name, c.value]));\n const path = authCookiePath(storeRef, hostMapped);\n jar.set(accessCookieName(storeRef, path), rotated.access_token);\n jar.set(refreshCookieName(storeRef, path), rotated.refresh_token);\n headers.set(\n \"cookie\",\n [...jar].map(([name, value]) => `${name}=${value}`).join(\"; \")\n );\n }\n\n return headers;\n}\n"],"mappings":"AACA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,iCAAiC;AAC1C,SAAS,2BAA2B;AACpC,SAAS,kCAAkC;AAQ3C,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;AAY1B,SAAS,cAAc,OAAe,SAA0B;AACrE,MAAI;AACF,UAAM,UAAU,KAAK;AAAA,MACnB,OAAO,KAAK,MAAM,MAAM,GAAG,EAAE,CAAC,GAAG,QAAQ,EAAE,SAAS,MAAM;AAAA,IAC5D;AACA,QAAI,OAAO,QAAQ,QAAQ,SAAU,QAAO;AAC5C,WAAO,QAAQ,MAAM,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAcA,eAAsB,oBACpB,KACA,UACA,YAC+B;AAC/B,QAAM,SAAS,IAAI,QAAQ,IAAI,iBAAiB,UAAU,UAAU,CAAC,GAAG;AACxE,QAAM,UAAU,IAAI,QAAQ;AAAA,IAC1B,kBAAkB,UAAU,UAAU;AAAA,EACxC,GAAG;AAEH,MAAI,CAAC,UAAU,CAAC,QAAS,QAAO;AAChC,MAAI,CAAC,cAAc,QAAQ,sBAAsB,EAAG,QAAO;AAE3D,MAAI;AACF,UAAM,MAAM,MAAM;AAAA,MAChB,GAAG,aAAa,EAAE,MAAM,sBAAsB,mBAAmB,QAAQ,CAAC;AAAA,MAC1E;AAAA,QACE,QAAQ;AAAA,QACR,SAAS;AAAA,UACP,gBAAgB;AAAA,UAChB,wBAAwB,oBAAoB;AAAA;AAAA;AAAA;AAAA,UAI5C,GAAG,mBAAmB,IAAI,OAAO;AAAA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../sdk\";\n\nexport type {\n CartApiItem,\n CartApiResponse,\n AddToCartRequest,\n UpdateCartItemRequest,\n} from \"@ecomweb/sdk\";\n\nexport interface MergeCartsRequest {\n // No body needed, user_id comes from header\n}\n\n/**\n * Plain module, not a component, so it cannot read React context or an\n * httpOnly cookie. `storeRef` and `isAuth` are therefore explicit parameters\n * supplied by `CartProvider`. When `isAuth` is true the SDK takes the\n * JWT-guarded `/stores/:ref/cart` branch, which reaches the backend through the\n * same-origin proxy (`lib/api/proxy.ts`) — that is what attaches the bearer\n * token server-side.\n */\nclass CartApiService {\n private getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n\n let sessionId = localStorage.getItem(\"cart_session_id\");\n if (!sessionId) {\n sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n localStorage.setItem(\"cart_session_id\", sessionId);\n }\n return sessionId;\n }\n\n async getCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.getCart(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n async addToCart(\n storeRef: string,\n data: Parameters<ReturnType<typeof createStoreSdk>[\"cart\"][\"addItem\"]>[1],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.addItem(\n storeRef,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async updateCartItem(\n storeRef: string,\n itemId: string,\n data: Parameters<\n ReturnType<typeof createStoreSdk>[\"cart\"][\"updateItem\"]\n >[2],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.updateItem(\n storeRef,\n itemId,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async removeFromCart(storeRef: string, itemId: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.removeItem(\n storeRef,\n itemId,\n this.getSessionId(),\n isAuth\n );\n }\n\n async clearCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.clear(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n /** Always authenticated: merging a guest cart needs an identity to merge into. */\n async mergeCarts(storeRef: string) {\n return createStoreSdk(storeRef).cart.merge(storeRef, this.getSessionId());\n }\n}\n\nexport const cartApiService = new CartApiService();\n"],"mappings":"AAAA,SAAS,sBAAsB;AAqB/B,MAAM,eAAe;AAAA,EACX,eAAuB;AAC7B,QAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,QAAI,YAAY,aAAa,QAAQ,iBAAiB;AACtD,QAAI,CAAC,WAAW;AACd,kBAAY,WAAW,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,GAAG,CAAC,CAAC;AAC5E,mBAAa,QAAQ,mBAAmB,SAAS;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,QAAQ,UAAkB,QAAiB;AAC/C,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UACJ,UACA,MACA,QACA;AACA,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eACJ,UACA,QACA,MAGA,QACA;AACA,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eAAe,UAAkB,QAAgB,QAAiB;AACtE,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,UAAkB,QAAiB;AACjD,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAAW,UAAkB;AACjC,WAAO,eAAe,QAAQ,EAAE,KAAK,MAAM,UAAU,KAAK,aAAa,CAAC;AAAA,EAC1E;AACF;AAEO,MAAM,iBAAiB,IAAI,eAAe;","names":[]}
1
+ {"version":3,"sources":["../../src/cart/api.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\n\nexport type {\n CartApiItem,\n CartApiResponse,\n AddToCartRequest,\n UpdateCartItemRequest,\n} from \"@ecomweb/sdk\";\n\nexport interface MergeCartsRequest {\n // No body needed, user_id comes from header\n}\n\n/**\n * Plain module, not a component, so it cannot read React context or an\n * httpOnly cookie. `storeRef` and `isAuth` are therefore explicit parameters\n * supplied by `CartProvider`. When `isAuth` is true the SDK takes the\n * JWT-guarded `/storefront/stores/:ref/customers/cart` branch, which reaches the backend through the\n * same-origin proxy (`lib/api/proxy.ts`) — that is what attaches the bearer\n * token server-side.\n */\nclass CartApiService {\n private getSessionId(): string {\n if (typeof window === \"undefined\") return \"\";\n\n let sessionId = localStorage.getItem(\"cart_session_id\");\n if (!sessionId) {\n sessionId = `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n localStorage.setItem(\"cart_session_id\", sessionId);\n }\n return sessionId;\n }\n\n async getCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.getCart(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n async addToCart(\n storeRef: string,\n data: Parameters<ReturnType<typeof createStoreSdk>[\"cart\"][\"addItem\"]>[1],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.addItem(\n storeRef,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async updateCartItem(\n storeRef: string,\n itemId: string,\n data: Parameters<\n ReturnType<typeof createStoreSdk>[\"cart\"][\"updateItem\"]\n >[2],\n isAuth: boolean\n ) {\n return createStoreSdk(storeRef).cart.updateItem(\n storeRef,\n itemId,\n data,\n this.getSessionId(),\n isAuth\n );\n }\n\n async removeFromCart(storeRef: string, itemId: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.removeItem(\n storeRef,\n itemId,\n this.getSessionId(),\n isAuth\n );\n }\n\n async clearCart(storeRef: string, isAuth: boolean) {\n return createStoreSdk(storeRef).cart.clear(\n storeRef,\n this.getSessionId(),\n isAuth\n );\n }\n\n /** Always authenticated: merging a guest cart needs an identity to merge into. */\n async mergeCarts(storeRef: string) {\n return createStoreSdk(storeRef).cart.merge(storeRef, this.getSessionId());\n }\n}\n\nexport const cartApiService = new CartApiService();\n"],"mappings":"AAAA,SAAS,sBAAsB;AAqB/B,MAAM,eAAe;AAAA,EACX,eAAuB;AAC7B,QAAI,OAAO,WAAW,YAAa,QAAO;AAE1C,QAAI,YAAY,aAAa,QAAQ,iBAAiB;AACtD,QAAI,CAAC,WAAW;AACd,kBAAY,WAAW,KAAK,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,OAAO,GAAG,CAAC,CAAC;AAC5E,mBAAa,QAAQ,mBAAmB,SAAS;AAAA,IACnD;AACA,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,QAAQ,UAAkB,QAAiB;AAC/C,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UACJ,UACA,MACA,QACA;AACA,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eACJ,UACA,QACA,MAGA,QACA;AACA,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,eAAe,UAAkB,QAAgB,QAAiB;AACtE,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,UAAU,UAAkB,QAAiB;AACjD,WAAO,eAAe,QAAQ,EAAE,KAAK;AAAA,MACnC;AAAA,MACA,KAAK,aAAa;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,WAAW,UAAkB;AACjC,WAAO,eAAe,QAAQ,EAAE,KAAK,MAAM,UAAU,KAAK,aAAa,CAAC;AAAA,EAC1E;AACF;AAEO,MAAM,iBAAiB,IAAI,eAAe;","names":[]}
@@ -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 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,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A,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\n/**\n * The shopper's cart and the actions to change it: `items`, `itemCount`,\n * `subtotal`, `total`, `discountAmount`, `isLoading`, `addItem`, `removeItem`,\n * `updateQuantity`, `clearCart`, `refreshCart`, `mergeCarts` and\n * `reorderItems`. Amounts are in the store's currency.\n *\n * Must run under {@link StorefrontKitProvider}, which includes the cart provider.\n *\n * @returns The cart context.\n * @throws When used outside the provider.\n *\n * @example\n * ```tsx\n * \"use client\";\n * import { useCart } from \"@ecomweb/storefront-kit\";\n *\n * export function CartBadge() {\n * const { itemCount, isLoading } = useCart();\n * return <span>{isLoading ? \"…\" : itemCount}</span>;\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"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ACd,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;AAwBO,SAAS,UAAU;AACxB,QAAM,UAAU,WAAW,WAAW;AACtC,MAAI,YAAY,QAAW;AACzB,UAAM,IAAI,MAAM,4CAA4C;AAAA,EAC9D;AACA,SAAO;AACT;","names":["item"]}
@@ -1,13 +1,9 @@
1
- import { publicApiClient } from "../api/client.js";
2
- import { unwrap } from "../api/response.js";
1
+ import { createStoreSdk } from "../sdk.js";
3
2
  async function getPaymentState(storeRef, order_code) {
4
- const res = await publicApiClient.get(
5
- // `order_code` carries a `#` prefix by default in this system — left
6
- // unencoded, it truncates the URL (everything from `#` on is treated
7
- // as a fragment) and the request silently hits a different route.
8
- `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`
3
+ return createStoreSdk(storeRef).payments.getPaymentState(
4
+ storeRef,
5
+ order_code
9
6
  );
10
- return unwrap(res);
11
7
  }
12
8
  export {
13
9
  getPaymentState
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.getPaymentState`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * — see `lib/checkout/initiate-gateway-payment.ts` for the full story\n * (same pinned commit, same missing module). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.getPaymentState()`'s request/response\n * shape exactly (same path, same result shape) so that once the SDK bump\n * lands, the fix is: delete this file, delete this import in\n * `payment-state-poll`'s caller, and call\n * `sdk.payments.getPaymentState(...)` instead — the call site already reads\n * as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.getPaymentState`.\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n const res = await publicApiClient.get<PaymentStateResult>(\n // `order_code` carries a `#` prefix by default in this system — left\n // unencoded, it truncates the URL (everything from `#` on is treated\n // as a fragment) and the request silently hits a different route.\n `/public/stores/${encodeURIComponent(storeRef)}/orders/${encodeURIComponent(order_code)}/payment-state`\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AAyBvB,eAAsB,gBACpB,UACA,YAC6B;AAC7B,QAAM,MAAM,MAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,IAIhC,kBAAkB,mBAAmB,QAAQ,CAAC,WAAW,mBAAmB,UAAU,CAAC;AAAA,EACzF;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/get-payment-state.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\nimport type { PaymentStateResult } from \"./payment-state-poll\";\n\n/**\n * Reads where a payment stands for an order, from the browser, through the\n * store's backend proxy (`createStoreSdk`), which adds the secret key. Browser\n * only: the proxied SDK uses a relative URL. On a server use `getServerSdk()`.\n *\n * @param storeRef - the store's ref\n * @param order_code - the order's code\n * @returns the payment state of the order\n */\nexport async function getPaymentState(\n storeRef: string,\n order_code: string\n): Promise<PaymentStateResult> {\n return createStoreSdk(storeRef).payments.getPaymentState(\n storeRef,\n order_code\n );\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAY/B,eAAsB,gBACpB,UACA,YAC6B;AAC7B,SAAO,eAAe,QAAQ,EAAE,SAAS;AAAA,IACvC;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
@@ -1,11 +1,9 @@
1
- import { publicApiClient } from "../api/client.js";
2
- import { unwrap } from "../api/response.js";
1
+ import { createStoreSdk } from "../sdk.js";
3
2
  async function initiateGatewayPayment(storeRef, input) {
4
- const res = await publicApiClient.post(
5
- `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,
6
- { order_code: input.order_code, provider_code: input.provider_code }
7
- );
8
- return unwrap(res);
3
+ return createStoreSdk(storeRef).payments.initiate(storeRef, {
4
+ order_code: input.order_code,
5
+ provider_code: input.provider_code
6
+ });
9
7
  }
10
8
  export {
11
9
  initiateGatewayPayment
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { publicApiClient } from \"../api/client\";\nimport { unwrap } from \"../api/response\";\n\n/**\n * TEMPORARY adapter standing in for `sdk.payments.initiate`.\n *\n * `sdk.payments` was added by this plan's Task 2\n * (`ecomweb-contracts` branch `feat/payment-client-methods`, commit `58c2c76`),\n * but that SDK PR is not yet merged to `main`, and this repo's lockfile\n * pins an older `@ecomweb/sdk` commit that has no `payments` module at all\n * (confirmed: nothing under `node_modules/@ecomweb/sdk/src` references\n * `payments`, `provider_code`, or `redirect_url`). Running\n * `pnpm update @ecomweb/sdk` here is explicitly out of scope for this task\n * — it is a deliberate later step in the plan.\n *\n * This function mirrors `PaymentsApi.initiate()`'s request/response shape\n * exactly (same path, same body keys, same result shape) so that once the\n * SDK bump lands, the fix is: delete this file, delete this import in\n * `checkout-page-client.tsx`, and call `sdk.payments.initiate(...)` instead\n * — the call site already reads as if it were doing that today.\n *\n * FOLLOW-UP: delete this file once `@ecomweb/sdk` is bumped past\n * `feat/payment-client-methods` and exposes `sdk.payments.initiate`.\n */\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n const res = await publicApiClient.post<InitiatePaymentResult>(\n `/public/stores/${encodeURIComponent(storeRef)}/payments/initiate`,\n { order_code: input.order_code, provider_code: input.provider_code }\n );\n return unwrap(res);\n}\n"],"mappings":"AAAA,SAAS,uBAAuB;AAChC,SAAS,cAAc;AA4BvB,eAAsB,uBACpB,UACA,OACgC;AAChC,QAAM,MAAM,MAAM,gBAAgB;AAAA,IAChC,kBAAkB,mBAAmB,QAAQ,CAAC;AAAA,IAC9C,EAAE,YAAY,MAAM,YAAY,eAAe,MAAM,cAAc;AAAA,EACrE;AACA,SAAO,OAAO,GAAG;AACnB;","names":[]}
1
+ {"version":3,"sources":["../../src/checkout/initiate-gateway-payment.ts"],"sourcesContent":["import { createStoreSdk } from \"../sdk\";\n\nexport interface InitiatePaymentResult {\n payment_id: number;\n redirect_url: string;\n}\n\nexport async function initiateGatewayPayment(\n storeRef: string,\n input: { order_code: string; provider_code: string }\n): Promise<InitiatePaymentResult> {\n return createStoreSdk(storeRef).payments.initiate(storeRef, {\n order_code: input.order_code,\n provider_code: input.provider_code,\n });\n}\n"],"mappings":"AAAA,SAAS,sBAAsB;AAO/B,eAAsB,uBACpB,UACA,OACgC;AAChC,SAAO,eAAe,QAAQ,EAAE,SAAS,SAAS,UAAU;AAAA,IAC1D,YAAY,MAAM;AAAA,IAClB,eAAe,MAAM;AAAA,EACvB,CAAC;AACH;","names":[]}