react-shopwave-connect 0.2.0 → 0.4.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.
@@ -1,86 +1,199 @@
1
+ //#region src/core/errors.ts
2
+ /**
3
+ * Thrown by every `core` function when a request fails, either at the HTTP
4
+ * level (`status` is the HTTP status) or because the Shopwave response carried
5
+ * `api.message.errors` (then `status` is the HTTP status of that response,
6
+ * usually 200/201, and `errors` holds the API errors).
7
+ *
8
+ * Branch on `status` (e.g. `isUnauthorized` → send the user to log in) rather
9
+ * than parsing `message`.
10
+ */
11
+ var ShopwaveApiError = class extends Error {
12
+ /** HTTP status of the response (0 when the request never got a response). */
13
+ status;
14
+ /** Shopwave API errors, when the response carried any. */
15
+ errors;
16
+ /** Parsed response body, when there was one. */
17
+ body;
18
+ constructor(status, message, details = {}) {
19
+ super(message, details.cause !== void 0 ? { cause: details.cause } : void 0);
20
+ this.name = "ShopwaveApiError";
21
+ this.status = status;
22
+ this.errors = details.errors ?? null;
23
+ this.body = details.body;
24
+ }
25
+ /** 401, or the Shopwave "token expired / invalid" error 908. */
26
+ get isUnauthorized() {
27
+ if (this.status === 401) return true;
28
+ return !!this.errors && Object.entries(this.errors).some(([k, v]) => k === "908" || Number(v?.id) === 908);
29
+ }
30
+ get isNotFound() {
31
+ return this.status === 404;
32
+ }
33
+ };
34
+ /** The `api.message.errors` (or `api.message.error`) map of a Shopwave response, or `null` when there are none. */
35
+ function getApiErrorMap(body) {
36
+ const message = body?.api?.message;
37
+ const errors = message?.errors ?? message?.error;
38
+ if (errors && typeof errors === "object" && Object.keys(errors).length > 0) return errors;
39
+ return null;
40
+ }
41
+ function describeErrors(errors) {
42
+ return Object.entries(errors).map(([code, e]) => {
43
+ const text = [e?.title, e?.details].filter(Boolean).join(": ");
44
+ return text ? `${code} ${text}` : code;
45
+ }).join("; ");
46
+ }
47
+ /**
48
+ * Builds a {@link ShopwaveApiError} for a response. Understands the Shopwave
49
+ * envelope (`api.message.errors`) and the `{ error, message }` bodies returned
50
+ * by the `react-shopwave-connect/next` routes.
51
+ */
52
+ function toShopwaveApiError(status, body, fallback) {
53
+ const errors = getApiErrorMap(body);
54
+ let detail = errors ? describeErrors(errors) : "";
55
+ if (!detail && body && typeof body === "object") {
56
+ const b = body;
57
+ if (typeof b.message === "string") detail = b.message;
58
+ else if (typeof b.error === "string") detail = b.error;
59
+ }
60
+ if (!detail) detail = fallback ?? (status >= 400 ? "request failed" : "API returned errors");
61
+ return new ShopwaveApiError(status, `Shopwave API error (${status}): ${detail}`, {
62
+ errors,
63
+ body
64
+ });
65
+ }
66
+ /** Throws a {@link ShopwaveApiError} when the response body carries API errors. */
67
+ function assertNoApiErrors(body, status) {
68
+ if (getApiErrorMap(body)) throw toShopwaveApiError(status, body);
69
+ }
70
+
71
+ //#endregion
1
72
  //#region src/core/request.ts
2
73
  function resolveFetch(options) {
3
74
  const f = options.fetch ?? (typeof fetch !== "undefined" ? fetch : void 0);
4
75
  if (!f) throw new Error("No fetch implementation available. Pass `options.fetch` (e.g. node-fetch / undici) when running outside the browser.");
5
76
  return f;
6
77
  }
