react-shopwave-connect 0.3.0 → 0.4.1

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.
@@ -41,8 +41,8 @@ function getApiErrorMap(body) {
41
41
  }
42
42
  function describeErrors(errors) {
43
43
  return Object.entries(errors).map(([code, e]) => {
44
- const text = [e?.title, e?.details].filter(Boolean).join(": ");
45
- return text ? `${code} ${text}` : code;
44
+ const text$1 = [e?.title, e?.details].filter(Boolean).join(": ");
45
+ return text$1 ? `${code} ${text$1}` : code;
46
46
  }).join("; ");
47
47
  }
48
48
  /**
@@ -104,12 +104,12 @@ function buildExtras(extras) {
104
104
  }
105
105
  /** Parses a response body as JSON; `null` for an empty body, `{ raw }` for non-JSON. */
106
106
  async function readBody(response) {
107
- const text = await response.text();
108
- if (!text) return null;
107
+ const text$1 = await response.text();
108
+ if (!text$1) return null;
109
109
  try {
110
- return JSON.parse(text);
110
+ return JSON.parse(text$1);
111
111
  } catch {
112
- return { raw: text };
112
+ return { raw: text$1 };
113
113
  }
114
114
  }
115
115
  /**
@@ -257,6 +257,83 @@ async function fetchProducts(params = {}, options = {}) {
257
257
  assertNoApiErrors(json, 200);
258
258
  return Object.values(json?.products ?? {});
259
259
  }
260
+ /** Fields the server sets on an instance; never sent back. */
261
+ const SERVER_INSTANCE_FIELDS = ["timestamp"];
262
+ function instanceList(instances) {
263
+ if (!instances) return [];
264
+ return (Array.isArray(instances) ? [...instances] : Object.values(instances)).filter((inst) => inst != null && typeof inst === "object");
265
+ }
266
+ function hasId(id) {
267
+ return id != null && String(id).trim() !== "";
268
+ }
269
+ /** Same number, so `"422.0"`, `"422"` and `422` are equal; blanks equal each other. */
270
+ function sameAmount(a, b) {
271
+ const blank = (v) => v == null || String(v).trim() === "";
272
+ if (blank(a) || blank(b)) return blank(a) && blank(b);
273
+ const x = Number(a);
274
+ const y = Number(b);
275
+ return Number.isNaN(x) || Number.isNaN(y) ? String(a).trim() === String(b).trim() : x === y;
276
+ }
277
+ /** True when two instances have the same price and tax (the fields Shopwave won't update). */
278
+ function isSameInstancePrice(a, b) {
279
+ return sameAmount(a.price, b.price) && sameAmount(a.taxPercentage, b.taxPercentage);
280
+ }
281
+ const text = (v) => v == null ? "" : String(v);
282
+ /**
283
+ * Lists the instances whose price or tax differs from the `original` instance
284
+ * with the same id: saving them creates new instances with new ids, which can
285
+ * affect anything that stores instance ids (integrations, reports, modifiers).
286
+ * Use it to warn before saving. New rows (no id) aren't listed.
287
+ */
288
+ function findRepricedInstances(instances, original) {
289
+ const byId = new Map(instanceList(original).filter((o) => hasId(o.id)).map((o) => [String(o.id), o]));
290
+ const result = [];
291
+ instanceList(instances).forEach((inst, index) => {
292
+ if (!hasId(inst.id)) return;
293
+ const before = byId.get(String(inst.id));
294
+ if (!before || isSameInstancePrice(inst, before)) return;
295
+ result.push({
296
+ index,
297
+ id: inst.id,
298
+ name: text(inst.name),
299
+ before: {
300
+ price: text(before.price),
301
+ taxPercentage: text(before.taxPercentage)
302
+ },
303
+ after: {
304
+ price: text(inst.price),
305
+ taxPercentage: text(inst.taxPercentage)
306
+ }
307
+ });
308
+ });
309
+ return result;
310
+ }
311
+ /**
312
+ * Builds the `instances` map for a product save:
313
+ * - keyed by position (`"0"`, `"1"`, …), like every other ref in a save;
314
+ * - an instance keeps its `id` only when `original` has an instance with that id
315
+ * and the same price and tax; otherwise the id is removed, so Shopwave creates
316
+ * a new instance instead of re-pointing or rewriting someone else's;
317
+ * - server fields (`timestamp`) are removed.
318
+ *
319
+ * Pass the product as last read from the API as `original`. Leave it out for a
320
+ * new product (including a duplicate): every id is then removed.
321
+ * Instances left out of the list are left out of the save (removed).
322
+ */
323
+ function toProductInstancesForSave(instances, original) {
324
+ const keep = new Map(instanceList(original).filter((o) => hasId(o.id)).map((o) => [String(o.id), o]));
325
+ const out = {};
326
+ instanceList(instances).forEach((inst, index) => {
327
+ const { id,...rest } = inst;
328
+ for (const field of SERVER_INSTANCE_FIELDS) delete rest[field];
329
+ const before = hasId(id) ? keep.get(String(id)) : void 0;
330
+ out[String(index)] = before && isSameInstancePrice(inst, before) ? {
331
+ id,
332
+ ...rest
333
+ } : rest;
334
+ });
335
+ return out;
336
+ }
260
337
  /**
261
338
  * Fetches products by id and returns them keyed by id, transparently batching
262
339
  * the request (default 200 ids per call) to stay within API limits. Extracted
@@ -540,7 +617,21 @@ async function fetchEntityById(kind, id, params = {}, options = {}) {
540
617
  const map = body?.[def.collection] ?? {};
541
618
  return map[String(id)] ?? Object.values(map).find((e) => String(e?.id) === String(id)) ?? null;
542
619
  }
543
- const saveProduct = (product, options) => saveEntity("product", product, options);
620
+ /**
621
+ * Creates (no `id`) or updates (with `id`) a product.
622
+ *
623
+ * Shopwave instances (prices) can't be updated, only replaced. Build
624
+ * `instances` with {@link toProductInstancesForSave} (passing the product as last
625
+ * read) so an edited price is sent as a new instance. As a safeguard, a new
626
+ * product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
627
+ * another product would otherwise point the save at that product's instances.
628
+ */
629
+ const saveProduct = (product, options) => {
630
+ return saveEntity("product", (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
631
+ ...product,
632
+ instances: toProductInstancesForSave(product.instances)
633
+ } : product, options);
634
+ };
544
635
  const deleteProduct = (id, options) => deleteEntityById("product", id, options);
