@asteby/storefront-react 0.8.0 → 0.10.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.
package/dist/payments.js CHANGED
@@ -1,7 +1,10 @@
1
1
  import { isSafeCssValue } from './chunk-672OTUM2.js';
2
- import { useResolvedLocale, useModalDialog } from './chunk-2WZIWIBW.js';
2
+ import { BrandMark, findBrand } from './chunk-DSZVJ2PW.js';
3
+ export { buildPayChoices, cashProviderData, checkoutToAttempt, choiceValue, parseChoice, payErrorResponse, paymentCsp, paymentCspHeaderName, paymentCspHeaders, paymentCspMode, paymentNonce, paymentNonceFromHeaders, voucherRows } from './chunk-ISEOCKIR.js';
4
+ import { useModalDialog } from './chunk-ZBH7JYU4.js';
5
+ import { useResolvedLocale } from './chunk-T52H5HL3.js';
3
6
  import './chunk-DQBL2DFJ.js';
4
- import { forwardRef, useImperativeHandle, useRef, useEffect, useMemo, useId, useState, useCallback } from 'react';
7
+ import { forwardRef, useImperativeHandle, useRef, useEffect, useMemo, useId, useState, useCallback, useSyncExternalStore } from 'react';
5
8
  import { paymentMessages, formatMoney, generateIdempotencyKey, paymentOutcome, paymentErrorView, formatVoucherExpiry } from '@asteby/storefront';
6
9
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
10
 
@@ -636,45 +639,337 @@ function createFetchTransport(url, options = {}) {
636
639
  };
637
640
  }
638
641
 