7
- function buildExtras(extras, options) {
78
+ /** Options with `token` filled in from a legacy per-call `params.token`, unless `options.token` is set. */
79
+ function withToken(options, token) {
80
+ return token && !options.token ? {
81
+ ...options,
82
+ token
83
+ } : options;
84
+ }
85
+ /** `Authorization` header value for a token (`OAuth <token>` unless it already has a scheme). */
86
+ function authorizationFor(token) {
87
+ const t = token.trim();
88
+ return /^(oauth|bearer)\s+\S/i.test(t) ? t : `OAuth ${t}`;
89
+ }
90
+ /** Headers shared by every request: Accept + the token, when one is given. */
91
+ function baseHeaders(options) {
92
+ const headers = { Accept: "application/json" };
93
+ if (options.token) headers.Authorization = authorizationFor(options.token);
94
+ return headers;
95
+ }
96
+ function buildExtras(extras) {
8
97
  const merged = {
9
98
  "Content-Type": "application/json",
10
99
  ...extras
11
100
  };
12
- if (options.token != null && merged.token == null) merged.token = options.token;
101
+ delete merged.token;
13
102
  return merged;
14
103
  }
104
+ /** Parses a response body as JSON; `null` for an empty body, `{ raw }` for non-JSON. */
105
+ async function readBody(response) {
106
+ const text = await response.text();
107
+ if (!text) return null;
108
+ try {
109
+ return JSON.parse(text);
110
+ } catch {
111
+ return { raw: text };
112
+ }
113
+ }
114
+ /**
115
+ * Low-level request: resolves `{ status, body }` for 2xx responses and throws
116
+ * {@link ShopwaveApiError} otherwise. `init.headers` are merged over the
117
+ * standard ones (Accept + Authorization).
118
+ */
119
+ async function apiRequest(path, init, options = {}) {
120
+ return send(path, {
121
+ ...init,
122
+ headers: {
123
+ ...baseHeaders(options),
124
+ ...init.headers
125
+ }
126
+ }, options);
127
+ }
128
+ async function send(path, init, options) {
129
+ const doFetch = resolveFetch(options);
130
+ const url = (options.baseUrl ?? "") + path;
131
+ let response;
132
+ try {
133
+ response = await doFetch(url, {
134
+ ...init,
135
+ signal: options.signal
136
+ });
137
+ } catch (error) {
138
+ if (error?.name === "AbortError") throw error;
139
+ throw new ShopwaveApiError(0, `Shopwave API request failed: ${error?.message ?? error}`, { cause: error });
140
+ }
141
+ const body = await readBody(response);
142
+ if (!response.ok) throw toShopwaveApiError(response.status, body, response.statusText || void 0);
143
+ return {
144
+ status: response.status,
145
+ body
146
+ };
147
+ }
15
148
  /**
16
149
  * Returns a JSON string of API errors if the response carries any, otherwise
17
- * `null`. Mirrors the original `!responseJson.api.message.errors` checks.
150
+ * `null`. Kept for backwards compatibility; prefer `ShopwaveApiError`.
18
151
  */
19
152
  function getApiErrors(api) {
20
- const errors = api?.message?.errors;
21
- if (errors && Object.keys(errors).length > 0) return JSON.stringify(errors);
22
- return null;
153
+ const errors = getApiErrorMap({ api });
154
+ return errors ? JSON.stringify(errors) : null;
23
155
  }
24
156
  /**
25
- * GET helper. Sends request metadata via the `extras` header exactly like the
26
- * original hooks did, parses JSON, and returns the typed payload.
157
+ * GET helper. Sends request metadata via the `extras` header, parses JSON and
158
+ * returns the payload. Throws {@link ShopwaveApiError} for non-2xx responses.
27
159
  */
28
160
  async function apiGet(path, extras, options = {}) {
29
- const doFetch = resolveFetch(options);
30
- const url = (options.baseUrl ?? "") + path;
31
- const headers = { extras: JSON.stringify(buildExtras(extras, options)) };
32
- console.log("[API GET]", {
33
- url,
34
- headers
35
- });
36
- const response = await doFetch(url, {
161
+ const { body } = await send(path, {
37
162
  method: "GET",
38
- headers,
39
- signal: options.signal
40
- });
41
- if (!response.ok) throw new Error(`Network response was not ok (${response.status})`);
42
- return await response.json();
163
+ headers: {
164
+ ...baseHeaders(options),
165
+ extras: JSON.stringify(buildExtras(extras))
166
+ }
167
+ }, options);
168
+ return body;
43
169
  }
44
170
  /**
45
- * JSON body helper for POST/PUT mutations.
171
+ * JSON body helper for POST/PUT mutations. Returns the parsed body (`null` for
172
+ * an empty one). Throws {@link ShopwaveApiError} for non-2xx responses.
46
173
  */
47
174
  async function apiSend(path, method, payload, options = {}) {
48
- const doFetch = resolveFetch(options);
49
- const url = (options.baseUrl ?? "") + path;
50
- const headers = { "Content-Type": "application/json" };
51
- if (options.token != null) headers.token = options.token;
52
- console.log(`[API ${method}]`, {
53
- url,
54
- headers,
55
- payload
56
- });
57
- const response = await doFetch(url, {
175
+ const { body } = await send(path, {
58
176
  method,
59
- headers,
60
- body: JSON.stringify(payload),
61
- signal: options.signal
62
- });
63
- if (!response.ok) throw new Error(`Failed to ${method.toLowerCase()}: ${response.statusText}`);
64
- return await response.json();
177
+ headers: {
178
+ ...baseHeaders(options),
179
+ "Content-Type": "application/json"
180
+ },
181
+ body: JSON.stringify(payload)
182
+ }, options);
183
+ return body;
65
184
  }
66
185
  /**
67
- * DELETE helper.
186
+ * DELETE helper. Shopwave answers deletes with 205 and an empty body; if a body
187
+ * does come back and carries API errors, they are thrown. Returns the parsed
188
+ * body (`null` when empty).
68
189
  */
69
190
  async function apiDelete(path, options = {}) {
70
- const doFetch = resolveFetch(options);
71
- const url = (options.baseUrl ?? "") + path;
72
- const headers = {};
73
- if (options.token != null) headers.token = options.token;
74
- console.log("[API DELETE]", {
75
- url,
76
- headers
77
- });
78
- const response = await doFetch(url, {
191
+ const { status, body } = await send(path, {
79
192
  method: "DELETE",
80
- headers,
81
- signal: options.signal
82
- });
83
- if (!response.ok) throw new Error(`Failed to delete: ${response.statusText}`);
193
+ headers: baseHeaders(options)
194
+ }, options);
195
+ if (getApiErrorMap(body)) throw toShopwaveApiError(status, body);
196
+ return body;
84
197
  }
85
198
 
86
199
  //#endregion
@@ -92,11 +205,9 @@ async function apiDelete(path, options = {}) {
92
205
  async function fetchCategories(params = {}, options = {}) {
93
206
  const extras = { deleted: params.deleted ?? false };
94
207
  if (params.categoryIds) extras.categoryIds = params.categoryIds;
95
- if (params.token) extras.token = params.token;
96
- const json = await apiGet("/api/categories", extras, options);
97
- const error = getApiErrors(json.api);
98
- if (error) throw new Error(error);
99
- return Object.values(json.categories ?? {});
208
+ const json = await apiGet("/api/categories", extras, withToken(options, params.token));
209
+ assertNoApiErrors(json, 200);
210
+ return Object.values(json?.categories ?? {});
100
211
  }
101
212
 
102
213
  //#endregion
@@ -108,9 +219,8 @@ async function fetchCategories(params = {}, options = {}) {
108
219
  async function fetchConsumers(consumerIds, options = {}) {
109
220
  if (!consumerIds || consumerIds.length === 0) return [];
110
221
  const json = await apiGet("/api/consumer", { ids: consumerIds.join(",") }, options);
111
- const error = getApiErrors(json.api);
112
- if (error) throw new Error(error);
113
- return Object.values(json.consumers ?? {});
222
+ assertNoApiErrors(json, 200);
223
+ return Object.values(json?.consumers ?? {});
114
224
  }
115
225
 
116
226
  //#endregion
@@ -128,10 +238,9 @@ const rolesById = {
128
238
  async function fetchEmployees(params = {}, options = {}) {
129
239
  const extras = { deleted: params.deleted ?? false };
130
240
  if (params.employeeIds) extras.employeeIds = params.employeeIds;
131
- const json = await apiGet("/api/employees", extras, options);
132
- const error = getApiErrors(json.api);
133
- if (error) throw new Error(error);
134
- return Object.values(json.employees ?? {});
241
+ const json = await apiGet("/api/employees", extras, withToken(options, params.token));
242
+ assertNoApiErrors(json, 200);
243
+ return Object.values(json?.employees ?? {});
135
244
  }
136
245
 
137
246
  //#endregion
@@ -143,11 +252,9 @@ async function fetchProducts(params = {}, options = {}) {
143
252
  const extras = { deleted: params.deleted ?? false };
144
253
  if (params.productIds) extras.productIds = params.productIds;
145
254
  if (params.storeId) extras.storeId = params.storeId;
146
- if (params.token) extras.token = params.token;
147
- const json = await apiGet("/api/products", extras, options);
148
- const error = getApiErrors(json.api);
149
- if (error) throw new Error(error);
150
- return Object.values(json.products ?? {});
255
+ const json = await apiGet("/api/products", extras, withToken(options, params.token));
256
+ assertNoApiErrors(json, 200);
257
+ return Object.values(json?.products ?? {});
151
258
  }
152
259
  /**
153
260
  * Fetches products by id and returns them keyed by id, transparently batching
@@ -183,11 +290,9 @@ async function fetchPromotions(params = {}, options = {}) {
183
290
  if (params.imminent !== void 0) extras.imminent = params.imminent;
184
291
  if (params.active !== void 0) extras.active = params.active;
185
292
  if (params.expired !== void 0) extras.expired = params.expired;
186
- if (params.token) extras.token = params.token;
187
- const json = await apiGet("/api/promotions", extras, options);
188
- const error = getApiErrors(json.api);
189
- if (error) throw new Error(error);
190
- return Object.values(json.promotions ?? {});
293
+ const json = await apiGet("/api/promotions", extras, withToken(options, params.token));
294
+ assertNoApiErrors(json, 200);
295
+ return Object.values(json?.promotions ?? {});
191
296
  }
192
297
 
193
298
  //#endregion
@@ -196,10 +301,11 @@ async function fetchPromotions(params = {}, options = {}) {
196
301
  * Fetches stores. Returns the flattened `Store[]`.
197
302
  */
198
303
  async function fetchStores(params = {}, options = {}) {
199
- const json = await apiGet("/api/stores", { deleted: params.deleted ?? false }, options);
200
- const error = getApiErrors(json.api);
201
- if (error) throw new Error(error);
202
- return Object.values(json.stores ?? {});
304
+ const extras = { deleted: params.deleted ?? false };
305
+ if (params.storeIds) extras.storeIds = params.storeIds;
306
+ const json = await apiGet("/api/stores", extras, withToken(options, params.token));
307
+ assertNoApiErrors(json, 200);
308
+ return Object.values(json?.stores ?? {});
203
309
  }
204
310
 
205
311
  //#endregion
@@ -211,9 +317,8 @@ async function fetchStores(params = {}, options = {}) {
211
317
  */
212
318
  async function fetchReport(query, options = {}) {
213
319
  const json = await apiGet("/api/report", { query: JSON.stringify(query) }, options);
214
- const error = getApiErrors(json.api);
215
- if (error) throw new Error(error);
216
- return json.reports ?? {};
320
+ assertNoApiErrors(json, 200);
321
+ return json?.reports ?? {};
217
322
  }
218
323
 
219
324
  //#endregion
@@ -268,10 +373,12 @@ async function logout(options = {}) {
268
373
  //#endregion
269
374
  //#region src/core/entity.ts
270
375
  /**
271
- * Generic CRUD-style mutations extracted from `useHandleDelete` /
272
- * `useHandleSubmit`. The original hooks also surfaced notistack snackbars; that
273
- * UI concern is deliberately left to the hooks/host layer so core stays
274
- * dependency-free.
376
+ * Low-level, untyped mutations: the caller supplies the route and payload.
377
+ *
378
+ * Prefer the typed functions in `./entities` (`saveProduct`, `deleteCategory`,
379
+ * …): they know each route, build the request envelope, check the response and
380
+ * return the saved entity with its id. Keep these for routes that have no typed
381
+ * function yet (e.g. `/api/merchant`).
275
382
  */
276
383
  /**
277
384
  * Deletes `/api/{resourcePath}/{entityId}`.
@@ -281,13 +388,182 @@ async function deleteEntity(resourcePath, entityId, options = {}) {
281
388
  await apiDelete(`/api/${resourcePath}/${entityId}`, options);
282
389
  }
283
390
  /**
284
- * Sends a create/update mutation and returns the parsed `result` field
285
- * (matching the original `result.result` access).
391
+ * Sends a create/update mutation. Returns the response's `result` field when it
392
+ * has one (older app routes wrapped their answer that way), otherwise the whole
393
+ * parsed response body. Throws `ShopwaveApiError` on HTTP or API errors.
286
394
  */
287
395
  async function submitEntity({ endpoint, method = "POST", payload }, options = {}) {
288
- return (await apiSend(endpoint, method, payload, options)).result;
396
+ const json = await apiSend(endpoint, method, payload, options);
397
+ assertNoApiErrors(json, 200);
398
+ if (json && typeof json === "object" && "result" in json) return json.result;
399
+ return json ?? void 0;
289
400
  }
290
401
 
402
+ //#endregion
403
+ //#region src/core/entities.ts
404
+ /**
405
+ * Addressing per entity, following the Shopwave API reference
406
+ * (https://developer.merchantstack.com/api-reference.html) and checked against
407
+ * the live API where noted:
408
+ * - category/product/store: GET filtered by `<x>Ids`, POST upsert, DELETE with `<x>Id` → 205.
409
+ * - promotion: no DELETE; "deleting" a promotion ends it by setting `endDate` to now.
410
+ * - employee: POST updates `roleId`, `joinedDate`, `exitDate` (names can't be
411
+ * changed); no DELETE (live API: "Cannot DELETE /employee") → retired via `exitDate`.
412
+ * - consumer: read-only (`GET` with `ids`, comma-separated); live POST → 404.
413
+ */
414
+ const SHOPWAVE_ENTITIES = Object.freeze({
415
+ product: {
416
+ route: "products",
417
+ collection: "products",
418
+ upstream: "product",
419
+ idsHeader: "productIds",
420
+ idHeader: "productId",
421
+ writable: true,
422
+ deleteMode: "delete"
423
+ },
424
+ category: {
425
+ route: "categories",
426
+ collection: "categories",
427
+ upstream: "category",
428
+ idsHeader: "categoryIds",
429
+ idHeader: "categoryId",
430
+ writable: true,
431
+ deleteMode: "delete"
432
+ },
433
+ store: {
434
+ route: "stores",
435
+ collection: "stores",
436
+ upstream: "store",
437
+ idsHeader: "storeIds",
438
+ idHeader: "storeId",
439
+ writable: true,
440
+ deleteMode: "delete"
441
+ },
442
+ promotion: {
443
+ route: "promotions",
444
+ collection: "promotions",
445
+ upstream: "promotion",
446
+ idsHeader: "promotionIds",
447
+ idHeader: "promotionId",
448
+ writable: true,
449
+ deleteMode: "retire",
450
+ retireField: "endDate"
451
+ },
452
+ employee: {
453
+ route: "employees",
454
+ collection: "employees",
455
+ upstream: "employee",
456
+ idsHeader: "employeeIds",
457
+ idHeader: "employeeId",
458
+ writable: true,
459
+ deleteMode: "retire",
460
+ retireField: "exitDate"
461
+ },
462
+ consumer: {
463
+ route: "consumer",
464
+ collection: "consumers",
465
+ upstream: "consumer",
466
+ idsHeader: "ids",
467
+ idHeader: "consumerId",
468
+ writable: false,
469
+ deleteMode: "none"
470
+ }
471
+ });
472
+ function definition(kind) {
473
+ const def = SHOPWAVE_ENTITIES[kind];
474
+ if (!def) throw new Error(`Unknown Shopwave entity "${kind}"`);
475
+ return def;
476
+ }
477
+ function assertId(kind, id) {
478
+ const s = id == null ? "" : String(id).trim();
479
+ if (!s) throw new Error(`${kind} id is missing`);
480
+ return encodeURIComponent(s);
481
+ }
482
+ /**
483
+ * Creates or updates several entities of one kind in a single request and
484
+ * returns them as saved (with their ids), in the order given.
485
+ *
486
+ * The request is `{ <collection>: { "0": item0, "1": item1, … } }`. Shopwave
487
+ * answers 201 and echoes every entity under the ref it was sent with, so each
488
+ * result is matched back by ref. Throws {@link ShopwaveApiError} when the
489
+ * response carries `api.message.errors` or any ref is missing from it.
490
+ *
491
+ * The API's partial-success semantics for multi-entity saves haven't been
492
+ * confirmed yet; single saves (`saveProduct` etc.) are the tested path.
493
+ */
494
+ async function saveEntities(kind, items, options = {}) {
495
+ const def = definition(kind);
496
+ if (items.length === 0) return [];
497
+ const refs = items.map((_, i) => String(i));
498
+ const payload = { [def.collection]: Object.fromEntries(refs.map((ref, i) => [ref, items[i]])) };
499
+ const { status, body: raw } = await apiRequest(`/api/${def.route}`, {
500
+ method: "POST",
501
+ headers: { "Content-Type": "application/json" },
502
+ body: JSON.stringify(payload)
503
+ }, options);
504
+ const body = raw;
505
+ assertNoApiErrors(body, status);
506
+ const echoed = body?.[def.collection] ?? {};
507
+ return refs.map((ref, i) => {
508
+ const saved = echoed[ref];
509
+ if (!saved || saved.id == null) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the saved ${kind} (ref "${ref}") was not returned`, { body });
510
+ return {
511
+ ...items[i],
512
+ ...saved,
513
+ id: Number(saved.id)
514
+ };
515
+ });
516
+ }
517
+ /** Creates (no `id`) or updates (with `id`) one entity and returns it with its id. */
518
+ async function saveEntity(kind, item, options = {}) {
519
+ const [saved] = await saveEntities(kind, [item], options);
520
+ return saved;
521
+ }
522
+ /**
523
+ * Deletes one entity (a soft delete: it stays readable with `deleted: true`).
524
+ * Employees and promotions can't be deleted in Shopwave; for them the route
525
+ * sets `exitDate` / `endDate` to now instead (see `SHOPWAVE_ENTITIES`).
526
+ *
527
+ * Shopwave answers 205 with an empty body — also for ids that don't exist — so
528
+ * a resolved promise means "the API accepted the request", not "a record was
529
+ * deleted".
530
+ */
531
+ async function deleteEntityById(kind, id, options = {}) {
532
+ await apiDelete(`/api/${definition(kind).route}/${assertId(kind, id)}`, options);
533
+ }
534
+ /** Reads one entity by id, or `null` when there's no such (non-deleted) record. */
535
+ async function fetchEntityById(kind, id, params = {}, options = {}) {
536
+ const def = definition(kind);
537
+ const body = await apiGet(`/api/${def.route}/${assertId(kind, id)}`, { deleted: params.deleted ?? false }, options);
538
+ assertNoApiErrors(body, 200);
539
+ const map = body?.[def.collection] ?? {};
540
+ return map[String(id)] ?? Object.values(map).find((e) => String(e?.id) === String(id)) ?? null;
541
+ }
542
+ const saveProduct = (product, options) => saveEntity("product", product, options);
543
+ const deleteProduct = (id, options) => deleteEntityById("product", id, options);
544
+ const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
545
+ const saveCategory = (category, options) => saveEntity("category", category, options);
546
+ const deleteCategory = (id, options) => deleteEntityById("category", id, options);
547
+ const fetchCategory = (id, params, options) => fetchEntityById("category", id, params, options);
548
+ const saveStore = (store, options) => saveEntity("store", store, options);
549
+ const deleteStore = (id, options) => deleteEntityById("store", id, options);
550
+ const fetchStore = (id, params, options) => fetchEntityById("store", id, params, options);
551
+ const savePromotion = (promotion, options) => saveEntity("promotion", promotion, options);
552
+ /** Ends a promotion: Shopwave has no promotion DELETE, so this sets `endDate` to now. */
553
+ const deletePromotion = (id, options) => deleteEntityById("promotion", id, options);
554
+ const fetchPromotion = (id, params, options) => fetchEntityById("promotion", id, params, options);
555
+ /**
556
+ * Creates an employee, or updates one (with `id`). On update Shopwave only
557
+ * applies `roleId`, `joinedDate` and `exitDate` (and store roles); names and
558
+ * email can't be changed, and the echo only carries the updated fields — re-read
559
+ * with `fetchEmployee` if you need the stored record.
560
+ */
561
+ const saveEmployee = (employee, options) => saveEntity("employee", employee, options);
562
+ /** Retires an employee: Shopwave has no employee DELETE, so this sets `exitDate` to now. */
563
+ const deleteEmployee = (id, options) => deleteEntityById("employee", id, options);
564
+ const fetchEmployee = (id, params, options) => fetchEntityById("employee", id, params, options);
565
+ const fetchConsumer = (id, params, options) => fetchEntityById("consumer", id, params, options);
566
+
291
567
  //#endregion
292
568
  //#region src/core/basket.ts
293
569
  const DEFAULT_BASKET_FILTERS = {
@@ -433,5 +709,485 @@ function buildConsumerMap(consumers) {
433
709
  }
434
710
 
435
711
  //#endregion
436
- export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, PromotionRuleSet, apiDelete, apiGet, apiSend, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, deleteEntity, fetchCategories, fetchConsumers, fetchEmployees, fetchProducts, fetchProductsMap, fetchPromotions, fetchReport, fetchSession, fetchStores, formatDateForQuery, getApiErrors, loginPath, logout, logoutPath, parseBasketReportData, rolesById, submitEntity };
712
+ //#region src/core/resources.ts
713
+ /**
714
+ * - merchant: `GET /merchant`; `POST /merchant` with `{ merchant: { id, … } }`
715
+ * updates it (without an `id` the API would create a second merchant, so the
716
+ * route requires one).
717
+ * - user: `GET /user` (read-only here; the API's `POST /user` invites users and
718
+ * needs the admin scope).
719
+ */
720
+ const SHOPWAVE_RESOURCES = Object.freeze({
721
+ merchant: {
722
+ route: "merchant",
723
+ key: "merchant",
724
+ upstream: "merchant",
725
+ writable: true
726
+ },
727
+ user: {
728
+ route: "user",
729
+ key: "user",
730
+ upstream: "user",
731
+ writable: false
732
+ }
733
+ });
734
+ /** `UploadKind` → the API's `contentType` value. */
735
+ const UPLOAD_KINDS = Object.freeze({
736
+ merchant: "merchant",
737
+ merchantFeature: "merchantFeature",
738
+ product: "product",
739
+ user: "user",
740
+ applicationLogo: "applicaionLogo",
741
+ applicationImages: "applicaionImages"
742
+ });
743
+ /** How uploads are addressed (app route and Shopwave uploader). */
744
+ const SHOPWAVE_UPLOAD = Object.freeze({
745
+ route: "upload",
746
+ upstream: "uploader",
747
+ kindHeader: "contentType",
748
+ fileField: "file",
749
+ kindField: "kind"
750
+ });
751
+ function isUploadKind(value) {
752
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
753
+ }
754
+
755
+ //#endregion
756
+ //#region src/core/imageFit.ts
757
+ /**
758
+ * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
759
+ * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
760
+ */
761
+ function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
762
+ if (![
763
+ srcWidth,
764
+ srcHeight,
765
+ dstWidth,
766
+ dstHeight
767
+ ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
768
+ const srcRatio = srcWidth / srcHeight;
769
+ const dstRatio = dstWidth / dstHeight;
770
+ if (srcRatio > dstRatio) {
771
+ const sw = Math.round(srcHeight * dstRatio);
772
+ return {
773
+ sx: Math.round((srcWidth - sw) / 2),
774
+ sy: 0,
775
+ sw,
776
+ sh: srcHeight
777
+ };
778
+ }
779
+ const sh = Math.round(srcWidth / dstRatio);
780
+ return {
781
+ sx: 0,
782
+ sy: Math.round((srcHeight - sh) / 2),
783
+ sw: srcWidth,
784
+ sh
785
+ };
786
+ }
787
+ function requireBrowserImages(fn) {
788
+ if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
789
+ }
790
+ /** Reads an image file's pixel size (browser only). */
791
+ async function readImageSize(file) {
792
+ requireBrowserImages("readImageSize");
793
+ const bitmap = await createImageBitmap(file);
794
+ try {
795
+ return {
796
+ width: bitmap.width,
797
+ height: bitmap.height
798
+ };
799
+ } finally {
800
+ bitmap.close?.();
801
+ }
802
+ }
803
+ /**
804
+ * Returns the image at exactly `width × height`: scaled and centre-cropped
805
+ * (never stretched). Browser only. The result is a `File` named like the
806
+ * input, with the output type's extension.
807
+ */
808
+ async function fitImageToSize(file, width, height, options = {}) {
809
+ requireBrowserImages("fitImageToSize");
810
+ const { type = "image/png", quality, keepIfExact = true } = options;
811
+ const name = file.name || "image";
812
+ const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
813
+ const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
814
+ const bitmap = await createImageBitmap(file);
815
+ try {
816
+ if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
817
+ const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
818
+ let blob;
819
+ if (typeof OffscreenCanvas === "function") {
820
+ const canvas = new OffscreenCanvas(width, height);
821
+ const ctx = canvas.getContext("2d");
822
+ if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
823
+ ctx.imageSmoothingQuality = "high";
824
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
825
+ blob = await canvas.convertToBlob({
826
+ type,
827
+ quality
828
+ });
829
+ } else {
830
+ const canvas = document.createElement("canvas");
831
+ canvas.width = width;
832
+ canvas.height = height;
833
+ const ctx = canvas.getContext("2d");
834
+ if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
835
+ ctx.imageSmoothingQuality = "high";
836
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
837
+ blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
838
+ }
839
+ return new File([blob], outName, { type });
840
+ } finally {
841
+ bitmap.close?.();
842
+ }
843
+ }
844
+
845
+ //#endregion
846
+ //#region src/core/upload.ts
847
+ /**
848
+ * HTTPS host that serves the Shopwave CDN's images. The API returns
849
+ * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
850
+ * (checked Sep 2026), so pages served over HTTPS can't show it.
851
+ */
852
+ const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
853
+ const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
854
+ /**
855
+ * Turns an image path from the API into a URL a page can load over HTTPS:
856
+ * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
857
+ * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
858
+ * Other absolute URLs are returned unchanged; empty input gives `""`.
859
+ */
860
+ function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
861
+ if (!path) return "";
862
+ const root = base.replace(/\/+$/, "");
863
+ if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
864
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
865
+ return `${root}/${path.replace(/^\/+/, "")}`;
866
+ }
867
+ /**
868
+ * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
869
+ * (`createShopwaveApi(...).upload()`), and returns its id and URL.
870
+ *
871
+ * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
872
+ * record has to point at it to use it. Live API (Sep 2026): the upload answers
873
+ * 201 `{ fileName, path }`.
874
+ */
875
+ async function uploadImage(file, params, options = {}) {
876
+ if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
877
+ if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
878
+ const name = params.fileName ?? file.name ?? "upload";
879
+ const form = new FormData();
880
+ form.append(SHOPWAVE_UPLOAD.fileField, file, name);
881
+ form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
882
+ const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
883
+ method: "POST",
884
+ body: form
885
+ }, options);
886
+ const body = raw;
887
+ assertNoApiErrors(body, status);
888
+ const id = typeof body?.fileName === "string" ? body.fileName : "";
889
+ const path = typeof body?.path === "string" ? body.path : "";
890
+ if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
891
+ return {
892
+ id,
893
+ url: getImageUrl(path),
894
+ path
895
+ };
896
+ }
897
+
898
+ //#endregion
899
+ //#region src/core/merchantImages.ts
900
+ /** The three image slots on the merchant settings page. */
901
+ const MERCHANT_IMAGE_SLOT_KEYS = [
902
+ "receipt",
903
+ "square",
904
+ "featured"
905
+ ];
906
+ /**
907
+ * Where each slot lives, its upload kind and its exact size (from adminV1's
908
+ * merchant settings page).
909
+ */
910
+ const MERCHANT_IMAGE_SLOTS = Object.freeze({
911
+ receipt: {
912
+ field: "logo.receipt",
913
+ uploadKind: "merchant",
914
+ width: 576,
915
+ height: 325
916
+ },
917
+ square: {
918
+ field: "logo.square",
919
+ uploadKind: "merchant",
920
+ width: 1e3,
921
+ height: 1e3
922
+ },
923
+ featured: {
924
+ field: "feature[0]",
925
+ uploadKind: "merchantFeature",
926
+ width: 1200,
927
+ height: 600
928
+ }
929
+ });
930
+ /**
931
+ * The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
932
+ * `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
933
+ * Returns `null` for empty or non-string values.
934
+ */
935
+ function imageFileName(value) {
936
+ if (typeof value !== "string") return null;
937
+ const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
938
+ return last ? decodeURIComponent(last) : null;
939
+ }
940
+ /** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
941
+ function getMerchantImage(imageIds, slot) {
942
+ if (!imageIds || typeof imageIds !== "object") return null;
943
+ let value;
944
+ if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
945
+ else {
946
+ const logo = imageIds.logo;
947
+ value = logo && typeof logo === "object" ? logo[slot] : void 0;
948
+ }
949
+ return typeof value === "string" && value.trim() ? value.trim() : null;
950
+ }
951
+ /**
952
+ * An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
953
+ * holds only a file name (a fresh upload not yet saved; use the upload's `url`).
954
+ */
955
+ function getMerchantImageUrl(imageIds, slot, base) {
956
+ const value = getMerchantImage(imageIds, slot);
957
+ if (!value || !value.includes("/")) return "";
958
+ return getImageUrl(value, base);
959
+ }
960
+ /**
961
+ * Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
962
+ * with `null`). Other slots and unknown keys are kept; an empty `logo` or
963
+ * `feature` is removed.
964
+ */
965
+ function setMerchantImage(imageIds, slot, fileName) {
966
+ const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
967
+ if (slot === "featured") {
968
+ const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
969
+ const feature = fileName ? [fileName, ...rest] : rest;
970
+ if (feature.length > 0) next.feature = feature;
971
+ else delete next.feature;
972
+ } else {
973
+ const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
974
+ if (fileName) logo[slot] = fileName;
975
+ else delete logo[slot];
976
+ if (Object.keys(logo).length > 0) next.logo = logo;
977
+ else delete next.logo;
978
+ }
979
+ return next;
980
+ }
981
+ function toStored(value) {
982
+ if (typeof value === "string") return imageFileName(value) ?? void 0;
983
+ if (Array.isArray(value)) {
984
+ const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
985
+ return items.length > 0 ? items : void 0;
986
+ }
987
+ if (value && typeof value === "object") {
988
+ const out = {};
989
+ for (const [k, v] of Object.entries(value)) {
990
+ const stored = toStored(v);
991
+ if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
992
+ }
993
+ return Object.keys(out).length > 0 ? out : void 0;
994
+ }
995
+ }
996
+ /**
997
+ * The `imageIds` to send on a save: every URL is turned back into its file
998
+ * name (what adminV1 does with images you didn't change) and empty values
999
+ * are dropped. No images gives `{}`.
1000
+ */
1001
+ function toStoredImageIds(imageIds) {
1002
+ return toStored(imageIds) ?? {};
1003
+ }
1004
+ /**
1005
+ * Uploads an image for a merchant slot: fits it to the slot's size, uploads
1006
+ * it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
1007
+ * `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
1008
+ */
1009
+ async function uploadMerchantImage(file, slot, options = {}) {
1010
+ const def = MERCHANT_IMAGE_SLOTS[slot];
1011
+ if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
1012
+ const { fit = true, fitOptions,...requestOptions } = options;
1013
+ return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
1014
+ }
1015
+
1016
+ //#endregion
1017
+ //#region src/core/merchant.ts
1018
+ const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
1019
+ /** Colour keys inside `colours.primary`, in display order. */
1020
+ const MERCHANT_COLOUR_KEYS = [
1021
+ "main",
1022
+ "highlight",
1023
+ "contrast"
1024
+ ];
1025
+ /** Flat link fields a form edits, in display order. */
1026
+ const MERCHANT_LINK_KEYS = [
1027
+ "website",
1028
+ "twitter",
1029
+ "facebook",
1030
+ "instagram"
1031
+ ];
1032
+ /** Where each flat link field lives in `merchant.links`. */
1033
+ const MERCHANT_LINK_PATHS = Object.freeze({
1034
+ website: ["website", "home"],
1035
+ twitter: ["social", "twitter"],
1036
+ facebook: ["social", "facebook"],
1037
+ instagram: ["social", "instagram"]
1038
+ });
1039
+ function trimmed(value) {
1040
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1041
+ }
1042
+ /**
1043
+ * Reads `merchant.links` as flat fields (`{ website, twitter, facebook,
1044
+ * instagram }`), whatever shape it was saved in:
1045
+ * - the nested shape adminV1 saves (`{ website: { home }, social: { … } }`);
1046
+ * - flat keys (`{ website: "…" }`, what SDK 0.4.0 pre-releases sent);
1047
+ * - an array in {@link MERCHANT_LINK_KEYS} order (older AdminUI versions).
1048
+ * Empty values are dropped.
1049
+ */
1050
+ function merchantLinksToForm(links) {
1051
+ const out = {};
1052
+ if (Array.isArray(links)) {
1053
+ links.forEach((value, i) => {
1054
+ const key = MERCHANT_LINK_KEYS[i];
1055
+ const v = trimmed(value);
1056
+ if (key && v) out[key] = v;
1057
+ });
1058
+ return out;
1059
+ }
1060
+ if (!links || typeof links !== "object") return out;
1061
+ const obj = links;
1062
+ for (const key of MERCHANT_LINK_KEYS) {
1063
+ const [group, field] = MERCHANT_LINK_PATHS[key];
1064
+ const nested = obj[group];
1065
+ const v = nested && typeof nested === "object" && !Array.isArray(nested) ? trimmed(nested[field]) : trimmed(obj[key]);
1066
+ if (v) out[key] = v;
1067
+ }
1068
+ return out;
1069
+ }
1070
+ /**
1071
+ * Builds the stored `links` object from flat fields. Empty values are left
1072
+ * out, and so is a group with nothing in it; no links gives `{}`.
1073
+ */
1074
+ function merchantLinksFromForm(form) {
1075
+ const out = {};
1076
+ for (const key of MERCHANT_LINK_KEYS) {
1077
+ const v = trimmed(form[key]);
1078
+ if (!v) continue;
1079
+ const [group, field] = MERCHANT_LINK_PATHS[key];
1080
+ (out[group] ??= {})[field] = v;
1081
+ }
1082
+ return out;
1083
+ }
1084
+ /** Reads any stored or older `links` value into the nested shape adminV1 saves. */
1085
+ function normalizeMerchantLinks(links) {
1086
+ return merchantLinksFromForm(merchantLinksToForm(links));
1087
+ }
1088
+ /**
1089
+ * Object fields of the merchant. The API keeps one you leave out, and
1090
+ * replaces it as a whole when you send it.
1091
+ */
1092
+ const MERCHANT_OBJECT_FIELDS = [
1093
+ "colours",
1094
+ "links",
1095
+ "imageIds"
1096
+ ];
1097
+ /** Fields the API sets itself; `updateMerchant` never sends them back. */
1098
+ const MERCHANT_READ_ONLY_FIELDS = ["createdDate", "modifiedDate"];
1099
+ /**
1100
+ * Longest values the API stores. Longer values are cut off silently
1101
+ * (live API, Sep 2026), so `updateMerchant` rejects them instead.
1102
+ * `vatNumber` fits a UK VAT number without the `GB` prefix.
1103
+ */
1104
+ const MERCHANT_FIELD_MAX_LENGTH = Object.freeze({
1105
+ companyNumber: 11,
1106
+ vatNumber: 9
1107
+ });
1108
+ /** Returns `"<field> is longer than <n> characters"` messages for over-long fields. */
1109
+ function validateMerchant(merchant) {
1110
+ const problems = [];
1111
+ for (const [field, max] of Object.entries(MERCHANT_FIELD_MAX_LENGTH)) {
1112
+ const value = merchant[field];
1113
+ if (typeof value === "string" && value.length > max) problems.push(`${field} is longer than ${max} characters`);
1114
+ }
1115
+ return problems;
1116
+ }
1117
+ /**
1118
+ * Reads the logged-in user's merchant (a user has exactly one), or `null`
1119
+ * when the API returns none.
1120
+ */
1121
+ async function fetchMerchant(options = {}) {
1122
+ const json = await apiGet(MERCHANT_PATH, {}, options);
1123
+ assertNoApiErrors(json, 200);
1124
+ return json?.merchant ?? null;
1125
+ }
1126
+ /**
1127
+ * Updates the merchant and returns it as stored.
1128
+ *
1129
+ * Shopwave's `POST /merchant` replaces the whole record: a scalar field you
1130
+ * leave out (`companyNumber`, `vatNumber`, `note`, …) is set to null, while
1131
+ * an object field you leave out (`colours`, `links`, `imageIds`) is kept and
1132
+ * one you send replaces the stored one; sending `{}` clears it (live API,
1133
+ * Sep 2026). So by default the
1134
+ * current merchant is read first and the patch is merged over it.
1135
+ *
1136
+ * `imageIds` is always sent as file names ({@link toStoredImageIds}), so you
1137
+ * can pass back what you read. See `MerchantImageIds` for the shape.
1138
+ *
1139
+ * The API answers 205 with an empty body, so the merchant is read again after
1140
+ * the save and that is what's returned (it shows exactly what was kept).
1141
+ * Throws before sending when a value is longer than the API stores
1142
+ * ({@link MERCHANT_FIELD_MAX_LENGTH}).
1143
+ */
1144
+ async function updateMerchant(patch, options = {}) {
1145
+ const { merge = true,...requestOptions } = options;
1146
+ let merchant = { ...patch };
1147
+ if (merge) {
1148
+ const current = await fetchMerchant(requestOptions);
1149
+ if (!current) throw new ShopwaveApiError(404, "Shopwave API error (404): no merchant to update");
1150
+ if (patch.id != null && String(patch.id) !== String(current.id)) throw new Error(`Merchant id ${patch.id} is not the logged-in merchant (${current.id})`);
1151
+ merchant = {
1152
+ ...current,
1153
+ ...patch,
1154
+ id: current.id
1155
+ };
1156
+ for (const field of MERCHANT_OBJECT_FIELDS) if (!(field in patch)) delete merchant[field];
1157
+ }
1158
+ if (merchant.imageIds && typeof merchant.imageIds === "object") merchant.imageIds = toStoredImageIds(merchant.imageIds);
1159
+ if (merchant.id == null || merchant.id === "") throw new Error("merchant id is missing");
1160
+ for (const field of MERCHANT_READ_ONLY_FIELDS) delete merchant[field];
1161
+ const problems = validateMerchant(merchant);
1162
+ if (problems.length > 0) throw new Error(`Invalid merchant: ${problems.join("; ")}`);
1163
+ const { status, body: raw } = await apiRequest(MERCHANT_PATH, {
1164
+ method: "PUT",
1165
+ headers: { "Content-Type": "application/json" },
1166
+ body: JSON.stringify({ merchant })
1167
+ }, requestOptions);
1168
+ const body = raw;
1169
+ assertNoApiErrors(body, status);
1170
+ const echoed = body?.merchant && typeof body.merchant === "object" ? body.merchant : null;
1171
+ if (echoed) return {
1172
+ ...merchant,
1173
+ ...echoed,
1174
+ id: Number(echoed.id ?? merchant.id)
1175
+ };
1176
+ return await fetchMerchant(requestOptions) ?? {
1177
+ ...merchant,
1178
+ id: Number(merchant.id)
1179
+ };
1180
+ }
1181
+
1182
+ //#endregion
1183
+ //#region src/core/user.ts
1184
+ /** Reads the logged-in user, or `null` when the API returns none. */
1185
+ async function fetchUser(options = {}) {
1186
+ const json = await apiGet(`/api/${SHOPWAVE_RESOURCES.user.route}`, {}, options);
1187
+ assertNoApiErrors(json, 200);
1188
+ return json?.user ?? null;
1189
+ }
1190
+
1191
+ //#endregion
1192
+ export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, PromotionRuleSet, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, ShopwaveApiError, UPLOAD_KINDS, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, validateMerchant, withToken };
437
1193
  //# sourceMappingURL=index.js.map