react-shopwave-connect 0.4.3 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -383,17 +383,29 @@ const UPLOAD_KINDS = Object.freeze({
383
383
  applicationLogo: "applicaionLogo",
384
384
  applicationImages: "applicaionImages"
385
385
  });
386
+ /** Every `UploadPrefix`, longest first so a name check never takes `product` for `product_thumbnail`. */
387
+ const UPLOAD_PREFIXES = Object.freeze([
388
+ "product_thumbnail",
389
+ "variant_thumbnail",
390
+ "product",
391
+ "variant"
392
+ ]);
386
393
  /** How uploads are addressed (app route and Shopwave uploader). */
387
394
  const SHOPWAVE_UPLOAD = Object.freeze({
388
395
  route: "upload",
389
396
  upstream: "uploader",
390
397
  kindHeader: "contentType",
398
+ prefixHeader: "prefix",
391
399
  fileField: "file",
392
- kindField: "kind"
400
+ kindField: "kind",
401
+ prefixField: "prefix"
393
402
  });
394
403
  function isUploadKind(value) {
395
404
  return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
396
405
  }
406
+ function isUploadPrefix(value) {
407
+ return typeof value === "string" && UPLOAD_PREFIXES.includes(value);
408
+ }
397
409
  const SHOPWAVE_LOOKUPS = Object.freeze({
398
410
  productTags: {
399
411
  route: "products/tags",
@@ -560,22 +572,503 @@ async function logout(options = {}) {
560
572
  * function yet (e.g. `/api/merchant`).
561
573
  */
562
574
  /**
563
- * Deletes `/api/{resourcePath}/{entityId}`.
575
+ * Deletes `/api/{resourcePath}/{entityId}`.
576
+ */
577
+ async function deleteEntity(resourcePath, entityId, options = {}) {
578
+ if (entityId == null || entityId === "") throw new Error("entityId is missing");
579
+ await apiDelete(`/api/${resourcePath}/${entityId}`, options);
580
+ }
581
+ /**
582
+ * Sends a create/update mutation. Returns the response's `result` field when it
583
+ * has one (older app routes wrapped their answer that way), otherwise the whole
584
+ * parsed response body. Throws `ShopwaveApiError` on HTTP or API errors.
585
+ */
586
+ async function submitEntity({ endpoint, method = "POST", payload }, options = {}) {
587
+ const json = await apiSend(endpoint, method, payload, options);
588
+ assertNoApiErrors(json, 200);
589
+ if (json && typeof json === "object" && "result" in json) return json.result;
590
+ return json ?? void 0;
591
+ }
592
+
593
+ //#endregion
594
+ //#region src/core/imageFit.ts
595
+ /**
596
+ * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
597
+ * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
598
+ */
599
+ function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
600
+ if (![
601
+ srcWidth,
602
+ srcHeight,
603
+ dstWidth,
604
+ dstHeight
605
+ ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
606
+ const srcRatio = srcWidth / srcHeight;
607
+ const dstRatio = dstWidth / dstHeight;
608
+ if (srcRatio > dstRatio) {
609
+ const sw = Math.round(srcHeight * dstRatio);
610
+ return {
611
+ sx: Math.round((srcWidth - sw) / 2),
612
+ sy: 0,
613
+ sw,
614
+ sh: srcHeight
615
+ };
616
+ }
617
+ const sh = Math.round(srcWidth / dstRatio);
618
+ return {
619
+ sx: 0,
620
+ sy: Math.round((srcHeight - sh) / 2),
621
+ sw: srcWidth,
622
+ sh
623
+ };
624
+ }
625
+ function requireBrowserImages(fn) {
626
+ if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
627
+ }
628
+ /** Reads an image file's pixel size (browser only). */
629
+ async function readImageSize(file) {
630
+ requireBrowserImages("readImageSize");
631
+ const bitmap = await createImageBitmap(file);
632
+ try {
633
+ return {
634
+ width: bitmap.width,
635
+ height: bitmap.height
636
+ };
637
+ } finally {
638
+ bitmap.close?.();
639
+ }
640
+ }
641
+ /** Draws `crop` of the bitmap at `width × height` and encodes it (one resample). */
642
+ async function drawCrop(bitmap, crop, width, height, type, quality, fn) {
643
+ const { sx, sy, sw, sh } = crop;
644
+ if (typeof OffscreenCanvas === "function") {
645
+ const canvas$1 = new OffscreenCanvas(width, height);
646
+ const ctx$1 = canvas$1.getContext("2d");
647
+ if (!ctx$1) throw new Error(`${fn}: no 2D canvas context`);
648
+ ctx$1.imageSmoothingQuality = "high";
649
+ ctx$1.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
650
+ return canvas$1.convertToBlob({
651
+ type,
652
+ quality
653
+ });
654
+ }
655
+ const canvas = document.createElement("canvas");
656
+ canvas.width = width;
657
+ canvas.height = height;
658
+ const ctx = canvas.getContext("2d");
659
+ if (!ctx) throw new Error(`${fn}: no 2D canvas context`);
660
+ ctx.imageSmoothingQuality = "high";
661
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
662
+ return new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error(`${fn}: encoding failed`)), type, quality));
663
+ }
664
+ /** The input's name with the output type's extension. */
665
+ function outputName(file, type) {
666
+ const name = file.name || "image";
667
+ const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
668
+ return `${name.replace(/\.[^.]+$/, "")}.${ext}`;
669
+ }
670
+ /**
671
+ * Returns the image at exactly `width × height`: scaled and centre-cropped
672
+ * (never stretched). Browser only. The result is a `File` named like the
673
+ * input, with the output type's extension.
674
+ */
675
+ async function fitImageToSize(file, width, height, options = {}) {
676
+ requireBrowserImages("fitImageToSize");
677
+ const { type = "image/png", quality, keepIfExact = true } = options;
678
+ const outName = outputName(file, type);
679
+ const bitmap = await createImageBitmap(file);
680
+ try {
681
+ if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
682
+ const blob = await drawCrop(bitmap, coverCrop(bitmap.width, bitmap.height, width, height), width, height, type, quality, "fitImageToSize");
683
+ return new File([blob], outName, { type });
684
+ } finally {
685
+ bitmap.close?.();
686
+ }
687
+ }
688
+ /** A rule that can't be met by any image (a mistake in the rule, not the image). */
689
+ var ImageRuleError = class extends Error {
690
+ constructor(message) {
691
+ super(message);
692
+ this.name = "ImageRuleError";
693
+ }
694
+ };
695
+ /** The image is smaller than the rule's minimum (and `allowUpscale` is off). */
696
+ var ImageTooSmallError = class extends Error {
697
+ /** The smallest size the rule accepts. */
698
+ required;
699
+ /** The largest area of the right shape the image could give. */
700
+ actual;
701
+ constructor(required, actual) {
702
+ super(`The image is too small: it needs to be at least ${required.width} × ${required.height}, and it's ${actual.width} × ${actual.height}`);
703
+ this.name = "ImageTooSmallError";
704
+ this.required = required;
705
+ this.actual = actual;
706
+ }
707
+ };
708
+ const isPositive = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
709
+ /**
710
+ * An aspect ratio as width ÷ height: `"100:77"`, `"100/77"`, `[100, 77]` →
711
+ * 1.2987…; `1.3` → 1.3. Throws {@link ImageRuleError} for anything else.
712
+ */
713
+ function parseAspectRatio(value) {
714
+ let parts = null;
715
+ if (typeof value === "number") return isPositive(value) ? value : badRatio(value);
716
+ if (Array.isArray(value)) parts = [value[0], value[1]];
717
+ else if (typeof value === "string") {
718
+ const text$1 = value.trim();
719
+ const match = /^(\d+(?:\.\d+)?)\s*[:/x×]\s*(\d+(?:\.\d+)?)$/i.exec(text$1);
720
+ if (match) parts = [Number(match[1]), Number(match[2])];
721
+ else if (/^\d+(?:\.\d+)?$/.test(text$1)) return isPositive(Number(text$1)) ? Number(text$1) : badRatio(value);
722
+ }
723
+ if (parts && isPositive(parts[0]) && isPositive(parts[1])) return parts[0] / parts[1];
724
+ return badRatio(value);
725
+ }
726
+ function badRatio(value) {
727
+ throw new ImageRuleError(`Not an aspect ratio: ${JSON.stringify(value)} (use e.g. "100:77", [100, 77] or 1.3)`);
728
+ }
729
+ /** Throws {@link ImageRuleError} when the rule contradicts itself. */
730
+ function checkImageRule(rule) {
731
+ if (!rule || typeof rule !== "object") throw new ImageRuleError("An image rule must be an object");
732
+ for (const key of [
733
+ "width",
734
+ "height",
735
+ "minWidth",
736
+ "minHeight",
737
+ "maxWidth",
738
+ "maxHeight",
739
+ "maxLongSide"
740
+ ]) if (rule[key] != null && !isPositive(rule[key])) throw new ImageRuleError(`${key} must be a positive number`);
741
+ if (rule.width != null || rule.height != null) {
742
+ if (rule.width == null || rule.height == null) throw new ImageRuleError("An exact size needs both width and height");
743
+ if (rule.aspectRatio != null) throw new ImageRuleError("Give an exact size or an aspectRatio, not both (the size sets the ratio)");
744
+ const extra = [
745
+ "minWidth",
746
+ "minHeight",
747
+ "maxWidth",
748
+ "maxHeight",
749
+ "maxLongSide"
750
+ ].filter((key) => rule[key] != null);
751
+ if (extra.length > 0) throw new ImageRuleError(`An exact size is already the minimum and the maximum; remove ${extra.join(", ")}`);
752
+ return;
753
+ }
754
+ if (rule.aspectRatio != null) parseAspectRatio(rule.aspectRatio);
755
+ if (rule.minWidth != null && rule.maxWidth != null && rule.minWidth > rule.maxWidth) throw new ImageRuleError("minWidth is larger than maxWidth");
756
+ if (rule.minHeight != null && rule.maxHeight != null && rule.minHeight > rule.maxHeight) throw new ImageRuleError("minHeight is larger than maxHeight");
757
+ if (rule.maxLongSide != null && Math.max(rule.minWidth ?? 0, rule.minHeight ?? 0) > rule.maxLongSide) throw new ImageRuleError("The minimum size is larger than maxLongSide");
758
+ }
759
+ /**
760
+ * Works out what to do to a `source`-sized image to meet `rule`: the centred
761
+ * crop of the right shape (the largest one), then the output size (scaled
762
+ * down to the maximum, never below the minimum). Pure: no browser needed.
763
+ *
764
+ * Throws {@link ImageTooSmallError} when the crop is below the minimum (or
765
+ * the exact size) and `allowUpscale` is off, and {@link ImageRuleError} for a
766
+ * contradictory rule.
767
+ *
768
+ * @example
769
+ * planImageFit({ width: 6000, height: 4000 }, { aspectRatio: "100:77", minWidth: 600, minHeight: 462, maxLongSide: 2000 })
770
+ * // → crop { sx: 403, sy: 0, sw: 5194, sh: 4000 }, 2000 × 1540
771
+ */
772
+ function planImageFit(source, rule) {
773
+ checkImageRule(rule);
774
+ const { width: W, height: H } = source ?? {};
775
+ if (!isPositive(W) || !isPositive(H)) throw new Error("planImageFit: the image has no size");
776
+ const exact = rule.width != null && rule.height != null;
777
+ const ratio = exact ? rule.width / rule.height : rule.aspectRatio != null ? parseAspectRatio(rule.aspectRatio) : null;
778
+ const crop = ratio == null ? {
779
+ sx: 0,
780
+ sy: 0,
781
+ sw: W,
782
+ sh: H
783
+ } : coverCrop(W, H, ratio, 1);
784
+ const { sw, sh } = crop;
785
+ const kept = {
786
+ width: sw,
787
+ height: sh
788
+ };
789
+ let width;
790
+ let height;
791
+ if (exact) {
792
+ width = rule.width;
793
+ height = rule.height;
794
+ if ((sw < width || sh < height) && !rule.allowUpscale) throw new ImageTooSmallError({
795
+ width,
796
+ height
797
+ }, kept);
798
+ } else {
799
+ const minW = rule.minWidth ?? 0;
800
+ const minH = rule.minHeight ?? 0;
801
+ if ((sw < minW || sh < minH) && !rule.allowUpscale) throw new ImageTooSmallError(requiredSize(minW, minH, ratio), kept);
802
+ let scale = 1;
803
+ if (rule.maxWidth != null) scale = Math.min(scale, rule.maxWidth / sw);
804
+ if (rule.maxHeight != null) scale = Math.min(scale, rule.maxHeight / sh);
805
+ if (rule.maxLongSide != null) scale = Math.min(scale, rule.maxLongSide / Math.max(sw, sh));
806
+ scale = Math.max(scale, minW / sw, minH / sh);
807
+ width = Math.max(1, Math.round(sw * scale));
808
+ height = Math.max(1, Math.round(sh * scale));
809
+ }
810
+ const unchanged = crop.sx === 0 && crop.sy === 0 && sw === W && sh === H && width === W && height === H;
811
+ return {
812
+ crop,
813
+ width,
814
+ height,
815
+ unchanged
816
+ };
817
+ }
818
+ /** The minimum as a full size: a ratio rule with only one minimum implies the other. */
819
+ function requiredSize(minW, minH, ratio) {
820
+ if (ratio == null) return {
821
+ width: minW,
822
+ height: minH
823
+ };
824
+ return {
825
+ width: Math.max(minW, Math.ceil(minH * ratio)),
826
+ height: Math.max(minH, Math.ceil(minW / ratio))
827
+ };
828
+ }
829
+ const OUTPUT_TYPES = [
830
+ "image/png",
831
+ "image/jpeg",
832
+ "image/webp"
833
+ ];
834
+ /**
835
+ * Returns the image meeting `rule` ({@link planImageFit}): centre-cropped to
836
+ * the right shape and scaled in a single draw. An image that already fits is
837
+ * returned untouched (same bytes). Browser only.
838
+ *
839
+ * Throws {@link ImageTooSmallError} (show `required` and `actual` to the
840
+ * person) or {@link ImageRuleError}; an unreadable file rejects with the
841
+ * browser's decoding error.
842
+ *
843
+ * @example
844
+ * const ready = await prepareImage(file, { aspectRatio: "100:77", minWidth: 600, minHeight: 462, maxLongSide: 2000 });
845
+ * await uploadImage(ready, { kind: "product", prefix: "product" });
846
+ */
847
+ async function prepareImage(file, rule, options = {}) {
848
+ checkImageRule(rule);
849
+ requireBrowserImages("prepareImage");
850
+ const sourceType = file.type && OUTPUT_TYPES.includes(file.type) ? file.type : "image/png";
851
+ const type = options.type ?? sourceType;
852
+ const quality = options.quality ?? (type === "image/png" ? void 0 : .9);
853
+ const bitmap = await createImageBitmap(file);
854
+ try {
855
+ const plan = planImageFit({
856
+ width: bitmap.width,
857
+ height: bitmap.height
858
+ }, rule);
859
+ if (plan.unchanged && type === file.type) return file instanceof File ? file : new File([file], outputName(file, type), { type });
860
+ const blob = await drawCrop(bitmap, plan.crop, plan.width, plan.height, type, quality, "prepareImage");
861
+ return new File([blob], outputName(file, type), { type });
862
+ } finally {
863
+ bitmap.close?.();
864
+ }
865
+ }
866
+
867
+ //#endregion
868
+ //#region src/core/upload.ts
869
+ /**
870
+ * HTTPS host that serves the Shopwave CDN's images. The API returns
871
+ * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
872
+ * (checked Sep 2026), so pages served over HTTPS can't show it.
873
+ */
874
+ const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
875
+ const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
876
+ /**
877
+ * Turns an image path from the API into a URL a page can load over HTTPS:
878
+ * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
879
+ * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
880
+ * Other absolute URLs are returned unchanged; empty input gives `""`.
881
+ */
882
+ function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
883
+ if (!path) return "";
884
+ const root = base.replace(/\/+$/, "");
885
+ if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
886
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
887
+ return `${root}/${path.replace(/^\/+/, "")}`;
888
+ }
889
+ /**
890
+ * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
891
+ * (`createShopwaveApi(...).upload()`), and returns its id and URL.
892
+ *
893
+ * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
894
+ * record has to point at it to use it. Live API (Sep 2026): the upload answers
895
+ * 201 `{ fileName, path }`.
896
+ */
897
+ async function uploadImage(file, params, options = {}) {
898
+ if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
899
+ if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
900
+ if (params.prefix != null && !isUploadPrefix(params.prefix)) throw new Error(`uploadImage: unknown prefix "${params.prefix}"`);
901
+ const name = params.fileName ?? file.name ?? "upload";
902
+ const form = new FormData();
903
+ form.append(SHOPWAVE_UPLOAD.fileField, file, name);
904
+ form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
905
+ if (params.prefix != null) form.append(SHOPWAVE_UPLOAD.prefixField, params.prefix);
906
+ const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
907
+ method: "POST",
908
+ body: form
909
+ }, options);
910
+ const body = raw;
911
+ assertNoApiErrors(body, status);
912
+ const id = typeof body?.fileName === "string" ? body.fileName : "";
913
+ const path = typeof body?.path === "string" ? body.path : "";
914
+ if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
915
+ return {
916
+ id,
917
+ url: getImageUrl(path),
918
+ path
919
+ };
920
+ }
921
+
922
+ //#endregion
923
+ //#region src/core/merchantImages.ts
924
+ /** The three image slots on the merchant settings page. */
925
+ const MERCHANT_IMAGE_SLOT_KEYS = [
926
+ "receipt",
927
+ "square",
928
+ "featured"
929
+ ];
930
+ /**
931
+ * Where each slot lives, its upload kind and its exact size (from adminV1's
932
+ * merchant settings page).
933
+ */
934
+ const MERCHANT_IMAGE_SLOTS = Object.freeze({
935
+ receipt: {
936
+ field: "logo.receipt",
937
+ uploadKind: "merchant",
938
+ width: 576,
939
+ height: 325
940
+ },
941
+ square: {
942
+ field: "logo.square",
943
+ uploadKind: "merchant",
944
+ width: 1e3,
945
+ height: 1e3
946
+ },
947
+ featured: {
948
+ field: "feature[0]",
949
+ uploadKind: "merchantFeature",
950
+ width: 1200,
951
+ height: 600
952
+ }
953
+ });
954
+ /**
955
+ * The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
956
+ * `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
957
+ * Returns `null` for empty or non-string values.
958
+ */
959
+ function imageFileName(value) {
960
+ if (typeof value !== "string") return null;
961
+ const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
962
+ return last ? decodeURIComponent(last) : null;
963
+ }
964
+ /** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
965
+ function getMerchantImage(imageIds, slot) {
966
+ if (!imageIds || typeof imageIds !== "object") return null;
967
+ let value;
968
+ if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
969
+ else {
970
+ const logo = imageIds.logo;
971
+ value = logo && typeof logo === "object" ? logo[slot] : void 0;
972
+ }
973
+ return typeof value === "string" && value.trim() ? value.trim() : null;
974
+ }
975
+ /**
976
+ * An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
977
+ * holds only a file name (a fresh upload not yet saved; use the upload's `url`).
978
+ */
979
+ function getMerchantImageUrl(imageIds, slot, base) {
980
+ const value = getMerchantImage(imageIds, slot);
981
+ if (!value || !value.includes("/")) return "";
982
+ return getImageUrl(value, base);
983
+ }
984
+ /**
985
+ * Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
986
+ * with `null`). Other slots and unknown keys are kept; an empty `logo` or
987
+ * `feature` is removed.
988
+ */
989
+ function setMerchantImage(imageIds, slot, fileName) {
990
+ const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
991
+ if (slot === "featured") {
992
+ const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
993
+ const feature = fileName ? [fileName, ...rest] : rest;
994
+ if (feature.length > 0) next.feature = feature;
995
+ else delete next.feature;
996
+ } else {
997
+ const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
998
+ if (fileName) logo[slot] = fileName;
999
+ else delete logo[slot];
1000
+ if (Object.keys(logo).length > 0) next.logo = logo;
1001
+ else delete next.logo;
1002
+ }
1003
+ return next;
1004
+ }
1005
+ function toStored(value) {
1006
+ if (typeof value === "string") return imageFileName(value) ?? void 0;
1007
+ if (Array.isArray(value)) {
1008
+ const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
1009
+ return items.length > 0 ? items : void 0;
1010
+ }
1011
+ if (value && typeof value === "object") {
1012
+ const out = {};
1013
+ for (const [k, v] of Object.entries(value)) {
1014
+ const stored = toStored(v);
1015
+ if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
1016
+ }
1017
+ return Object.keys(out).length > 0 ? out : void 0;
1018
+ }
1019
+ }
1020
+ /**
1021
+ * The `imageIds` to send on a save: every URL is turned back into its file
1022
+ * name (what adminV1 does with images you didn't change) and empty values
1023
+ * are dropped. No images gives `{}`.
1024
+ */
1025
+ function toStoredImageIds(imageIds) {
1026
+ return toStored(imageIds) ?? {};
1027
+ }
1028
+ /**
1029
+ * Uploads an image for a merchant slot: fits it to the slot's size, uploads
1030
+ * it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
1031
+ * `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
1032
+ */
1033
+ async function uploadMerchantImage(file, slot, options = {}) {
1034
+ const def = MERCHANT_IMAGE_SLOTS[slot];
1035
+ if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
1036
+ const { fit = true, fitOptions,...requestOptions } = options;
1037
+ return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
1038
+ }
1039
+
1040
+ //#endregion
1041
+ //#region src/core/productImages.ts
1042
+ /**
1043
+ * Product images, as the live API stores them (merchant 5644, 4 Nov 2026):
1044
+ * - A product's `images` is a list. **Reads return full URLs**
1045
+ * (`http://static.merchantstack.com/images/merchant/<id>/product/<file>`);
1046
+ * **writes take the uploader's file names** ({@link toStoredProductImages};
1047
+ * `saveProduct` does this for you).
1048
+ * - The uploader takes one file per request. With a `prefix` (see
1049
+ * `UploadPrefix`) it names the file `<prefix>_<hash>.<ext>`
1050
+ * (`product_thumbnail_1bdd…41090b.png`); without one, `<hash>.<ext>`. So an
1051
+ * image's role can be read back from its name ({@link productImageRole}).
1052
+ */
1053
+ /**
1054
+ * The role in an image's file name or URL, from the uploader's `prefix`:
1055
+ * `"…/product_thumbnail_1bdd.png"` → `"product_thumbnail"`. `null` for a name
1056
+ * without one (images uploaded without a prefix, e.g. before prefixes existed).
564
1057
  */
