@ecomweb/storefront-kit 0.2.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/LICENSE +21 -0
- package/README.md +55 -0
- package/dist/api/client.js +162 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/index.js +7 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/proxy.js +145 -0
- package/dist/api/proxy.js.map +1 -0
- package/dist/api/response.js +55 -0
- package/dist/api/response.js.map +1 -0
- package/dist/api/server-client.js +159 -0
- package/dist/api/server-client.js.map +1 -0
- package/dist/auth/client-ip.js +44 -0
- package/dist/auth/client-ip.js.map +1 -0
- package/dist/auth/context.js +125 -0
- package/dist/auth/context.js.map +1 -0
- package/dist/auth/cookies.js +97 -0
- package/dist/auth/cookies.js.map +1 -0
- package/dist/auth/error-copy.js +49 -0
- package/dist/auth/error-copy.js.map +1 -0
- package/dist/auth/password-policy.js +29 -0
- package/dist/auth/password-policy.js.map +1 -0
- package/dist/auth/route-handlers.js +337 -0
- package/dist/auth/route-handlers.js.map +1 -0
- package/dist/auth/safe-redirect.js +20 -0
- package/dist/auth/safe-redirect.js.map +1 -0
- package/dist/auth/sdk.js +76 -0
- package/dist/auth/sdk.js.map +1 -0
- package/dist/auth/session-refresh.js +81 -0
- package/dist/auth/session-refresh.js.map +1 -0
- package/dist/auth/session.js +26 -0
- package/dist/auth/session.js.map +1 -0
- package/dist/auth/use-public-auth-config.js +29 -0
- package/dist/auth/use-public-auth-config.js.map +1 -0
- package/dist/cart/api.js +60 -0
- package/dist/cart/api.js.map +1 -0
- package/dist/cart/server-context.js +279 -0
- package/dist/cart/server-context.js.map +1 -0
- package/dist/cart/types.js +1 -0
- package/dist/cart/types.js.map +1 -0
- package/dist/cart/utils.js +49 -0
- package/dist/cart/utils.js.map +1 -0
- package/dist/checkout/get-payment-state.js +15 -0
- package/dist/checkout/get-payment-state.js.map +1 -0
- package/dist/checkout/initiate-gateway-payment.js +13 -0
- package/dist/checkout/initiate-gateway-payment.js.map +1 -0
- package/dist/checkout/order-handoff.js +61 -0
- package/dist/checkout/order-handoff.js.map +1 -0
- package/dist/checkout/payment-redirect.js +11 -0
- package/dist/checkout/payment-redirect.js.map +1 -0
- package/dist/checkout/payment-state-poll.js +45 -0
- package/dist/checkout/payment-state-poll.js.map +1 -0
- package/dist/checkout/start-gateway-redirect.js +16 -0
- package/dist/checkout/start-gateway-redirect.js.map +1 -0
- package/dist/checkout/stock-issues.js +35 -0
- package/dist/checkout/stock-issues.js.map +1 -0
- package/dist/checkout/success-state.js +15 -0
- package/dist/checkout/success-state.js.map +1 -0
- package/dist/checkout/types.js +1 -0
- package/dist/checkout/types.js.map +1 -0
- package/dist/checkout/use-checkout.js +256 -0
- package/dist/checkout/use-checkout.js.map +1 -0
- package/dist/checkout/utils.js +7 -0
- package/dist/checkout/utils.js.map +1 -0
- package/dist/config/index.js +7 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/log-level.js +8 -0
- package/dist/config/log-level.js.map +1 -0
- package/dist/config/mode.js +18 -0
- package/dist/config/mode.js.map +1 -0
- package/dist/config/public.js +115 -0
- package/dist/config/public.js.map +1 -0
- package/dist/config/schema.js +70 -0
- package/dist/config/schema.js.map +1 -0
- package/dist/config/server.js +68 -0
- package/dist/config/server.js.map +1 -0
- package/dist/config.d.ts +16 -0
- package/dist/config.js +15 -0
- package/dist/config.js.map +1 -0
- package/dist/currency.js +68 -0
- package/dist/currency.js.map +1 -0
- package/dist/index.d.ts +968 -0
- package/dist/index.js +146 -0
- package/dist/index.js.map +1 -0
- package/dist/interfaces/api.types.js +1 -0
- package/dist/interfaces/api.types.js.map +1 -0
- package/dist/interfaces/index.js +2 -0
- package/dist/interfaces/index.js.map +1 -0
- package/dist/logging.js +42 -0
- package/dist/logging.js.map +1 -0
- package/dist/middleware/create-storefront-middleware.js +175 -0
- package/dist/middleware/create-storefront-middleware.js.map +1 -0
- package/dist/middleware.d.ts +24 -0
- package/dist/middleware.js +9 -0
- package/dist/middleware.js.map +1 -0
- package/dist/mode-1ZKDELPZ.d.ts +16 -0
- package/dist/notices.js +31 -0
- package/dist/notices.js.map +1 -0
- package/dist/orders/api-client.js +32 -0
- package/dist/orders/api-client.js.map +1 -0
- package/dist/orders/derive-progress.js +36 -0
- package/dist/orders/derive-progress.js.map +1 -0
- package/dist/orders/index.js +6 -0
- package/dist/orders/index.js.map +1 -0
- package/dist/orders/types.js +13 -0
- package/dist/orders/types.js.map +1 -0
- package/dist/orders/use-order-status.js +137 -0
- package/dist/orders/use-order-status.js.map +1 -0
- package/dist/promotions/use-promotion-validation.js +106 -0
- package/dist/promotions/use-promotion-validation.js.map +1 -0
- package/dist/promotions/utils.js +40 -0
- package/dist/promotions/utils.js.map +1 -0
- package/dist/provider.js +25 -0
- package/dist/provider.js.map +1 -0
- package/dist/redirects/index.js +2 -0
- package/dist/redirects/index.js.map +1 -0
- package/dist/redirects/lookup-redirect.js +13 -0
- package/dist/redirects/lookup-redirect.js.map +1 -0
- package/dist/request/public-url.js +20 -0
- package/dist/request/public-url.js.map +1 -0
- package/dist/schema-CEMKsCwh.d.ts +52 -0
- package/dist/sdk.js +33 -0
- package/dist/sdk.js.map +1 -0
- package/dist/server/routes.js +56 -0
- package/dist/server/routes.js.map +1 -0
- package/dist/server.d.ts +58 -0
- package/dist/server.js +19 -0
- package/dist/server.js.map +1 -0
- package/dist/shipping/format-shipping-option.js +12 -0
- package/dist/shipping/format-shipping-option.js.map +1 -0
- package/dist/shipping/location-areas.js +104 -0
- package/dist/shipping/location-areas.js.map +1 -0
- package/dist/shipping/messages.js +19 -0
- package/dist/shipping/messages.js.map +1 -0
- package/dist/shipping/shipping-calculation-reducer.js +75 -0
- package/dist/shipping/shipping-calculation-reducer.js.map +1 -0
- package/dist/shipping/use-shipping-calculation.js +84 -0
- package/dist/shipping/use-shipping-calculation.js.map +1 -0
- package/dist/shipping/utils.js +18 -0
- package/dist/shipping/utils.js.map +1 -0
- package/dist/storage.js +116 -0
- package/dist/storage.js.map +1 -0
- package/dist/store/store-context.js +72 -0
- package/dist/store/store-context.js.map +1 -0
- package/dist/store-scope/index.js +33 -0
- package/dist/store-scope/index.js.map +1 -0
- package/dist/store-scope/root.js +15 -0
- package/dist/store-scope/root.js.map +1 -0
- package/dist/store-scope/store-url.js +45 -0
- package/dist/store-scope/store-url.js.map +1 -0
- package/dist/stores/basic-settings.js +67 -0
- package/dist/stores/basic-settings.js.map +1 -0
- package/dist/stores/cached.js +20 -0
- package/dist/stores/cached.js.map +1 -0
- package/dist/stores/get-store-by-host.js +38 -0
- package/dist/stores/get-store-by-host.js.map +1 -0
- package/dist/stores/index.js +7 -0
- package/dist/stores/index.js.map +1 -0
- package/dist/stores/metadata.js +19 -0
- package/dist/stores/metadata.js.map +1 -0
- package/dist/stores/store-path.js +9 -0
- package/dist/stores/store-path.js.map +1 -0
- package/dist/stores/store-suspension.js +14 -0
- package/dist/stores/store-suspension.js.map +1 -0
- package/package.json +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ecomweb
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# @ecomweb/storefront-kit
|
|
2
|
+
|
|
3
|
+
Headless storefront logic for [ecomweb](https://ecomweb.app) stores on
|
|
4
|
+
Next.js 16: auth and session, the same-origin API proxy, cart, checkout,
|
|
5
|
+
order status and the middleware. No UI: you own every page and component.
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @ecomweb/storefront-kit @ecomweb/sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
| Entry | Use it from | Main exports |
|
|
12
|
+
|---|---|---|
|
|
13
|
+
| `@ecomweb/storefront-kit` | client and server components | `StorefrontKitProvider`, `useAuth`, `useCart`, `useCheckout`, `useOrderStatus`, `useOrderLookup`, `storePath`, `storeApiPath` |
|
|
14
|
+
| `@ecomweb/storefront-kit/server` | route handlers, server components | `createAuthRoutes`, `createBackendProxy`, `requireSession`, `serverConfig`, `resolveRootStoreRef` |
|
|
15
|
+
| `@ecomweb/storefront-kit/middleware` | `proxy.ts` | `createStorefrontMiddleware`, `storefrontMiddlewareConfig` |
|
|
16
|
+
| `@ecomweb/storefront-kit/config` | anywhere | `publicConfig`, `parsePublicConfig`, `resolveMode` |
|
|
17
|
+
|
|
18
|
+
## Modes
|
|
19
|
+
|
|
20
|
+
`ECOMWEB_MODE` (`NEXT_PUBLIC_ECOMWEB_MODE` in the browser) picks the
|
|
21
|
+
behaviour; it defaults to `single`:
|
|
22
|
+
|
|
23
|
+
- `single`: one store (`ECOMWEB_STORE_REF`), pages at the site root.
|
|
24
|
+
- `multi`: the ecomweb platform storefront, every store under
|
|
25
|
+
`/store/<ref>` or its own domain.
|
|
26
|
+
|
|
27
|
+
## Wiring
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
// proxy.ts
|
|
31
|
+
import { createStorefrontMiddleware } from "@ecomweb/storefront-kit/middleware";
|
|
32
|
+
export default createStorefrontMiddleware();
|
|
33
|
+
export const config = {
|
|
34
|
+
matcher: ["/((?!api|_next/static|_next/image|favicon.ico).*)"],
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// app/api/auth/[...route]/route.ts
|
|
38
|
+
import { createAuthRoutes } from "@ecomweb/storefront-kit/server";
|
|
39
|
+
export const { GET, POST } = createAuthRoutes();
|
|
40
|
+
|
|
41
|
+
// app/api/backend/[...path]/route.ts
|
|
42
|
+
import { createBackendProxy } from "@ecomweb/storefront-kit/server";
|
|
43
|
+
export const { GET, POST, PUT, PATCH, DELETE } = createBackendProxy();
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Wrap the store layout in `<StorefrontKitProvider store={store} onNotice={…}>`;
|
|
47
|
+
`onNotice` receives the kit's messages (item added, request failed) for your
|
|
48
|
+
toasts. `useCheckout().placeOrder()` returns `redirect`, `redirect_failed`,
|
|
49
|
+
`success`, `stock_issues` or `error`, and your page decides what to show.
|
|
50
|
+
|
|
51
|
+
## Versioning
|
|
52
|
+
|
|
53
|
+
Semver. Within 1.x no export is removed and no required prop or parameter
|
|
54
|
+
is added. Before 1.0, a minor (0.x) release may break; your caret range
|
|
55
|
+
(`^0.y.z`) only takes the patches of your minor.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import axios from "axios";
|
|
2
|
+
import {
|
|
3
|
+
isStoreSuspendedResponseBody,
|
|
4
|
+
STORE_SUSPENDED_REDIRECT_PATH
|
|
5
|
+
} from "../stores/store-suspension.js";
|
|
6
|
+
import { publicConfig } from "../config.js";
|
|
7
|
+
import { storeApiPath } from "../store-scope/index.js";
|
|
8
|
+
const DEFAULT_TIMEOUT = 1e4;
|
|
9
|
+
class ApiClient {
|
|
10
|
+
axiosInstance;
|
|
11
|
+
withApiKey;
|
|
12
|
+
constructor(baseUrl = publicConfig().apiUrl, options) {
|
|
13
|
+
this.withApiKey = options?.withApiKey ?? true;
|
|
14
|
+
const defaultHeaders = {
|
|
15
|
+
"Content-Type": "application/json"
|
|
16
|
+
};
|
|
17
|
+
const platformApiKey = publicConfig().storefrontApiKey;
|
|
18
|
+
if (this.withApiKey && platformApiKey) {
|
|
19
|
+
defaultHeaders["x-storefront-api-key"] = platformApiKey;
|
|
20
|
+
}
|
|
21
|
+
this.axiosInstance = axios.create({
|
|
22
|
+
baseURL: baseUrl.replace(/\/$/, ""),
|
|
23
|
+
// Remove trailing slash
|
|
24
|
+
timeout: options?.timeout ?? DEFAULT_TIMEOUT,
|
|
25
|
+
headers: defaultHeaders
|
|
26
|
+
});
|
|
27
|
+
this.setupInterceptors();
|
|
28
|
+
}
|
|
29
|
+
setupInterceptors() {
|
|
30
|
+
this.axiosInstance.interceptors.request.use(
|
|
31
|
+
async (config) => {
|
|
32
|
+
const platformApiKey = publicConfig().storefrontApiKey;
|
|
33
|
+
if (this.withApiKey && platformApiKey && !config.headers["x-storefront-api-key"]) {
|
|
34
|
+
config.headers["x-storefront-api-key"] = platformApiKey;
|
|
35
|
+
}
|
|
36
|
+
return config;
|
|
37
|
+
},
|
|
38
|
+
(error) => {
|
|
39
|
+
return Promise.reject(error);
|
|
40
|
+
}
|
|
41
|
+
);
|
|
42
|
+
this.axiosInstance.interceptors.response.use(
|
|
43
|
+
(response) => {
|
|
44
|
+
return response;
|
|
45
|
+
},
|
|
46
|
+
(error) => {
|
|
47
|
+
console.error("API Client Error:", error);
|
|
48
|
+
if (error.code === "ECONNABORTED") {
|
|
49
|
+
error.message = "Request timeout - please try again";
|
|
50
|
+
} else if (!error.response) {
|
|
51
|
+
error.message = "Network error - check your connection";
|
|
52
|
+
}
|
|
53
|
+
if (typeof window !== "undefined" && error.response?.status === 403 && isStoreSuspendedResponseBody(error.response?.data)) {
|
|
54
|
+
window.location.href = STORE_SUSPENDED_REDIRECT_PATH;
|
|
55
|
+
}
|
|
56
|
+
return Promise.reject(error);
|
|
57
|
+
}
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
handleResponse(response) {
|
|
61
|
+
return {
|
|
62
|
+
success: true,
|
|
63
|
+
data: response.data
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
handleError(error) {
|
|
67
|
+
if (axios.isAxiosError(error)) {
|
|
68
|
+
const axiosError = error;
|
|
69
|
+
const responseData = axiosError.response?.data || {};
|
|
70
|
+
return {
|
|
71
|
+
success: false,
|
|
72
|
+
error: {
|
|
73
|
+
message: responseData.message || axiosError.message || "Request failed",
|
|
74
|
+
statusCode: axiosError.response?.status || 0,
|
|
75
|
+
// The backend serialises business errors as
|
|
76
|
+
// `{ code, message, details, timestamp }`, so the stable identifier
|
|
77
|
+
// lands in `code` — this is the browser-side twin of the same read
|
|
78
|
+
// in `lib/auth/sdk.ts`. `unwrap()` copies it onto
|
|
79
|
+
// `ApiClientError.code`, which `lib/auth/error-copy.ts` localises.
|
|
80
|
+
// `responseData.error` is kept for any endpoint using Nest's default
|
|
81
|
+
// envelope, and the axios code (ECONNABORTED, ERR_NETWORK) last.
|
|
82
|
+
error: responseData.code || responseData.error || axiosError.code,
|
|
83
|
+
// `unwrap()` copies this onto `ApiClientError.details`; checkout
|
|
84
|
+
// reads `details.items` to mark the cart lines that are short.
|
|
85
|
+
details: responseData.details
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
return {
|
|
90
|
+
success: false,
|
|
91
|
+
error: {
|
|
92
|
+
message: error instanceof Error ? error.message : "Unknown error occurred",
|
|
93
|
+
statusCode: 0
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
async get(url, config) {
|
|
98
|
+
try {
|
|
99
|
+
const response = await this.axiosInstance.get(url, config);
|
|
100
|
+
return this.handleResponse(response);
|
|
101
|
+
} catch (error) {
|
|
102
|
+
return this.handleError(error);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async post(url, data, config) {
|
|
106
|
+
try {
|
|
107
|
+
const response = await this.axiosInstance.post(url, data, config);
|
|
108
|
+
return this.handleResponse(response);
|
|
109
|
+
} catch (error) {
|
|
110
|
+
return this.handleError(error);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
async put(url, data, config) {
|
|
114
|
+
try {
|
|
115
|
+
const response = await this.axiosInstance.put(url, data, config);
|
|
116
|
+
return this.handleResponse(response);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
return this.handleError(error);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
async patch(url, data, config) {
|
|
122
|
+
try {
|
|
123
|
+
const response = await this.axiosInstance.patch(url, data, config);
|
|
124
|
+
return this.handleResponse(response);
|
|
125
|
+
} catch (error) {
|
|
126
|
+
return this.handleError(error);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
async delete(url, config) {
|
|
130
|
+
try {
|
|
131
|
+
const response = await this.axiosInstance.delete(url, config);
|
|
132
|
+
return this.handleResponse(response);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
return this.handleError(error);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
// Additional utility methods
|
|
138
|
+
getAxiosInstance() {
|
|
139
|
+
return this.axiosInstance;
|
|
140
|
+
}
|
|
141
|
+
// Method to update base URL if needed
|
|
142
|
+
setBaseURL(baseUrl) {
|
|
143
|
+
this.axiosInstance.defaults.baseURL = baseUrl.replace(/\/$/, "");
|
|
144
|
+
}
|
|
145
|
+
// Method to set default timeout
|
|
146
|
+
setTimeout(timeout) {
|
|
147
|
+
this.axiosInstance.defaults.timeout = timeout;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const publicApiClient = new ApiClient(publicConfig().apiUrl);
|
|
151
|
+
function createStoreApiClient(storeRef) {
|
|
152
|
+
return new ApiClient(storeApiPath(storeRef, "backend"), {
|
|
153
|
+
withApiKey: false,
|
|
154
|
+
timeout: 2e4
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
export {
|
|
158
|
+
ApiClient,
|
|
159
|
+
createStoreApiClient,
|
|
160
|
+
publicApiClient
|
|
161
|
+
};
|
|
162
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +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 { publicConfig } from \"../config\";\nimport { storeApiPath } from \"../store-scope\";\n\nconst DEFAULT_TIMEOUT = 10000; // 10 seconds\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\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 // 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 console.error(\"API Client Error:\", error);\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 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 async get<T>(\n url: string,\n config?: AxiosRequestConfig\n ): Promise<ApiResponse<T>> {\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 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 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 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 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":"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","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/api/index.ts"],"sourcesContent":["// Client-side API clients (for use in React components).\n// `publicApiClient` talks to the backend origin directly and can never carry a\n// session token; `createStoreApiClient(storeRef)` routes through the\n// same-origin proxy that attaches one server-side.\nexport { publicApiClient, createStoreApiClient, ApiClient } from \"./client\";\n\n// Note: serverApiClient is not exported here to avoid bundling server-only\n// dependencies on the client. Use getApiClient() for universal usage,\n// or import { serverApiClient } from './server-client' directly\n// in server-only contexts if needed.\n"],"mappings":"AAIA,SAAS,iBAAiB,sBAAsB,iBAAiB;","names":[]}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import "server-only";
|
|
2
|
+
import { NextResponse } from "next/server";
|
|
3
|
+
import {
|
|
4
|
+
authCookiePathFor,
|
|
5
|
+
readAuthCookies,
|
|
6
|
+
writeAuthCookies
|
|
7
|
+
} from "../auth/cookies.js";
|
|
8
|
+
import {
|
|
9
|
+
clientIpFrom,
|
|
10
|
+
FORWARDER_SECRET_HEADER,
|
|
11
|
+
forwardingHeaders
|
|
12
|
+
} from "../auth/client-ip.js";
|
|
13
|
+
import { backendBaseUrl, createAuthApi, storefrontApiKey } from "../auth/sdk.js";
|
|
14
|
+
const BLOCKED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
|
|
15
|
+
"connection",
|
|
16
|
+
"keep-alive",
|
|
17
|
+
"proxy-authenticate",
|
|
18
|
+
"proxy-authorization",
|
|
19
|
+
"te",
|
|
20
|
+
"trailer",
|
|
21
|
+
"transfer-encoding",
|
|
22
|
+
"upgrade",
|
|
23
|
+
"host",
|
|
24
|
+
"content-length",
|
|
25
|
+
"accept-encoding",
|
|
26
|
+
"origin",
|
|
27
|
+
"authorization",
|
|
28
|
+
"cookie",
|
|
29
|
+
"x-storefront-api-key",
|
|
30
|
+
"x-forwarded-for",
|
|
31
|
+
"x-real-ip",
|
|
32
|
+
"cf-connecting-ip",
|
|
33
|
+
FORWARDER_SECRET_HEADER
|
|
34
|
+
]);
|
|
35
|
+
const METHODS_WITH_BODY = /* @__PURE__ */ new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
|
36
|
+
function jsonError(status, message, code) {
|
|
37
|
+
return NextResponse.json({ code, message }, { status });
|
|
38
|
+
}
|
|
39
|
+
function resolveTarget(segments, search) {
|
|
40
|
+
if (segments.length === 0) return null;
|
|
41
|
+
for (const segment of segments) {
|
|
42
|
+
if (segment === "" || segment === "." || segment === ".." || segment.includes("/") || segment.includes("\\")) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const base = new URL(backendBaseUrl());
|
|
47
|
+
const prefix = base.pathname.replace(/\/$/, "");
|
|
48
|
+
const target = new URL(
|
|
49
|
+
`${prefix}/${segments.map(encodeURIComponent).join("/")}`,
|
|
50
|
+
base
|
|
51
|
+
);
|
|
52
|
+
if (target.origin !== base.origin) return null;
|
|
53
|
+
if (!target.pathname.startsWith(`${prefix}/`)) return null;
|
|
54
|
+
target.search = search;
|
|
55
|
+
return target;
|
|
56
|
+
}
|
|
57
|
+
function forwardedHeaders(request, accessToken) {
|
|
58
|
+
const headers = new Headers();
|
|
59
|
+
request.headers.forEach((value, key) => {
|
|
60
|
+
if (!BLOCKED_REQUEST_HEADERS.has(key.toLowerCase())) {
|
|
61
|
+
headers.set(key, value);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
headers.set("x-storefront-api-key", storefrontApiKey());
|
|
65
|
+
for (const [key, value] of Object.entries(
|
|
66
|
+
forwardingHeaders(clientIpFrom(request.headers))
|
|
67
|
+
)) {
|
|
68
|
+
headers.set(key, value);
|
|
69
|
+
}
|
|
70
|
+
if (accessToken) headers.set("authorization", `Bearer ${accessToken}`);
|
|
71
|
+
return headers;
|
|
72
|
+
}
|
|
73
|
+
async function callUpstream(request, target, body, accessToken) {
|
|
74
|
+
const response = await fetch(target, {
|
|
75
|
+
method: request.method,
|
|
76
|
+
headers: forwardedHeaders(request, accessToken),
|
|
77
|
+
body,
|
|
78
|
+
cache: "no-store",
|
|
79
|
+
redirect: "manual"
|
|
80
|
+
});
|
|
81
|
+
return {
|
|
82
|
+
status: response.status,
|
|
83
|
+
body: await response.text(),
|
|
84
|
+
contentType: response.headers.get("content-type")
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function respond(result) {
|
|
88
|
+
return new NextResponse(result.body || null, {
|
|
89
|
+
status: result.status,
|
|
90
|
+
headers: result.contentType ? { "content-type": result.contentType } : void 0
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
async function handleBackendProxy(request, storeRef, segments) {
|
|
94
|
+
const target = resolveTarget(segments, request.nextUrl.search);
|
|
95
|
+
if (!target) {
|
|
96
|
+
return jsonError(400, "Invalid proxy path", "PROXY_INVALID_PATH");
|
|
97
|
+
}
|
|
98
|
+
const body = METHODS_WITH_BODY.has(request.method) ? await request.text() : void 0;
|
|
99
|
+
const tokens = readAuthCookies(request.cookies, storeRef);
|
|
100
|
+
let result;
|
|
101
|
+
try {
|
|
102
|
+
result = await callUpstream(
|
|
103
|
+
request,
|
|
104
|
+
target,
|
|
105
|
+
body || void 0,
|
|
106
|
+
tokens?.access_token
|
|
107
|
+
);
|
|
108
|
+
} catch {
|
|
109
|
+
return jsonError(502, "Upstream request failed", "PROXY_UPSTREAM_ERROR");
|
|
110
|
+
}
|
|
111
|
+
if (result.status !== 401 || !tokens) return respond(result);
|
|
112
|
+
const refreshed = await createAuthApi(
|
|
113
|
+
storeRef,
|
|
114
|
+
clientIpFrom(request.headers)
|
|
115
|
+
).refresh(tokens.refresh_token);
|
|
116
|
+
if (!refreshed.success || !refreshed.data?.access_token || !refreshed.data.refresh_token) {
|
|
117
|
+
return respond(result);
|
|
118
|
+
}
|
|
119
|
+
let retry;
|
|
120
|
+
try {
|
|
121
|
+
retry = await callUpstream(
|
|
122
|
+
request,
|
|
123
|
+
target,
|
|
124
|
+
body || void 0,
|
|
125
|
+
refreshed.data.access_token
|
|
126
|
+
);
|
|
127
|
+
} catch {
|
|
128
|
+
return jsonError(502, "Upstream request failed", "PROXY_UPSTREAM_ERROR");
|
|
129
|
+
}
|
|
130
|
+
const response = respond(retry);
|
|
131
|
+
writeAuthCookies(
|
|
132
|
+
response,
|
|
133
|
+
storeRef,
|
|
134
|
+
{
|
|
135
|
+
access_token: refreshed.data.access_token,
|
|
136
|
+
refresh_token: refreshed.data.refresh_token
|
|
137
|
+
},
|
|
138
|
+
authCookiePathFor(request, storeRef)
|
|
139
|
+
);
|
|
140
|
+
return response;
|
|
141
|
+
}
|
|
142
|
+
export {
|
|
143
|
+
handleBackendProxy
|
|
144
|
+
};
|
|
145
|
+
//# sourceMappingURL=proxy.js.map
|
|
@@ -0,0 +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\";\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 */\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]);\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\nfunction forwardedHeaders(request: NextRequest, accessToken?: string) {\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 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 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, 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(request.cookies, storeRef);\n\n let result: UpstreamResult;\n\n try {\n result = await callUpstream(\n request,\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 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":"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","names":[]}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
class ApiClientError extends Error {
|
|
2
|
+
statusCode;
|
|
3
|
+
code;
|
|
4
|
+
/**
|
|
5
|
+
* A business error's structured payload, for example the per-line items of
|
|
6
|
+
* an INSUFFICIENT_INVENTORY rejection. Carried here as well as on the SDK's
|
|
7
|
+
* own error class because this repo has two: checkout's order creation
|
|
8
|
+
* throws the SDK's, while the payment helpers throw this one. Dropping the
|
|
9
|
+
* payload on one of them would lose it silently on whichever path a caller
|
|
10
|
+
* happens to be using.
|
|
11
|
+
*/
|
|
12
|
+
details;
|
|
13
|
+
constructor(message, statusCode = 0, code, details) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.name = "ApiClientError";
|
|
16
|
+
this.statusCode = statusCode;
|
|
17
|
+
this.code = code;
|
|
18
|
+
this.details = details;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function unwrap(response) {
|
|
22
|
+
if (response.success && response.data !== void 0) {
|
|
23
|
+
return response.data;
|
|
24
|
+
}
|
|
25
|
+
const message = response.error?.message || "Request failed";
|
|
26
|
+
const status = response.error?.statusCode || 0;
|
|
27
|
+
const code = response.error?.error;
|
|
28
|
+
throw new ApiClientError(message, status, code, response.error?.details);
|
|
29
|
+
}
|
|
30
|
+
function unwrapOrNull(response, nullStatusCodes = [404]) {
|
|
31
|
+
if (response.success && response.data !== void 0) {
|
|
32
|
+
return response.data;
|
|
33
|
+
}
|
|
34
|
+
if (!response.success && response.error && nullStatusCodes.includes(response.error.statusCode)) {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
const message = response.error?.message || "Request failed";
|
|
38
|
+
const status = response.error?.statusCode || 0;
|
|
39
|
+
const code = response.error?.error;
|
|
40
|
+
throw new ApiClientError(message, status, code, response.error?.details);
|
|
41
|
+
}
|
|
42
|
+
function ensureSuccess(response) {
|
|
43
|
+
if (response.success) return;
|
|
44
|
+
const message = response.error?.message || "Request failed";
|
|
45
|
+
const status = response.error?.statusCode || 0;
|
|
46
|
+
const code = response.error?.error;
|
|
47
|
+
throw new ApiClientError(message, status, code, response.error?.details);
|
|
48
|
+
}
|
|
49
|
+
export {
|
|
50
|
+
ApiClientError,
|
|
51
|
+
ensureSuccess,
|
|
52
|
+
unwrap,
|
|
53
|
+
unwrapOrNull
|
|
54
|
+
};
|
|
55
|
+
//# sourceMappingURL=response.js.map
|
|
@@ -0,0 +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":[]}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { readAuthCookies } from "../auth/cookies.js";
|
|
2
|
+
import { publicConfig } from "../config.js";
|
|
3
|
+
const DEFAULT_TIMEOUT = 1e4;
|
|
4
|
+
class ServerApiClient {
|
|
5
|
+
baseUrl;
|
|
6
|
+
timeout;
|
|
7
|
+
requireAuth;
|
|
8
|
+
constructor(baseUrl = publicConfig().apiUrl, options) {
|
|
9
|
+
this.requireAuth = options?.requireAuth !== void 0 ? options.requireAuth : true;
|
|
10
|
+
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
11
|
+
this.timeout = DEFAULT_TIMEOUT;
|
|
12
|
+
}
|
|
13
|
+
async getAuthToken(storeRef) {
|
|
14
|
+
if (!this.requireAuth) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
if (!storeRef) {
|
|
18
|
+
throw new Error(
|
|
19
|
+
"ServerApiClient: storeRef is required for authenticated requests"
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
const { cookies } = await import("next/headers");
|
|
23
|
+
const jar = await cookies();
|
|
24
|
+
const tokens = readAuthCookies(jar, storeRef);
|
|
25
|
+
if (!tokens) {
|
|
26
|
+
throw new Error("User not authenticated");
|
|
27
|
+
}
|
|
28
|
+
return tokens.access_token;
|
|
29
|
+
}
|
|
30
|
+
async makeRequest(url, options = {}, config) {
|
|
31
|
+
try {
|
|
32
|
+
const controller = new AbortController();
|
|
33
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
34
|
+
const headers = {
|
|
35
|
+
"Content-Type": "application/json",
|
|
36
|
+
...config?.headers
|
|
37
|
+
};
|
|
38
|
+
const platformApiKey = publicConfig().storefrontApiKey;
|
|
39
|
+
if (platformApiKey) {
|
|
40
|
+
headers["x-storefront-api-key"] = platformApiKey;
|
|
41
|
+
}
|
|
42
|
+
if (this.requireAuth) {
|
|
43
|
+
const token = await this.getAuthToken(config?.storeRef);
|
|
44
|
+
if (token) {
|
|
45
|
+
headers.Authorization = `Bearer ${token}`;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const response = await fetch(`${this.baseUrl}${url}`, {
|
|
49
|
+
...options,
|
|
50
|
+
headers,
|
|
51
|
+
signal: config?.signal || controller.signal
|
|
52
|
+
});
|
|
53
|
+
clearTimeout(timeoutId);
|
|
54
|
+
let data;
|
|
55
|
+
const contentType = response.headers.get("content-type");
|
|
56
|
+
if (contentType && contentType.includes("application/json")) {
|
|
57
|
+
data = await response.json();
|
|
58
|
+
} else {
|
|
59
|
+
data = await response.text();
|
|
60
|
+
}
|
|
61
|
+
if (!response.ok) {
|
|
62
|
+
return {
|
|
63
|
+
success: false,
|
|
64
|
+
error: {
|
|
65
|
+
message: data?.message || `Request failed with status ${response.status}`,
|
|
66
|
+
statusCode: response.status,
|
|
67
|
+
error: data?.error || response.statusText,
|
|
68
|
+
details: data?.details
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
success: true,
|
|
74
|
+
data
|
|
75
|
+
};
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (error.name === "AbortError") {
|
|
78
|
+
return {
|
|
79
|
+
success: false,
|
|
80
|
+
error: {
|
|
81
|
+
message: "Request timeout - please try again",
|
|
82
|
+
statusCode: 0,
|
|
83
|
+
error: "TIMEOUT"
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
if (error instanceof TypeError) {
|
|
88
|
+
return {
|
|
89
|
+
success: false,
|
|
90
|
+
error: {
|
|
91
|
+
message: "Network error - check your connection",
|
|
92
|
+
statusCode: 0,
|
|
93
|
+
error: "NETWORK_ERROR"
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
return {
|
|
98
|
+
success: false,
|
|
99
|
+
error: {
|
|
100
|
+
message: error instanceof Error ? error.message : "Unknown error occurred",
|
|
101
|
+
statusCode: 0
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
async get(url, config) {
|
|
107
|
+
return this.makeRequest(url, { method: "GET" }, config);
|
|
108
|
+
}
|
|
109
|
+
async post(url, data, config) {
|
|
110
|
+
return this.makeRequest(
|
|
111
|
+
url,
|
|
112
|
+
{
|
|
113
|
+
method: "POST",
|
|
114
|
+
body: data ? JSON.stringify(data) : void 0
|
|
115
|
+
},
|
|
116
|
+
config
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
async put(url, data, config) {
|
|
120
|
+
return this.makeRequest(
|
|
121
|
+
url,
|
|
122
|
+
{
|
|
123
|
+
method: "PUT",
|
|
124
|
+
body: data ? JSON.stringify(data) : void 0
|
|
125
|
+
},
|
|
126
|
+
config
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
async patch(url, data, config) {
|
|
130
|
+
return this.makeRequest(
|
|
131
|
+
url,
|
|
132
|
+
{
|
|
133
|
+
method: "PATCH",
|
|
134
|
+
body: data ? JSON.stringify(data) : void 0
|
|
135
|
+
},
|
|
136
|
+
config
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
async delete(url, config) {
|
|
140
|
+
return this.makeRequest(url, { method: "DELETE" }, config);
|
|
141
|
+
}
|
|
142
|
+
// Additional utility methods for server-side use
|
|
143
|
+
setBaseURL(baseUrl) {
|
|
144
|
+
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
145
|
+
}
|
|
146
|
+
setTimeout(timeout) {
|
|
147
|
+
this.timeout = timeout;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const serverApiClient = new ServerApiClient();
|
|
151
|
+
const serverPublicApiClient = new ServerApiClient(publicConfig().apiUrl, {
|
|
152
|
+
requireAuth: false
|
|
153
|
+
});
|
|
154
|
+
export {
|
|
155
|
+
ServerApiClient,
|
|
156
|
+
serverApiClient,
|
|
157
|
+
serverPublicApiClient
|
|
158
|
+
};
|
|
159
|
+
//# sourceMappingURL=server-client.js.map
|