react-shopwave-connect 0.1.2 → 0.3.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.
@@ -0,0 +1,987 @@
1
+ import { cookies } from "next/headers";
2
+ import { NextResponse } from "next/server";
3
+ import { getIronSession, unsealData } from "iron-session";
4
+
5
+ //#region src/server/errors.ts
6
+ var ShopwaveAuthError = class extends Error {
7
+ code;
8
+ status;
9
+ /** Raw response body from the auth server, if any. Never contains our secret. */
10
+ body;
11
+ constructor(code, message, details = {}) {
12
+ super(message, details.cause !== void 0 ? { cause: details.cause } : void 0);
13
+ this.name = "ShopwaveAuthError";
14
+ this.code = code;
15
+ this.status = details.status;
16
+ this.body = details.body;
17
+ }
18
+ /**
19
+ * True when the auth server rejected the grant itself (bad/expired code or
20
+ * refresh token) rather than failing for a transient reason. Callers should
21
+ * treat the user as logged out.
22
+ */
23
+ get isInvalidGrant() {
24
+ return (this.code === "token_exchange_failed" || this.code === "token_refresh_failed") && this.status !== void 0 && this.status >= 400 && this.status < 500;
25
+ }
26
+ };
27
+
28
+ //#endregion
29
+ //#region src/server/token.ts
30
+ /** Shopwave API error id meaning "access token expired / invalid". */
31
+ const SHOPWAVE_TOKEN_EXPIRED_ERROR_ID = 908;
32
+ /**
33
+ * Converts a token-endpoint response into a {@link ShopwaveToken}.
34
+ * Returns `null` when the response has no access token.
35
+ *
36
+ * @param previous the token being refreshed; its refresh token is kept when
37
+ * the server doesn't send a new one.
38
+ */
39
+ function tokenFromResponse(response, previous, now = Date.now()) {
40
+ if (!response || typeof response.access_token !== "string" || !response.access_token) return null;
41
+ const expiresIn = Number(response.expires_in);
42
+ return {
43
+ accessToken: response.access_token,
44
+ refreshToken: typeof response.refresh_token === "string" && response.refresh_token || previous?.refreshToken,
45
+ tokenType: typeof response.token_type === "string" && response.token_type || "OAuth",
46
+ expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? now + expiresIn * 1e3 : void 0
47
+ };
48
+ }
49
+ /**
50
+ * Reads a token from session storage. Accepts both the current shape and the
51
+ * legacy raw response that older apps (e.g. AdminUI ≤ 0.1) stored directly in
52
+ * the session, so existing sessions survive an upgrade.
53
+ */
54
+ function normalizeStoredToken(raw) {
55
+ if (!raw || typeof raw !== "object") return null;
56
+ const t = raw;
57
+ if (typeof t.accessToken === "string" && t.accessToken) return {
58
+ accessToken: t.accessToken,
59
+ refreshToken: typeof t.refreshToken === "string" ? t.refreshToken : void 0,
60
+ tokenType: typeof t.tokenType === "string" && t.tokenType ? t.tokenType : "OAuth",
61
+ expiresAt: typeof t.expiresAt === "number" ? t.expiresAt : void 0
62
+ };
63
+ if (typeof t.access_token === "string" && t.access_token) return {
64
+ accessToken: t.access_token,
65
+ refreshToken: typeof t.refresh_token === "string" ? t.refresh_token : void 0,
66
+ tokenType: typeof t.token_type === "string" && t.token_type ? t.token_type : "OAuth"
67
+ };
68
+ return null;
69
+ }
70
+ /**
71
+ * True when the token has passed its expiry (minus `skewSeconds`).
72
+ * Tokens without a known expiry are treated as valid.
73
+ *
74
+ * Shopwave only issues a new access token once the old one has actually
75
+ * expired, so the default skew is 0 — refreshing early just returns the same
76
+ * token.
77
+ */
78
+ function isTokenExpired(token, { skewSeconds = 0, now = Date.now() } = {}) {
79
+ if (token.expiresAt === void 0) return false;
80
+ return now >= token.expiresAt - skewSeconds * 1e3;
81
+ }
82
+ /** `Authorization` header value, e.g. `OAuth 111ad…`. */
83
+ function authorizationHeader(token) {
84
+ return `${token.tokenType || "OAuth"} ${token.accessToken}`;
85
+ }
86
+ /**
87
+ * True when a Shopwave API response means "your access token is no longer
88
+ * valid": HTTP 401, or the API error 908 in the response envelope.
89
+ * Use it to trigger a forced refresh + a single retry.
90
+ */
91
+ function isExpiredTokenResponse(status, body) {
92
+ if (status === 401) return true;
93
+ const message = body?.api?.message;
94
+ const errors = message?.errors ?? message?.error;
95
+ if (!errors || typeof errors !== "object") return false;
96
+ return Object.entries(errors).some(([key, value]) => key === String(SHOPWAVE_TOKEN_EXPIRED_ERROR_ID) || Number(value?.id) === SHOPWAVE_TOKEN_EXPIRED_ERROR_ID);
97
+ }
98
+
99
+ //#endregion
100
+ //#region src/server/oauth.ts
101
+ const REQUIRED_KEYS = [
102
+ "authServerUrl",
103
+ "clientId",
104
+ "clientSecret",
105
+ "redirectUri"
106
+ ];
107
+ /** Throws a readable error when required settings are missing. */
108
+ function assertOAuthConfig(config) {
109
+ const missing = REQUIRED_KEYS.filter((k) => !config?.[k]);
110
+ if (missing.length > 0) throw new ShopwaveAuthError("config_invalid", `Shopwave auth is missing required settings: ${missing.join(", ")}`);
111
+ }
112
+ function trimSlash(url) {
113
+ return url.replace(/\/+$/, "");
114
+ }
115
+ /**
116
+ * Creates a framework-agnostic Shopwave OAuth client (authorization-code flow
117
+ * with a client secret — the Shopwave auth server does not support PKCE, so
118
+ * this must run on a server).
119
+ *
120
+ * Config is validated lazily on first use, so creating the client at module
121
+ * scope doesn't break builds where env vars aren't present.
122
+ */
123
+ function createShopwaveOAuth(config) {
124
+ const endpoints = {
125
+ login: config.endpoints?.login ?? "/login",
126
+ token: config.endpoints?.token ?? "/oauth/token",
127
+ logout: config.endpoints?.logout ?? "/logout"
128
+ };
129
+ const base = () => {
130
+ assertOAuthConfig(config);
131
+ return trimSlash(config.authServerUrl);
132
+ };
133
+ const commonParams = (redirectUri) => new URLSearchParams({
134
+ access_type: config.accessType ?? "online",
135
+ redirect_uri: redirectUri,
136
+ response_type: "code",
137
+ client_id: config.clientId,
138
+ scope: config.scope ?? "application"
139
+ });
140
+ async function postToken(fields, errorCode) {
141
+ const url = `${base()}${endpoints.token}`;
142
+ const doFetch = config.fetch ?? globalThis.fetch;
143
+ let body;
144
+ if (config.tokenRequestFormat === "multipart") {
145
+ const fd = new FormData();
146
+ for (const [k, v] of Object.entries(fields)) fd.append(k, v);
147
+ body = fd;
148
+ } else body = new URLSearchParams(fields);
149
+ let response;
150
+ try {
151
+ response = await doFetch(url, {
152
+ method: "POST",
153
+ body,
154
+ headers: { Accept: "application/json" },
155
+ cache: "no-store"
156
+ });
157
+ } catch (cause) {
158
+ throw new ShopwaveAuthError("network_error", `Could not reach the Shopwave auth server`, { cause });
159
+ }
160
+ const text = await response.text();
161
+ if (!response.ok) throw new ShopwaveAuthError(errorCode, `Shopwave auth server returned ${response.status} for ${fields.grant_type}`, {
162
+ status: response.status,
163
+ body: text.slice(0, 2e3)
164
+ });
165
+ try {
166
+ return JSON.parse(text);
167
+ } catch (cause) {
168
+ throw new ShopwaveAuthError("token_response_invalid", "Token response was not JSON", {
169
+ status: response.status,
170
+ body: text.slice(0, 2e3),
171
+ cause
172
+ });
173
+ }
174
+ }
175
+ return {
176
+ config,
177
+ buildLoginUrl({ state } = {}) {
178
+ const params = commonParams(config.redirectUri);
179
+ if (state) params.set("state", state);
180
+ return `${base()}${endpoints.login}?${params.toString()}`;
181
+ },
182
+ buildLogoutUrl({ redirectUri } = {}) {
183
+ const params = commonParams(redirectUri ?? config.postLogoutRedirectUri ?? config.redirectUri);
184
+ return `${base()}${endpoints.logout}?${params.toString()}`;
185
+ },
186
+ async exchangeCode(code) {
187
+ if (!code) throw new ShopwaveAuthError("token_exchange_failed", "Missing authorization code");
188
+ const token = tokenFromResponse(await postToken({
189
+ code,
190
+ redirect_uri: config.redirectUri,
191
+ client_id: config.clientId,
192
+ client_secret: config.clientSecret,
193
+ scope: config.scope ?? "application",
194
+ grant_type: "authorization_code"
195
+ }, "token_exchange_failed"));
196
+ if (!token) throw new ShopwaveAuthError("token_response_invalid", "Token response had no access_token");
197
+ return token;
198
+ },
199
+ async refreshToken(tokenOrRefreshToken) {
200
+ const previous = typeof tokenOrRefreshToken === "string" ? {
201
+ accessToken: "",
202
+ refreshToken: tokenOrRefreshToken,
203
+ tokenType: "OAuth"
204
+ } : tokenOrRefreshToken;
205
+ if (!previous.refreshToken) throw new ShopwaveAuthError("token_refresh_failed", "No refresh token available", { status: 400 });
206
+ const token = tokenFromResponse(await postToken({
207
+ refresh_token: previous.refreshToken,
208
+ redirect_uri: config.redirectUri,
209
+ client_id: config.clientId,
210
+ client_secret: config.clientSecret,
211
+ grant_type: "refresh_token"
212
+ }, "token_refresh_failed"), previous);
213
+ if (!token) throw new ShopwaveAuthError("token_response_invalid", "Refresh response had no access_token");
214
+ return token;
215
+ }
216
+ };
217
+ }
218
+
219
+ //#endregion
220
+ //#region src/server/returnTo.ts
221
+ /**
222
+ * Helpers for the round trip through the auth server.
223
+ */
224
+ /**
225
+ * Only allows same-origin relative paths ("/products?tab=1"). Anything that
226
+ * could send the user to another site after login — absolute URLs,
227
+ * protocol-relative "//evil.com", backslash tricks, control characters —
228
+ * falls back to `fallback`.
229
+ */
230
+ function sanitizeReturnTo(value, fallback = "/") {
231
+ if (typeof value !== "string" || value.length === 0 || value.length > 2048) return fallback;
232
+ if (!/^\/(?![/\\])/.test(value)) return fallback;
233
+ if (/[\u0000-\u001f\u007f]/.test(value)) return fallback;
234
+ if (value.includes("\\")) return fallback;
235
+ return value;
236
+ }
237
+ /** Random, URL-safe value for the OAuth `state` parameter (128 bits, hex). */
238
+ function createState() {
239
+ const bytes = new Uint8Array(16);
240
+ globalThis.crypto.getRandomValues(bytes);
241
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
242
+ }
243
+ /** Constant-time string comparison for state values. */
244
+ function safeEqual(a, b) {
245
+ if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
246
+ let diff = 0;
247
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
248
+ return diff === 0;
249
+ }
250
+
251
+ //#endregion
252
+ //#region src/core/entities.ts
253
+ /**
254
+ * Addressing per entity, following the Shopwave API reference
255
+ * (https://developer.merchantstack.com/api-reference.html) and checked against
256
+ * the live API where noted:
257
+ * - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
258
+ * - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
259
+ * - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
260
+ * changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
261
+ * - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
262
+ */
263
+ const SHOPWAVE_ENTITIES = Object.freeze({
264
+ product: {
265
+ route: "products",
266
+ collection: "products",
267
+ upstream: "product",
268
+ idsHeader: "productIds",
269
+ idHeader: "productId",
270
+ writable: true,
271
+ deleteMode: "delete"
272
+ },
273
+ category: {
274
+ route: "categories",
275
+ collection: "categories",
276
+ upstream: "category",
277
+ idsHeader: "categoryIds",
278
+ idHeader: "categoryId",
279
+ writable: true,
280
+ deleteMode: "delete"
281
+ },
282
+ store: {
283
+ route: "stores",
284
+ collection: "stores",
285
+ upstream: "store",
286
+ idsHeader: "storeIds",
287
+ idHeader: "storeId",
288
+ writable: true,
289
+ deleteMode: "delete"
290
+ },
291
+ promotion: {
292
+ route: "promotions",
293
+ collection: "promotions",
294
+ upstream: "promotion",
295
+ idsHeader: "promotionIds",
296
+ idHeader: "promotionId",
297
+ writable: true,
298
+ deleteMode: "retire",
299
+ retireField: "endDate"
300
+ },
301
+ employee: {
302
+ route: "employees",
303
+ collection: "employees",
304
+ upstream: "employee",
305
+ idsHeader: "employeeIds",
306
+ idHeader: "employeeId",
307
+ writable: true,
308
+ deleteMode: "retire",
309
+ retireField: "exitDate"
310
+ },
311
+ consumer: {
312
+ route: "consumer",
313
+ collection: "consumers",
314
+ upstream: "consumer",
315
+ idsHeader: "ids",
316
+ idHeader: "consumerId",
317
+ writable: false,
318
+ deleteMode: "none"
319
+ }
320
+ });
321
+
322
+ //#endregion
323
+ //#region src/server/api.ts
324
+ /**
325
+ * The OAuth token a caller sent with the request, without its scheme, or `null`.
326
+ *
327
+ * Reads, in order: `Authorization: OAuth|Bearer <token>` (what the SDK sends
328
+ * from 0.3), the `token` header (SDK ≤ 0.2 writes), and `extras.token`
329
+ * (SDK ≤ 0.2 reads).
330
+ */
331
+ function readRequestToken(request) {
332
+ const authz = request.headers.get("authorization");
333
+ if (authz) {
334
+ const match = /^(?:oauth|bearer)\s+(\S+)\s*$/i.exec(authz);
335
+ if (match) return match[1];
336
+ }
337
+ const legacyHeader = request.headers.get("token");
338
+ if (legacyHeader && legacyHeader.trim()) return legacyHeader.trim();
339
+ const extras = request.headers.get("extras");
340
+ if (extras) try {
341
+ const token = JSON.parse(extras)?.token;
342
+ if (typeof token === "string" && token.trim()) return token.trim();
343
+ } catch {}
344
+ return null;
345
+ }
346
+ /**
347
+ * `extras` keys that are never forwarded upstream (case-insensitive).
348
+ * `Content-Type` is allowed (SDK clients have always sent `application/json`
349
+ * on reads) but is replaced by the form content type on writes.
350
+ */
351
+ const BLOCKED_EXTRAS = new Set([
352
+ "authorization",
353
+ "token",
354
+ "cookie",
355
+ "host",
356
+ "x-accept-version",
357
+ "content-length",
358
+ "connection",
359
+ "transfer-encoding",
360
+ "te",
361
+ "upgrade",
362
+ "expect",
363
+ "keep-alive",
364
+ "proxy-authorization",
365
+ "forwarded"
366
+ ]);
367
+ const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
368
+ function headerValue(value) {
369
+ if (value == null) return null;
370
+ let text;
371
+ if (Array.isArray(value)) text = value.map((v) => v != null && typeof v === "object" ? JSON.stringify(v) : String(v)).join(",");
372
+ else if (typeof value === "object") text = JSON.stringify(value);
373
+ else text = String(value);
374
+ return /[\r\n\0]/.test(text) ? null : text;
375
+ }
376
+ /**
377
+ * Parses the `extras` request header into upstream headers.
378
+ * Returns `null` when the header isn't a JSON object.
379
+ */
380
+ function parseExtras(raw, blocked = BLOCKED_EXTRAS) {
381
+ if (!raw) return {};
382
+ let parsed;
383
+ try {
384
+ parsed = JSON.parse(raw);
385
+ } catch {
386
+ return null;
387
+ }
388
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
389
+ const headers = {};
390
+ for (const [key, value] of Object.entries(parsed)) {
391
+ const lower = key.toLowerCase();
392
+ if (!HEADER_NAME.test(key) || blocked.has(lower) || lower.startsWith("x-forwarded-") || lower.startsWith("proxy-")) continue;
393
+ const text = headerValue(value);
394
+ if (text !== null) headers[key] = text;
395
+ }
396
+ return headers;
397
+ }
398
+ var RequestBodyError = class extends Error {};
399
+ function isPlainObject(value) {
400
+ return !!value && typeof value === "object" && !Array.isArray(value);
401
+ }
402
+ /**
403
+ * Normalises a write request body into the Shopwave envelope
404
+ * `{ <collection>: { <ref>: entity, … } }`.
405
+ *
406
+ * Accepts:
407
+ * - the SDK ≥ 0.3 shape `{ <collection>: { "0": {...}, "1": {...} } }` (refs kept),
408
+ * - the older AdminUI shapes `{ <collection>: { new: {...} } }` / `{ updated: {...} }`,
409
+ * - a bare entity object `{ title: … }`.
410
+ *
411
+ * With `forcedId` (item routes) exactly one entity is allowed and its `id` is
412
+ * set from the URL.
413
+ */
414
+ function normalizeWriteBody(def, body, forcedId) {
415
+ if (!isPlainObject(body)) throw new RequestBodyError("Request body must be a JSON object");
416
+ let refs;
417
+ const wrapped = body[def.collection];
418
+ if (wrapped !== void 0) {
419
+ if (!isPlainObject(wrapped)) throw new RequestBodyError(`"${def.collection}" must be an object keyed by ref`);
420
+ const keys = Object.keys(wrapped);
421
+ const entries = keys.length === 1 && (keys[0] === "new" || keys[0] === "updated") ? [["0", wrapped[keys[0]]]] : Object.entries(wrapped);
422
+ refs = {};
423
+ for (const [ref, entity] of entries) {
424
+ if (!isPlainObject(entity)) throw new RequestBodyError(`"${def.collection}.${ref}" must be an object`);
425
+ refs[ref] = { ...entity };
426
+ }
427
+ } else refs = { "0": { ...body } };
428
+ const count = Object.keys(refs).length;
429
+ if (count === 0) throw new RequestBodyError(`No ${def.collection} to save`);
430
+ if (forcedId !== void 0) {
431
+ if (count !== 1) throw new RequestBodyError("Only one entity can be saved at an id route");
432
+ const only = refs[Object.keys(refs)[0]];
433
+ only.id = /^\d+$/.test(forcedId) ? Number(forcedId) : forcedId;
434
+ }
435
+ return { [def.collection]: refs };
436
+ }
437
+ const NO_STORE = { "Cache-Control": "no-store" };
438
+ function jsonError(status, error, message) {
439
+ return new Response(JSON.stringify({
440
+ error,
441
+ message
442
+ }), {
443
+ status,
444
+ headers: {
445
+ "Content-Type": "application/json",
446
+ ...NO_STORE
447
+ }
448
+ });
449
+ }
450
+ /** `YYYY-MM-DD HH:mm:ss` in UTC, the datetime format Shopwave writes use (e.g. promotions). */
451
+ function shopwaveDateTime(date = /* @__PURE__ */ new Date()) {
452
+ return date.toISOString().slice(0, 19).replace("T", " ");
453
+ }
454
+ const NULL_BODY_STATUS = new Set([
455
+ 101,
456
+ 103,
457
+ 204,
458
+ 205,
459
+ 304
460
+ ]);
461
+ const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
462
+ async function readUpstream(response) {
463
+ const text = await response.text();
464
+ if (!text) return {
465
+ text,
466
+ json: null
467
+ };
468
+ try {
469
+ return {
470
+ text,
471
+ json: JSON.parse(text)
472
+ };
473
+ } catch {
474
+ return {
475
+ text,
476
+ json: null
477
+ };
478
+ }
479
+ }
480
+ async function routeParam(context, name) {
481
+ const value = (await context?.params)?.[name];
482
+ const id = Array.isArray(value) ? value[0] : value;
483
+ return typeof id === "string" && ID_PATTERN.test(id) ? id : null;
484
+ }
485
+ function createShopwaveApiHandlers(config) {
486
+ const allowRequestToken = config.allowRequestToken ?? true;
487
+ const apiVersion = config.apiVersion ?? "2.0";
488
+ const blocked = new Set([...BLOCKED_EXTRAS, ...(config.blockedExtras ?? []).map((k) => k.toLowerCase())]);
489
+ const onError = config.onError ?? ((error, ctx) => console.error(`[react-shopwave-connect] Shopwave API ${ctx.method} /${ctx.path} failed:`, error?.message ?? error));
490
+ function apiBase() {
491
+ const url = config.apiUrl;
492
+ if (!url) throw new Error("Shopwave API: apiUrl is not set (e.g. SHOPWAVE_API_SERVER_URL).");
493
+ return url.replace(/\/+$/, "");
494
+ }
495
+ function entity(kind) {
496
+ const base = SHOPWAVE_ENTITIES[kind];
497
+ if (!base) throw new Error(`Unknown Shopwave entity "${kind}"`);
498
+ return {
499
+ ...base,
500
+ ...config.entities?.[kind] ?? {}
501
+ };
502
+ }
503
+ async function forward(request, init) {
504
+ const method = (init.method ?? "GET").toUpperCase();
505
+ const path = init.path.replace(/^\/+/, "");
506
+ const extras = init.forwardExtras === false ? {} : parseExtras(request.headers.get("extras"), blocked);
507
+ if (!extras) return jsonError(400, "invalid_extras", "The extras header must be a JSON object");
508
+ const requestToken = allowRequestToken ? readRequestToken(request) : null;
509
+ let authorization;
510
+ try {
511
+ authorization = requestToken ? `OAuth ${requestToken}` : await config.getAuthorization?.() ?? null;
512
+ } catch (error) {
513
+ onError(error, {
514
+ method,
515
+ path: "oauth/token"
516
+ });
517
+ return jsonError(502, "auth_unavailable", "Could not refresh the Shopwave session");
518
+ }
519
+ if (!authorization) return jsonError(401, "unauthorized", "Not logged in");
520
+ const body = init.postBody === void 0 ? void 0 : new URLSearchParams({ postBody: JSON.stringify(init.postBody) });
521
+ const call = (authz) => {
522
+ const headers = new Headers(extras);
523
+ for (const [k, v] of Object.entries(init.headers ?? {})) headers.set(k, v);
524
+ headers.set("Authorization", authz);
525
+ headers.set("x-accept-version", apiVersion);
526
+ if (body) headers.set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
527
+ return (config.fetch ?? fetch)(`${apiBase()}/${path}`, {
528
+ method,
529
+ headers,
530
+ body,
531
+ cache: "no-store"
532
+ });
533
+ };
534
+ try {
535
+ let response = await call(authorization);
536
+ let upstream = await readUpstream(response);
537
+ if (!requestToken && config.getAuthorization && isExpiredTokenResponse(response.status, upstream.json)) {
538
+ const fresh = await config.getAuthorization({ forceRefresh: true });
539
+ if (!fresh) return jsonError(401, "unauthorized", "The Shopwave session has expired");
540
+ response = await call(fresh);
541
+ upstream = await readUpstream(response);
542
+ }
543
+ if (NULL_BODY_STATUS.has(response.status) || !upstream.text) return new Response(null, {
544
+ status: response.status,
545
+ headers: NO_STORE
546
+ });
547
+ return new Response(upstream.text, {
548
+ status: response.status,
549
+ headers: {
550
+ "Content-Type": upstream.json !== null ? "application/json" : response.headers.get("content-type") ?? "text/plain",
551
+ ...NO_STORE
552
+ }
553
+ });
554
+ } catch (error) {
555
+ onError(error, {
556
+ method,
557
+ path
558
+ });
559
+ return jsonError(502, "upstream_unavailable", "The Shopwave API could not be reached");
560
+ }
561
+ }
562
+ async function readJsonBody(request) {
563
+ const text = await request.text();
564
+ if (!text) throw new RequestBodyError("Request body is empty");
565
+ try {
566
+ return JSON.parse(text);
567
+ } catch {
568
+ throw new RequestBodyError("Request body is not valid JSON");
569
+ }
570
+ }
571
+ function notSupported(def, what) {
572
+ return jsonError(405, "method_not_allowed", `The Shopwave API doesn't support ${what} for ${def.collection}`);
573
+ }
574
+ async function write(request, def, forcedId) {
575
+ if (!def.writable) return notSupported(def, "writes");
576
+ let postBody;
577
+ try {
578
+ postBody = normalizeWriteBody(def, await readJsonBody(request), forcedId);
579
+ } catch (error) {
580
+ if (error instanceof RequestBodyError) return jsonError(400, "invalid_body", error.message);
581
+ throw error;
582
+ }
583
+ return forward(request, {
584
+ method: "POST",
585
+ path: def.upstream,
586
+ postBody
587
+ });
588
+ }
589
+ function badId() {
590
+ return jsonError(400, "invalid_id", "Missing or invalid id");
591
+ }
592
+ return {
593
+ forward,
594
+ entity,
595
+ collection(kind) {
596
+ const def = entity(kind);
597
+ const save = (request) => write(request, def);
598
+ return {
599
+ GET: (request) => forward(request, { path: def.upstream }),
600
+ POST: save,
601
+ PUT: save
602
+ };
603
+ },
604
+ item(kind, options = {}) {
605
+ const def = entity(kind);
606
+ const param = options.param ?? "id";
607
+ return {
608
+ async GET(request, context) {
609
+ const id = await routeParam(context, param);
610
+ if (!id) return badId();
611
+ return forward(request, {
612
+ path: def.upstream,
613
+ headers: { [def.idsHeader]: id }
614
+ });
615
+ },
616
+ async PUT(request, context) {
617
+ const id = await routeParam(context, param);
618
+ if (!id) return badId();
619
+ return write(request, def, id);
620
+ },
621
+ async DELETE(request, context) {
622
+ const id = await routeParam(context, param);
623
+ if (!id) return badId();
624
+ if (def.deleteMode === "none") return notSupported(def, "deletes");
625
+ if (def.deleteMode === "retire") {
626
+ const field = def.retireField ?? "exitDate";
627
+ return forward(request, {
628
+ method: "POST",
629
+ path: def.upstream,
630
+ postBody: { [def.collection]: { 0: {
631
+ id: /^\d+$/.test(id) ? Number(id) : id,
632
+ [field]: shopwaveDateTime()
633
+ } } },
634
+ forwardExtras: false
635
+ });
636
+ }
637
+ return forward(request, {
638
+ method: "DELETE",
639
+ path: def.upstream,
640
+ headers: { [def.idHeader]: id },
641
+ forwardExtras: false
642
+ });
643
+ }
644
+ };
645
+ },
646
+ passthrough(path) {
647
+ return { GET: (request) => forward(request, { path }) };
648
+ }
649
+ };
650
+ }
651
+
652
+ //#endregion
653
+ //#region src/next/index.ts
654
+ function normalizePath(p) {
655
+ const withSlash = p.startsWith("/") ? p : `/${p}`;
656
+ return withSlash.length > 1 ? withSlash.replace(/\/+$/, "") : withSlash;
657
+ }
658
+ function pathMatches(pathname, list) {
659
+ return list.some((raw) => {
660
+ const p = normalizePath(raw);
661
+ if (p === "/") return pathname === "/";
662
+ return pathname === p || pathname.startsWith(`${p}/`);
663
+ });
664
+ }
665
+ function escapeHtml(s) {
666
+ return s.replace(/[&<>"']/g, (c) => ({
667
+ "&": "&amp;",
668
+ "<": "&lt;",
669
+ ">": "&gt;",
670
+ "\"": "&quot;",
671
+ "'": "&#39;"
672
+ })[c]);
673
+ }
674
+ function readCookie(request, name) {
675
+ const fromNext = request.cookies?.get?.(name)?.value;
676
+ if (fromNext) return fromNext;
677
+ const header = request.headers.get("cookie");
678
+ if (!header) return void 0;
679
+ for (const part of header.split(";")) {
680
+ const idx = part.indexOf("=");
681
+ if (idx === -1) continue;
682
+ if (part.slice(0, idx).trim() === name) {
683
+ const value = part.slice(idx + 1).trim();
684
+ try {
685
+ return decodeURIComponent(value);
686
+ } catch {
687
+ return value;
688
+ }
689
+ }
690
+ }
691
+ }
692
+ let warnedAboutReadOnlyCookies = false;
693
+ /**
694
+ * Creates the Shopwave auth instance for one Next.js app. Call once at module
695
+ * scope (e.g. `lib/auth.ts`) and reuse. Config is validated on first use, so
696
+ * a missing env var doesn't fail `next build`.
697
+ */
698
+ function createShopwaveAuth(config) {
699
+ if (typeof window !== "undefined") throw new Error("react-shopwave-connect/next is server-only. Import it from route handlers, server code or proxy.ts.");
700
+ const oauth = createShopwaveOAuth(config);
701
+ const authPath = normalizePath(config.authPath ?? "/auth");
702
+ const logoutPath = normalizePath(config.logoutPath ?? `${authPath}/logout`);
703
+ const sessionPath = normalizePath(config.sessionPath ?? "/api/session");
704
+ const defaultReturnTo = sanitizeReturnTo(config.defaultReturnTo, "/");
705
+ const requireState = config.requireState ?? true;
706
+ const skewSeconds = config.refreshSkewSeconds ?? 0;
707
+ const loginTimeoutMs = (config.loginTimeoutSeconds ?? 600) * 1e3;
708
+ const cookieName = config.session?.cookieName ?? "shopwave_session";
709
+ /**
710
+ * Refresh de-duplication, per server instance. Requests that read the same
711
+ * (old) token share one refresh while it's in flight, and for a short while
712
+ * afterwards reuse its result instead of refreshing again.
713
+ */
714
+ const inflightRefresh = /* @__PURE__ */ new Map();
715
+ const recentRefresh = /* @__PURE__ */ new Map();
716
+ const RECENT_REFRESH_MS = 3e4;
717
+ function sessionOptions() {
718
+ const password = config.session?.password;
719
+ const passwords = typeof password === "string" ? [password] : Object.values(password ?? {});
720
+ if (passwords.length === 0 || passwords.some((p) => typeof p !== "string" || p.length < 32)) throw new ShopwaveAuthError("config_invalid", "Shopwave auth: session.password must be at least 32 characters (set a long random secret in your env).");
721
+ const cookieOptions = {
722
+ httpOnly: true,
723
+ secure: config.session.secure ?? process.env.NODE_ENV === "production",
724
+ sameSite: config.session.sameSite ?? "lax",
725
+ path: "/"
726
+ };
727
+ if (config.session.domain) cookieOptions.domain = config.session.domain;
728
+ const options = {
729
+ cookieName,
730
+ password,
731
+ cookieOptions
732
+ };
733
+ if (typeof config.session.ttl === "number") options.ttl = config.session.ttl;
734
+ return options;
735
+ }
736
+ async function getSession() {
737
+ return getIronSession(await cookies(), sessionOptions());
738
+ }
739
+ /**
740
+ * Cookies can only be written from route handlers, server actions and proxy.
741
+ * From a Server Component the token is still usable for this request; it will
742
+ * simply be refreshed again next time.
743
+ */
744
+ async function trySave(session) {
745
+ try {
746
+ await session.save();
747
+ } catch (error) {
748
+ if (!warnedAboutReadOnlyCookies) {
749
+ warnedAboutReadOnlyCookies = true;
750
+ console.warn("[react-shopwave-connect] Could not update the session cookie (called outside a route handler / server action?).", error?.message);
751
+ }
752
+ }
753
+ }
754
+ function tryDestroy(session) {
755
+ try {
756
+ session.destroy();
757
+ } catch {}
758
+ }
759
+ function refreshOnce(token) {
760
+ const key = `${token.refreshToken}\u0000${token.accessToken}`;
761
+ const now = Date.now();
762
+ const recent = recentRefresh.get(key);
763
+ if (recent && now - recent.at < RECENT_REFRESH_MS) return Promise.resolve(recent.token);
764
+ let pending = inflightRefresh.get(key);
765
+ if (!pending) {
766
+ pending = oauth.refreshToken(token).then((fresh) => {
767
+ for (const [k, v] of recentRefresh) if (now - v.at >= RECENT_REFRESH_MS) recentRefresh.delete(k);
768
+ recentRefresh.set(key, {
769
+ token: fresh,
770
+ at: Date.now()
771
+ });
772
+ return fresh;
773
+ }).finally(() => inflightRefresh.delete(key));
774
+ inflightRefresh.set(key, pending);
775
+ }
776
+ return pending;
777
+ }
778
+ async function getToken({ forceRefresh = false } = {}) {
779
+ const session = await getSession();
780
+ const token = normalizeStoredToken(session.token);
781
+ if (!token) return null;
782
+ const expired = isTokenExpired(token, { skewSeconds });
783
+ if (!forceRefresh && !expired) return token;
784
+ if (!token.refreshToken) {
785
+ if (expired || forceRefresh) {
786
+ tryDestroy(session);
787
+ return null;
788
+ }
789
+ return token;
790
+ }
791
+ try {
792
+ const refreshed = await refreshOnce(token);
793
+ session.token = refreshed;
794
+ await trySave(session);
795
+ return refreshed;
796
+ } catch (error) {
797
+ if (error instanceof ShopwaveAuthError && error.isInvalidGrant) {
798
+ tryDestroy(session);
799
+ return null;
800
+ }
801
+ throw error;
802
+ }
803
+ }
804
+ function loginPath(returnTo) {
805
+ if (!returnTo) return authPath;
806
+ const safe = sanitizeReturnTo(returnTo, defaultReturnTo);
807
+ return `${authPath}?returnTo=${encodeURIComponent(safe)}`;
808
+ }
809
+ function redirectTo(location, request) {
810
+ return NextResponse.redirect(new URL(location, request.url), 302);
811
+ }
812
+ function errorPage(status, message, retryHref) {
813
+ return new NextResponse(`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign-in problem</title></head><body style="font-family:system-ui,sans-serif;max-width:32rem;margin:15vh auto;padding:0 1rem;line-height:1.5"><h1 style="font-size:1.25rem">Sign-in didn’t complete</h1><p>${escapeHtml(message)}</p><p><a href="${escapeHtml(retryHref)}">Try again</a></p></body></html>`, {
814
+ status,
815
+ headers: {
816
+ "Content-Type": "text/html; charset=utf-8",
817
+ "Cache-Control": "no-store"
818
+ }
819
+ });
820
+ }
821
+ async function authHandler(request) {
822
+ const url = new URL(request.url);
823
+ const session = await getSession();
824
+ const pending = session.pendingLogin;
825
+ const oauthError = url.searchParams.get("error");
826
+ if (oauthError) {
827
+ delete session.pendingLogin;
828
+ await trySave(session);
829
+ return errorPage(400, `Shopwave sign-in reported: ${url.searchParams.get("error_description") || oauthError}.`, loginPath(pending?.returnTo));
830
+ }
831
+ const code = url.searchParams.get("code");
832
+ if (!code) {
833
+ const returnTo$1 = sanitizeReturnTo(url.searchParams.get("returnTo"), defaultReturnTo);
834
+ const state = createState();
835
+ session.pendingLogin = {
836
+ state,
837
+ returnTo: returnTo$1,
838
+ createdAt: Date.now()
839
+ };
840
+ await session.save();
841
+ return NextResponse.redirect(oauth.buildLoginUrl({ state }), 302);
842
+ }
843
+ const returnedState = url.searchParams.get("state");
844
+ const isFresh = !!pending && Date.now() - pending.createdAt <= loginTimeoutMs;
845
+ const stateMatches = !!pending && !!returnedState && safeEqual(returnedState, pending.state);
846
+ if (requireState ? !(stateMatches && isFresh) : !!pending && !!returnedState && !stateMatches) {
847
+ delete session.pendingLogin;
848
+ await trySave(session);
849
+ return errorPage(400, "This sign-in link has expired or didn’t start from this browser. Please sign in again.", loginPath(pending?.returnTo));
850
+ }
851
+ let token;
852
+ try {
853
+ token = await oauth.exchangeCode(code);
854
+ } catch (error) {
855
+ console.error("[react-shopwave-connect] Code exchange failed:", error?.message);
856
+ delete session.pendingLogin;
857
+ await trySave(session);
858
+ return errorPage(error instanceof ShopwaveAuthError && error.isInvalidGrant ? 400 : 502, "We couldn’t complete sign-in with Shopwave.", loginPath(pending?.returnTo));
859
+ }
860
+ const returnTo = pending?.returnTo ?? defaultReturnTo;
861
+ delete session.pendingLogin;
862
+ session.token = token;
863
+ await session.save();
864
+ return redirectTo(returnTo, request);
865
+ }
866
+ async function logoutHandler(_request) {
867
+ (await getSession()).destroy();
868
+ return NextResponse.redirect(oauth.buildLogoutUrl(), 302);
869
+ }
870
+ async function getStatus() {
871
+ const token = normalizeStoredToken((await getSession()).token);
872
+ if (!token) return { loggedIn: false };
873
+ return !isTokenExpired(token) || !!token.refreshToken ? {
874
+ loggedIn: true,
875
+ expiresAt: token.expiresAt
876
+ } : { loggedIn: false };
877
+ }
878
+ async function isAuthenticated(request) {
879
+ const value = readCookie(request, cookieName);
880
+ if (!value) return false;
881
+ try {
882
+ const { password, ttl } = sessionOptions();
883
+ const token = normalizeStoredToken((await unsealData(value, {
884
+ password,
885
+ ttl
886
+ }))?.token);
887
+ return !!token && (!isTokenExpired(token) || !!token.refreshToken);
888
+ } catch {
889
+ return false;
890
+ }
891
+ }
892
+ const noStore = { "Cache-Control": "no-store" };
893
+ return {
894
+ oauth,
895
+ logoutPath,
896
+ loginPath,
897
+ getSession,
898
+ getStatus,
899
+ getToken,
900
+ async getAccessToken(options) {
901
+ return (await getToken(options))?.accessToken ?? null;
902
+ },
903
+ async getAuthorizationHeader(options) {
904
+ const token = await getToken(options);
905
+ return token ? authorizationHeader(token) : null;
906
+ },
907
+ withAuth(handler) {
908
+ return async (request, context) => {
909
+ const token = await getToken();
910
+ if (!token) return NextResponse.json({ error: "unauthorized" }, {
911
+ status: 401,
912
+ headers: noStore
913
+ });
914
+ return handler(request, context, {
915
+ accessToken: token.accessToken,
916
+ authorization: authorizationHeader(token),
917
+ token
918
+ });
919
+ };
920
+ },
921
+ isAuthenticated,
922
+ async protect(request, options = {}) {
923
+ const { pathname, search } = new URL(request.url);
924
+ if (pathMatches(pathname, [
925
+ authPath,
926
+ logoutPath,
927
+ sessionPath,
928
+ ...options.publicPaths ?? []
929
+ ])) return;
930
+ const isApi = pathMatches(pathname, options.apiPaths ?? ["/api"]);
931
+ if (isApi && options.allowRequestToken && readRequestToken(request)) return void 0;
932
+ if (await isAuthenticated(request)) return void 0;
933
+ if (isApi) return NextResponse.json({ error: "unauthorized" }, {
934
+ status: 401,
935
+ headers: noStore
936
+ });
937
+ return redirectTo(loginPath(pathname + search), request);
938
+ },
939
+ handlers: {
940
+ auth: authHandler,
941
+ logout: logoutHandler,
942
+ session: {
943
+ async GET() {
944
+ return NextResponse.json(await getStatus(), { headers: noStore });
945
+ },
946
+ async DELETE() {
947
+ (await getSession()).destroy();
948
+ return new NextResponse(null, {
949
+ status: 204,
950
+ headers: noStore
951
+ });
952
+ }
953
+ }
954
+ }
955
+ };
956
+ }
957
+ /**
958
+ * Ready-made Next.js route handlers for the SDK's `/api/*` contract, using the
959
+ * session from `createShopwaveAuth`. Create once (e.g. `lib/shopwave.ts`):
960
+ *
961
+ * ```ts
962
+ * export const shopwave = createShopwaveApi({ auth, apiUrl: process.env.SHOPWAVE_API_SERVER_URL! });
963
+ * ```
964
+ *
965
+ * then each route file is one line:
966
+ *
967
+ * ```ts
968
+ * // app/api/products/route.ts
969
+ * export const { GET, POST, PUT } = shopwave.collection("product");
970
+ * // app/api/products/[id]/route.ts
971
+ * export const { GET, PUT, DELETE } = shopwave.item("product");
972
+ * // app/api/report/route.ts
973
+ * export const { GET } = shopwave.passthrough("report");
974
+ * ```
975
+ */
976
+ function createShopwaveApi(config) {
977
+ if (typeof window !== "undefined") throw new Error("react-shopwave-connect/next is server-only. Import it from route handlers or server code.");
978
+ const { auth,...rest } = config;
979
+ return createShopwaveApiHandlers({
980
+ ...rest,
981
+ getAuthorization: (options) => auth.getAuthorizationHeader(options)
982
+ });
983
+ }
984
+
985
+ //#endregion
986
+ export { SHOPWAVE_ENTITIES, ShopwaveAuthError, authorizationHeader, createShopwaveApi, createShopwaveAuth, isExpiredTokenResponse, readRequestToken };
987
+ //# sourceMappingURL=index.js.map