565
- async function deleteEntity(resourcePath, entityId, options = {}) {
566
- if (entityId == null || entityId === "") throw new Error("entityId is missing");
567
- await apiDelete(`/api/${resourcePath}/${entityId}`, options);
1058
+ function productImageRole(value) {
1059
+ const name = imageFileName(value);
1060
+ if (!name) return null;
1061
+ return UPLOAD_PREFIXES.find((prefix) => name.startsWith(`${prefix}_`)) ?? null;
568
1062
  }
569
1063
  /**
570
- * Sends a create/update mutation. Returns the response's `result` field when it
571
- * has one (older app routes wrapped their answer that way), otherwise the whole
572
- * parsed response body. Throws `ShopwaveApiError` on HTTP or API errors.
1064
+ * A product's `images` as the API takes them on a save: file names, not the
1065
+ * URLs a read returns. Non-strings, blanks and duplicates are dropped; the
1066
+ * order is kept.
573
1067
  */
574
- async function submitEntity({ endpoint, method = "POST", payload }, options = {}) {
575
- const json = await apiSend(endpoint, method, payload, options);
576
- assertNoApiErrors(json, 200);
577
- if (json && typeof json === "object" && "result" in json) return json.result;
578
- return json ?? void 0;
1068
+ function toStoredProductImages(images) {
1069
+ if (!Array.isArray(images)) return [];
1070
+ const names = images.map(imageFileName).filter((name) => Boolean(name));
1071
+ return Array.from(new Set(names));
579
1072
  }
580
1073
 
581
1074
  //#endregion
@@ -732,12 +1225,20 @@ async function fetchEntityById(kind, id, params = {}, options = {}) {
732
1225
  * read) so an edited price is sent as a new instance. As a safeguard, a new
733
1226
  * product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
734
1227
  * another product would otherwise point the save at that product's instances.
1228
+ *
1229
+ * `images` is sent as file names ({@link toStoredProductImages}), so the URLs a
1230
+ * read returns can be passed straight back; leaving `images` out keeps them.
735
1231
  */
736
1232
  const saveProduct = (product, options) => {
737
- return saveEntity("product", (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
1233
+ let toSave = (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
738
1234
  ...product,
739
1235
  instances: toProductInstancesForSave(product.instances)
740
- } : product, options);
1236
+ } : product;
1237
+ if (Array.isArray(toSave.images)) toSave = {
1238
+ ...toSave,
1239
+ images: toStoredProductImages(toSave.images)
1240
+ };
1241
+ return saveEntity("product", toSave, options);
741
1242
  };
742
1243
  const deleteProduct = (id, options) => deleteEntityById("product", id, options);
743
1244
  const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
@@ -912,267 +1413,6 @@ function buildConsumerMap(consumers) {
912
1413
  return map;
913
1414
  }
914
1415
 
915
- //#endregion
916
- //#region src/core/imageFit.ts
917
- /**
918
- * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
919
- * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
920
- */
921
- function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
922
- if (![
923
- srcWidth,
924
- srcHeight,
925
- dstWidth,
926
- dstHeight
927
- ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
928
- const srcRatio = srcWidth / srcHeight;
929
- const dstRatio = dstWidth / dstHeight;
930
- if (srcRatio > dstRatio) {
931
- const sw = Math.round(srcHeight * dstRatio);
932
- return {
933
- sx: Math.round((srcWidth - sw) / 2),
934
- sy: 0,
935
- sw,
936
- sh: srcHeight
937
- };
938
- }
939
- const sh = Math.round(srcWidth / dstRatio);
940
- return {
941
- sx: 0,
942
- sy: Math.round((srcHeight - sh) / 2),
943
- sw: srcWidth,
944
- sh
945
- };
946
- }
947
- function requireBrowserImages(fn) {
948
- if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
949
- }
950
- /** Reads an image file's pixel size (browser only). */
951
- async function readImageSize(file) {
952
- requireBrowserImages("readImageSize");
953
- const bitmap = await createImageBitmap(file);
954
- try {
955
- return {
956
- width: bitmap.width,
957
- height: bitmap.height
958
- };
959
- } finally {
960
- bitmap.close?.();
961
- }
962
- }
963
- /**
964
- * Returns the image at exactly `width × height`: scaled and centre-cropped
965
- * (never stretched). Browser only. The result is a `File` named like the
966
- * input, with the output type's extension.
967
- */
968
- async function fitImageToSize(file, width, height, options = {}) {
969
- requireBrowserImages("fitImageToSize");
970
- const { type = "image/png", quality, keepIfExact = true } = options;
971
- const name = file.name || "image";
972
- const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
973
- const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
974
- const bitmap = await createImageBitmap(file);
975
- try {
976
- if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
977
- const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
978
- let blob;
979
- if (typeof OffscreenCanvas === "function") {
980
- const canvas = new OffscreenCanvas(width, height);
981
- const ctx = canvas.getContext("2d");
982
- if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
983
- ctx.imageSmoothingQuality = "high";
984
- ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
985
- blob = await canvas.convertToBlob({
986
- type,
987
- quality
988
- });
989
- } else {
990
- const canvas = document.createElement("canvas");
991
- canvas.width = width;
992
- canvas.height = height;
993
- const ctx = canvas.getContext("2d");
994
- if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
995
- ctx.imageSmoothingQuality = "high";
996
- ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
997
- blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
998
- }
999
- return new File([blob], outName, { type });
1000
- } finally {
1001
- bitmap.close?.();
1002
- }
1003
- }
1004
-
1005
- //#endregion
1006
- //#region src/core/upload.ts
1007
- /**
1008
- * HTTPS host that serves the Shopwave CDN's images. The API returns
1009
- * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
1010
- * (checked Sep 2026), so pages served over HTTPS can't show it.
1011
- */
1012
- const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
1013
- const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
1014
- /**
1015
- * Turns an image path from the API into a URL a page can load over HTTPS:
1016
- * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
1017
- * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
1018
- * Other absolute URLs are returned unchanged; empty input gives `""`.
1019
- */
1020
- function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
1021
- if (!path) return "";
1022
- const root = base.replace(/\/+$/, "");
1023
- if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
1024
- if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
1025
- return `${root}/${path.replace(/^\/+/, "")}`;
1026
- }
1027
- /**
1028
- * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
1029
- * (`createShopwaveApi(...).upload()`), and returns its id and URL.
1030
- *
1031
- * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
1032
- * record has to point at it to use it. Live API (Sep 2026): the upload answers
1033
- * 201 `{ fileName, path }`.
1034
- */
1035
- async function uploadImage(file, params, options = {}) {
1036
- if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
1037
- if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
1038
- const name = params.fileName ?? file.name ?? "upload";
1039
- const form = new FormData();
1040
- form.append(SHOPWAVE_UPLOAD.fileField, file, name);
1041
- form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
1042
- const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
1043
- method: "POST",
1044
- body: form
1045
- }, options);
1046
- const body = raw;
1047
- assertNoApiErrors(body, status);
1048
- const id = typeof body?.fileName === "string" ? body.fileName : "";
1049
- const path = typeof body?.path === "string" ? body.path : "";
1050
- if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
1051
- return {
1052
- id,
1053
- url: getImageUrl(path),
1054
- path
1055
- };
1056
- }
1057
-
1058
- //#endregion
1059
- //#region src/core/merchantImages.ts
1060
- /** The three image slots on the merchant settings page. */
1061
- const MERCHANT_IMAGE_SLOT_KEYS = [
1062
- "receipt",
1063
- "square",
1064
- "featured"
1065
- ];
1066
- /**
1067
- * Where each slot lives, its upload kind and its exact size (from adminV1's
1068
- * merchant settings page).
1069
- */
1070
- const MERCHANT_IMAGE_SLOTS = Object.freeze({
1071
- receipt: {
1072
- field: "logo.receipt",
1073
- uploadKind: "merchant",
1074
- width: 576,
1075
- height: 325
1076
- },
1077
- square: {
1078
- field: "logo.square",
1079
- uploadKind: "merchant",
1080
- width: 1e3,
1081
- height: 1e3
1082
- },
1083
- featured: {
1084
- field: "feature[0]",
1085
- uploadKind: "merchantFeature",
1086
- width: 1200,
1087
- height: 600
1088
- }
1089
- });
1090
- /**
1091
- * The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
1092
- * `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
1093
- * Returns `null` for empty or non-string values.
1094
- */
1095
- function imageFileName(value) {
1096
- if (typeof value !== "string") return null;
1097
- const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
1098
- return last ? decodeURIComponent(last) : null;
1099
- }
1100
- /** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
1101
- function getMerchantImage(imageIds, slot) {
1102
- if (!imageIds || typeof imageIds !== "object") return null;
1103
- let value;
1104
- if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
1105
- else {
1106
- const logo = imageIds.logo;
1107
- value = logo && typeof logo === "object" ? logo[slot] : void 0;
1108
- }
1109
- return typeof value === "string" && value.trim() ? value.trim() : null;
1110
- }
1111
- /**
1112
- * An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
1113
- * holds only a file name (a fresh upload not yet saved; use the upload's `url`).
1114
- */
1115
- function getMerchantImageUrl(imageIds, slot, base) {
1116
- const value = getMerchantImage(imageIds, slot);
1117
- if (!value || !value.includes("/")) return "";
1118
- return getImageUrl(value, base);
1119
- }
1120
- /**
1121
- * Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
1122
- * with `null`). Other slots and unknown keys are kept; an empty `logo` or
1123
- * `feature` is removed.
1124
- */
1125
- function setMerchantImage(imageIds, slot, fileName) {
1126
- const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
1127
- if (slot === "featured") {
1128
- const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
1129
- const feature = fileName ? [fileName, ...rest] : rest;
1130
- if (feature.length > 0) next.feature = feature;
1131
- else delete next.feature;
1132
- } else {
1133
- const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
1134
- if (fileName) logo[slot] = fileName;
1135
- else delete logo[slot];
1136
- if (Object.keys(logo).length > 0) next.logo = logo;
1137
- else delete next.logo;
1138
- }
1139
- return next;
1140
- }
1141
- function toStored(value) {
1142
- if (typeof value === "string") return imageFileName(value) ?? void 0;
1143
- if (Array.isArray(value)) {
1144
- const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
1145
- return items.length > 0 ? items : void 0;
1146
- }
1147
- if (value && typeof value === "object") {
1148
- const out = {};
1149
- for (const [k, v] of Object.entries(value)) {
1150
- const stored = toStored(v);
1151
- if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
1152
- }
1153
- return Object.keys(out).length > 0 ? out : void 0;
1154
- }
1155
- }
1156
- /**
1157
- * The `imageIds` to send on a save: every URL is turned back into its file
1158
- * name (what adminV1 does with images you didn't change) and empty values
1159
- * are dropped. No images gives `{}`.
1160
- */
1161
- function toStoredImageIds(imageIds) {
1162
- return toStored(imageIds) ?? {};
1163
- }
1164
- /**
1165
- * Uploads an image for a merchant slot: fits it to the slot's size, uploads
1166
- * it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
1167
- * `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
1168
- */
1169
- async function uploadMerchantImage(file, slot, options = {}) {
1170
- const def = MERCHANT_IMAGE_SLOTS[slot];
1171
- if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
1172
- const { fit = true, fitOptions,...requestOptions } = options;
1173
- return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
1174
- }
1175
-
1176
1416
  //#endregion
1177
1417
  //#region src/core/merchant.ts
1178
1418
  const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
@@ -1915,5 +2155,5 @@ function useBasketReport(options) {
1915
2155
  }
1916
2156
 
1917
2157
  //#endregion
1918
- 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_LOOKUPS, 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, fetchProductInstanceTags, fetchProductTags, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, findRepricedInstances, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isSameInstancePrice, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, normalizeTagList, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, useProductInstanceTags, useProductTags, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
2158
+ export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, ImageRuleError, ImageTooSmallError, 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_LOOKUPS, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, ShopwaveApiError, UPLOAD_KINDS, UPLOAD_PREFIXES, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, checkImageRule, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProductInstanceTags, fetchProductTags, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, findRepricedInstances, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isSameInstancePrice, isUploadKind, isUploadPrefix, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, normalizeTagList, parseAspectRatio, parseBasketReportData, planImageFit, prepareImage, productImageRole, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, toStoredProductImages, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, useProductInstanceTags, useProductTags, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1919
2159
  //# sourceMappingURL=index.js.map