@apextelemed/partner-core 0.25.0-dev.91 → 0.25.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.
@@ -804,15 +804,172 @@ function useCatalogAvailability(ids, state) {
804
804
  function catalogUnavailableMessage(itemName, state) {
805
805
  return `${itemName} isn\u2019t available for delivery to ${stateLabel(state)}.`;
806
806
  }
807
+ var collectJsLoad = null;
808
+ function loadCollectJs(src, tokenizationKey) {
809
+ if (collectJsLoad?.src === src) return collectJsLoad.promise;
810
+ const promise = new Promise((resolve, reject) => {
811
+ if (typeof document === "undefined") {
812
+ reject(new Error("No document"));
813
+ return;
814
+ }
815
+ const script = document.createElement("script");
816
+ script.src = src;
817
+ script.async = true;
818
+ script.dataset.tokenizationKey = tokenizationKey;
819
+ script.dataset.variant = "inline";
820
+ script.onload = () => window.CollectJS ? resolve(window.CollectJS) : reject(new Error("Collect.js loaded without CollectJS"));
821
+ script.onerror = () => reject(new Error("Collect.js failed to load"));
822
+ document.head.appendChild(script);
823
+ });
824
+ collectJsLoad = { src, promise };
825
+ promise.catch(() => {
826
+ if (collectJsLoad?.promise === promise) collectJsLoad = null;
827
+ });
828
+ return promise;
829
+ }
830
+ var hostedFieldSeq = 0;
831
+ function selectorFor(el) {
832
+ if (!el.id) el.id = `apc-hosted-card-${++hostedFieldSeq}`;
833
+ const escape = typeof CSS !== "undefined" && typeof CSS.escape === "function" ? CSS.escape : (s) => s.replace(/[^a-zA-Z0-9_-]/g, "\\$&");
834
+ return `#${escape(el.id)}`;
835
+ }
836
+ var FIELD_ORDER = ["ccnumber", "ccexp", "cvv"];
837
+ var FIELD_LABEL = {
838
+ ccnumber: "card number",
839
+ ccexp: "expiration date",
840
+ cvv: "CVV"
841
+ };
842
+ var OUR_FIELD = { ccnumber: "number", ccexp: "expiry", cvv: "cvv" };
843
+ var GENERIC_FONTS = /^(serif|sans-serif|monospace|cursive|fantasy|system-ui|math|emoji|fangsong|inherit|initial|-apple-system|blinkmacsystemfont|ui-[a-z-]+)$/i;
844
+ function googleFontFor(fontFamily, fontWeight) {
845
+ const first = fontFamily.split(",")[0]?.trim().replace(/^['"]|['"]$/g, "");
846
+ if (!first || GENERIC_FONTS.test(first)) return void 0;
847
+ const weight = /^\d{3}$/.test(fontWeight) ? fontWeight : "400";
848
+ return `${first}:${weight}`;
849
+ }
850
+ function cssVar(cs, names, fallback) {
851
+ for (const n of names) {
852
+ const v = cs?.getPropertyValue(n).trim();
853
+ if (v) return v;
854
+ }
855
+ return fallback;
856
+ }
857
+ var NO_OUTLINE = { "outline-style": "none", "outline-width": "0", "outline-color": "transparent" };
858
+ var COLLECT_TIMEOUT_MS = 2e4;
807
859
  function useCardTokenizer() {
808
860
  const [config, setConfig] = createSignal(null);
809
861
  const [scriptLoaded, setScriptLoaded] = createSignal(false);
810
862
  const [error, setError] = createSignal(null);
863
+ const [collectJs, setCollectJs] = createSignal(null);
864
+ const [hostedEls, setHostedEls] = createSignal({});
865
+ const [hostedFieldsLive, setHostedFieldsLive] = createSignal(false);
866
+ let pendingNmi = null;
867
+ const invalidDuringSubmit = /* @__PURE__ */ new Map();
868
+ let invalidReport = null;
869
+ const hostedFields = () => config()?.provider === "nmi";
811
870
  const ready = () => {
812
871
  const cfg = config();
813
872
  if (!cfg) return false;
814
- return cfg.provider === "authorizenet" ? scriptLoaded() : true;
873
+ if (cfg.provider === "authorizenet") return scriptLoaded();
874
+ if (cfg.provider === "nmi") return hostedFieldsLive();
875
+ return true;
815
876
  };
877
+ const listeners = /* @__PURE__ */ new Map();
878
+ function registerHostedField(field, el) {
879
+ if (!el) return;
880
+ if (!listeners.has(el)) {
881
+ const onFocus = () => el.setAttribute("data-focused", "");
882
+ const onBlur = () => el.removeAttribute("data-focused");
883
+ el.addEventListener("focus", onFocus, true);
884
+ el.addEventListener("blur", onBlur, true);
885
+ listeners.set(el, () => {
886
+ el.removeEventListener("focus", onFocus, true);
887
+ el.removeEventListener("blur", onBlur, true);
888
+ });
889
+ }
890
+ setHostedEls((prev) => prev[field] === el ? prev : { ...prev, [field]: el });
891
+ }
892
+ onCleanup(() => {
893
+ for (const off of listeners.values()) off();
894
+ listeners.clear();
895
+ });
896
+ function settleNmi(outcome) {
897
+ const p = pendingNmi;
898
+ if (!p) return;
899
+ pendingNmi = null;
900
+ if (invalidReport) clearTimeout(invalidReport);
901
+ invalidReport = null;
902
+ invalidDuringSubmit.clear();
903
+ clearTimeout(p.timer);
904
+ if ("token" in outcome) p.resolve(outcome.token);
905
+ else p.reject(outcome.error);
906
+ }
907
+ createEffect(() => {
908
+ const cj = collectJs();
909
+ const els = hostedEls();
910
+ if (!cj || !els.number || !els.expiry || !els.cvv) return;
911
+ setHostedFieldsLive(false);
912
+ try {
913
+ const cs = typeof getComputedStyle === "function" ? getComputedStyle(els.number) : null;
914
+ const text = cs ? { color: cs.color, "font-size": cs.fontSize, "font-family": cs.fontFamily, "font-weight": cs.fontWeight } : {};
915
+ const googleFont = cs ? googleFontFor(cs.fontFamily, cs.fontWeight) : void 0;
916
+ const danger = cssVar(cs, ["--apc-card-danger", "--app-flow-danger"], "#c0392b");
917
+ cj.configure({
918
+ variant: "inline",
919
+ styleSniffer: false,
920
+ ...googleFont ? { googleFont } : {},
921
+ // Collect.js keeps only the CSS properties it allows and silently drops
922
+ // the rest: the `outline` and `background` SHORTHANDS are dropped (which
923
+ // left Chrome's black focus box in the field), their longhands survive.
924
+ // The container shows focus instead (`data-focused`, set below).
925
+ customCss: { ...text, border: "none", ...NO_OUTLINE, "background-color": "transparent", padding: "0", height: "100%" },
926
+ placeholderCss: cs ? { color: cs.color, opacity: "0.4" } : {},
927
+ invalidCss: { color: danger },
928
+ validCss: {},
929
+ focusCss: { ...NO_OUTLINE, border: "none", "box-shadow": "none" },
930
+ fields: {
931
+ ccnumber: { selector: selectorFor(els.number), title: "Card number", placeholder: "1234 1234 1234 1234", enableCardBrandPreviews: false },
932
+ ccexp: { selector: selectorFor(els.expiry), title: "Expiration date", placeholder: "MM / YY" },
933
+ cvv: { display: "required", selector: selectorFor(els.cvv), title: "CVV", placeholder: "123" }
934
+ },
935
+ // Fires once every iframe has loaded and can take input.
936
+ fieldsAvailableCallback: () => setHostedFieldsLive(true),
937
+ // A field that fails Collect.js's own check (bad number, past expiry,
938
+ // empty) during a submit stops the submit: Collect.js never calls
939
+ // `callback` then, so say why instead of waiting it out.
940
+ // Collect.js reports every bad field, in no particular order (CVV
941
+ // first, seen live), so collect them for a moment and name the first
942
+ // one on screen.
943
+ validationCallback: (field, valid, message) => {
944
+ const container = hostedEls()[OUR_FIELD[field]];
945
+ if (container) {
946
+ if (valid) container.removeAttribute("data-invalid");
947
+ else container.setAttribute("data-invalid", "");
948
+ }
949
+ if (valid || !pendingNmi) return;
950
+ invalidDuringSubmit.set(field, message);
951
+ if (invalidReport) return;
952
+ invalidReport = setTimeout(() => {
953
+ invalidReport = null;
954
+ const first = FIELD_ORDER.find((f) => invalidDuringSubmit.has(f)) ?? [...invalidDuringSubmit.keys()][0];
955
+ const msg = invalidDuringSubmit.get(first) ?? "";
956
+ invalidDuringSubmit.clear();
957
+ const label = FIELD_LABEL[first] ?? "card details";
958
+ settleNmi({ error: new Error(msg && !/^field is empty$/i.test(msg) ? `Check the ${label}: ${msg}` : `Enter the ${label}.`) });
959
+ }, 30);
960
+ },
961
+ callback: (response) => {
962
+ if (response?.token) settleNmi({ token: { token: response.token } });
963
+ else settleNmi({ error: new Error("Card processing failed. Please check your card details.") });
964
+ },
965
+ timeoutDuration: COLLECT_TIMEOUT_MS,
966
+ timeoutCallback: () => settleNmi({ error: new Error("The payment form took too long to respond. Please try again.") })
967
+ });
968
+ } catch (err) {
969
+ fail("The secure card form could not be set up. Please refresh the page.", err);
970
+ }
971
+ });
972
+ onCleanup(() => settleNmi({ error: new Error("The payment form was closed.") }));
816
973
  const status = () => error() ? "failed" : ready() ? "ready" : "loading";
817
974
  function fail(userMessage, logDetail) {
818
975
  console.warn(`[useCardTokenizer] ${userMessage}`, logDetail ?? "");
@@ -833,6 +990,18 @@ function useCardTokenizer() {
833
990
  setConfig({ provider: "mxmerchant" });
834
991
  return;
835
992
  }
993
+ if (raw.provider === "nmi") {
994
+ if (typeof raw.tokenizationKey !== "string" || !raw.tokenizationKey || typeof raw.collectJsUrl !== "string" || !raw.collectJsUrl) {
995
+ fail("Payments are not fully configured for this site yet. Please contact support.");
996
+ return;
997
+ }
998
+ setConfig({ provider: "nmi", tokenizationKey: raw.tokenizationKey, collectJsUrl: raw.collectJsUrl });
999
+ loadCollectJs(raw.collectJsUrl, raw.tokenizationKey).then(
1000
+ setCollectJs,
1001
+ (err) => fail("The secure payment library could not load. Check your connection (or ad blocker) and refresh the page.", err)
1002
+ );
1003
+ return;
1004
+ }
836
1005
  if (!raw.apiLoginId || !raw.clientKey) {
837
1006
  fail("Payments are not fully configured for this site yet. Please contact support.");
838
1007
  return;
@@ -972,13 +1141,32 @@ function useCardTokenizer() {
972
1141
  lastMxCard = { key, token };
973
1142
  return token;
974
1143
  }
1144
+ function tokenizeNmi() {
1145
+ const cj = collectJs();
1146
+ if (!cj || !hostedFieldsLive()) return Promise.reject(new Error("The secure card form is still loading. Please try again in a moment."));
1147
+ if (pendingNmi) return Promise.reject(new Error("Your card is already being processed."));
1148
+ return new Promise((resolve, reject) => {
1149
+ const timer = setTimeout(
1150
+ () => settleNmi({ error: new Error("The payment form took too long to respond. Please try again.") }),
1151
+ COLLECT_TIMEOUT_MS + 5e3
1152
+ );
1153
+ pendingNmi = { resolve, reject, timer };
1154
+ try {
1155
+ cj.startPaymentRequest();
1156
+ } catch (err) {
1157
+ settleNmi({ error: new Error("Card processing failed. Please try again.") });
1158
+ console.warn("[useCardTokenizer] Collect.js startPaymentRequest threw", err);
1159
+ }
1160
+ });
1161
+ }
975
1162
  function tokenize(card) {
976
1163
  const cfg = config();
977
1164
  if (!cfg) return Promise.reject(new Error("Payment configuration not loaded. Please refresh."));
1165
+ if (cfg.provider === "nmi") return tokenizeNmi();
978
1166
  if (cfg.provider === "mxmerchant") return tokenizeMxMerchant(card);
979
1167
  return cfg.provider === "quickbooks" ? tokenizeQuickBooks(card, cfg) : tokenizeAcceptJs(card, cfg);
980
1168
  }
981
- return { ready, status, error, tokenize };
1169
+ return { ready, status, error, tokenize, hostedFields, registerHostedField };
982
1170
  }
983
1171
 
984
1172
  // src/flows/checkout.ts
@@ -1137,9 +1325,11 @@ function useCheckoutFlow(options = {}) {
1137
1325
  }
1138
1326
  });
1139
1327
  function validateCard() {
1140
- if (!cardNumberRaw().replace(/\s/g, "").trim()) return "Card number is required.";
1141
- if (!expiryRaw().trim()) return "Expiration date is required.";
1142
- if (!cvvRaw().trim()) return "CVV is required.";
1328
+ if (!accept.hostedFields()) {
1329
+ if (!cardNumberRaw().replace(/\s/g, "").trim()) return "Card number is required.";
1330
+ if (!expiryRaw().trim()) return "Expiration date is required.";
1331
+ if (!cvvRaw().trim()) return "CVV is required.";
1332
+ }
1143
1333
  return null;
1144
1334
  }
1145
1335
  async function submit() {
@@ -1248,6 +1438,8 @@ function useCheckoutFlow(options = {}) {
1248
1438
  expiry: expiryRaw,
1249
1439
  setExpiry: (v) => setExpiryRaw(formatExpiry(v)),
1250
1440
  cvv: cvvRaw,
1441
+ hostedCardFields: accept.hostedFields,
1442
+ registerCardField: accept.registerHostedField,
1251
1443
  setCvv: (v) => setCvvRaw(formatCvv(v)),
1252
1444
  paymentError,
1253
1445
  processing,
@@ -1346,9 +1538,11 @@ function useCartCheckoutFlow() {
1346
1538
  setOutcome({ kind: "in_progress" });
1347
1539
  });
1348
1540
  function validateCard() {
1349
- if (!cardNumberRaw().replace(/\s/g, "").trim()) return "Card number is required.";
1350
- if (!expiryRaw().trim()) return "Expiration date is required.";
1351
- if (!cvvRaw().trim()) return "CVV is required.";
1541
+ if (!accept.hostedFields()) {
1542
+ if (!cardNumberRaw().replace(/\s/g, "").trim()) return "Card number is required.";
1543
+ if (!expiryRaw().trim()) return "Expiration date is required.";
1544
+ if (!cvvRaw().trim()) return "CVV is required.";
1545
+ }
1352
1546
  return null;
1353
1547
  }
1354
1548
  function orderMatchesSubmission(order, submitted) {
@@ -1505,6 +1699,8 @@ function useCartCheckoutFlow() {
1505
1699
  expiry: expiryRaw,
1506
1700
  setExpiry: (v) => setExpiryRaw(formatExpiry(v)),
1507
1701
  cvv: cvvRaw,
1702
+ hostedCardFields: accept.hostedFields,
1703
+ registerCardField: accept.registerHostedField,
1508
1704
  setCvv: (v) => setCvvRaw(formatCvv(v)),
1509
1705
  paymentError,
1510
1706
  processing,
@@ -1688,9 +1884,11 @@ function useSignupFlow(options) {
1688
1884
  if (!zip().trim()) return "ZIP code is required.";
1689
1885
  if (!/^\d{5}(-\d{4})?$/.test(zip().trim())) return "Enter a valid ZIP code.";
1690
1886
  } else if (s === 2) {
1691
- if (!cardNumberRaw().trim()) return "Card number is required.";
1692
- if (!expiryRaw().trim()) return "Expiration date is required.";
1693
- if (!cvvRaw().trim()) return "CVV is required.";
1887
+ if (!accept.hostedFields()) {
1888
+ if (!cardNumberRaw().trim()) return "Card number is required.";
1889
+ if (!expiryRaw().trim()) return "Expiration date is required.";
1890
+ if (!cvvRaw().trim()) return "CVV is required.";
1891
+ }
1694
1892
  }
1695
1893
  return null;
1696
1894
  }
@@ -1879,6 +2077,8 @@ function useSignupFlow(options) {
1879
2077
  expiry: expiryRaw,
1880
2078
  setExpiry: (v) => setExpiryRaw(formatExpiry(v)),
1881
2079
  cvv: cvvRaw,
2080
+ hostedCardFields: accept.hostedFields,
2081
+ registerCardField: accept.registerHostedField,
1882
2082
  setCvv: (v) => setCvvRaw(formatCvv(v)),
1883
2083
  promoCode,
1884
2084
  setPromoCode,
@@ -2279,9 +2479,11 @@ function useSubscribeFlow(options) {
2279
2479
  );
2280
2480
  const addrErr = firstAddressError(a);
2281
2481
  if (addrErr) return addrErr;
2282
- if (!cardNumberRaw().trim()) return "Card number is required.";
2283
- if (!expiryRaw().trim()) return "Expiration date is required.";
2284
- if (!cvvRaw().trim()) return "CVV is required.";
2482
+ if (!accept.hostedFields()) {
2483
+ if (!cardNumberRaw().trim()) return "Card number is required.";
2484
+ if (!expiryRaw().trim()) return "Expiration date is required.";
2485
+ if (!cvvRaw().trim()) return "CVV is required.";
2486
+ }
2285
2487
  return null;
2286
2488
  }
2287
2489
  let awaitingAvailability = false;
@@ -2402,6 +2604,8 @@ function useSubscribeFlow(options) {
2402
2604
  expiry: expiryRaw,
2403
2605
  setExpiry: (v) => setExpiryRaw(formatExpiry(v)),
2404
2606
  cvv: cvvRaw,
2607
+ hostedCardFields: accept.hostedFields,
2608
+ registerCardField: accept.registerHostedField,
2405
2609
  setCvv: (v) => setCvvRaw(formatCvv(v)),
2406
2610
  submit
2407
2611
  };
@@ -3553,7 +3757,8 @@ function useUpdatePaymentMethodFlow(subscriptionId) {
3553
3757
  const setCardNumber = (v) => setCardNumberRaw(formatCardNumber(v));
3554
3758
  const setExpiry = (v) => setExpiryRaw(formatExpiry(v));
3555
3759
  const setCvv = (v) => setCvvRaw(formatCvv(v));
3556
- const canSubmit = () => accept.ready() && !submitting() && cardNumber().trim().length > 0 && expiry().trim().length > 0 && cvv().trim().length > 0;
3760
+ const canSubmit = () => accept.ready() && !submitting() && // Hosted fields (NMI): the card is in the gateway's iframes, which check it on submit.
3761
+ (accept.hostedFields() || cardNumber().trim().length > 0 && expiry().trim().length > 0 && cvv().trim().length > 0);
3557
3762
  async function submit() {
3558
3763
  const id = subscriptionId();
3559
3764
  if (!id) {
@@ -3590,6 +3795,8 @@ function useUpdatePaymentMethodFlow(subscriptionId) {
3590
3795
  expiry,
3591
3796
  setExpiry,
3592
3797
  cvv,
3798
+ hostedCardFields: accept.hostedFields,
3799
+ registerCardField: accept.registerHostedField,
3593
3800
  setCvv,
3594
3801
  ready: accept.ready,
3595
3802
  submitting,
@@ -6555,5 +6762,5 @@ function useSmsPreferences() {
6555
6762
  }
6556
6763
 
6557
6764
  export { ACCOUNT_SOURCE_LABEL, DEFAULT_COLOR_PALETTE, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, MATCH_DEPENDENT_WARNINGS, MATCH_HOW_LABEL, ORPHAN_REASON, PHONE_ERROR, READINESS_LABEL, SOURCE_FIELD_NOTE, SUPPORT_CATEGORIES, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, accountSource, addCatalogItemAsProduct, applyPriceDrafts, availableStateOptions, availableStates, bestOfferDiscount, buildFulfillmentRows, buildMatrixView, buildRefillView, buildSaveBody, buildStrengthRows, buildTimeline, buildTrackerView, buildTrackingUrl, canLeaveUnmatched, canOfferConversion, captureFunnelEmail, catalogUnavailableMessage, categoryColor, categoryLabel, classifyAddPharmacyError, classifyCatalogError, classifyConversionError, compareStrengths, createCatalogProduct, createFunnelTelemetry, deriveAttention, deriveCatalogAvailabilityDecision, deriveJourney, describeConversion, emailGateAnswered, explainFinding, findStoredDosePrice, firstAddressError, flaggedSubscribers, fmtDay, formatCalendarDate, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, formatUsPhone, groupDrugsByPharmacy, hasBlockers, hasConversion, hasErrors, hasStateRestrictions, initialMatches, intakeEvidence, invalidDraftKeys, isCatalogItemId, isCssColorValue, isImageAttachment, isLive, isQuestionVisible, isReconcilable, isValidUsPhone, lifecycleReason, liveDoses, lowestPrice, lowestSalePrice, markEmailGateAnswered, matchKey, matchProblem, matchesComplete, missingPrices, moveInOrder, needsReview, normalizeState, normalizeStates, offerBeatsPromo, offerDurationText, offerSummaryText, orphanKey, parseMoney, pharmacyIsOnProduct, pharmacyLabel, primarySubscription, readinessStatus, reconcileCartAgainstCatalog, reconcileCartLines, redeemResumeLink, removeStoredDosePrice, resetResumeRedemption, resolveCategoryColor, resolveStrengthPrices, resolveSurveyV2DrugIntent, salePriceForBase, skuBindingModeFor, sourceKey, sourceLabel, stateAvailabilityNote, strengthsChanged, subscribeToSupportTopic, toChoices, toTrackerRequest, uploadPrescriptionPhoto, upsertDosePrice, useAddPharmacy, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCardTokenizer, useCartCheckoutFlow, useCartReconcile, useCatalog, useCatalogAvailability, useCatalogConversion, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductCatalogEditor, useProductDetail, useRegisterFlow, useSignupFlow, useSmsConsent, useSmsPreferences, useSubscribeFlow, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress, visibleWarnings };
6558
- //# sourceMappingURL=POF64TCZ.js.map
6559
- //# sourceMappingURL=POF64TCZ.js.map
6765
+ //# sourceMappingURL=LIGPTJRM.js.map
6766
+ //# sourceMappingURL=LIGPTJRM.js.map