545
636
  const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
546
637
  const saveCategory = (category, options) => saveEntity("category", category, options);
@@ -709,12 +800,504 @@ function buildConsumerMap(consumers) {
709
800
  return map;
710
801
  }
711
802
 
803
+ //#endregion
804
+ //#region src/core/resources.ts
805
+ /**
806
+ * - merchant: `GET /merchant`; `POST /merchant` with `{ merchant: { id, … } }`
807
+ * updates it (without an `id` the API would create a second merchant, so the
808
+ * route requires one).
809
+ * - user: `GET /user` (read-only here; the API's `POST /user` invites users and
810
+ * needs the admin scope).
811
+ */
812
+ const SHOPWAVE_RESOURCES = Object.freeze({
813
+ merchant: {
814
+ route: "merchant",
815
+ key: "merchant",
816
+ upstream: "merchant",
817
+ writable: true
818
+ },
819
+ user: {
820
+ route: "user",
821
+ key: "user",
822
+ upstream: "user",
823
+ writable: false
824
+ }
825
+ });
826
+ /** `UploadKind` → the API's `contentType` value. */
827
+ const UPLOAD_KINDS = Object.freeze({
828
+ merchant: "merchant",
829
+ merchantFeature: "merchantFeature",
830
+ product: "product",
831
+ user: "user",
832
+ applicationLogo: "applicaionLogo",
833
+ applicationImages: "applicaionImages"
834
+ });
835
+ /** How uploads are addressed (app route and Shopwave uploader). */
836
+ const SHOPWAVE_UPLOAD = Object.freeze({
837
+ route: "upload",
838
+ upstream: "uploader",
839
+ kindHeader: "contentType",
840
+ fileField: "file",
841
+ kindField: "kind"
842
+ });
843
+ function isUploadKind(value) {
844
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
845
+ }
846
+
847
+ //#endregion
848
+ //#region src/core/imageFit.ts
849
+ /**
850
+ * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
851
+ * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
852
+ */
853
+ function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
854
+ if (![
855
+ srcWidth,
856
+ srcHeight,
857
+ dstWidth,
858
+ dstHeight
859
+ ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
860
+ const srcRatio = srcWidth / srcHeight;
861
+ const dstRatio = dstWidth / dstHeight;
862
+ if (srcRatio > dstRatio) {
863
+ const sw = Math.round(srcHeight * dstRatio);
864
+ return {
865
+ sx: Math.round((srcWidth - sw) / 2),
866
+ sy: 0,
867
+ sw,
868
+ sh: srcHeight
869
+ };
870
+ }
871
+ const sh = Math.round(srcWidth / dstRatio);
872
+ return {
873
+ sx: 0,
874
+ sy: Math.round((srcHeight - sh) / 2),
875
+ sw: srcWidth,
876
+ sh
877
+ };
878
+ }
879
+ function requireBrowserImages(fn) {
880
+ if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
881
+ }
882
+ /** Reads an image file's pixel size (browser only). */
883
+ async function readImageSize(file) {
884
+ requireBrowserImages("readImageSize");
885
+ const bitmap = await createImageBitmap(file);
886
+ try {
887
+ return {
888
+ width: bitmap.width,
889
+ height: bitmap.height
890
+ };
891
+ } finally {
892
+ bitmap.close?.();
893
+ }
894
+ }
895
+ /**
896
+ * Returns the image at exactly `width × height`: scaled and centre-cropped
897
+ * (never stretched). Browser only. The result is a `File` named like the
898
+ * input, with the output type's extension.
899
+ */
900
+ async function fitImageToSize(file, width, height, options = {}) {
901
+ requireBrowserImages("fitImageToSize");
902
+ const { type = "image/png", quality, keepIfExact = true } = options;
903
+ const name = file.name || "image";
904
+ const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
905
+ const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
906
+ const bitmap = await createImageBitmap(file);
907
+ try {
908
+ if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
909
+ const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
910
+ let blob;
911
+ if (typeof OffscreenCanvas === "function") {
912
+ const canvas = new OffscreenCanvas(width, height);
913
+ const ctx = canvas.getContext("2d");
914
+ if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
915
+ ctx.imageSmoothingQuality = "high";
916
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
917
+ blob = await canvas.convertToBlob({
918
+ type,
919
+ quality
920
+ });
921
+ } else {
922
+ const canvas = document.createElement("canvas");
923
+ canvas.width = width;
924
+ canvas.height = height;
925
+ const ctx = canvas.getContext("2d");
926
+ if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
927
+ ctx.imageSmoothingQuality = "high";
928
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
929
+ blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
930
+ }
931
+ return new File([blob], outName, { type });
932
+ } finally {
933
+ bitmap.close?.();
934
+ }
935
+ }
936
+
937
+ //#endregion
938
+ //#region src/core/upload.ts
939
+ /**
940
+ * HTTPS host that serves the Shopwave CDN's images. The API returns
941
+ * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
942
+ * (checked Sep 2026), so pages served over HTTPS can't show it.
943
+ */
944
+ const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
945
+ const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
946
+ /**
947
+ * Turns an image path from the API into a URL a page can load over HTTPS:
948
+ * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
949
+ * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
950
+ * Other absolute URLs are returned unchanged; empty input gives `""`.
951
+ */
952
+ function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
953
+ if (!path) return "";
954
+ const root = base.replace(/\/+$/, "");
955
+ if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
956
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
957
+ return `${root}/${path.replace(/^\/+/, "")}`;
958
+ }
959
+ /**
960
+ * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
961
+ * (`createShopwaveApi(...).upload()`), and returns its id and URL.
962
+ *
963
+ * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
964
+ * record has to point at it to use it. Live API (Sep 2026): the upload answers
965
+ * 201 `{ fileName, path }`.
966
+ */
967
+ async function uploadImage(file, params, options = {}) {
968
+ if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
969
+ if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
970
+ const name = params.fileName ?? file.name ?? "upload";
971
+ const form = new FormData();
972
+ form.append(SHOPWAVE_UPLOAD.fileField, file, name);
973
+ form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
974
+ const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
975
+ method: "POST",
976
+ body: form
977
+ }, options);
978
+ const body = raw;
979
+ assertNoApiErrors(body, status);
980
+ const id = typeof body?.fileName === "string" ? body.fileName : "";
981
+ const path = typeof body?.path === "string" ? body.path : "";
982
+ if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
983
+ return {
984
+ id,
985
+ url: getImageUrl(path),
986
+ path
987
+ };
988
+ }
989
+
990
+ //#endregion
991
+ //#region src/core/merchantImages.ts
992
+ /** The three image slots on the merchant settings page. */
993
+ const MERCHANT_IMAGE_SLOT_KEYS = [
994
+ "receipt",
995
+ "square",
996
+ "featured"
997
+ ];
998
+ /**
999
+ * Where each slot lives, its upload kind and its exact size (from adminV1's
1000
+ * merchant settings page).
1001
+ */
1002
+ const MERCHANT_IMAGE_SLOTS = Object.freeze({
1003
+ receipt: {
1004
+ field: "logo.receipt",
1005
+ uploadKind: "merchant",
1006
+ width: 576,
1007
+ height: 325
1008
+ },
1009
+ square: {
1010
+ field: "logo.square",
1011
+ uploadKind: "merchant",
1012
+ width: 1e3,
1013
+ height: 1e3
1014
+ },
1015
+ featured: {
1016
+ field: "feature[0]",
1017
+ uploadKind: "merchantFeature",
1018
+ width: 1200,
1019
+ height: 600
1020
+ }
1021
+ });
1022
+ /**
1023
+ * The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
1024
+ * `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
1025
+ * Returns `null` for empty or non-string values.
1026
+ */
1027
+ function imageFileName(value) {
1028
+ if (typeof value !== "string") return null;
1029
+ const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
1030
+ return last ? decodeURIComponent(last) : null;
1031
+ }
1032
+ /** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
1033
+ function getMerchantImage(imageIds, slot) {
1034
+ if (!imageIds || typeof imageIds !== "object") return null;
1035
+ let value;
1036
+ if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
1037
+ else {
1038
+ const logo = imageIds.logo;
1039
+ value = logo && typeof logo === "object" ? logo[slot] : void 0;
1040
+ }
1041
+ return typeof value === "string" && value.trim() ? value.trim() : null;
1042
+ }
1043
+ /**
1044
+ * An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
1045
+ * holds only a file name (a fresh upload not yet saved; use the upload's `url`).
1046
+ */
1047
+ function getMerchantImageUrl(imageIds, slot, base) {
1048
+ const value = getMerchantImage(imageIds, slot);
1049
+ if (!value || !value.includes("/")) return "";
1050
+ return getImageUrl(value, base);
1051
+ }
1052
+ /**
1053
+ * Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
1054
+ * with `null`). Other slots and unknown keys are kept; an empty `logo` or
1055
+ * `feature` is removed.
1056
+ */
1057
+ function setMerchantImage(imageIds, slot, fileName) {
1058
+ const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
1059
+ if (slot === "featured") {
1060
+ const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
1061
+ const feature = fileName ? [fileName, ...rest] : rest;
1062
+ if (feature.length > 0) next.feature = feature;
1063
+ else delete next.feature;
1064
+ } else {
1065
+ const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
1066
+ if (fileName) logo[slot] = fileName;
1067
+ else delete logo[slot];
1068
+ if (Object.keys(logo).length > 0) next.logo = logo;
1069
+ else delete next.logo;
1070
+ }
1071
+ return next;
1072
+ }
1073
+ function toStored(value) {
1074
+ if (typeof value === "string") return imageFileName(value) ?? void 0;
1075
+ if (Array.isArray(value)) {
1076
+ const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
1077
+ return items.length > 0 ? items : void 0;
1078
+ }
1079
+ if (value && typeof value === "object") {
1080
+ const out = {};
1081
+ for (const [k, v] of Object.entries(value)) {
1082
+ const stored = toStored(v);
1083
+ if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
1084
+ }
1085
+ return Object.keys(out).length > 0 ? out : void 0;
1086
+ }
1087
+ }
1088
+ /**
1089
+ * The `imageIds` to send on a save: every URL is turned back into its file
1090
+ * name (what adminV1 does with images you didn't change) and empty values
1091
+ * are dropped. No images gives `{}`.
1092
+ */
1093
+ function toStoredImageIds(imageIds) {
1094
+ return toStored(imageIds) ?? {};
1095
+ }
1096
+ /**
1097
+ * Uploads an image for a merchant slot: fits it to the slot's size, uploads
1098
+ * it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
1099
+ * `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
1100
+ */
1101
+ async function uploadMerchantImage(file, slot, options = {}) {
1102
+ const def = MERCHANT_IMAGE_SLOTS[slot];
1103
+ if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
1104
+ const { fit = true, fitOptions,...requestOptions } = options;
1105
+ return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
1106
+ }
1107
+
1108
+ //#endregion
1109
+ //#region src/core/merchant.ts
1110
+ const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
1111
+ /** Colour keys inside `colours.primary`, in display order. */
1112
+ const MERCHANT_COLOUR_KEYS = [
1113
+ "main",
1114
+ "highlight",
1115
+ "contrast"
1116
+ ];
1117
+ /** Flat link fields a form edits, in display order. */
1118
+ const MERCHANT_LINK_KEYS = [
1119
+ "website",
1120
+ "twitter",
1121
+ "facebook",
1122
+ "instagram"
1123
+ ];
1124
+ /** Where each flat link field lives in `merchant.links`. */
1125
+ const MERCHANT_LINK_PATHS = Object.freeze({
1126
+ website: ["website", "home"],
1127
+ twitter: ["social", "twitter"],
1128
+ facebook: ["social", "facebook"],
1129
+ instagram: ["social", "instagram"]
1130
+ });
1131
+ function trimmed(value) {
1132
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1133
+ }
1134
+ /**
1135
+ * Reads `merchant.links` as flat fields (`{ website, twitter, facebook,
1136
+ * instagram }`), whatever shape it was saved in:
1137
+ * - the nested shape adminV1 saves (`{ website: { home }, social: { … } }`);
1138
+ * - flat keys (`{ website: "…" }`, what SDK 0.4.0 pre-releases sent);
1139
+ * - an array in {@link MERCHANT_LINK_KEYS} order (older AdminUI versions).
1140
+ * Empty values are dropped.
1141
+ */
1142
+ function merchantLinksToForm(links) {
1143
+ const out = {};
1144
+ if (Array.isArray(links)) {
1145
+ links.forEach((value, i) => {
1146
+ const key = MERCHANT_LINK_KEYS[i];
1147
+ const v = trimmed(value);
1148
+ if (key && v) out[key] = v;
1149
+ });
1150
+ return out;
1151
+ }
1152
+ if (!links || typeof links !== "object") return out;
1153
+ const obj = links;
1154
+ for (const key of MERCHANT_LINK_KEYS) {
1155
+ const [group, field] = MERCHANT_LINK_PATHS[key];
1156
+ const nested = obj[group];
1157
+ const v = nested && typeof nested === "object" && !Array.isArray(nested) ? trimmed(nested[field]) : trimmed(obj[key]);
1158
+ if (v) out[key] = v;
1159
+ }
1160
+ return out;
1161
+ }
1162
+ /**
1163
+ * Builds the stored `links` object from flat fields. Empty values are left
1164
+ * out, and so is a group with nothing in it; no links gives `{}`.
1165
+ */
1166
+ function merchantLinksFromForm(form) {
1167
+ const out = {};
1168
+ for (const key of MERCHANT_LINK_KEYS) {
1169
+ const v = trimmed(form[key]);
1170
+ if (!v) continue;
1171
+ const [group, field] = MERCHANT_LINK_PATHS[key];
1172
+ (out[group] ??= {})[field] = v;
1173
+ }
1174
+ return out;
1175
+ }
1176
+ /** Reads any stored or older `links` value into the nested shape adminV1 saves. */
1177
+ function normalizeMerchantLinks(links) {
1178
+ return merchantLinksFromForm(merchantLinksToForm(links));
1179
+ }
1180
+ /**
1181
+ * Object fields of the merchant. The API keeps one you leave out, and
1182
+ * replaces it as a whole when you send it.
1183
+ */
1184
+ const MERCHANT_OBJECT_FIELDS = [
1185
+ "colours",
1186
+ "links",
1187
+ "imageIds"
1188
+ ];
1189
+ /** Fields the API sets itself; `updateMerchant` never sends them back. */
1190
+ const MERCHANT_READ_ONLY_FIELDS = ["createdDate", "modifiedDate"];
1191
+ /**
1192
+ * Longest values the API stores. Longer values are cut off silently
1193
+ * (live API, Sep 2026), so `updateMerchant` rejects them instead.
1194
+ * `vatNumber` fits a UK VAT number without the `GB` prefix.
1195
+ */
1196
+ const MERCHANT_FIELD_MAX_LENGTH = Object.freeze({
1197
+ companyNumber: 11,
1198
+ vatNumber: 9
1199
+ });
1200
+ /** Returns `"<field> is longer than <n> characters"` messages for over-long fields. */
1201
+ function validateMerchant(merchant) {
1202
+ const problems = [];
1203
+ for (const [field, max] of Object.entries(MERCHANT_FIELD_MAX_LENGTH)) {
1204
+ const value = merchant[field];
1205
+ if (typeof value === "string" && value.length > max) problems.push(`${field} is longer than ${max} characters`);
1206
+ }
1207
+ return problems;
1208
+ }
1209
+ /**
1210
+ * Reads the logged-in user's merchant (a user has exactly one), or `null`
1211
+ * when the API returns none.
1212
+ */
1213
+ async function fetchMerchant(options = {}) {
1214
+ const json = await apiGet(MERCHANT_PATH, {}, options);
1215
+ assertNoApiErrors(json, 200);
1216
+ return json?.merchant ?? null;
1217
+ }
1218
+ /**
1219
+ * Updates the merchant and returns it as stored.
1220
+ *
1221
+ * Shopwave's `POST /merchant` replaces the whole record: a scalar field you
1222
+ * leave out (`companyNumber`, `vatNumber`, `note`, …) is set to null, while
1223
+ * an object field you leave out (`colours`, `links`, `imageIds`) is kept and
1224
+ * one you send replaces the stored one; sending `{}` clears it (live API,
1225
+ * Sep 2026). So by default the
1226
+ * current merchant is read first and the patch is merged over it.
1227
+ *
1228
+ * `imageIds` is always sent as file names ({@link toStoredImageIds}), so you
1229
+ * can pass back what you read. See `MerchantImageIds` for the shape.
1230
+ *
1231
+ * The API answers 205 with an empty body, so the merchant is read again after
1232
+ * the save and that is what's returned (it shows exactly what was kept).
1233
+ * Throws before sending when a value is longer than the API stores
1234
+ * ({@link MERCHANT_FIELD_MAX_LENGTH}).
1235
+ */
1236
+ async function updateMerchant(patch, options = {}) {
1237
+ const { merge = true,...requestOptions } = options;
1238
+ let merchant = { ...patch };
1239
+ if (merge) {
1240
+ const current = await fetchMerchant(requestOptions);
1241
+ if (!current) throw new ShopwaveApiError(404, "Shopwave API error (404): no merchant to update");
1242
+ 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})`);
1243
+ merchant = {
1244
+ ...current,
1245
+ ...patch,
1246
+ id: current.id
1247
+ };
1248
+ for (const field of MERCHANT_OBJECT_FIELDS) if (!(field in patch)) delete merchant[field];
1249
+ }
1250
+ if (merchant.imageIds && typeof merchant.imageIds === "object") merchant.imageIds = toStoredImageIds(merchant.imageIds);
1251
+ if (merchant.id == null || merchant.id === "") throw new Error("merchant id is missing");
1252
+ for (const field of MERCHANT_READ_ONLY_FIELDS) delete merchant[field];
1253
+ const problems = validateMerchant(merchant);
1254
+ if (problems.length > 0) throw new Error(`Invalid merchant: ${problems.join("; ")}`);
1255
+ const { status, body: raw } = await apiRequest(MERCHANT_PATH, {
1256
+ method: "PUT",
1257
+ headers: { "Content-Type": "application/json" },
1258
+ body: JSON.stringify({ merchant })
1259
+ }, requestOptions);
1260
+ const body = raw;
1261
+ assertNoApiErrors(body, status);
1262
+ const echoed = body?.merchant && typeof body.merchant === "object" ? body.merchant : null;
1263
+ if (echoed) return {
1264
+ ...merchant,
1265
+ ...echoed,
1266
+ id: Number(echoed.id ?? merchant.id)
1267
+ };
1268
+ return await fetchMerchant(requestOptions) ?? {
1269
+ ...merchant,
1270
+ id: Number(merchant.id)
1271
+ };
1272
+ }
1273
+
1274
+ //#endregion
1275
+ //#region src/core/user.ts
1276
+ /** Reads the logged-in user, or `null` when the API returns none. */
1277
+ async function fetchUser(options = {}) {
1278
+ const json = await apiGet(`/api/${SHOPWAVE_RESOURCES.user.route}`, {}, options);
1279
+ assertNoApiErrors(json, 200);
1280
+ return json?.user ?? null;
1281
+ }
1282
+
712
1283
  //#endregion
713
1284
  exports.DEFAULT_BASKET_FILTERS = DEFAULT_BASKET_FILTERS;
714
1285
  exports.DEFAULT_PAGINATION = DEFAULT_PAGINATION;
1286
+ exports.MERCHANT_COLOUR_KEYS = MERCHANT_COLOUR_KEYS;
1287
+ exports.MERCHANT_FIELD_MAX_LENGTH = MERCHANT_FIELD_MAX_LENGTH;
1288
+ exports.MERCHANT_IMAGE_SLOTS = MERCHANT_IMAGE_SLOTS;
1289
+ exports.MERCHANT_IMAGE_SLOT_KEYS = MERCHANT_IMAGE_SLOT_KEYS;
1290
+ exports.MERCHANT_LINK_KEYS = MERCHANT_LINK_KEYS;
1291
+ exports.MERCHANT_LINK_PATHS = MERCHANT_LINK_PATHS;
1292
+ exports.MERCHANT_OBJECT_FIELDS = MERCHANT_OBJECT_FIELDS;
1293
+ exports.MERCHANT_READ_ONLY_FIELDS = MERCHANT_READ_ONLY_FIELDS;
715
1294
  exports.PromotionRuleSet = PromotionRuleSet;
716
1295
  exports.SHOPWAVE_ENTITIES = SHOPWAVE_ENTITIES;
1296
+ exports.SHOPWAVE_IMAGE_BASE_URL = SHOPWAVE_IMAGE_BASE_URL;
1297
+ exports.SHOPWAVE_RESOURCES = SHOPWAVE_RESOURCES;
1298
+ exports.SHOPWAVE_UPLOAD = SHOPWAVE_UPLOAD;
717
1299
  exports.ShopwaveApiError = ShopwaveApiError;
1300
+ exports.UPLOAD_KINDS = UPLOAD_KINDS;
718
1301
  exports.apiDelete = apiDelete;
719
1302
  exports.apiGet = apiGet;
720
1303
  exports.apiRequest = apiRequest;
@@ -727,6 +1310,7 @@ exports.collectConsumerIds = collectConsumerIds;
727
1310
  exports.collectProductIds = collectProductIds;
728
1311
  exports.combineBasketRows = combineBasketRows;
729
1312
  exports.computeBasketSummary = computeBasketSummary;
1313
+ exports.coverCrop = coverCrop;
730
1314
  exports.deleteCategory = deleteCategory;
731
1315
  exports.deleteEmployee = deleteEmployee;
732
1316
  exports.deleteEntity = deleteEntity;
@@ -741,6 +1325,7 @@ exports.fetchConsumers = fetchConsumers;
741
1325
  exports.fetchEmployee = fetchEmployee;
742
1326
  exports.fetchEmployees = fetchEmployees;
743
1327
  exports.fetchEntityById = fetchEntityById;
1328
+ exports.fetchMerchant = fetchMerchant;
744
1329
  exports.fetchProduct = fetchProduct;
745
1330
  exports.fetchProducts = fetchProducts;
746
1331
  exports.fetchProductsMap = fetchProductsMap;
@@ -750,13 +1335,26 @@ exports.fetchReport = fetchReport;
750
1335
  exports.fetchSession = fetchSession;
751
1336
  exports.fetchStore = fetchStore;
752
1337
  exports.fetchStores = fetchStores;
1338
+ exports.fetchUser = fetchUser;
1339
+ exports.findRepricedInstances = findRepricedInstances;
1340
+ exports.fitImageToSize = fitImageToSize;
753
1341
  exports.formatDateForQuery = formatDateForQuery;
754
1342
  exports.getApiErrorMap = getApiErrorMap;
755
1343
  exports.getApiErrors = getApiErrors;
1344
+ exports.getImageUrl = getImageUrl;
1345
+ exports.getMerchantImage = getMerchantImage;
1346
+ exports.getMerchantImageUrl = getMerchantImageUrl;
1347
+ exports.imageFileName = imageFileName;
1348
+ exports.isSameInstancePrice = isSameInstancePrice;
1349
+ exports.isUploadKind = isUploadKind;
756
1350
  exports.loginPath = loginPath;
757
1351
  exports.logout = logout;
758
1352
  exports.logoutPath = logoutPath;
1353
+ exports.merchantLinksFromForm = merchantLinksFromForm;
1354
+ exports.merchantLinksToForm = merchantLinksToForm;
1355
+ exports.normalizeMerchantLinks = normalizeMerchantLinks;
759
1356
  exports.parseBasketReportData = parseBasketReportData;
1357
+ exports.readImageSize = readImageSize;
760
1358
  exports.rolesById = rolesById;
761
1359
  exports.saveCategory = saveCategory;
762
1360
  exports.saveEmployee = saveEmployee;
@@ -765,7 +1363,14 @@ exports.saveEntity = saveEntity;
765
1363
  exports.saveProduct = saveProduct;
766
1364
  exports.savePromotion = savePromotion;
767
1365
  exports.saveStore = saveStore;
1366
+ exports.setMerchantImage = setMerchantImage;
768
1367
  exports.submitEntity = submitEntity;
1368
+ exports.toProductInstancesForSave = toProductInstancesForSave;
769
1369
  exports.toShopwaveApiError = toShopwaveApiError;
1370
+ exports.toStoredImageIds = toStoredImageIds;
1371
+ exports.updateMerchant = updateMerchant;
1372
+ exports.uploadImage = uploadImage;
1373
+ exports.uploadMerchantImage = uploadMerchantImage;
1374
+ exports.validateMerchant = validateMerchant;
770
1375
  exports.withToken = withToken;
771
1376
  //# sourceMappingURL=index.cjs.map