@ecomweb/storefront-kit 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/api/client.js +13 -1
- package/dist/api/client.js.map +1 -1
- package/dist/auth/sdk.js +6 -1
- package/dist/auth/sdk.js.map +1 -1
- package/dist/client-info.js +1 -1
- package/dist/index.d.ts +2 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -70,7 +70,7 @@ Needs kit 0.15.0. Carts, checkout, orders and accounts need a storefront
|
|
|
70
70
|
&& ecomweb-check-client-bundle"`): it fails the build if a secret ended up
|
|
71
71
|
in the client output.
|
|
72
72
|
|
|
73
|
-
See [
|
|
73
|
+
See [API keys](https://developers.ecomweb.app/guides/api-keys/) on the developer site.
|
|
74
74
|
|
|
75
75
|
## Coming soon stores and store previews
|
|
76
76
|
|
package/dist/api/client.js
CHANGED
|
@@ -94,7 +94,10 @@ class ApiClient {
|
|
|
94
94
|
handleResponse(response) {
|
|
95
95
|
return {
|
|
96
96
|
success: true,
|
|
97
|
-
data: response.data
|
|
97
|
+
data: response.data,
|
|
98
|
+
// Totals ride in headers (`x-total-count`); axios already lowercases
|
|
99
|
+
// the names.
|
|
100
|
+
headers: plainHeaders(response.headers)
|
|
98
101
|
};
|
|
99
102
|
}
|
|
100
103
|
handleError(error) {
|
|
@@ -224,6 +227,15 @@ function createStoreApiClient(storeRef) {
|
|
|
224
227
|
timeout: 2e4
|
|
225
228
|
});
|
|
226
229
|
}
|
|
230
|
+
function plainHeaders(headers) {
|
|
231
|
+
const out = {};
|
|
232
|
+
const source = headers && typeof headers.toJSON === "function" ? headers.toJSON() : headers ?? {};
|
|
233
|
+
for (const [name, value] of Object.entries(source)) {
|
|
234
|
+
if (value == null) continue;
|
|
235
|
+
out[name.toLowerCase()] = Array.isArray(value) ? value.join(", ") : String(value);
|
|
236
|
+
}
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
227
239
|
export {
|
|
228
240
|
ApiClient,
|
|
229
241
|
createStoreApiClient,
|
package/dist/api/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/api/client.ts"],"sourcesContent":["import axios, {\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n AxiosError,\n} from \"axios\";\nimport { ApiResponse, AuthenticatedApiClient } from \"../interfaces\";\nimport {\n isStoreSuspendedResponseBody,\n STORE_SUSPENDED_REDIRECT_PATH,\n} from \"../stores/store-suspension\";\nimport {\n isStoreComingSoonResponseBody,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"../stores/store-coming-soon\";\nimport {\n skipsStorePreview,\n STORE_PREVIEW_HEADER,\n} from \"../stores/store-preview-cookie\";\nimport {\n currentStorePreviewToken,\n isBrowserStorePreview,\n requestStorePreviewRenewal,\n} from \"./store-preview-header\";\nimport { publicConfig } from \"../config\";\nimport { storeApiPath } from \"../store-scope\";\nimport { findPrivateStorefrontRoute } from \"./proxy-routes\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\n\n/**\n * Whether a browser call's STORE_COMING_SOON 403 ends this visit, so the\n * browser goes to the coming soon page.\n * - Not previewing: yes, the store is closed to this shopper.\n * - Previewing, a write: no. A preview is read-only (the API opens GET and\n * HEAD only), so the write was refused, not the preview; the caller\n * reports it.\n * - Previewing, a read: the token ran out. A preview host renews it\n * (`requestStorePreviewRenewal`), so the preview goes on; a link\n * preview has no renewer, and its preview is over.\n */\nfunction comingSoonEndsThisVisit(method: string | undefined): boolean {\n if (!isBrowserStorePreview()) return true;\n const verb = (method ?? \"get\").toUpperCase();\n if (verb !== \"GET\" && verb !== \"HEAD\") return false;\n return !requestStorePreviewRenewal();\n}\n\ninterface ApiClientOptions {\n /**\n * Send `x-storefront-api-key` from the browser. True for direct calls to the\n * backend's own origin; false for calls routed through the same-origin proxy\n * (`lib/api/proxy.ts`), which attaches the key server-side.\n */\n withApiKey?: boolean;\n timeout?: number;\n}\n\nconst PRIVATE_ROUTE_MESSAGE =\n \"This route needs the storefront's secret key: call it with createStoreSdk(storeRef) in the browser or getServerSdk() on the server\";\n\n// Route patterns already reported, so a retry loop logs once.\nconst reportedPrivateRoutes = new Set<string>();\n\nclass ApiClient implements AuthenticatedApiClient {\n private axiosInstance: AxiosInstance;\n private withApiKey: boolean;\n\n constructor(\n baseUrl: string = publicConfig().apiUrl,\n options?: ApiClientOptions\n ) {\n this.withApiKey = options?.withApiKey ?? true;\n\n const defaultHeaders: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const platformApiKey = publicConfig().storefrontApiKey;\n if (this.withApiKey && platformApiKey) {\n defaultHeaders[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n this.axiosInstance = axios.create({\n baseURL: baseUrl.replace(/\\/$/, \"\"), // Remove trailing slash\n timeout: options?.timeout ?? DEFAULT_TIMEOUT,\n headers: defaultHeaders,\n });\n\n this.setupInterceptors();\n }\n\n private setupInterceptors(): void {\n // Request interceptor - add platform API key\n this.axiosInstance.interceptors.request.use(\n async config => {\n // Ensure API key is always present (in case instance was created before env loaded)\n const platformApiKey = publicConfig().storefrontApiKey;\n if (\n this.withApiKey &&\n platformApiKey &&\n !config.headers[\"x-storefront-api-key\"]\n ) {\n config.headers[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n // Opens a coming soon store for a previewer (read-only on the API's\n // side). An explicit header wins, such as the token the middleware\n // passes to `getByDomain`, and a call carrying SKIP_STORE_PREVIEW (a\n // plain, cached host lookup) never gets the request's token.\n // `get`/`set` match the header name case-insensitively.\n const previewToken = await currentStorePreviewToken();\n if (\n previewToken &&\n !skipsStorePreview(config) &&\n !config.headers.get(STORE_PREVIEW_HEADER)\n ) {\n config.headers.set(STORE_PREVIEW_HEADER, previewToken);\n }\n\n // No Authorization header is ever set here. Session tokens live in\n // httpOnly, store-scoped cookies (lib/auth/cookies.ts) that browser JS\n // cannot read; authenticated calls go through the same-origin proxy\n // built by createStoreApiClient() below, which attaches the bearer\n // token server-side.\n return config;\n },\n error => {\n return Promise.reject(error);\n }\n );\n\n // Response interceptor - handle common errors and format responses\n this.axiosInstance.interceptors.response.use(\n (response: AxiosResponse) => {\n // Success response\n return response;\n },\n (error: AxiosError) => {\n // Never the error itself: its config carries the request headers,\n // the preview token and the API key among them.\n console.error(\"API Client Error:\", {\n method: error.config?.method?.toUpperCase(),\n url: error.config?.url,\n status: error.response?.status,\n code:\n (error.response?.data as { code?: unknown } | undefined)?.code ??\n error.code,\n });\n // Handle common error scenarios\n if (error.code === \"ECONNABORTED\") {\n // Timeout error\n error.message = \"Request timeout - please try again\";\n } else if (!error.response) {\n // Network error\n error.message = \"Network error - check your connection\";\n }\n\n // A platform admin suspended this store mid-session. The initial\n // page render already handles suspension at store-resolution time\n // (app/store/[storeRef]/layout.tsx, proxy.ts) — but a client-side\n // call *after* that render (add-to-cart, checkout, a review\n // submission) hits this same guarded backend independently, and\n // isn't covered by that one-time check. Only the browser can\n // navigate on it; server-side callers still just get the rejection.\n if (\n typeof window !== \"undefined\" &&\n error.response?.status === 403 &&\n isStoreSuspendedResponseBody(error.response?.data)\n ) {\n window.location.href = STORE_SUSPENDED_REDIRECT_PATH;\n }\n\n // Likewise, the store went (or still is) coming soon. Not from the\n // coming soon page itself, so a call made there cannot reload it in\n // a loop. It is always this root path in the browser: the\n // middleware rewrites to it without changing the URL, and the shared\n // path-based host has no such page (known limitation,\n // create-storefront-middleware.ts).\n if (\n typeof window !== \"undefined\" &&\n error.response?.status === 403 &&\n isStoreComingSoonResponseBody(error.response?.data) &&\n window.location.pathname !== STORE_COMING_SOON_REDIRECT_PATH &&\n comingSoonEndsThisVisit(error.config?.method)\n ) {\n window.location.href = STORE_COMING_SOON_REDIRECT_PATH;\n }\n\n return Promise.reject(error);\n }\n );\n }\n\n private handleResponse<T>(response: AxiosResponse<T>): ApiResponse<T> {\n return {\n success: true,\n data: response.data,\n };\n }\n\n private handleError(error: any): ApiResponse<never> {\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError<any>;\n const responseData = axiosError.response?.data || {};\n return {\n success: false,\n error: {\n message:\n responseData.message || axiosError.message || \"Request failed\",\n statusCode: axiosError.response?.status || 0,\n // The backend serialises business errors as\n // `{ code, message, details, timestamp }`, so the stable identifier\n // lands in `code` — this is the browser-side twin of the same read\n // in `lib/auth/sdk.ts`. `unwrap()` copies it onto\n // `ApiClientError.code`, which `lib/auth/error-copy.ts` localises.\n // `responseData.error` is kept for any endpoint using Nest's default\n // envelope, and the axios code (ECONNABORTED, ERR_NETWORK) last.\n error: responseData.code || responseData.error || axiosError.code,\n // `unwrap()` copies this onto `ApiClientError.details`; checkout\n // reads `details.items` to mark the cart lines that are short.\n details: responseData.details,\n },\n };\n }\n\n return {\n success: false,\n error: {\n message:\n error instanceof Error ? error.message : \"Unknown error occurred\",\n statusCode: 0,\n },\n };\n }\n\n /**\n * The direct, publishable-key client cannot call a private route: the API\n * would refuse it, so refuse here, before the network. Logs the matched\n * route pattern, never the raw path (it can carry a review token or an\n * order code).\n */\n private refusePrivateRoute(\n method: string,\n url: string\n ): ApiResponse<never> | null {\n if (!this.withApiKey) return null;\n const route = findPrivateStorefrontRoute(method, url);\n if (!route) return null;\n const label = `${route.method} ${route.path}`;\n if (!reportedPrivateRoutes.has(label)) {\n reportedPrivateRoutes.add(label);\n console.error(\n `STOREFRONT_PRIVATE_ROUTE: ${label}. ${PRIVATE_ROUTE_MESSAGE}`\n );\n }\n return {\n success: false,\n error: {\n message: PRIVATE_ROUTE_MESSAGE,\n statusCode: 0,\n error: \"STOREFRONT_PRIVATE_ROUTE\",\n },\n };\n }\n\n async get<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"GET\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.get<T>(url, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async post<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"POST\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.post<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async put<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"PUT\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.put<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async patch<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"PATCH\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.patch<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async delete<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"DELETE\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.delete<T>(url, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n // Additional utility methods\n getAxiosInstance(): AxiosInstance {\n return this.axiosInstance;\n }\n\n // Method to update base URL if needed\n setBaseURL(baseUrl: string): void {\n this.axiosInstance.defaults.baseURL = baseUrl.replace(/\\/$/, \"\");\n }\n\n // Method to set default timeout\n setTimeout(timeout: number): void {\n this.axiosInstance.defaults.timeout = timeout;\n }\n}\n\n/**\n * Direct, key-authenticated client for the backend's own origin. Public\n * endpoints only — it can never carry a session token (see the request\n * interceptor above).\n */\nexport const publicApiClient = new ApiClient(publicConfig().apiUrl);\n\n/**\n * A store-scoped instance whose baseURL is the same-origin proxy route\n * `/store/<storeRef>/api/backend`, so the httpOnly session cookie is sent with\n * every request and `lib/api/proxy.ts` turns it into a bearer token\n * server-side. It deliberately does NOT send `x-storefront-api-key` from the\n * browser: the proxy attaches it.\n *\n * The timeout is wider than the direct client's because a proxied call may\n * include one refresh round trip plus a retry.\n */\nexport function createStoreApiClient(storeRef: string): ApiClient {\n return new ApiClient(storeApiPath(storeRef, \"backend\"), {\n withApiKey: false,\n timeout: 20000,\n });\n}\n\n// Export the class for custom instances\nexport { ApiClient };\n"],"mappings":"AAAA,OAAO,WAKA;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,oBAAoB;AAC7B,SAAS,kCAAkC;AAE3C,MAAM,kBAAkB;AAaxB,SAAS,wBAAwB,QAAqC;AACpE,MAAI,CAAC,sBAAsB,EAAG,QAAO;AACrC,QAAM,QAAQ,UAAU,OAAO,YAAY;AAC3C,MAAI,SAAS,SAAS,SAAS,OAAQ,QAAO;AAC9C,SAAO,CAAC,2BAA2B;AACrC;AAYA,MAAM,wBACJ;AAGF,MAAM,wBAAwB,oBAAI,IAAY;AAE9C,MAAM,UAA4C;AAAA,EACxC;AAAA,EACA;AAAA,EAER,YACE,UAAkB,aAAa,EAAE,QACjC,SACA;AACA,SAAK,aAAa,SAAS,cAAc;AAEzC,UAAM,iBAAyC;AAAA,MAC7C,gBAAgB;AAAA,IAClB;AAEA,UAAM,iBAAiB,aAAa,EAAE;AACtC,QAAI,KAAK,cAAc,gBAAgB;AACrC,qBAAe,sBAAsB,IAAI;AAAA,IAC3C;AAEA,SAAK,gBAAgB,MAAM,OAAO;AAAA,MAChC,SAAS,QAAQ,QAAQ,OAAO,EAAE;AAAA;AAAA,MAClC,SAAS,SAAS,WAAW;AAAA,MAC7B,SAAS;AAAA,IACX,CAAC;AAED,SAAK,kBAAkB;AAAA,EACzB;AAAA,EAEQ,oBAA0B;AAEhC,SAAK,cAAc,aAAa,QAAQ;AAAA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AM;AAC/D,aAAO,KAAK,eAAe,QAAQ;AAAA,IACrC,SAAS,OAAO;AACd,aAAO,KAAK,YAAY,KAAK;AAAA,IAC/B;AAAA,EACF;AAAA;AAAA,EAGA,mBAAkC;AAChC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA,EAGA,WAAW,SAAuB;AAChC,SAAK,cAAc,SAAS,UAAU,QAAQ,QAAQ,OAAO,EAAE;AAAA,EACjE;AAAA;AAAA,EAGA,WAAW,SAAuB;AAChC,SAAK,cAAc,SAAS,UAAU;AAAA,EACxC;AACF;AAOO,MAAM,kBAAkB,IAAI,UAAU,aAAa,EAAE,MAAM;AAY3D,SAAS,qBAAqB,UAA6B;AAChE,SAAO,IAAI,UAAU,aAAa,UAAU,SAAS,GAAG;AAAA,IACtD,YAAY;AAAA,IACZ,SAAS;AAAA,EACX,CAAC;AACH;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/api/client.ts"],"sourcesContent":["import axios, {\n AxiosInstance,\n AxiosRequestConfig,\n AxiosResponse,\n AxiosError,\n} from \"axios\";\nimport { ApiResponse, AuthenticatedApiClient } from \"../interfaces\";\nimport {\n isStoreSuspendedResponseBody,\n STORE_SUSPENDED_REDIRECT_PATH,\n} from \"../stores/store-suspension\";\nimport {\n isStoreComingSoonResponseBody,\n STORE_COMING_SOON_REDIRECT_PATH,\n} from \"../stores/store-coming-soon\";\nimport {\n skipsStorePreview,\n STORE_PREVIEW_HEADER,\n} from \"../stores/store-preview-cookie\";\nimport {\n currentStorePreviewToken,\n isBrowserStorePreview,\n requestStorePreviewRenewal,\n} from \"./store-preview-header\";\nimport { publicConfig } from \"../config\";\nimport { storeApiPath } from \"../store-scope\";\nimport { findPrivateStorefrontRoute } from \"./proxy-routes\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\n\n/**\n * Whether a browser call's STORE_COMING_SOON 403 ends this visit, so the\n * browser goes to the coming soon page.\n * - Not previewing: yes, the store is closed to this shopper.\n * - Previewing, a write: no. A preview is read-only (the API opens GET and\n * HEAD only), so the write was refused, not the preview; the caller\n * reports it.\n * - Previewing, a read: the token ran out. A preview host renews it\n * (`requestStorePreviewRenewal`), so the preview goes on; a link\n * preview has no renewer, and its preview is over.\n */\nfunction comingSoonEndsThisVisit(method: string | undefined): boolean {\n if (!isBrowserStorePreview()) return true;\n const verb = (method ?? \"get\").toUpperCase();\n if (verb !== \"GET\" && verb !== \"HEAD\") return false;\n return !requestStorePreviewRenewal();\n}\n\ninterface ApiClientOptions {\n /**\n * Send `x-storefront-api-key` from the browser. True for direct calls to the\n * backend's own origin; false for calls routed through the same-origin proxy\n * (`lib/api/proxy.ts`), which attaches the key server-side.\n */\n withApiKey?: boolean;\n timeout?: number;\n}\n\nconst PRIVATE_ROUTE_MESSAGE =\n \"This route needs the storefront's secret key: call it with createStoreSdk(storeRef) in the browser or getServerSdk() on the server\";\n\n// Route patterns already reported, so a retry loop logs once.\nconst reportedPrivateRoutes = new Set<string>();\n\nclass ApiClient implements AuthenticatedApiClient {\n private axiosInstance: AxiosInstance;\n private withApiKey: boolean;\n\n constructor(\n baseUrl: string = publicConfig().apiUrl,\n options?: ApiClientOptions\n ) {\n this.withApiKey = options?.withApiKey ?? true;\n\n const defaultHeaders: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n };\n\n const platformApiKey = publicConfig().storefrontApiKey;\n if (this.withApiKey && platformApiKey) {\n defaultHeaders[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n this.axiosInstance = axios.create({\n baseURL: baseUrl.replace(/\\/$/, \"\"), // Remove trailing slash\n timeout: options?.timeout ?? DEFAULT_TIMEOUT,\n headers: defaultHeaders,\n });\n\n this.setupInterceptors();\n }\n\n private setupInterceptors(): void {\n // Request interceptor - add platform API key\n this.axiosInstance.interceptors.request.use(\n async config => {\n // Ensure API key is always present (in case instance was created before env loaded)\n const platformApiKey = publicConfig().storefrontApiKey;\n if (\n this.withApiKey &&\n platformApiKey &&\n !config.headers[\"x-storefront-api-key\"]\n ) {\n config.headers[\"x-storefront-api-key\"] = platformApiKey;\n }\n\n // Opens a coming soon store for a previewer (read-only on the API's\n // side). An explicit header wins, such as the token the middleware\n // passes to `getByDomain`, and a call carrying SKIP_STORE_PREVIEW (a\n // plain, cached host lookup) never gets the request's token.\n // `get`/`set` match the header name case-insensitively.\n const previewToken = await currentStorePreviewToken();\n if (\n previewToken &&\n !skipsStorePreview(config) &&\n !config.headers.get(STORE_PREVIEW_HEADER)\n ) {\n config.headers.set(STORE_PREVIEW_HEADER, previewToken);\n }\n\n // No Authorization header is ever set here. Session tokens live in\n // httpOnly, store-scoped cookies (lib/auth/cookies.ts) that browser JS\n // cannot read; authenticated calls go through the same-origin proxy\n // built by createStoreApiClient() below, which attaches the bearer\n // token server-side.\n return config;\n },\n error => {\n return Promise.reject(error);\n }\n );\n\n // Response interceptor - handle common errors and format responses\n this.axiosInstance.interceptors.response.use(\n (response: AxiosResponse) => {\n // Success response\n return response;\n },\n (error: AxiosError) => {\n // Never the error itself: its config carries the request headers,\n // the preview token and the API key among them.\n console.error(\"API Client Error:\", {\n method: error.config?.method?.toUpperCase(),\n url: error.config?.url,\n status: error.response?.status,\n code:\n (error.response?.data as { code?: unknown } | undefined)?.code ??\n error.code,\n });\n // Handle common error scenarios\n if (error.code === \"ECONNABORTED\") {\n // Timeout error\n error.message = \"Request timeout - please try again\";\n } else if (!error.response) {\n // Network error\n error.message = \"Network error - check your connection\";\n }\n\n // A platform admin suspended this store mid-session. The initial\n // page render already handles suspension at store-resolution time\n // (app/store/[storeRef]/layout.tsx, proxy.ts) — but a client-side\n // call *after* that render (add-to-cart, checkout, a review\n // submission) hits this same guarded backend independently, and\n // isn't covered by that one-time check. Only the browser can\n // navigate on it; server-side callers still just get the rejection.\n if (\n typeof window !== \"undefined\" &&\n error.response?.status === 403 &&\n isStoreSuspendedResponseBody(error.response?.data)\n ) {\n window.location.href = STORE_SUSPENDED_REDIRECT_PATH;\n }\n\n // Likewise, the store went (or still is) coming soon. Not from the\n // coming soon page itself, so a call made there cannot reload it in\n // a loop. It is always this root path in the browser: the\n // middleware rewrites to it without changing the URL, and the shared\n // path-based host has no such page (known limitation,\n // create-storefront-middleware.ts).\n if (\n typeof window !== \"undefined\" &&\n error.response?.status === 403 &&\n isStoreComingSoonResponseBody(error.response?.data) &&\n window.location.pathname !== STORE_COMING_SOON_REDIRECT_PATH &&\n comingSoonEndsThisVisit(error.config?.method)\n ) {\n window.location.href = STORE_COMING_SOON_REDIRECT_PATH;\n }\n\n return Promise.reject(error);\n }\n );\n }\n\n private handleResponse<T>(response: AxiosResponse<T>): ApiResponse<T> {\n return {\n success: true,\n data: response.data,\n // Totals ride in headers (`x-total-count`); axios already lowercases\n // the names.\n headers: plainHeaders(response.headers),\n };\n }\n\n private handleError(error: any): ApiResponse<never> {\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError<any>;\n const responseData = axiosError.response?.data || {};\n return {\n success: false,\n error: {\n message:\n responseData.message || axiosError.message || \"Request failed\",\n statusCode: axiosError.response?.status || 0,\n // The backend serialises business errors as\n // `{ code, message, details, timestamp }`, so the stable identifier\n // lands in `code` — this is the browser-side twin of the same read\n // in `lib/auth/sdk.ts`. `unwrap()` copies it onto\n // `ApiClientError.code`, which `lib/auth/error-copy.ts` localises.\n // `responseData.error` is kept for any endpoint using Nest's default\n // envelope, and the axios code (ECONNABORTED, ERR_NETWORK) last.\n error: responseData.code || responseData.error || axiosError.code,\n // `unwrap()` copies this onto `ApiClientError.details`; checkout\n // reads `details.items` to mark the cart lines that are short.\n details: responseData.details,\n },\n };\n }\n\n return {\n success: false,\n error: {\n message:\n error instanceof Error ? error.message : \"Unknown error occurred\",\n statusCode: 0,\n },\n };\n }\n\n /**\n * The direct, publishable-key client cannot call a private route: the API\n * would refuse it, so refuse here, before the network. Logs the matched\n * route pattern, never the raw path (it can carry a review token or an\n * order code).\n */\n private refusePrivateRoute(\n method: string,\n url: string\n ): ApiResponse<never> | null {\n if (!this.withApiKey) return null;\n const route = findPrivateStorefrontRoute(method, url);\n if (!route) return null;\n const label = `${route.method} ${route.path}`;\n if (!reportedPrivateRoutes.has(label)) {\n reportedPrivateRoutes.add(label);\n console.error(\n `STOREFRONT_PRIVATE_ROUTE: ${label}. ${PRIVATE_ROUTE_MESSAGE}`\n );\n }\n return {\n success: false,\n error: {\n message: PRIVATE_ROUTE_MESSAGE,\n statusCode: 0,\n error: \"STOREFRONT_PRIVATE_ROUTE\",\n },\n };\n }\n\n async get<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"GET\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.get<T>(url, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async post<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"POST\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.post<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async put<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"PUT\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.put<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async patch<T>(\n url: string,\n data?: any,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"PATCH\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.patch<T>(url, data, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n async delete<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\n const refused = this.refusePrivateRoute(\"DELETE\", url);\n if (refused) return refused;\n try {\n const response = await this.axiosInstance.delete<T>(url, config);\n return this.handleResponse(response);\n } catch (error) {\n return this.handleError(error);\n }\n }\n\n // Additional utility methods\n getAxiosInstance(): AxiosInstance {\n return this.axiosInstance;\n }\n\n // Method to update base URL if needed\n setBaseURL(baseUrl: string): void {\n this.axiosInstance.defaults.baseURL = baseUrl.replace(/\\/$/, \"\");\n }\n\n // Method to set default timeout\n setTimeout(timeout: number): void {\n this.axiosInstance.defaults.timeout = timeout;\n }\n}\n\n/**\n * Direct, key-authenticated client for the backend's own origin. Public\n * endpoints only — it can never carry a session token (see the request\n * interceptor above).\n */\nexport const publicApiClient = new ApiClient(publicConfig().apiUrl);\n\n/**\n * A store-scoped instance whose baseURL is the same-origin proxy route\n * `/store/<storeRef>/api/backend`, so the httpOnly session cookie is sent with\n * every request and `lib/api/proxy.ts` turns it into a bearer token\n * server-side. It deliberately does NOT send `x-storefront-api-key` from the\n * browser: the proxy attaches it.\n *\n * The timeout is wider than the direct client's because a proxied call may\n * include one refresh round trip plus a retry.\n */\nexport function createStoreApiClient(storeRef: string): ApiClient {\n return new ApiClient(storeApiPath(storeRef, \"backend\"), {\n withApiKey: false,\n timeout: 20000,\n });\n}\n\n// Export the class for custom instances\nexport { ApiClient };\n\n/** Axios headers as a plain record of lowercase names to string values. */\nfunction plainHeaders(headers: unknown): Record<string, string> {\n const out: Record<string, string> = {};\n const source =\n headers && typeof (headers as { toJSON?: unknown }).toJSON === \"function\"\n ? (headers as { toJSON(): Record<string, unknown> }).toJSON()\n : ((headers ?? {}) as Record<string, unknown>);\n for (const [name, value] of Object.entries(source)) {\n if (value == null) continue;\n out[name.toLowerCase()] = Array.isArray(value)\n ? value.join(\", \")\n : String(value);\n }\n return out;\n}\n"],"mappings":"AAAA,OAAO,WAKA;AAEP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,oBA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Aa,EAAE,MAAM;AAY3D,SAAS,qBAAqB,UAA6B;AAChE,SAAO,IAAI,UAAU,aAAa,UAAU,SAAS,GAAG;AAAA,IACtD,YAAY;AAAA,IACZ,SAAS;AAAA,EACX,CAAC;AACH;AAMA,SAAS,aAAa,SAA0C;AAC9D,QAAM,MAA8B,CAAC;AACrC,QAAM,SACJ,WAAW,OAAQ,QAAiC,WAAW,aAC1D,QAAkD,OAAO,IACxD,WAAW,CAAC;AACpB,aAAW,CAAC,MAAM,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AAClD,QAAI,SAAS,KAAM;AACnB,QAAI,KAAK,YAAY,CAAC,IAAI,MAAM,QAAQ,KAAK,IACzC,MAAM,KAAK,IAAI,IACf,OAAO,KAAK;AAAA,EAClB;AACA,SAAO;AACT;","names":[]}
|
package/dist/auth/sdk.js
CHANGED
|
@@ -59,7 +59,12 @@ async function send(method, url, data, options, clientIp, previewToken) {
|
|
|
59
59
|
}
|
|
60
60
|
};
|
|
61
61
|
}
|
|
62
|
-
return {
|
|
62
|
+
return {
|
|
63
|
+
success: true,
|
|
64
|
+
data: body,
|
|
65
|
+
// fetch's Headers yields lowercase names.
|
|
66
|
+
headers: Object.fromEntries(response.headers.entries())
|
|
67
|
+
};
|
|
63
68
|
} catch (error) {
|
|
64
69
|
return {
|
|
65
70
|
success: false,
|
package/dist/auth/sdk.js.map
CHANGED
|
@@ -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 * 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 {
|
|
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 {\n success: true,\n data: body as T,\n // fetch's Headers yields lowercase names.\n headers: Object.fromEntries(response.headers.entries()),\n };\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,GAAG,IAAI,OAAO,IAAI,IAAI,EAAE;AAC3D;AAEA,eAAe,KACb,QACA,KACA,MACA,SACA,UACA,cACyB;AACzB,MAAI;AACF,UAAM,WAAW,MAAM,MAAM,WAAW,GAAG,GAAG;AAAA,MAC5C;AAAA,MACA,SAAS;AAAA,QACP,gBAAgB;AAAA,QAChB,wBAAwB,oBAAoB;AAAA;AAAA;AAAA,QAG5C,GAAI,gBAAgB,WAAW,QAC3B,EAAE,CAAC,oBAAoB,GAAG,aAAa,IACvC,CAAC;AAAA,QACL,GAAI,SAAS,WAAW,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAMzB,GAAG,kBAAkB,QAAQ;AAAA,MAC/B;AAAA,MACA,MAAM,SAAS,SAAY,SAAY,KAAK,UAAU,IAAI;AAAA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]}
|
package/dist/client-info.js
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -554,6 +554,8 @@ interface ApiResponse<T = any> {
|
|
|
554
554
|
data?: T;
|
|
555
555
|
error?: ApiError;
|
|
556
556
|
success: boolean;
|
|
557
|
+
/** The response headers, names in lowercase (totals ride in `x-total-count`). */
|
|
558
|
+
headers?: Record<string, string>;
|
|
557
559
|
}
|
|
558
560
|
interface RequestConfig {
|
|
559
561
|
headers?: Record<string, string>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecomweb/storefront-kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.16.0",
|
|
4
4
|
"description": "Headless storefront logic for ecomweb: auth, cart, checkout, API proxy",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
"currency.js": "^2.0.4",
|
|
54
54
|
"server-only": "^0.0.1",
|
|
55
55
|
"zod": "^4.1.12",
|
|
56
|
-
"@ecomweb/sdk": "^0.
|
|
56
|
+
"@ecomweb/sdk": "^0.16.0"
|
|
57
57
|
},
|
|
58
58
|
"peerDependencies": {
|
|
59
59
|
"next": ">=16",
|