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,650 @@
1
+ //#region src/server/errors.ts
2
+ var ShopwaveAuthError = class extends Error {
3
+ code;
4
+ status;
5
+ /** Raw response body from the auth server, if any. Never contains our secret. */
6
+ body;
7
+ constructor(code, message, details = {}) {
8
+ super(message, details.cause !== void 0 ? { cause: details.cause } : void 0);
9
+ this.name = "ShopwaveAuthError";
10
+ this.code = code;
11
+ this.status = details.status;
12
+ this.body = details.body;
13
+ }
14
+ /**
15
+ * True when the auth server rejected the grant itself (bad/expired code or
16
+ * refresh token) rather than failing for a transient reason. Callers should
17
+ * treat the user as logged out.
18
+ */
19
+ get isInvalidGrant() {
20
+ return (this.code === "token_exchange_failed" || this.code === "token_refresh_failed") && this.status !== void 0 && this.status >= 400 && this.status < 500;
21
+ }
22
+ };
23
+
24
+ //#endregion
25
+ //#region src/server/token.ts
26
+ /** Shopwave API error id meaning "access token expired / invalid". */
27
+ const SHOPWAVE_TOKEN_EXPIRED_ERROR_ID = 908;
28
+ /**
29
+ * Converts a token-endpoint response into a {@link ShopwaveToken}.
30
+ * Returns `null` when the response has no access token.
31
+ *
32
+ * @param previous the token being refreshed; its refresh token is kept when
33
+ * the server doesn't send a new one.
34
+ */
35
+ function tokenFromResponse(response, previous, now = Date.now()) {
36
+ if (!response || typeof response.access_token !== "string" || !response.access_token) return null;
37
+ const expiresIn = Number(response.expires_in);
38
+ return {
39
+ accessToken: response.access_token,
40
+ refreshToken: typeof response.refresh_token === "string" && response.refresh_token || previous?.refreshToken,
41
+ tokenType: typeof response.token_type === "string" && response.token_type || "OAuth",
42
+ expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? now + expiresIn * 1e3 : void 0
43
+ };
44
+ }
45
+ /**
46
+ * Reads a token from session storage. Accepts both the current shape and the
47
+ * legacy raw response that older apps (e.g. AdminUI ≤ 0.1) stored directly in
48
+ * the session, so existing sessions survive an upgrade.
49
+ */
50
+ function normalizeStoredToken(raw) {
51
+ if (!raw || typeof raw !== "object") return null;
52
+ const t = raw;
53
+ if (typeof t.accessToken === "string" && t.accessToken) return {
54
+ accessToken: t.accessToken,
55
+ refreshToken: typeof t.refreshToken === "string" ? t.refreshToken : void 0,
56
+ tokenType: typeof t.tokenType === "string" && t.tokenType ? t.tokenType : "OAuth",
57
+ expiresAt: typeof t.expiresAt === "number" ? t.expiresAt : void 0
58
+ };
59
+ if (typeof t.access_token === "string" && t.access_token) return {
60
+ accessToken: t.access_token,
61
+ refreshToken: typeof t.refresh_token === "string" ? t.refresh_token : void 0,
62
+ tokenType: typeof t.token_type === "string" && t.token_type ? t.token_type : "OAuth"
63
+ };
64
+ return null;
65
+ }
66
+ /**
67
+ * True when the token has passed its expiry (minus `skewSeconds`).
68
+ * Tokens without a known expiry are treated as valid.
69
+ *
70
+ * Shopwave only issues a new access token once the old one has actually
71
+ * expired, so the default skew is 0 — refreshing early just returns the same
72
+ * token.
73
+ */
74
+ function isTokenExpired(token, { skewSeconds = 0, now = Date.now() } = {}) {
75
+ if (token.expiresAt === void 0) return false;
76
+ return now >= token.expiresAt - skewSeconds * 1e3;
77
+ }
78
+ /** `Authorization` header value, e.g. `OAuth 111ad…`. */
79
+ function authorizationHeader(token) {
80
+ return `${token.tokenType || "OAuth"} ${token.accessToken}`;
81
+ }
82
+ /**
83
+ * True when a Shopwave API response means "your access token is no longer
84
+ * valid": HTTP 401, or the API error 908 in the response envelope.
85
+ * Use it to trigger a forced refresh + a single retry.
86
+ */
87
+ function isExpiredTokenResponse(status, body) {
88
+ if (status === 401) return true;
89
+ const message = body?.api?.message;
90
+ const errors = message?.errors ?? message?.error;
91
+ if (!errors || typeof errors !== "object") return false;
92
+ return Object.entries(errors).some(([key, value]) => key === String(SHOPWAVE_TOKEN_EXPIRED_ERROR_ID) || Number(value?.id) === SHOPWAVE_TOKEN_EXPIRED_ERROR_ID);
93
+ }
94
+
95
+ //#endregion
96
+ //#region src/server/oauth.ts
97
+ const REQUIRED_KEYS = [
98
+ "authServerUrl",
99
+ "clientId",
100
+ "clientSecret",
101
+ "redirectUri"
102
+ ];
103
+ /** Throws a readable error when required settings are missing. */
104
+ function assertOAuthConfig(config) {
105
+ const missing = REQUIRED_KEYS.filter((k) => !config?.[k]);
106
+ if (missing.length > 0) throw new ShopwaveAuthError("config_invalid", `Shopwave auth is missing required settings: ${missing.join(", ")}`);
107
+ }
108
+ function trimSlash(url) {
109
+ return url.replace(/\/+$/, "");
110
+ }
111
+ /**
112
+ * Creates a framework-agnostic Shopwave OAuth client (authorization-code flow
113
+ * with a client secret — the Shopwave auth server does not support PKCE, so
114
+ * this must run on a server).
115
+ *
116
+ * Config is validated lazily on first use, so creating the client at module
117
+ * scope doesn't break builds where env vars aren't present.
118
+ */
119
+ function createShopwaveOAuth(config) {
120
+ const endpoints = {
121
+ login: config.endpoints?.login ?? "/login",
122
+ token: config.endpoints?.token ?? "/oauth/token",
123
+ logout: config.endpoints?.logout ?? "/logout"
124
+ };
125
+ const base = () => {
126
+ assertOAuthConfig(config);
127
+ return trimSlash(config.authServerUrl);
128
+ };
129
+ const commonParams = (redirectUri) => new URLSearchParams({
130
+ access_type: config.accessType ?? "online",
131
+ redirect_uri: redirectUri,
132
+ response_type: "code",
133
+ client_id: config.clientId,
134
+ scope: config.scope ?? "application"
135
+ });
136
+ async function postToken(fields, errorCode) {
137
+ const url = `${base()}${endpoints.token}`;
138
+ const doFetch = config.fetch ?? globalThis.fetch;
139
+ let body;
140
+ if (config.tokenRequestFormat === "multipart") {
141
+ const fd = new FormData();
142
+ for (const [k, v] of Object.entries(fields)) fd.append(k, v);
143
+ body = fd;
144
+ } else body = new URLSearchParams(fields);
145
+ let response;
146
+ try {
147
+ response = await doFetch(url, {
148
+ method: "POST",
149
+ body,
150
+ headers: { Accept: "application/json" },
151
+ cache: "no-store"
152
+ });
153
+ } catch (cause) {
154
+ throw new ShopwaveAuthError("network_error", `Could not reach the Shopwave auth server`, { cause });
155
+ }
156
+ const text = await response.text();
157
+ if (!response.ok) throw new ShopwaveAuthError(errorCode, `Shopwave auth server returned ${response.status} for ${fields.grant_type}`, {
158
+ status: response.status,
159
+ body: text.slice(0, 2e3)
160
+ });
161
+ try {
162
+ return JSON.parse(text);
163
+ } catch (cause) {
164
+ throw new ShopwaveAuthError("token_response_invalid", "Token response was not JSON", {
165
+ status: response.status,
166
+ body: text.slice(0, 2e3),
167
+ cause
168
+ });
169
+ }
170
+ }
171
+ return {
172
+ config,
173
+ buildLoginUrl({ state } = {}) {
174
+ const params = commonParams(config.redirectUri);
175
+ if (state) params.set("state", state);
176
+ return `${base()}${endpoints.login}?${params.toString()}`;
177
+ },
178
+ buildLogoutUrl({ redirectUri } = {}) {
179
+ const params = commonParams(redirectUri ?? config.postLogoutRedirectUri ?? config.redirectUri);
180
+ return `${base()}${endpoints.logout}?${params.toString()}`;
181
+ },
182
+ async exchangeCode(code) {
183
+ if (!code) throw new ShopwaveAuthError("token_exchange_failed", "Missing authorization code");
184
+ const token = tokenFromResponse(await postToken({
185
+ code,
186
+ redirect_uri: config.redirectUri,
187
+ client_id: config.clientId,
188
+ client_secret: config.clientSecret,
189
+ scope: config.scope ?? "application",
190
+ grant_type: "authorization_code"
191
+ }, "token_exchange_failed"));
192
+ if (!token) throw new ShopwaveAuthError("token_response_invalid", "Token response had no access_token");
193
+ return token;
194
+ },
195
+ async refreshToken(tokenOrRefreshToken) {
196
+ const previous = typeof tokenOrRefreshToken === "string" ? {
197
+ accessToken: "",
198
+ refreshToken: tokenOrRefreshToken,
199
+ tokenType: "OAuth"
200
+ } : tokenOrRefreshToken;
201
+ if (!previous.refreshToken) throw new ShopwaveAuthError("token_refresh_failed", "No refresh token available", { status: 400 });
202
+ const token = tokenFromResponse(await postToken({
203
+ refresh_token: previous.refreshToken,
204
+ redirect_uri: config.redirectUri,
205
+ client_id: config.clientId,
206
+ client_secret: config.clientSecret,
207
+ grant_type: "refresh_token"
208
+ }, "token_refresh_failed"), previous);
209
+ if (!token) throw new ShopwaveAuthError("token_response_invalid", "Refresh response had no access_token");
210
+ return token;
211
+ }
212
+ };
213
+ }
214
+
215
+ //#endregion
216
+ //#region src/server/returnTo.ts
217
+ /**
218
+ * Helpers for the round trip through the auth server.
219
+ */
220
+ /**
221
+ * Only allows same-origin relative paths ("/products?tab=1"). Anything that
222
+ * could send the user to another site after login — absolute URLs,
223
+ * protocol-relative "//evil.com", backslash tricks, control characters —
224
+ * falls back to `fallback`.
225
+ */
226
+ function sanitizeReturnTo(value, fallback = "/") {
227
+ if (typeof value !== "string" || value.length === 0 || value.length > 2048) return fallback;
228
+ if (!/^\/(?![/\\])/.test(value)) return fallback;
229
+ if (/[\u0000-\u001f\u007f]/.test(value)) return fallback;
230
+ if (value.includes("\\")) return fallback;
231
+ return value;
232
+ }
233
+ /** Random, URL-safe value for the OAuth `state` parameter (128 bits, hex). */
234
+ function createState() {
235
+ const bytes = new Uint8Array(16);
236
+ globalThis.crypto.getRandomValues(bytes);
237
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
238
+ }
239
+ /** Constant-time string comparison for state values. */
240
+ function safeEqual(a, b) {
241
+ if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
242
+ let diff = 0;
243
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
244
+ return diff === 0;
245
+ }
246
+
247
+ //#endregion
248
+ //#region src/core/entities.ts
249
+ /**
250
+ * Addressing per entity, following the Shopwave API reference
251
+ * (https://developer.merchantstack.com/api-reference.html) and checked against
252
+ * the live API where noted:
253
+ * - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
254
+ * - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
255
+ * - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
256
+ * changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
257
+ * - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
258
+ */
259
+ const SHOPWAVE_ENTITIES = Object.freeze({
260
+ product: {
261
+ route: "products",
262
+ collection: "products",
263
+ upstream: "product",
264
+ idsHeader: "productIds",
265
+ idHeader: "productId",
266
+ writable: true,
267
+ deleteMode: "delete"
268
+ },
269
+ category: {
270
+ route: "categories",
271
+ collection: "categories",
272
+ upstream: "category",
273
+ idsHeader: "categoryIds",
274
+ idHeader: "categoryId",
275
+ writable: true,
276
+ deleteMode: "delete"
277
+ },
278
+ store: {
279
+ route: "stores",
280
+ collection: "stores",
281
+ upstream: "store",
282
+ idsHeader: "storeIds",
283
+ idHeader: "storeId",
284
+ writable: true,
285
+ deleteMode: "delete"
286
+ },
287
+ promotion: {
288
+ route: "promotions",
289
+ collection: "promotions",
290
+ upstream: "promotion",
291
+ idsHeader: "promotionIds",
292
+ idHeader: "promotionId",
293
+ writable: true,
294
+ deleteMode: "retire",
295
+ retireField: "endDate"
296
+ },
297
+ employee: {
298
+ route: "employees",
299
+ collection: "employees",
300
+ upstream: "employee",
301
+ idsHeader: "employeeIds",
302
+ idHeader: "employeeId",
303
+ writable: true,
304
+ deleteMode: "retire",
305
+ retireField: "exitDate"
306
+ },
307
+ consumer: {
308
+ route: "consumer",
309
+ collection: "consumers",
310
+ upstream: "consumer",
311
+ idsHeader: "ids",
312
+ idHeader: "consumerId",
313
+ writable: false,
314
+ deleteMode: "none"
315
+ }
316
+ });
317
+
318
+ //#endregion
319
+ //#region src/server/api.ts
320
+ /**
321
+ * The OAuth token a caller sent with the request, without its scheme, or `null`.
322
+ *
323
+ * Reads, in order: `Authorization: OAuth|Bearer <token>` (what the SDK sends
324
+ * from 0.3), the `token` header (SDK ≤ 0.2 writes), and `extras.token`
325
+ * (SDK ≤ 0.2 reads).
326
+ */
327
+ function readRequestToken(request) {
328
+ const authz = request.headers.get("authorization");
329
+ if (authz) {
330
+ const match = /^(?:oauth|bearer)\s+(\S+)\s*$/i.exec(authz);
331
+ if (match) return match[1];
332
+ }
333
+ const legacyHeader = request.headers.get("token");
334
+ if (legacyHeader && legacyHeader.trim()) return legacyHeader.trim();
335
+ const extras = request.headers.get("extras");
336
+ if (extras) try {
337
+ const token = JSON.parse(extras)?.token;
338
+ if (typeof token === "string" && token.trim()) return token.trim();
339
+ } catch {}
340
+ return null;
341
+ }
342
+ /**
343
+ * `extras` keys that are never forwarded upstream (case-insensitive).
344
+ * `Content-Type` is allowed (SDK clients have always sent `application/json`
345
+ * on reads) but is replaced by the form content type on writes.
346
+ */
347
+ const BLOCKED_EXTRAS = new Set([
348
+ "authorization",
349
+ "token",
350
+ "cookie",
351
+ "host",
352
+ "x-accept-version",
353
+ "content-length",
354
+ "connection",
355
+ "transfer-encoding",
356
+ "te",
357
+ "upgrade",
358
+ "expect",
359
+ "keep-alive",
360
+ "proxy-authorization",
361
+ "forwarded"
362
+ ]);
363
+ const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/;
364
+ function headerValue(value) {
365
+ if (value == null) return null;
366
+ let text;
367
+ if (Array.isArray(value)) text = value.map((v) => v != null && typeof v === "object" ? JSON.stringify(v) : String(v)).join(",");
368
+ else if (typeof value === "object") text = JSON.stringify(value);
369
+ else text = String(value);
370
+ return /[\r\n\0]/.test(text) ? null : text;
371
+ }
372
+ /**
373
+ * Parses the `extras` request header into upstream headers.
374
+ * Returns `null` when the header isn't a JSON object.
375
+ */
376
+ function parseExtras(raw, blocked = BLOCKED_EXTRAS) {
377
+ if (!raw) return {};
378
+ let parsed;
379
+ try {
380
+ parsed = JSON.parse(raw);
381
+ } catch {
382
+ return null;
383
+ }
384
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
385
+ const headers = {};
386
+ for (const [key, value] of Object.entries(parsed)) {
387
+ const lower = key.toLowerCase();
388
+ if (!HEADER_NAME.test(key) || blocked.has(lower) || lower.startsWith("x-forwarded-") || lower.startsWith("proxy-")) continue;
389
+ const text = headerValue(value);
390
+ if (text !== null) headers[key] = text;
391
+ }
392
+ return headers;
393
+ }
394
+ var RequestBodyError = class extends Error {};
395
+ function isPlainObject(value) {
396
+ return !!value && typeof value === "object" && !Array.isArray(value);
397
+ }
398
+ /**
399
+ * Normalises a write request body into the Shopwave envelope
400
+ * `{ <collection>: { <ref>: entity, … } }`.
401
+ *
402
+ * Accepts:
403
+ * - the SDK ≥ 0.3 shape `{ <collection>: { "0": {...}, "1": {...} } }` (refs kept),
404
+ * - the older AdminUI shapes `{ <collection>: { new: {...} } }` / `{ updated: {...} }`,
405
+ * - a bare entity object `{ title: … }`.
406
+ *
407
+ * With `forcedId` (item routes) exactly one entity is allowed and its `id` is
408
+ * set from the URL.
409
+ */
410
+ function normalizeWriteBody(def, body, forcedId) {
411
+ if (!isPlainObject(body)) throw new RequestBodyError("Request body must be a JSON object");
412
+ let refs;
413
+ const wrapped = body[def.collection];
414
+ if (wrapped !== void 0) {
415
+ if (!isPlainObject(wrapped)) throw new RequestBodyError(`"${def.collection}" must be an object keyed by ref`);
416
+ const keys = Object.keys(wrapped);
417
+ const entries = keys.length === 1 && (keys[0] === "new" || keys[0] === "updated") ? [["0", wrapped[keys[0]]]] : Object.entries(wrapped);
418
+ refs = {};
419
+ for (const [ref, entity] of entries) {
420
+ if (!isPlainObject(entity)) throw new RequestBodyError(`"${def.collection}.${ref}" must be an object`);
421
+ refs[ref] = { ...entity };
422
+ }
423
+ } else refs = { "0": { ...body } };
424
+ const count = Object.keys(refs).length;
425
+ if (count === 0) throw new RequestBodyError(`No ${def.collection} to save`);
426
+ if (forcedId !== void 0) {
427
+ if (count !== 1) throw new RequestBodyError("Only one entity can be saved at an id route");
428
+ const only = refs[Object.keys(refs)[0]];
429
+ only.id = /^\d+$/.test(forcedId) ? Number(forcedId) : forcedId;
430
+ }
431
+ return { [def.collection]: refs };
432
+ }
433
+ const NO_STORE = { "Cache-Control": "no-store" };
434
+ function jsonError(status, error, message) {
435
+ return new Response(JSON.stringify({
436
+ error,
437
+ message
438
+ }), {
439
+ status,
440
+ headers: {
441
+ "Content-Type": "application/json",
442
+ ...NO_STORE
443
+ }
444
+ });
445
+ }
446
+ /** `YYYY-MM-DD HH:mm:ss` in UTC, the datetime format Shopwave writes use (e.g. promotions). */
447
+ function shopwaveDateTime(date = /* @__PURE__ */ new Date()) {
448
+ return date.toISOString().slice(0, 19).replace("T", " ");
449
+ }
450
+ const NULL_BODY_STATUS = new Set([
451
+ 101,
452
+ 103,
453
+ 204,
454
+ 205,
455
+ 304
456
+ ]);
457
+ const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
458
+ async function readUpstream(response) {
459
+ const text = await response.text();
460
+ if (!text) return {
461
+ text,
462
+ json: null
463
+ };
464
+ try {
465
+ return {
466
+ text,
467
+ json: JSON.parse(text)
468
+ };
469
+ } catch {
470
+ return {
471
+ text,
472
+ json: null
473
+ };
474
+ }
475
+ }
476
+ async function routeParam(context, name) {
477
+ const value = (await context?.params)?.[name];
478
+ const id = Array.isArray(value) ? value[0] : value;
479
+ return typeof id === "string" && ID_PATTERN.test(id) ? id : null;
480
+ }
481
+ function createShopwaveApiHandlers(config) {
482
+ const allowRequestToken = config.allowRequestToken ?? true;
483
+ const apiVersion = config.apiVersion ?? "2.0";
484
+ const blocked = new Set([...BLOCKED_EXTRAS, ...(config.blockedExtras ?? []).map((k) => k.toLowerCase())]);
485
+ const onError = config.onError ?? ((error, ctx) => console.error(`[react-shopwave-connect] Shopwave API ${ctx.method} /${ctx.path} failed:`, error?.message ?? error));
486
+ function apiBase() {
487
+ const url = config.apiUrl;
488
+ if (!url) throw new Error("Shopwave API: apiUrl is not set (e.g. SHOPWAVE_API_SERVER_URL).");
489
+ return url.replace(/\/+$/, "");
490
+ }
491
+ function entity(kind) {
492
+ const base = SHOPWAVE_ENTITIES[kind];
493
+ if (!base) throw new Error(`Unknown Shopwave entity "${kind}"`);
494
+ return {
495
+ ...base,
496
+ ...config.entities?.[kind] ?? {}
497
+ };
498
+ }
499
+ async function forward(request, init) {
500
+ const method = (init.method ?? "GET").toUpperCase();
501
+ const path = init.path.replace(/^\/+/, "");
502
+ const extras = init.forwardExtras === false ? {} : parseExtras(request.headers.get("extras"), blocked);
503
+ if (!extras) return jsonError(400, "invalid_extras", "The extras header must be a JSON object");
504
+ const requestToken = allowRequestToken ? readRequestToken(request) : null;
505
+ let authorization;
506
+ try {
507
+ authorization = requestToken ? `OAuth ${requestToken}` : await config.getAuthorization?.() ?? null;
508
+ } catch (error) {
509
+ onError(error, {
510
+ method,
511
+ path: "oauth/token"
512
+ });
513
+ return jsonError(502, "auth_unavailable", "Could not refresh the Shopwave session");
514
+ }
515
+ if (!authorization) return jsonError(401, "unauthorized", "Not logged in");
516
+ const body = init.postBody === void 0 ? void 0 : new URLSearchParams({ postBody: JSON.stringify(init.postBody) });
517
+ const call = (authz) => {
518
+ const headers = new Headers(extras);
519
+ for (const [k, v] of Object.entries(init.headers ?? {})) headers.set(k, v);
520
+ headers.set("Authorization", authz);
521
+ headers.set("x-accept-version", apiVersion);
522
+ if (body) headers.set("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
523
+ return (config.fetch ?? fetch)(`${apiBase()}/${path}`, {
524
+ method,
525
+ headers,
526
+ body,
527
+ cache: "no-store"
528
+ });
529
+ };
530
+ try {
531
+ let response = await call(authorization);
532
+ let upstream = await readUpstream(response);
533
+ if (!requestToken && config.getAuthorization && isExpiredTokenResponse(response.status, upstream.json)) {
534
+ const fresh = await config.getAuthorization({ forceRefresh: true });
535
+ if (!fresh) return jsonError(401, "unauthorized", "The Shopwave session has expired");
536
+ response = await call(fresh);
537
+ upstream = await readUpstream(response);
538
+ }
539
+ if (NULL_BODY_STATUS.has(response.status) || !upstream.text) return new Response(null, {
540
+ status: response.status,
541
+ headers: NO_STORE
542
+ });
543
+ return new Response(upstream.text, {
544
+ status: response.status,
545
+ headers: {
546
+ "Content-Type": upstream.json !== null ? "application/json" : response.headers.get("content-type") ?? "text/plain",
547
+ ...NO_STORE
548
+ }
549
+ });
550
+ } catch (error) {
551
+ onError(error, {
552
+ method,
553
+ path
554
+ });
555
+ return jsonError(502, "upstream_unavailable", "The Shopwave API could not be reached");
556
+ }
557
+ }
558
+ async function readJsonBody(request) {
559
+ const text = await request.text();
560
+ if (!text) throw new RequestBodyError("Request body is empty");
561
+ try {
562
+ return JSON.parse(text);
563
+ } catch {
564
+ throw new RequestBodyError("Request body is not valid JSON");
565
+ }
566
+ }
567
+ function notSupported(def, what) {
568
+ return jsonError(405, "method_not_allowed", `The Shopwave API doesn't support ${what} for ${def.collection}`);
569
+ }
570
+ async function write(request, def, forcedId) {
571
+ if (!def.writable) return notSupported(def, "writes");
572
+ let postBody;
573
+ try {
574
+ postBody = normalizeWriteBody(def, await readJsonBody(request), forcedId);
575
+ } catch (error) {
576
+ if (error instanceof RequestBodyError) return jsonError(400, "invalid_body", error.message);
577
+ throw error;
578
+ }
579
+ return forward(request, {
580
+ method: "POST",
581
+ path: def.upstream,
582
+ postBody
583
+ });
584
+ }
585
+ function badId() {
586
+ return jsonError(400, "invalid_id", "Missing or invalid id");
587
+ }
588
+ return {
589
+ forward,
590
+ entity,
591
+ collection(kind) {
592
+ const def = entity(kind);
593
+ const save = (request) => write(request, def);
594
+ return {
595
+ GET: (request) => forward(request, { path: def.upstream }),
596
+ POST: save,
597
+ PUT: save
598
+ };
599
+ },
600
+ item(kind, options = {}) {
601
+ const def = entity(kind);
602
+ const param = options.param ?? "id";
603
+ return {
604
+ async GET(request, context) {
605
+ const id = await routeParam(context, param);
606
+ if (!id) return badId();
607
+ return forward(request, {
608
+ path: def.upstream,
609
+ headers: { [def.idsHeader]: id }
610
+ });
611
+ },
612
+ async PUT(request, context) {
613
+ const id = await routeParam(context, param);
614
+ if (!id) return badId();
615
+ return write(request, def, id);
616
+ },
617
+ async DELETE(request, context) {
618
+ const id = await routeParam(context, param);
619
+ if (!id) return badId();
620
+ if (def.deleteMode === "none") return notSupported(def, "deletes");
621
+ if (def.deleteMode === "retire") {
622
+ const field = def.retireField ?? "exitDate";
623
+ return forward(request, {
624
+ method: "POST",
625
+ path: def.upstream,
626
+ postBody: { [def.collection]: { 0: {
627
+ id: /^\d+$/.test(id) ? Number(id) : id,
628
+ [field]: shopwaveDateTime()
629
+ } } },
630
+ forwardExtras: false
631
+ });
632
+ }
633
+ return forward(request, {
634
+ method: "DELETE",
635
+ path: def.upstream,
636
+ headers: { [def.idHeader]: id },
637
+ forwardExtras: false
638
+ });
639
+ }
640
+ };
641
+ },
642
+ passthrough(path) {
643
+ return { GET: (request) => forward(request, { path }) };
644
+ }
645
+ };
646
+ }
647
+
648
+ //#endregion
649
+ export { BLOCKED_EXTRAS, RequestBodyError, SHOPWAVE_ENTITIES, SHOPWAVE_TOKEN_EXPIRED_ERROR_ID, ShopwaveAuthError, assertOAuthConfig, authorizationHeader, createShopwaveApiHandlers, createShopwaveOAuth, createState, isExpiredTokenResponse, isTokenExpired, normalizeStoredToken, normalizeWriteBody, parseExtras, readRequestToken, safeEqual, sanitizeReturnTo, shopwaveDateTime, tokenFromResponse };
650
+ //# sourceMappingURL=index.js.map