639
- // src/payments/csp.ts
640
- var ORIGIN = /^https:\/\/(\*\.)?[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*(:\d{1,5})?$/i;
641
- function origins(...lists) {
642
- const out = /* @__PURE__ */ new Set();
643
- for (const list of lists) for (const o of list ?? []) if (ORIGIN.test(o)) out.add(o);
644
- return [...out];
642
+ // src/payments/payment-method.messages.ts
643
+ var ES = {
644
+ legend: "M\xE9todo de pago",
645
+ pay: "Pagar",
646
+ placeOrder: "Realizar el pedido",
647
+ payRedirect: "Continuar al pago",
648
+ continue: "Continuar",
649
+ retryAddress: "Guardar direcci\xF3n y continuar",
650
+ processing: "Procesando\u2026",
651
+ redirectNote: "Te llevamos a la p\xE1gina del proveedor para terminar el pago y regresas aqu\xED.",
652
+ cashPoints: "Elige d\xF3nde pagar en efectivo",
653
+ cashMore: "Ver m\xE1s puntos de pago",
654
+ cashNote: "Al hacer el pedido te damos una ficha con la referencia y la fecha l\xEDmite. El pedido se confirma cuando pagas.",
655
+ secureCard: "Tus datos de tarjeta los captura directamente nuestro proveedor de pagos; la tienda nunca los ve.",
656
+ pickDeliveryFirst: "Elige primero la entrega para ver el total y pagar con tarjeta.",
657
+ updatingTotal: "Actualizando el total\u2026",
658
+ syncFailed: "No pudimos actualizar el total con tu entrega. Puedes continuar al sitio del proveedor para pagar con tarjeta.",
659
+ quoteChanged: "Las tarifas de env\xEDo se actualizaron. Revisa tu env\xEDo para ver el total.",
660
+ rebuildCart: "Volver a armar mi carrito",
661
+ noPaymentTitle: "Por ahora no hay formas de pago disponibles",
662
+ noPayment: "Intenta de nuevo en unos minutos o escr\xEDbenos para completar tu pedido.",
663
+ paymentNote: "El pago se procesa de forma segura con nuestro proveedor de pagos.",
664
+ options: {
665
+ card: "Tarjeta de cr\xE9dito o d\xE9bito",
666
+ cash: "Efectivo",
667
+ wallet: "Cuenta del proveedor de pagos",
668
+ credits: "Pagos sin tarjeta"
669
+ }
670
+ };
671
+ var EN = {
672
+ legend: "Payment method",
673
+ pay: "Pay",
674
+ placeOrder: "Place order",
675
+ payRedirect: "Continue to payment",
676
+ continue: "Continue",
677
+ retryAddress: "Save address and continue",
678
+ processing: "Processing\u2026",
679
+ redirectNote: "We'll take you to the provider's page to finish paying, then bring you back here.",
680
+ cashPoints: "Choose where to pay in cash",
681
+ cashMore: "Show more payment points",
682
+ cashNote: "When you place the order you get a slip with the reference and the deadline. The order is confirmed once you pay.",
683
+ secureCard: "Your card details are captured directly by our payment provider; the shop never sees them.",
684
+ pickDeliveryFirst: "Choose delivery first to see the total and pay by card.",
685
+ updatingTotal: "Updating the total\u2026",
686
+ syncFailed: "We couldn't update the total with your delivery. You can continue to the provider's site to pay by card.",
687
+ quoteChanged: "Shipping rates were updated. Check your delivery to see the total.",
688
+ rebuildCart: "Rebuild my cart",
689
+ noPaymentTitle: "No payment methods are available right now",
690
+ noPayment: "Try again in a few minutes or contact us to complete your order.",
691
+ paymentNote: "Payment is processed securely by our payment provider.",
692
+ options: {
693
+ card: "Credit or debit card",
694
+ cash: "Cash",
695
+ wallet: "Payment provider account",
696
+ credits: "Pay without a card"
697
+ }
698
+ };
699
+ function paymentMethodMessages(locale, overrides) {
700
+ const base = (locale ?? "es-MX").toLowerCase().startsWith("en") ? EN : ES;
701
+ if (!overrides) return base;
702
+ const { options, ...rest } = overrides;
703
+ return { ...base, ...rest, options: { ...base.options, ...options } };
645
704
  }
646
- function paymentCsp(clients, options = {}) {
647
- const list = clients.filter((c) => !!c);
648
- const pick = (k) => list.map((c) => c.csp?.[k]);
649
- const nonce = options.nonce && /^[A-Za-z0-9+/=_-]+$/.test(options.nonce) ? options.nonce : void 0;
650
- const sdkOrigins = list.flatMap((c) => {
651
- try {
652
- const u = new URL(c.sdk_url);
653
- return u.protocol === "https:" ? [u.origin] : [];
654
- } catch {
655
- return [];
705
+ var PAYMENT_CHOICE_FIELD = "payment_choice";
706
+ var CASH_POINT_FIELD = "cash_point";
707
+ function formFields(form) {
708
+ const out = {};
709
+ if (!form) return out;
710
+ for (const [k, v] of new FormData(form).entries()) if (typeof v === "string") out[k] = v;
711
+ return out;
712
+ }
713
+ var useHydrated = () => useSyncExternalStore(
714
+ () => () => {
715
+ },
716
+ () => true,
717
+ () => false
718
+ );
719
+ function PaymentMethodSection(props) {
720
+ const {
721
+ choices,
722
+ amount,
723
+ scope,
724
+ formRef,
725
+ payUrl,
726
+ statusUrl,
727
+ delivery = "",
728
+ deliveryReady = true,
729
+ syncDelivery,
730
+ addressFirst = false,
731
+ retryAddress = false,
732
+ blocked = false,
733
+ busy = false,
734
+ invalid,
735
+ nonce,
736
+ methodLabel,
737
+ icons,
738
+ brandMarks = true,
739
+ cardBrands = [],
740
+ renderAmount,
741
+ rebuildHref,
742
+ renderLink,
743
+ onDone,
744
+ onAmountChanged,
745
+ onEvent,
746
+ classNames: cx = {},
747
+ testIds = {},
748
+ hideSubmit,
749
+ brickProps
750
+ } = props;
751
+ const locale = useResolvedLocale(props.locale);
752
+ const m = useMemo(() => paymentMethodMessages(locale, props.messages), [locale, props.messages]);
753
+ const hydrated = useHydrated();
754
+ const [choiceValue2, setChoiceValue] = useState(props.defaultChoice ?? choices.defaultValue);
755
+ const selected = choices.choices.find((c) => c.value === choiceValue2) ?? null;
756
+ const noPayment = choices.choices.length === 0;
757
+ const tid = (k) => testIds[k] ? { "data-testid": testIds[k] } : {};
758
+ const [fallback, setFallback] = useState(false);
759
+ const [ready, setReady] = useState(false);
760
+ const [processing, setProcessing] = useState(false);
761
+ const [expired, setExpired] = useState(false);
762
+ const brick = useRef(null);
763
+ const cardChosen = selected?.mode === "card" && !retryAddress && !addressFirst;
764
+ const cardActive = hydrated && cardChosen && !fallback;
765
+ const wantSync = hydrated && selected !== null && !addressFirst && !retryAddress && deliveryReady && Boolean(syncDelivery);
766
+ const [sync, setSync] = useState(null);
767
+ const syncRef = useRef(syncDelivery);
768
+ syncRef.current = syncDelivery;
769
+ useEffect(() => {
770
+ if (!wantSync || !syncRef.current) return;
771
+ if (sync?.key === delivery && sync.ok) return;
772
+ let cancelled = false;
773
+ syncRef.current(delivery).then(
774
+ (ok) => !cancelled && setSync(ok === "requote" ? { key: delivery, ok: false, requote: true } : { key: delivery, ok }),
775
+ () => !cancelled && setSync({ key: delivery, ok: false })
776
+ );
777
+ return () => {
778
+ cancelled = true;
779
+ };
780
+ }, [wantSync, delivery]);
781
+ const settled = sync?.key === delivery;
782
+ const synced = !syncDelivery || settled && sync.ok;
783
+ const requote = wantSync && settled && sync.requote === true;
784
+ const syncFailed = wantSync && settled && !sync.ok && !requote;
785
+ const brickReady = cardActive && deliveryReady && synced && !syncFailed;
786
+ const transport = useMemo(
787
+ () => props.transport ?? createFetchTransport(payUrl, {
788
+ ...statusUrl ? { refreshUrl: statusUrl } : {},
789
+ buildBody: (request) => ({ ...request, fields: formFields(formRef.current) })
790
+ }),
791
+ [props.transport, payUrl, statusUrl, formRef]
792
+ );
793
+ const handleEvent = (e) => {
794
+ if (e.type === "form_ready") setReady(true);
795
+ if (e.type === "submit") setProcessing(true);
796
+ if (e.type === "tokenize_error" || e.type === "retry") setProcessing(e.type === "retry");
797
+ if (e.type === "result" && e.status === "rejected") setProcessing(false);
798
+ if (e.type === "error") {
799
+ setProcessing(false);
800
+ if (e.kind === "price_mismatch") onAmountChanged?.();
801
+ if (e.kind === "expired") setExpired(true);
656
802
  }
657
- });
658
- const dir = (name, values) => `${name} ${values.join(" ")}`;
659
- const parts = [
660
- "default-src 'self'",
661
- dir("script-src", ["'self'", ...nonce ? [`'nonce-${nonce}'`] : [], ...origins(sdkOrigins, ...pick("script"), options.extra?.script)]),
662
- dir("frame-src", origins(...pick("frame"), options.extra?.frame).length ? origins(...pick("frame"), options.extra?.frame) : ["'none'"]),
663
- dir("connect-src", ["'self'", ...origins(...pick("connect"), options.extra?.connect)]),
664
- dir("img-src", ["'self'", "data:", ...origins(...pick("img"), options.extra?.img)]),
665
- "style-src 'self' 'unsafe-inline'",
666
- dir("form-action", ["'self'", ...origins(...pick("form"), options.extra?.form)]),
667
- "frame-ancestors 'none'",
668
- "base-uri 'self'",
669
- "object-src 'none'"
670
- ];
671
- if (options.reportUri && /^(https:\/\/|\/)[^\s;,]+$/.test(options.reportUri)) parts.push(`report-uri ${options.reportUri}`);
672
- return parts.join("; ");
803
+ onEvent?.(e);
804
+ };
805
+ const total = wantSync && (!settled || requote) ? null : renderAmount ? renderAmount(amount) : formatMoney(amount, locale);
806
+ const label = retryAddress ? m.retryAddress : addressFirst ? m.continue : selected?.mode === "plain" || !selected ? /* @__PURE__ */ jsxs(Fragment, { children: [
807
+ m.pay,
808
+ total ? /* @__PURE__ */ jsxs(Fragment, { children: [
809
+ " ",
810
+ total
811
+ ] }) : null
812
+ ] }) : selected.mode === "redirect" || selected.mode === "card" && (fallback || syncFailed) ? m.payRedirect : /* @__PURE__ */ jsxs(Fragment, { children: [
813
+ m.placeOrder,
814
+ total ? /* @__PURE__ */ jsxs(Fragment, { children: [
815
+ " ",
816
+ total
817
+ ] }) : null
818
+ ] });
819
+ function onPayClick(event) {
820
+ if (!cardActive || syncFailed) return;
821
+ event.preventDefault();
822
+ const form = formRef.current;
823
+ if (form && !form.reportValidity()) return;
824
+ if (brickReady) void brick.current?.submit();
825
+ }
826
+ const cardNotice = (k, node) => k === "syncFailed" ? /* @__PURE__ */ jsx("p", { role: "alert", className: cx.alert, "data-sf-pay-notice": "sync-failed", ...tid("syncFailed"), children: node }) : /* @__PURE__ */ jsx("p", { role: "status", className: cx.status, "data-sf-pay-notice": k, ...k === "syncing" ? tid("syncing") : {}, children: node });
827
+ const Link = renderLink ?? (({ href, className, children, testId }) => /* @__PURE__ */ jsx("a", { href, className, ...testId ? { "data-testid": testId } : {}, children }));
828
+ return /* @__PURE__ */ jsxs("fieldset", { id: "pago", className: cx.root, "data-sf-pay-method": true, children: [
829
+ /* @__PURE__ */ jsx("legend", { className: cx.legend, children: m.legend }),
830
+ choices.choices.map((choice) => {
831
+ const { label: rowLabel, hint } = rowText(choice, m, methodLabel);
832
+ const checked = choice.value === choiceValue2;
833
+ const slot = choice.option ?? "plain";
834
+ const icon = icons?.[slot] ?? (brandMarks ? defaultIcon(choice) : null);
835
+ const marks = brandMarks ? rowMarks(choice, cardBrands) : [];
836
+ return /* @__PURE__ */ jsxs("div", { className: cx.choice, "data-sf-pay-choice": true, children: [
837
+ /* @__PURE__ */ jsxs("label", { className: cx.radioLabel, children: [
838
+ /* @__PURE__ */ jsx(
839
+ "input",
840
+ {
841
+ type: "radio",
842
+ name: PAYMENT_CHOICE_FIELD,
843
+ value: choice.value,
844
+ checked,
845
+ onChange: () => setChoiceValue(choice.value),
846
+ "aria-invalid": invalid?.has("payment_method") || void 0,
847
+ "data-mode": choice.mode,
848
+ required: true,
849
+ className: cx.radio,
850
+ ...tid("method")
851
+ }
852
+ ),
853
+ icon ? /* @__PURE__ */ jsx("span", { className: cx.icon, "aria-hidden": "true", children: icon }) : null,
854
+ /* @__PURE__ */ jsxs("span", { className: cx.labelText, children: [
855
+ rowLabel,
856
+ hint ? /* @__PURE__ */ jsxs("span", { className: cx.hint, children: [
857
+ " ",
858
+ hint
859
+ ] }) : null
860
+ ] }),
861
+ marks.length ? /* @__PURE__ */ jsx("span", { className: cx.brands, "data-sf-pay-brands": choice.option ?? "plain", "aria-hidden": "true", children: marks.map((mk) => /* @__PURE__ */ jsx(BrandMark, { brand: mk.key, logoUrl: mk.logoUrl ?? null, size: 20 }, mk.key)) }) : null
862
+ ] }),
863
+ /* @__PURE__ */ jsx(ChoicePanel, { choice, m, invalid, cx, tid, hidden: hydrated && !checked, marks: brandMarks })
864
+ ] }, choice.value);
865
+ }),
866
+ noPayment ? /* @__PURE__ */ jsxs("div", { role: "alert", className: cx.alert, "data-sf-pay-notice": "no-payment", ...tid("noPayment"), children: [
867
+ /* @__PURE__ */ jsx("p", { children: /* @__PURE__ */ jsx("strong", { children: m.noPaymentTitle }) }),
868
+ /* @__PURE__ */ jsx("p", { children: m.noPayment })
869
+ ] }) : null,
870
+ cardChosen && hydrated && choices.cardClient ? /* @__PURE__ */ jsxs("div", { className: cx.brickWrap, "data-sf-pay-card": true, ...tid("card"), children: [
871
+ fallback ? null : !deliveryReady ? cardNotice("pickDelivery", m.pickDeliveryFirst) : syncFailed ? cardNotice("syncFailed", m.syncFailed) : requote ? cardNotice("requote", m.quoteChanged) : !synced ? cardNotice("syncing", m.updatingTotal) : null,
872
+ brickReady || fallback ? /* @__PURE__ */ jsx(
873
+ PaymentBrick,
874
+ {
875
+ ...brickProps,
876
+ ref: brick,
877
+ client: choices.cardClient,
878
+ amount,
879
+ transport,
880
+ ...nonce ? { nonce } : {},
881
+ locale,
882
+ ...scope ? { scope } : {},
883
+ enabled: brickReady,
884
+ ...cx.brick ? { className: cx.brick } : {},
885
+ onEvent: handleEvent,
886
+ onFallback: () => setFallback(true),
887
+ onResult: (o) => {
888
+ if (o.kind === "approved" || o.kind === "in_review" || o.kind === "voucher") onDone(o);
889
+ }
890
+ }
891
+ ) : null,
892
+ /* @__PURE__ */ jsx("p", { className: cx.note, children: m.secureCard }),
893
+ expired && rebuildHref ? Link({ href: rebuildHref, ...cx.rebuild ? { className: cx.rebuild } : {}, children: m.rebuildCart, ...testIds.rebuild ? { testId: testIds.rebuild } : {} }) : null
894
+ ] }) : null,
895
+ noPayment || choices.choices.some((c) => c.option) ? null : /* @__PURE__ */ jsx("p", { className: cx.note, children: m.paymentNote }),
896
+ hideSubmit ? null : /* @__PURE__ */ jsx(
897
+ "button",
898
+ {
899
+ type: "submit",
900
+ onClick: onPayClick,
901
+ className: cx.submit,
902
+ disabled: busy || blocked,
903
+ "aria-disabled": blocked || brickReady && (!ready || processing) || void 0,
904
+ "aria-busy": processing || void 0,
905
+ "data-sf-pay-method-submit": true,
906
+ ...tid("submit"),
907
+ children: busy || processing ? m.processing : label
908
+ }
909
+ )
910
+ ] });
911
+ }
912
+ function rowText(choice, m, methodLabel) {
913
+ if (choice.mode === "plain") return methodLabel ? methodLabel(choice.methodKey) : { label: choice.methodKey };
914
+ return { label: choice.label ?? (choice.option ? m.options[choice.option] : void 0) ?? choice.option ?? choice.methodKey };
673
915
  }
674
- function paymentCspHeaderName(reportOnly) {
675
- return reportOnly ? "Content-Security-Policy-Report-Only" : "Content-Security-Policy";
916
+ function ChoicePanel({
917
+ choice,
918
+ m,
919
+ invalid,
920
+ cx,
921
+ tid,
922
+ hidden,
923
+ marks = true
924
+ }) {
925
+ if (choice.mode === "redirect") {
926
+ return /* @__PURE__ */ jsx("p", { className: cx.panel, hidden, "data-sf-pay-panel": "redirect", ...tid("redirectNote"), children: m.redirectNote });
927
+ }
928
+ if (choice.mode !== "cash") return null;
929
+ const main = choice.points.filter((p) => p.group === "main");
930
+ const more = choice.points.filter((p) => p.group !== "main");
931
+ const row = (p, i, first) => /* @__PURE__ */ jsxs("label", { className: cx.cashPoint, "data-sf-pay-point": true, children: [
932
+ /* @__PURE__ */ jsx("input", { type: "radio", name: CASH_POINT_FIELD, value: p.id, defaultChecked: first && i === 0, className: cx.cashPointInput, "aria-invalid": invalid?.has("cash_point") || void 0 }),
933
+ marks ? /* @__PURE__ */ jsx(BrandMark, { brand: p.payment_point || p.id, logoUrl: p.logo_url ?? null, size: 22 }) : null,
934
+ /* @__PURE__ */ jsx("span", { children: p.label })
935
+ ] }, p.id);
936
+ return /* @__PURE__ */ jsxs("div", { className: cx.panel, hidden, "data-sf-pay-panel": "cash", ...tid("cash"), children: [
937
+ /* @__PURE__ */ jsxs("fieldset", { children: [
938
+ /* @__PURE__ */ jsx("legend", { children: m.cashPoints }),
939
+ /* @__PURE__ */ jsx("div", { "data-sf-pay-points": true, children: main.map((p, i) => row(p, i, true)) }),
940
+ more.length ? /* @__PURE__ */ jsxs("details", { children: [
941
+ /* @__PURE__ */ jsx("summary", { className: cx.cashMore, style: { minHeight: 44 }, children: m.cashMore }),
942
+ /* @__PURE__ */ jsx("div", { "data-sf-pay-points": true, children: more.map((p, i) => row(p, i, false)) })
943
+ ] }) : null
944
+ ] }),
945
+ /* @__PURE__ */ jsx("p", { className: cx.note, children: m.cashNote })
946
+ ] });
947
+ }
948
+ var glyph = (d) => /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", width: "24", height: "24", fill: "none", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round", focusable: "false", "data-sf-pay-glyph": true, children: /* @__PURE__ */ jsx("path", { d }) });
949
+ var CARD_GLYPH = "M3 6.5h18v11H3zM3 10h18M6.5 14.5h4";
950
+ var CASH_GLYPH = "M3 7h18v10H3zM12 14.5a2.5 2.5 0 1 0 0-5a2.5 2.5 0 0 0 0 5zM6 10v4M18 10v4";
951
+ function defaultIcon(choice) {
952
+ if (choice.option === "card") return glyph(CARD_GLYPH);
953
+ if (choice.option === "cash") return glyph(CASH_GLYPH);
954
+ return findBrand(choice.methodKey) ? /* @__PURE__ */ jsx(BrandMark, { brand: choice.methodKey, size: 24 }) : null;
955
+ }
956
+ function rowMarks(choice, cardBrands) {
957
+ if (choice.option === "card") return cardBrands.map((key) => ({ key }));
958
+ if (choice.option === "cash") {
959
+ const seen = /* @__PURE__ */ new Set();
960
+ const out = [];
961
+ for (const p of choice.points) {
962
+ const key = p.payment_point || p.id;
963
+ if (p.group !== "main" || seen.has(key)) continue;
964
+ seen.add(key);
965
+ out.push({ key, logoUrl: p.logo_url ?? null });
966
+ if (out.length === 4) break;
967
+ }
968
+ return out;
969
+ }
970
+ return [];
676
971
  }
677
972
 
678
- export { MERCADOPAGO_BRICKS_KIND, PAYMENT_THEME_TOKENS, PaymentBrick, PaymentChallenge, PaymentHttpError, VoucherCard, createFetchTransport, loadPaymentSdk, mercadoPagoBricksAdapter, paymentCsp, paymentCspHeaderName, readPaymentTheme, resetPaymentSdkCache, sanitizeMercadoPagoFormData, useEmbeddedPayment };
973
+ export { CASH_POINT_FIELD, MERCADOPAGO_BRICKS_KIND, PAYMENT_CHOICE_FIELD, PAYMENT_THEME_TOKENS, PaymentBrick, PaymentChallenge, PaymentHttpError, PaymentMethodSection, VoucherCard, createFetchTransport, formFields, loadPaymentSdk, mercadoPagoBricksAdapter, paymentMethodMessages, readPaymentTheme, resetPaymentSdkCache, sanitizeMercadoPagoFormData, useEmbeddedPayment };
679
974
  //# sourceMappingURL=payments.js.map
680
975
  //# sourceMappingURL=payments.js.map