@apextelemed/partner-core 0.4.1 → 0.5.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.
Files changed (44) hide show
  1. package/dist/api/index.d.ts +2 -2
  2. package/dist/api/index.js +3 -3
  3. package/dist/api/index.jsx +5 -3
  4. package/dist/{cart-CBH8Em8f.d.ts → cart-BwUwSzWh.d.ts} +25 -2
  5. package/dist/chunk/{OJSQZEB3.js → 4W5ONAFF.js} +7 -6
  6. package/dist/chunk/4W5ONAFF.js.map +1 -0
  7. package/dist/chunk/{DS4E7FAI.js → 4YUUZ532.js} +14 -4
  8. package/dist/chunk/4YUUZ532.js.map +1 -0
  9. package/dist/chunk/{T6IKS76T.jsx → 5CXUPFZU.jsx} +33 -15
  10. package/dist/chunk/{EIXZJX6R.js → 6MDLP62Y.js} +34 -17
  11. package/dist/chunk/6MDLP62Y.js.map +1 -0
  12. package/dist/chunk/{NYLIUR7O.jsx → 6QC4BETO.jsx} +6 -5
  13. package/dist/chunk/{MN4GWQC4.js → 7COJH6FZ.js} +308 -155
  14. package/dist/chunk/7COJH6FZ.js.map +1 -0
  15. package/dist/chunk/{MEF3FUQB.jsx → B5RBZKAK.jsx} +1 -1
  16. package/dist/chunk/{STEVQZ6U.jsx → CXBPVQ7W.jsx} +2 -2
  17. package/dist/chunk/{NP4CMOLW.jsx → GGY7VMZ2.jsx} +5 -3
  18. package/dist/chunk/{2XJBOTK5.js → ITK5F5AI.js} +2 -2
  19. package/dist/chunk/{2XJBOTK5.js.map → ITK5F5AI.js.map} +1 -1
  20. package/dist/chunk/{YHWX4NMV.js → NNTB7KL5.js} +3 -3
  21. package/dist/chunk/{YHWX4NMV.js.map → NNTB7KL5.js.map} +1 -1
  22. package/dist/chunk/{XMYPS7PT.js → O4V2YXBF.js} +5 -4
  23. package/dist/chunk/O4V2YXBF.js.map +1 -0
  24. package/dist/chunk/{LPERM6T7.jsx → YPZVHEBG.jsx} +152 -20
  25. package/dist/chunk/{I46Y2J5W.jsx → Z2CR6WKF.jsx} +15 -2
  26. package/dist/{client-DUrhrzOG.d.ts → client-Cm6n4V0r.d.ts} +8 -0
  27. package/dist/flows/index.d.ts +49 -3
  28. package/dist/flows/index.js +6 -6
  29. package/dist/flows/index.jsx +10 -8
  30. package/dist/index/index.d.ts +3 -3
  31. package/dist/index/index.js +7 -7
  32. package/dist/index/index.jsx +13 -9
  33. package/dist/pages/index.d.ts +1 -1
  34. package/dist/pages/index.js +5 -5
  35. package/dist/pages/index.jsx +5 -5
  36. package/dist/stores/index.d.ts +1 -1
  37. package/dist/stores/index.js +2 -2
  38. package/dist/stores/index.jsx +2 -2
  39. package/package.json +1 -1
  40. package/dist/chunk/DS4E7FAI.js.map +0 -1
  41. package/dist/chunk/EIXZJX6R.js.map +0 -1
  42. package/dist/chunk/MN4GWQC4.js.map +0 -1
  43. package/dist/chunk/OJSQZEB3.js.map +0 -1
  44. package/dist/chunk/XMYPS7PT.js.map +0 -1
@@ -1,10 +1,10 @@
1
1
  import { Accessor, Resource } from 'solid-js';
2
- import { A as AddressVerifyResult, a4 as CheckoutAddress, aX as User, ag as DeliveryInfo, aE as RenewalStatus, ax as PendingRenewalSurvey, q as AdminLifecycleBucket, i as AdminCustomerOverview, D as AdminSubscriptionDetail, k as AdminCustomerRequest, a3 as CatalogProduct, N as AffiliateConversion, R as AffiliateDownlineMember, O as AffiliateDashboardLinks, Q as AffiliateDashboardStats, aA as PromoValidationResponse } from '../client-DUrhrzOG.js';
2
+ import { A as AddressVerifyResult, a4 as CheckoutAddress, aX as User, ag as DeliveryInfo, aE as RenewalStatus, ax as PendingRenewalSurvey, q as AdminLifecycleBucket, i as AdminCustomerOverview, D as AdminSubscriptionDetail, k as AdminCustomerRequest, a3 as CatalogProduct, N as AffiliateConversion, R as AffiliateDownlineMember, O as AffiliateDashboardLinks, Q as AffiliateDashboardStats, aA as PromoValidationResponse } from '../client-Cm6n4V0r.js';
3
3
  import { C as CartItem } from '../cart-D4mVX_zx.js';
4
4
  export { U as UseSurveyV2FlowOptions, u as useSurveyV2Flow } from '../surveyV2-BgQHK0GE.js';
5
5
  import { EmbedEvent } from '@apextelemed/survey-solid';
6
6
  export { SurveyV2Flow, SurveyV2Outcome } from '@apextelemed/survey-solid';
7
- import { d as ResumedDraft, R as ResumedCart } from '../cart-CBH8Em8f.js';
7
+ import { d as ResumedDraft, a as CartSnapshotLine, R as ResumedCart } from '../cart-BwUwSzWh.js';
8
8
  import '@apextelemed/survey-core';
9
9
 
10
10
  interface SurveyOption {
@@ -1443,7 +1443,53 @@ interface CartCaptureOptions {
1443
1443
  * nothing here — the backend reads their email off the token.
1444
1444
  */
1445
1445
  email?: () => string | null | undefined;
1446
+ /**
1447
+ * Where the basket lives, for a site that has no catalog cart.
1448
+ *
1449
+ * Abandonment is not a storefront-only event: a single-subscription partner
1450
+ * (mytruemeds, axiom-md) lets a patient choose a medication and a dose and
1451
+ * then walk away from the payment step, which is the same loss and the same
1452
+ * recoverable moment — but the selection lives in that site's own intake
1453
+ * state, not in `stores/cart`, so the default wiring watches an empty store
1454
+ * forever.
1455
+ *
1456
+ * Read and write are one option rather than two on purpose: a site that
1457
+ * supplies its own items must also say how a resumed cart gets back in, or
1458
+ * the `?cart=` link would rebuild into core's cart store, which such a site
1459
+ * never renders. Omit entirely to drive core's cart store (the default).
1460
+ */
1461
+ source?: CartSource;
1462
+ }
1463
+ /** A site's own basket, in the shape the wire already speaks. */
1464
+ interface CartSource {
1465
+ /** Current lines. Must be reactive — this is tracked. */
1466
+ items: () => CartSnapshotLine[];
1467
+ /** Promo code riding on the cart, if the site has one. */
1468
+ promoCode?: () => string | null | undefined;
1469
+ /**
1470
+ * Rebuild the site's own state from a cart resumed off a `?cart=` link. The
1471
+ * lines are re-priced against today's catalog; the promo code (if any) is
1472
+ * NOT re-validated for a custom source — `validateResumedPromo` does that
1473
+ * for a site that wants it.
1474
+ */
1475
+ restore: (cart: ResumedCart) => void;
1446
1476
  }
1477
+ interface ValidatedResumedPromo {
1478
+ code: string;
1479
+ discountType: 'percent' | 'fixed';
1480
+ discountValueCents: number;
1481
+ discountCents: number;
1482
+ }
1483
+ /**
1484
+ * Re-check the promo code a resumed cart was carrying, against today's rules
1485
+ * and today's lines. Null when there was no code, when it no longer validates,
1486
+ * or when the check itself fails — the cart is restored either way.
1487
+ *
1488
+ * Exported because a site with its own `CartSource` needs the same guarantee
1489
+ * without core's cart store: showing a discount checkout won't honour is worse
1490
+ * than showing none.
1491
+ */
1492
+ declare function validateResumedPromo(resumed: ResumedCart): Promise<ValidatedResumedPromo | null>;
1447
1493
  /**
1448
1494
  * Redeem a `?cart=` token if the URL carries one.
1449
1495
  *
@@ -1464,4 +1510,4 @@ declare function restoreCartFromLink(): Promise<ResumedCart | null>;
1464
1510
  */
1465
1511
  declare function startCartCapture(opts?: CartCaptureOptions): () => void;
1466
1512
 
1467
- export { type AccountSource, type AddressErrors, type AddressPair, type AddressValue, type AffiliateConversionsFlow, type AffiliateDownlineFlow, type AffiliateLinksFlow, type AffiliateStatsFlow, type AnswerValue, type AttentionAction, type AttentionActionKind, type AttentionItem, type CartCaptureOptions, type CartCheckoutFlow, type CartCheckoutOutcome, type CartCheckoutPricing, type CatalogFlow, CatalogProduct, type CategoryColorOpts, type CheckoutFlow, type CheckoutOutcome, type Conversation, DEFAULT_COLOR_PALETTE, type DashboardActivityItem, type DashboardData, type DashboardRxListItem, type DashboardRxStatus, type DashboardSubscription, type DrugResult, type FlatStep, type FulfillmentStage, type FunnelTelemetry, type JourneyState, type JourneyStep, type JourneyStepKey, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, type MedicationPricing, type MedicationSelectFlow, type MemberPortalData, type MemberPortalRx, type MemberPortalSubscription, type MessagesThread, type PricingBreakdown, type ProductDetailFlow, type PromoPricing, type RefillEvent, type RefillView, type RegisterFlow, type RegisterOutcome, type RequestStatus, type RxRequestStatus, type Severity, type ShipmentInfo, type SignupFlow, type SignupOutcome, type StageState, type SubscribeFlow, type SubscribeOutcome, type SubscriptionIntakeFlow, type SubscriptionIntakeOutcome, type SurveyFlow, type SurveyOption, type SurveyOutcome, type SurveyQuestion, type SurveyResult, TERMINAL_SUBSCRIPTION_STATUSES, type ThreadMessage, type TimelineEvent, type TimelineKind, type Tone, type TrackerRequest, type TrackerRequestStatus, type TrackerSubscription, type TrackerSubscriptionStatus, type TrackerView, type TrackingUrlCarrier, US_STATES, US_STATE_OPTIONS, type UpdatePaymentMethodFlow, type UseAddressPairOptions, type UseCheckoutFlowOptions, type UseMedicationSelectOptions, type UseMessagesThreadOptions, type UseSignupFlowOptions, type UseSubscribeFlowOptions, type UseSubscriptionIntakeFlowOptions, type UseSurveyFlowOptions, type ValidateAddressOptions, type VisibilityCondition, accountSource, availableStateOptions, availableStates, buildRefillView, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, categoryColor, createFunnelTelemetry, deriveAttention, deriveJourney, emailGateAnswered, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, hasErrors, isLive, isQuestionVisible, isReconcilable, lifecycleReason, lowestPrice, lowestSalePrice, markEmailGateAnswered, normalizeState, primarySubscription, redeemResumeLink, resetResumeRedemption, restoreCartFromLink, startCartCapture, stateAvailabilityNote, toTrackerRequest, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCatalog, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductDetail, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSubscriptionIntakeFlow, useSurveyFlow, useUpdatePaymentMethodFlow, validateAddress };
1513
+ export { type AccountSource, type AddressErrors, type AddressPair, type AddressValue, type AffiliateConversionsFlow, type AffiliateDownlineFlow, type AffiliateLinksFlow, type AffiliateStatsFlow, type AnswerValue, type AttentionAction, type AttentionActionKind, type AttentionItem, type CartCaptureOptions, type CartCheckoutFlow, type CartCheckoutOutcome, type CartCheckoutPricing, type CartSource, type CatalogFlow, CatalogProduct, type CategoryColorOpts, type CheckoutFlow, type CheckoutOutcome, type Conversation, DEFAULT_COLOR_PALETTE, type DashboardActivityItem, type DashboardData, type DashboardRxListItem, type DashboardRxStatus, type DashboardSubscription, type DrugResult, type FlatStep, type FulfillmentStage, type FunnelTelemetry, type JourneyState, type JourneyStep, type JourneyStepKey, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, type MedicationPricing, type MedicationSelectFlow, type MemberPortalData, type MemberPortalRx, type MemberPortalSubscription, type MessagesThread, type PricingBreakdown, type ProductDetailFlow, type PromoPricing, type RefillEvent, type RefillView, type RegisterFlow, type RegisterOutcome, type RequestStatus, type RxRequestStatus, type Severity, type ShipmentInfo, type SignupFlow, type SignupOutcome, type StageState, type SubscribeFlow, type SubscribeOutcome, type SubscriptionIntakeFlow, type SubscriptionIntakeOutcome, type SurveyFlow, type SurveyOption, type SurveyOutcome, type SurveyQuestion, type SurveyResult, TERMINAL_SUBSCRIPTION_STATUSES, type ThreadMessage, type TimelineEvent, type TimelineKind, type Tone, type TrackerRequest, type TrackerRequestStatus, type TrackerSubscription, type TrackerSubscriptionStatus, type TrackerView, type TrackingUrlCarrier, US_STATES, US_STATE_OPTIONS, type UpdatePaymentMethodFlow, type UseAddressPairOptions, type UseCheckoutFlowOptions, type UseMedicationSelectOptions, type UseMessagesThreadOptions, type UseSignupFlowOptions, type UseSubscribeFlowOptions, type UseSubscriptionIntakeFlowOptions, type UseSurveyFlowOptions, type ValidateAddressOptions, type ValidatedResumedPromo, type VisibilityCondition, accountSource, availableStateOptions, availableStates, buildRefillView, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, categoryColor, createFunnelTelemetry, deriveAttention, deriveJourney, emailGateAnswered, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, hasErrors, isLive, isQuestionVisible, isReconcilable, lifecycleReason, lowestPrice, lowestSalePrice, markEmailGateAnswered, normalizeState, primarySubscription, redeemResumeLink, resetResumeRedemption, restoreCartFromLink, startCartCapture, stateAvailabilityNote, toTrackerRequest, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCatalog, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductDetail, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSubscriptionIntakeFlow, useSurveyFlow, useUpdatePaymentMethodFlow, validateAddress, validateResumedPromo };
@@ -1,9 +1,9 @@
1
- export { DEFAULT_COLOR_PALETTE, categoryColor, lowestPrice, lowestSalePrice, restoreCartFromLink, startCartCapture, useCatalog, useMedicationSelect, useProductDetail, useSubscriptionIntakeFlow } from '../chunk/EIXZJX6R.js';
2
- import '../chunk/XMYPS7PT.js';
3
- export { LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, accountSource, availableStateOptions, availableStates, buildRefillView, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, createFunnelTelemetry, deriveAttention, deriveJourney, emailGateAnswered, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, hasErrors, isLive, isQuestionVisible, isReconcilable, lifecycleReason, markEmailGateAnswered, normalizeState, primarySubscription, redeemResumeLink, resetResumeRedemption, stateAvailabilityNote, toTrackerRequest, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCheckoutFlow, useDashboardData, useMemberPortalData, useMessagesThread, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress } from '../chunk/OJSQZEB3.js';
4
- import '../chunk/DS4E7FAI.js';
5
- import '../chunk/YHWX4NMV.js';
6
- import '../chunk/2XJBOTK5.js';
1
+ export { DEFAULT_COLOR_PALETTE, categoryColor, lowestPrice, lowestSalePrice, restoreCartFromLink, startCartCapture, useCatalog, useMedicationSelect, useProductDetail, useSubscriptionIntakeFlow, validateResumedPromo } from '../chunk/6MDLP62Y.js';
2
+ import '../chunk/O4V2YXBF.js';
3
+ export { LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, accountSource, availableStateOptions, availableStates, buildRefillView, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, createFunnelTelemetry, deriveAttention, deriveJourney, emailGateAnswered, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, hasErrors, isLive, isQuestionVisible, isReconcilable, lifecycleReason, markEmailGateAnswered, normalizeState, primarySubscription, redeemResumeLink, resetResumeRedemption, stateAvailabilityNote, toTrackerRequest, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCheckoutFlow, useDashboardData, useMemberPortalData, useMessagesThread, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress } from '../chunk/4W5ONAFF.js';
4
+ import '../chunk/4YUUZ532.js';
5
+ import '../chunk/NNTB7KL5.js';
6
+ import '../chunk/ITK5F5AI.js';
7
7
  import '../chunk/5XGPFYIJ.js';
8
8
  //# sourceMappingURL=index.js.map
9
9
  //# sourceMappingURL=index.js.map
@@ -8,9 +8,10 @@ import {
8
8
  useCatalog,
9
9
  useMedicationSelect,
10
10
  useProductDetail,
11
- useSubscriptionIntakeFlow
12
- } from "../chunk/T6IKS76T.jsx";
13
- import "../chunk/NP4CMOLW.jsx";
11
+ useSubscriptionIntakeFlow,
12
+ validateResumedPromo
13
+ } from "../chunk/5CXUPFZU.jsx";
14
+ import "../chunk/GGY7VMZ2.jsx";
14
15
  import {
15
16
  LIFECYCLE_BUCKETS,
16
17
  LIFECYCLE_LABEL,
@@ -68,10 +69,10 @@ import {
68
69
  useSurveyV2Flow,
69
70
  useUpdatePaymentMethodFlow,
70
71
  validateAddress
71
- } from "../chunk/NYLIUR7O.jsx";
72
- import "../chunk/I46Y2J5W.jsx";
73
- import "../chunk/STEVQZ6U.jsx";
74
- import "../chunk/MEF3FUQB.jsx";
72
+ } from "../chunk/6QC4BETO.jsx";
73
+ import "../chunk/Z2CR6WKF.jsx";
74
+ import "../chunk/CXBPVQ7W.jsx";
75
+ import "../chunk/B5RBZKAK.jsx";
75
76
  import "../chunk/LDZIUFDM.jsx";
76
77
  export {
77
78
  DEFAULT_COLOR_PALETTE,
@@ -139,6 +140,7 @@ export {
139
140
  useSurveyFlow,
140
141
  useSurveyV2Flow,
141
142
  useUpdatePaymentMethodFlow,
142
- validateAddress
143
+ validateAddress,
144
+ validateResumedPromo
143
145
  };
144
146
  //# sourceMappingURL=index.jsx.map
@@ -1,14 +1,14 @@
1
1
  export { PortalConfig, configure, getConfig } from '../config/index.js';
2
2
  export { BannerProps, BannerVariant, ButtonProps, ButtonSize, ButtonVariant, CardProps, CheckboxGroupProps, ChoiceOption, HeadingProps, Primitives, PrimitivesProvider, RadioGroupProps, SelectOption, SelectProps, SpinnerProps, Status, StatusPillProps, StepIndicatorProps, TextFieldProps, TextareaProps, usePrimitives } from '../primitives/index.js';
3
3
  export { defaultPrimitives } from '../primitives/default/index.js';
4
- export { A as AddressVerifyResult, a as AdminApexDrug, b as AdminBillingAttempt, c as AdminCategory, d as AdminCategoryInput, e as AdminCustomer, f as AdminCustomerFacts, g as AdminCustomerFunnel, h as AdminCustomerListParams, i as AdminCustomerOverview, j as AdminCustomerProfile, k as AdminCustomerRequest, l as AdminCustomerRow, m as AdminCustomerSupport, n as AdminCustomerSupportThread, o as AdminDashboardStats, p as AdminLifecycle, q as AdminLifecycleBucket, r as AdminListParams, s as AdminOrderSummary, t as AdminPayment, u as AdminPaymentDetail, v as AdminProduct, w as AdminPromoCode, x as AdminPromoCodeInput, y as AdminRefundResult, z as AdminSale, B as AdminSaleInput, C as AdminSubscription, D as AdminSubscriptionDetail, E as AdminSubscriptionPatch, F as AdminSubscriptionWriteResult, G as AdminSupportCustomer, H as AdminSupportStats, I as AdminSupportThread, J as AdminWebhookEvent, K as Affiliate, L as AffiliateAuthTokens, M as AffiliateClickRecord, N as AffiliateConversion, O as AffiliateDashboardLinks, P as AffiliateDashboardProfile, Q as AffiliateDashboardStats, R as AffiliateDownlineMember, S as AffiliateEarningsBreakdown, T as AffiliatePaymentMethod, U as AffiliateProgram, V as AffiliateRegisterInput, W as AffiliateRegisterResponse, X as AffiliateSession, Y as AffiliateStatsResponse, Z as AffiliateStatus, _ as AffiliateTrackResponse, $ as ApiError, a0 as ApiResponse, a1 as AttributionMethod, a2 as AuthTokens, a3 as CatalogProduct, a4 as CheckoutAddress, a5 as CheckoutPayload, a6 as CheckoutResult, a7 as CommissionConfig, a8 as CommissionStatus, a9 as CompleteSurveyPayload, aa as CreateAffiliatePayload, ab as CreateAffiliateProgramPayload, ac as CreateOrderPayload, ad as CreateRequestPayload, ae as CreateSubscriptionPayload, af as CustomerDiscountConfig, ag as DeliveryInfo, ah as DiscountType, ai as EmailTemplatesMap, aj as LoginPayload, ak as MemberPrescriptionRequest, al as MemberSurveyMode, am as MemberSurveyResponseSummary, an as MemberSurveyTranscript, ao as MemberSurveyTranscriptItem, ap as MemberSurveyTranscriptSection, aq as MembersMeResponse, ar as Order, as as OrderItemInput, at as PaginationParams, au as PaymentCallbackPayload, av as PaymentInitiatePayload, aw as PaymentType, ax as PendingRenewalSurvey, ay as Placeholder, az as ProductSaleSummary, aA as PromoValidationResponse, aB as PublicCategory, aC as RegisterAndSubscribePayload, aD as RegisterPayload, aE as RenewalStatus, aF as SUPPORT_ATTACHMENT_MAX_BYTES, aG as SUPPORT_ATTACHMENT_MIME_TYPES, aH as SelectDrugPayload, aI as SendMessagePayload, aJ as SendToPharmacyPayload, aK as SupportAttachment, aL as SupportMessage, aM as SupportRealtimeToken, aN as SupportThread, aO as SupportThreadStatus, aP as SurveySubmitPayload, aQ as TemplatePlaceholdersMap, aR as TemplateText, aS as TokenTrackName, aT as UpdateAffiliatePayload, aU as UpdateAffiliateProgramPayload, aV as UpdatePaymentMethodPayload, aW as UpdateProfilePayload, aX as User, aY as addressesApi, aZ as adminAffiliatesApi, a_ as adminApi, a$ as affiliateAuthStorageKey, b0 as affiliatePortalApi, b1 as apexApi, b2 as apiFetch, b3 as authApi, b4 as authStorageKey, b5 as clearAffiliateTokens, b6 as clearTokens, b7 as getAffiliateTokens, b8 as getTokens, b9 as membersApi, ba as messagesApi, bb as newIdempotencyKey, bc as onTokensCleared, bd as ordersApi, be as paymentsApi, bf as productsApi, bg as promoCodesApi, bh as setAffiliateTokens, bi as setTokens, bj as subscriptionsApi, bk as supportApi, bl as usersApi } from '../client-DUrhrzOG.js';
4
+ export { A as AddressVerifyResult, a as AdminApexDrug, b as AdminBillingAttempt, c as AdminCategory, d as AdminCategoryInput, e as AdminCustomer, f as AdminCustomerFacts, g as AdminCustomerFunnel, h as AdminCustomerListParams, i as AdminCustomerOverview, j as AdminCustomerProfile, k as AdminCustomerRequest, l as AdminCustomerRow, m as AdminCustomerSupport, n as AdminCustomerSupportThread, o as AdminDashboardStats, p as AdminLifecycle, q as AdminLifecycleBucket, r as AdminListParams, s as AdminOrderSummary, t as AdminPayment, u as AdminPaymentDetail, v as AdminProduct, w as AdminPromoCode, x as AdminPromoCodeInput, y as AdminRefundResult, z as AdminSale, B as AdminSaleInput, C as AdminSubscription, D as AdminSubscriptionDetail, E as AdminSubscriptionPatch, F as AdminSubscriptionWriteResult, G as AdminSupportCustomer, H as AdminSupportStats, I as AdminSupportThread, J as AdminWebhookEvent, K as Affiliate, L as AffiliateAuthTokens, M as AffiliateClickRecord, N as AffiliateConversion, O as AffiliateDashboardLinks, P as AffiliateDashboardProfile, Q as AffiliateDashboardStats, R as AffiliateDownlineMember, S as AffiliateEarningsBreakdown, T as AffiliatePaymentMethod, U as AffiliateProgram, V as AffiliateRegisterInput, W as AffiliateRegisterResponse, X as AffiliateSession, Y as AffiliateStatsResponse, Z as AffiliateStatus, _ as AffiliateTrackResponse, $ as ApiError, a0 as ApiResponse, a1 as AttributionMethod, a2 as AuthTokens, a3 as CatalogProduct, a4 as CheckoutAddress, a5 as CheckoutPayload, a6 as CheckoutResult, a7 as CommissionConfig, a8 as CommissionStatus, a9 as CompleteSurveyPayload, aa as CreateAffiliatePayload, ab as CreateAffiliateProgramPayload, ac as CreateOrderPayload, ad as CreateRequestPayload, ae as CreateSubscriptionPayload, af as CustomerDiscountConfig, ag as DeliveryInfo, ah as DiscountType, ai as EmailTemplatesMap, aj as LoginPayload, ak as MemberPrescriptionRequest, al as MemberSurveyMode, am as MemberSurveyResponseSummary, an as MemberSurveyTranscript, ao as MemberSurveyTranscriptItem, ap as MemberSurveyTranscriptSection, aq as MembersMeResponse, ar as Order, as as OrderItemInput, at as PaginationParams, au as PaymentCallbackPayload, av as PaymentInitiatePayload, aw as PaymentType, ax as PendingRenewalSurvey, ay as Placeholder, az as ProductSaleSummary, aA as PromoValidationResponse, aB as PublicCategory, aC as RegisterAndSubscribePayload, aD as RegisterPayload, aE as RenewalStatus, aF as SUPPORT_ATTACHMENT_MAX_BYTES, aG as SUPPORT_ATTACHMENT_MIME_TYPES, aH as SelectDrugPayload, aI as SendMessagePayload, aJ as SendToPharmacyPayload, aK as SupportAttachment, aL as SupportMessage, aM as SupportRealtimeToken, aN as SupportThread, aO as SupportThreadStatus, aP as SurveySubmitPayload, aQ as TemplatePlaceholdersMap, aR as TemplateText, aS as TokenTrackName, aT as UpdateAffiliatePayload, aU as UpdateAffiliateProgramPayload, aV as UpdatePaymentMethodPayload, aW as UpdateProfilePayload, aX as User, aY as addressesApi, aZ as adminAffiliatesApi, a_ as adminApi, a$ as affiliateAuthStorageKey, b0 as affiliatePortalApi, b1 as apexApi, b2 as apiFetch, b3 as authApi, b4 as authStorageKey, b5 as clearAffiliateTokens, b6 as clearTokens, b7 as getAffiliateTokens, b8 as getTokens, b9 as membersApi, ba as messagesApi, bb as newIdempotencyKey, bc as onTokensCleared, bd as ordersApi, be as paymentsApi, bf as productsApi, bg as promoCodesApi, bh as setAffiliateTokens, bi as setTokens, bj as subscriptionsApi, bk as supportApi, bl as usersApi } from '../client-Cm6n4V0r.js';
5
5
  export { EmbedApiError as ApexV2ApiError, EmbedApiClient, EmbedApiClientOptions, EmbedApiError, EmbedEvent, EmbedEventType, FetchLike, PatientInfo, V2Answer, V2ComposedSurvey, V2DrugResult, V2QualificationResult, V2Question, V2QuestionOption, V2Section, V2Step, V2SubmitResult, V2VisibilityCondition, createEmbedApiClient, disqualificationReasonText, disqualifiedDrugIds, qualifiedDrugIds } from '@apextelemed/survey-core';
6
6
  export { captureAffiliateRef, capturePromoCode, clearAffiliateRef, clearPromoCode, readAffiliateRef, readPromoCode } from '../api/index.js';
7
- export { C as CartCaptureConfig, a as CartSnapshotLine, F as FunnelConfig, b as FunnelDraftPayload, R as ResumedCart, c as ResumedCartLine, d as ResumedDraft, e as adoptCartId, f as adoptFunnelSessionId, g as cartId, h as fetchCartConfig, i as fetchFunnelConfig, j as fetchResumedCart, k as fetchResumedDraft, l as funnelSessionId, p as peekFunnelSessionId, m as postCartSnapshot, n as postFunnelEvent, r as readCartToken, o as readResumeToken, q as resetCartConfigCache, s as resetCartId, t as resetFunnelConfigCache, u as saveFunnelDraft, v as stripCartToken, w as stripResumeToken } from '../cart-CBH8Em8f.js';
7
+ export { C as CartCaptureConfig, a as CartSnapshotLine, F as FunnelConfig, b as FunnelDraftPayload, R as ResumedCart, c as ResumedCartLine, d as ResumedDraft, e as adoptCartId, f as adoptFunnelSessionId, g as captureAuthHeader, h as cartId, i as fetchCartConfig, j as fetchFunnelConfig, k as fetchResumedCart, l as fetchResumedDraft, m as funnelSessionId, p as peekFunnelSessionId, n as postCartSnapshot, o as postFunnelEvent, r as readCartToken, q as readResumeToken, s as resetCartConfigCache, t as resetCartId, u as resetFunnelConfigCache, v as saveFunnelDraft, w as stripCartToken, x as stripResumeToken } from '../cart-BwUwSzWh.js';
8
8
  export { MedicationSelection, affiliateAuthStore, authStore, medicationStore } from '../stores/index.js';
9
9
  export { A as AppliedPromoCode, C as CartItem, c as cartStore } from '../cart-D4mVX_zx.js';
10
10
  import { AddressPair } from '../flows/index.js';
11
- export { AccountSource, AddressErrors, AddressValue, AffiliateConversionsFlow, AffiliateDownlineFlow, AffiliateLinksFlow, AffiliateStatsFlow, AnswerValue, AttentionAction, AttentionActionKind, AttentionItem, CartCaptureOptions, CartCheckoutFlow, CartCheckoutOutcome, CartCheckoutPricing, CatalogFlow, CategoryColorOpts, CheckoutFlow, CheckoutOutcome, Conversation, DEFAULT_COLOR_PALETTE, DashboardActivityItem, DashboardData, DashboardRxListItem, DashboardRxStatus, DashboardSubscription, DrugResult, FlatStep, FulfillmentStage, FunnelTelemetry, JourneyState, JourneyStep, JourneyStepKey, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, MedicationPricing, MedicationSelectFlow, MemberPortalData, MemberPortalRx, MemberPortalSubscription, MessagesThread, PricingBreakdown, ProductDetailFlow, PromoPricing, RefillEvent, RefillView, RegisterFlow, RegisterOutcome, RequestStatus, RxRequestStatus, Severity, ShipmentInfo, SignupFlow, SignupOutcome, StageState, SubscribeFlow, SubscribeOutcome, SubscriptionIntakeFlow, SubscriptionIntakeOutcome, SurveyFlow, SurveyOption, SurveyOutcome, SurveyQuestion, SurveyResult, TERMINAL_SUBSCRIPTION_STATUSES, ThreadMessage, TimelineEvent, TimelineKind, Tone, TrackerRequest, TrackerRequestStatus, TrackerSubscription, TrackerSubscriptionStatus, TrackerView, TrackingUrlCarrier, US_STATES, US_STATE_OPTIONS, UpdatePaymentMethodFlow, UseAddressPairOptions, UseCheckoutFlowOptions, UseMedicationSelectOptions, UseMessagesThreadOptions, UseSignupFlowOptions, UseSubscribeFlowOptions, UseSubscriptionIntakeFlowOptions, UseSurveyFlowOptions, ValidateAddressOptions, VisibilityCondition, accountSource, availableStateOptions, availableStates, buildRefillView, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, categoryColor, createFunnelTelemetry, deriveAttention, deriveJourney, emailGateAnswered, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, hasErrors, isLive, isQuestionVisible, isReconcilable, lifecycleReason, lowestPrice, lowestSalePrice, markEmailGateAnswered, normalizeState, primarySubscription, redeemResumeLink, resetResumeRedemption, restoreCartFromLink, startCartCapture, stateAvailabilityNote, toTrackerRequest, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCatalog, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductDetail, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSubscriptionIntakeFlow, useSurveyFlow, useUpdatePaymentMethodFlow, validateAddress } from '../flows/index.js';
11
+ export { AccountSource, AddressErrors, AddressValue, AffiliateConversionsFlow, AffiliateDownlineFlow, AffiliateLinksFlow, AffiliateStatsFlow, AnswerValue, AttentionAction, AttentionActionKind, AttentionItem, CartCaptureOptions, CartCheckoutFlow, CartCheckoutOutcome, CartCheckoutPricing, CartSource, CatalogFlow, CategoryColorOpts, CheckoutFlow, CheckoutOutcome, Conversation, DEFAULT_COLOR_PALETTE, DashboardActivityItem, DashboardData, DashboardRxListItem, DashboardRxStatus, DashboardSubscription, DrugResult, FlatStep, FulfillmentStage, FunnelTelemetry, JourneyState, JourneyStep, JourneyStepKey, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, MedicationPricing, MedicationSelectFlow, MemberPortalData, MemberPortalRx, MemberPortalSubscription, MessagesThread, PricingBreakdown, ProductDetailFlow, PromoPricing, RefillEvent, RefillView, RegisterFlow, RegisterOutcome, RequestStatus, RxRequestStatus, Severity, ShipmentInfo, SignupFlow, SignupOutcome, StageState, SubscribeFlow, SubscribeOutcome, SubscriptionIntakeFlow, SubscriptionIntakeOutcome, SurveyFlow, SurveyOption, SurveyOutcome, SurveyQuestion, SurveyResult, TERMINAL_SUBSCRIPTION_STATUSES, ThreadMessage, TimelineEvent, TimelineKind, Tone, TrackerRequest, TrackerRequestStatus, TrackerSubscription, TrackerSubscriptionStatus, TrackerView, TrackingUrlCarrier, US_STATES, US_STATE_OPTIONS, UpdatePaymentMethodFlow, UseAddressPairOptions, UseCheckoutFlowOptions, UseMedicationSelectOptions, UseMessagesThreadOptions, UseSignupFlowOptions, UseSubscribeFlowOptions, UseSubscriptionIntakeFlowOptions, UseSurveyFlowOptions, ValidateAddressOptions, ValidatedResumedPromo, VisibilityCondition, accountSource, availableStateOptions, availableStates, buildRefillView, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, categoryColor, createFunnelTelemetry, deriveAttention, deriveJourney, emailGateAnswered, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, hasErrors, isLive, isQuestionVisible, isReconcilable, lifecycleReason, lowestPrice, lowestSalePrice, markEmailGateAnswered, normalizeState, primarySubscription, redeemResumeLink, resetResumeRedemption, restoreCartFromLink, startCartCapture, stateAvailabilityNote, toTrackerRequest, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCatalog, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductDetail, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSubscriptionIntakeFlow, useSurveyFlow, useUpdatePaymentMethodFlow, validateAddress, validateResumedPromo } from '../flows/index.js';
12
12
  export { U as UseSurveyV2FlowOptions, u as useSurveyV2Flow } from '../surveyV2-BgQHK0GE.js';
13
13
  export { AdminAuthAdapter, AdminDashboard, AdminDashboardProps, AdminTab, AdminTabGroup, AdminToast, AffiliateAuthAdapter, AffiliateForgotPassword, AffiliateForgotPasswordProps, AffiliateLogin, AffiliateLoginProps, AffiliatePortal, AffiliatePortalProps, AffiliatePortalTab, AffiliateRegister, AffiliateRegisterProps, AffiliateResetPassword, AffiliateResetPasswordProps, AffiliateSubTab, AffiliatesProps, CartCheckoutPage, CartCheckoutPageProps, CheckoutPage, CheckoutPageProps, EmailTemplates, ForgotPasswordPage, ForgotPasswordPageProps, LegalLink, MedicationGuideContent, MedicationGuideResolver, MemberAuthAdapter, MemberPortal, MemberPortalBrand, MemberPortalProps, MemberPortalRoutes, PatientDashboardPreview, PatientDashboardPreviewProps, RegisterPage, RegisterPageProps, ResetPasswordPage, ResetPasswordPageProps, SignupPage, SignupPageProps, SubscribePage, SubscribePageProps, SurveyPage, SurveyPageProps, SurveyV2Page, SurveyV2PageProps, UpdatePaymentMethod, UpdatePaymentMethodProps } from '../pages/index.js';
14
14
  import { JSX } from 'solid-js';
@@ -1,15 +1,15 @@
1
1
  import '../chunk/JSHO46VZ.js';
2
- export { DEFAULT_COLOR_PALETTE, categoryColor, lowestPrice, lowestSalePrice, restoreCartFromLink, startCartCapture, useCatalog, useMedicationSelect, useProductDetail, useSubscriptionIntakeFlow } from '../chunk/EIXZJX6R.js';
3
- export { adoptCartId, capturePromoCode, cartId, clearPromoCode, fetchCartConfig, fetchResumedCart, postCartSnapshot, readCartToken, readPromoCode, resetCartConfigCache, resetCartId, stripCartToken } from '../chunk/XMYPS7PT.js';
4
- export { AddressFields, AdminDashboard, AffiliateForgotPassword, AffiliateLogin, AffiliatePortal, AffiliateRegister, AffiliateResetPassword, CartCheckoutPage, CheckoutPage, EmailTemplates, ForgotPasswordPage, MemberPortal, PatientDashboardPreview, RegisterPage, ResetPasswordPage, SignupPage, SubscribePage, SurveyPage, SurveyV2Page, UpdatePaymentMethod } from '../chunk/MN4GWQC4.js';
2
+ export { DEFAULT_COLOR_PALETTE, categoryColor, lowestPrice, lowestSalePrice, restoreCartFromLink, startCartCapture, useCatalog, useMedicationSelect, useProductDetail, useSubscriptionIntakeFlow, validateResumedPromo } from '../chunk/6MDLP62Y.js';
3
+ export { adoptCartId, capturePromoCode, cartId, clearPromoCode, fetchCartConfig, fetchResumedCart, postCartSnapshot, readCartToken, readPromoCode, resetCartConfigCache, resetCartId, stripCartToken } from '../chunk/O4V2YXBF.js';
4
+ export { AddressFields, AdminDashboard, AffiliateForgotPassword, AffiliateLogin, AffiliatePortal, AffiliateRegister, AffiliateResetPassword, CartCheckoutPage, CheckoutPage, EmailTemplates, ForgotPasswordPage, MemberPortal, PatientDashboardPreview, RegisterPage, ResetPasswordPage, SignupPage, SubscribePage, SurveyPage, SurveyV2Page, UpdatePaymentMethod } from '../chunk/7COJH6FZ.js';
5
5
  export { EmbedApiError2 as ApexV2ApiError, EmbedApiError, createEmbedApiClient, disqualificationReasonText, disqualifiedDrugIds, qualifiedDrugIds } from '../chunk/LZWA44KD.js';
6
- export { LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, accountSource, availableStateOptions, availableStates, buildRefillView, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, createFunnelTelemetry, deriveAttention, deriveJourney, emailGateAnswered, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, hasErrors, isLive, isQuestionVisible, isReconcilable, lifecycleReason, markEmailGateAnswered, normalizeState, primarySubscription, redeemResumeLink, resetResumeRedemption, stateAvailabilityNote, toTrackerRequest, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCheckoutFlow, useDashboardData, useMemberPortalData, useMessagesThread, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress } from '../chunk/OJSQZEB3.js';
7
- export { adoptFunnelSessionId, fetchFunnelConfig, fetchResumedDraft, funnelSessionId, peekFunnelSessionId, postFunnelEvent, readResumeToken, resetFunnelConfigCache, saveFunnelDraft, stripResumeToken } from '../chunk/DS4E7FAI.js';
6
+ export { LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, accountSource, availableStateOptions, availableStates, buildRefillView, buildTimeline, buildTrackerView, buildTrackingUrl, captureFunnelEmail, createFunnelTelemetry, deriveAttention, deriveJourney, emailGateAnswered, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, hasErrors, isLive, isQuestionVisible, isReconcilable, lifecycleReason, markEmailGateAnswered, normalizeState, primarySubscription, redeemResumeLink, resetResumeRedemption, stateAvailabilityNote, toTrackerRequest, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCartCheckoutFlow, useCheckoutFlow, useDashboardData, useMemberPortalData, useMessagesThread, useRegisterFlow, useSignupFlow, useSubscribeFlow, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress } from '../chunk/4W5ONAFF.js';
7
+ export { adoptFunnelSessionId, captureAuthHeader, fetchFunnelConfig, fetchResumedDraft, funnelSessionId, peekFunnelSessionId, postFunnelEvent, readResumeToken, resetFunnelConfigCache, saveFunnelDraft, stripResumeToken } from '../chunk/4YUUZ532.js';
8
8
  export { PrimitivesProvider, usePrimitives } from '../chunk/67KHO66G.js';
9
9
  export { defaultPrimitives } from '../chunk/YJEHCCLY.js';
10
10
  import '../chunk/NVRAOAVV.js';
11
- export { affiliateAuth_default as affiliateAuthStore, auth_default as authStore, cart_default as cartStore, medication_default as medicationStore } from '../chunk/YHWX4NMV.js';
12
- export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi } from '../chunk/2XJBOTK5.js';
11
+ export { affiliateAuth_default as affiliateAuthStore, auth_default as authStore, cart_default as cartStore, medication_default as medicationStore } from '../chunk/NNTB7KL5.js';
12
+ export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi } from '../chunk/ITK5F5AI.js';
13
13
  export { configure, getConfig } from '../chunk/5XGPFYIJ.js';
14
14
  //# sourceMappingURL=index.js.map
15
15
  //# sourceMappingURL=index.js.map
@@ -9,8 +9,9 @@ import {
9
9
  useCatalog,
10
10
  useMedicationSelect,
11
11
  useProductDetail,
12
- useSubscriptionIntakeFlow
13
- } from "../chunk/T6IKS76T.jsx";
12
+ useSubscriptionIntakeFlow,
13
+ validateResumedPromo
14
+ } from "../chunk/5CXUPFZU.jsx";
14
15
  import {
15
16
  adoptCartId,
16
17
  capturePromoCode,
@@ -24,7 +25,7 @@ import {
24
25
  resetCartConfigCache,
25
26
  resetCartId,
26
27
  stripCartToken
27
- } from "../chunk/NP4CMOLW.jsx";
28
+ } from "../chunk/GGY7VMZ2.jsx";
28
29
  import {
29
30
  AddressFields,
30
31
  AdminDashboard,
@@ -46,7 +47,7 @@ import {
46
47
  SurveyPage,
47
48
  SurveyV2Page,
48
49
  UpdatePaymentMethod
49
- } from "../chunk/LPERM6T7.jsx";
50
+ } from "../chunk/YPZVHEBG.jsx";
50
51
  import {
51
52
  EmbedApiError,
52
53
  EmbedApiError2,
@@ -112,9 +113,10 @@ import {
112
113
  useSurveyV2Flow,
113
114
  useUpdatePaymentMethodFlow,
114
115
  validateAddress
115
- } from "../chunk/NYLIUR7O.jsx";
116
+ } from "../chunk/6QC4BETO.jsx";
116
117
  import {
117
118
  adoptFunnelSessionId,
119
+ captureAuthHeader,
118
120
  fetchFunnelConfig,
119
121
  fetchResumedDraft,
120
122
  funnelSessionId,
@@ -124,7 +126,7 @@ import {
124
126
  resetFunnelConfigCache,
125
127
  saveFunnelDraft,
126
128
  stripResumeToken
127
- } from "../chunk/I46Y2J5W.jsx";
129
+ } from "../chunk/Z2CR6WKF.jsx";
128
130
  import {
129
131
  PrimitivesProvider,
130
132
  usePrimitives
@@ -138,7 +140,7 @@ import {
138
140
  auth_default,
139
141
  cart_default,
140
142
  medication_default
141
- } from "../chunk/STEVQZ6U.jsx";
143
+ } from "../chunk/CXBPVQ7W.jsx";
142
144
  import {
143
145
  ApiError,
144
146
  SUPPORT_ATTACHMENT_MAX_BYTES,
@@ -172,7 +174,7 @@ import {
172
174
  subscriptionsApi,
173
175
  supportApi,
174
176
  usersApi
175
- } from "../chunk/MEF3FUQB.jsx";
177
+ } from "../chunk/B5RBZKAK.jsx";
176
178
  import {
177
179
  configure,
178
180
  getConfig
@@ -233,6 +235,7 @@ export {
233
235
  buildTrackerView,
234
236
  buildTrackingUrl,
235
237
  captureAffiliateRef,
238
+ captureAuthHeader,
236
239
  captureFunnelEmail,
237
240
  capturePromoCode,
238
241
  cartId,
@@ -332,6 +335,7 @@ export {
332
335
  useSurveyV2Flow,
333
336
  useUpdatePaymentMethodFlow,
334
337
  usersApi,
335
- validateAddress
338
+ validateAddress,
339
+ validateResumedPromo
336
340
  };
337
341
  //# sourceMappingURL=index.jsx.map
@@ -2,7 +2,7 @@ import * as solid_js from 'solid-js';
2
2
  import { JSX } from 'solid-js';
3
3
  import { U as UseSurveyV2FlowOptions } from '../surveyV2-BgQHK0GE.js';
4
4
  import { V2SubmitResult, PatientInfo, V2DrugResult } from '@apextelemed/survey-core';
5
- import { q as AdminLifecycleBucket, v as AdminProduct } from '../client-DUrhrzOG.js';
5
+ import { q as AdminLifecycleBucket, v as AdminProduct } from '../client-Cm6n4V0r.js';
6
6
  import '@apextelemed/survey-solid';
7
7
 
8
8
  interface SurveyPageProps {
@@ -1,10 +1,10 @@
1
- export { AdminDashboard, AffiliateForgotPassword, AffiliateLogin, AffiliatePortal, AffiliateRegister, AffiliateResetPassword, CartCheckoutPage, CheckoutPage, EmailTemplates, ForgotPasswordPage, MemberPortal, PatientDashboardPreview, RegisterPage, ResetPasswordPage, SignupPage, SubscribePage, SurveyPage, SurveyV2Page, UpdatePaymentMethod } from '../chunk/MN4GWQC4.js';
1
+ export { AdminDashboard, AffiliateForgotPassword, AffiliateLogin, AffiliatePortal, AffiliateRegister, AffiliateResetPassword, CartCheckoutPage, CheckoutPage, EmailTemplates, ForgotPasswordPage, MemberPortal, PatientDashboardPreview, RegisterPage, ResetPasswordPage, SignupPage, SubscribePage, SurveyPage, SurveyV2Page, UpdatePaymentMethod } from '../chunk/7COJH6FZ.js';
2
2
  import '../chunk/LZWA44KD.js';
3
- import '../chunk/OJSQZEB3.js';
4
- import '../chunk/DS4E7FAI.js';
3
+ import '../chunk/4W5ONAFF.js';
4
+ import '../chunk/4YUUZ532.js';
5
5
  import '../chunk/67KHO66G.js';
6
- import '../chunk/YHWX4NMV.js';
7
- import '../chunk/2XJBOTK5.js';
6
+ import '../chunk/NNTB7KL5.js';
7
+ import '../chunk/ITK5F5AI.js';
8
8
  import '../chunk/5XGPFYIJ.js';
9
9
  //# sourceMappingURL=index.js.map
10
10
  //# sourceMappingURL=index.js.map
@@ -18,13 +18,13 @@ import {
18
18
  SurveyPage,
19
19
  SurveyV2Page,
20
20
  UpdatePaymentMethod
21
- } from "../chunk/LPERM6T7.jsx";
21
+ } from "../chunk/YPZVHEBG.jsx";
22
22
  import "../chunk/UZCST66N.jsx";
23
- import "../chunk/NYLIUR7O.jsx";
24
- import "../chunk/I46Y2J5W.jsx";
23
+ import "../chunk/6QC4BETO.jsx";
24
+ import "../chunk/Z2CR6WKF.jsx";
25
25
  import "../chunk/J63XPQP4.jsx";
26
- import "../chunk/STEVQZ6U.jsx";
27
- import "../chunk/MEF3FUQB.jsx";
26
+ import "../chunk/CXBPVQ7W.jsx";
27
+ import "../chunk/B5RBZKAK.jsx";
28
28
  import "../chunk/LDZIUFDM.jsx";
29
29
  export {
30
30
  AdminDashboard,
@@ -1,5 +1,5 @@
1
1
  import * as solid_js from 'solid-js';
2
- import { a2 as AuthTokens, aX as User, aD as RegisterPayload, aC as RegisterAndSubscribePayload, L as AffiliateAuthTokens, K as Affiliate, V as AffiliateRegisterInput } from '../client-DUrhrzOG.js';
2
+ import { a2 as AuthTokens, aX as User, aD as RegisterPayload, aC as RegisterAndSubscribePayload, L as AffiliateAuthTokens, K as Affiliate, V as AffiliateRegisterInput } from '../client-Cm6n4V0r.js';
3
3
  export { A as AppliedPromoCode, C as CartItem, c as cartStore } from '../cart-D4mVX_zx.js';
4
4
 
5
5
  declare const authStore: {
@@ -1,6 +1,6 @@
1
1
  import '../chunk/NVRAOAVV.js';
2
- export { affiliateAuth_default as affiliateAuthStore, auth_default as authStore, cart_default as cartStore, medication_default as medicationStore } from '../chunk/YHWX4NMV.js';
3
- import '../chunk/2XJBOTK5.js';
2
+ export { affiliateAuth_default as affiliateAuthStore, auth_default as authStore, cart_default as cartStore, medication_default as medicationStore } from '../chunk/NNTB7KL5.js';
3
+ import '../chunk/ITK5F5AI.js';
4
4
  import '../chunk/5XGPFYIJ.js';
5
5
  //# sourceMappingURL=index.js.map
6
6
  //# sourceMappingURL=index.js.map
@@ -4,8 +4,8 @@ import {
4
4
  auth_default,
5
5
  cart_default,
6
6
  medication_default
7
- } from "../chunk/STEVQZ6U.jsx";
8
- import "../chunk/MEF3FUQB.jsx";
7
+ } from "../chunk/CXBPVQ7W.jsx";
8
+ import "../chunk/B5RBZKAK.jsx";
9
9
  import "../chunk/LDZIUFDM.jsx";
10
10
  export {
11
11
  affiliateAuth_default as affiliateAuthStore,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apextelemed/partner-core",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "description": "Shared frontend library for telehealth patient portals (api client, stores, headless flows).",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/api/funnel.ts"],"names":[],"mappings":";;;AAkBA,IAAM,WAAyB,EAAE,SAAA,EAAW,OAAO,SAAA,EAAW,KAAA,EAAO,mBAAmB,KAAA,EAAM;AAE9F,IAAI,aAAA,GAA8C,IAAA;AAM3C,SAAS,iBAAA,GAA2C;AACzD,EAAA,IAAI,CAAC,aAAA,EAAe;AAClB,IAAA,aAAA,GAAA,CAAiB,YAAY;AAC3B,MAAA,IAAI;AACF,QAAA,MAAM,MAAM,SAAA,EAAU;AACtB,QAAA,MAAM,MAAM,MAAM,KAAA,CAAM,CAAA,EAAG,GAAA,CAAI,OAAO,CAAA,cAAA,CAAA,EAAkB;AAAA,UACtD,OAAA,EAAS,EAAE,cAAA,EAAgB,GAAA,CAAI,SAAA;AAAU,SAC1C,CAAA;AACD,QAAA,IAAI,CAAC,GAAA,CAAI,EAAA,EAAI,OAAO,QAAA;AACpB,QAAA,MAAM,IAAA,GAAQ,MAAM,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E,IAAA,OAAO,KAAA,IAAS,KAAA,CAAM,MAAA,GAAS,CAAA,GAAI,KAAA,GAAQ,IAAA;AAAA,EAC7C,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAYO,SAAS,gBAAA,GAAyB;AACvC,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,IAAI,GAAA,CAAI,MAAA,CAAO,SAAS,IAAI,CAAA;AACxC,IAAA,IAAI,CAAC,GAAA,CAAI,YAAA,CAAa,GAAA,CAAI,QAAQ,CAAA,EAAG;AACrC,IAAA,GAAA,CAAI,YAAA,CAAa,OAAO,QAAQ,CAAA;AAChC,IAAA,MAAA,CAAO,QAAQ,YAAA,CAAa,IAAI,EAAA,EAAI,GAAA,CAAI,UAAU,CAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"DS4E7FAI.js","sourcesContent":["import { getConfig } from '../config';\n\n// ── Funnel telemetry transport ──────────────────────────────────────────────\n//\n// Thin client for the-backend's abandoned-funnel capture endpoints:\n// GET /config/funnel → which capture features this tenant enabled\n// POST /funnel/events → survey-session telemetry sink\n//\n// Everything here is fire-and-forget and fail-silent: funnel capture is\n// marketing instrumentation, and it must never break or slow the survey.\n\nexport interface FunnelConfig {\n telemetry: boolean;\n emailGate: boolean;\n /** When true (tenant features.funnelEmailGateRequired), the gate offers no skip. */\n emailGateRequired: boolean;\n}\n\nconst DISABLED: FunnelConfig = { telemetry: false, emailGate: false, emailGateRequired: false };\n\nlet configPromise: Promise<FunnelConfig> | null = null;\n\n/**\n * The tenant's funnel-capture posture, fetched once per page load and cached.\n * Fails closed: any error reads as \"both off\".\n */\nexport function fetchFunnelConfig(): Promise<FunnelConfig> {\n if (!configPromise) {\n configPromise = (async () => {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/config/funnel`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return DISABLED;\n const body = (await res.json()) as Partial<FunnelConfig>;\n return {\n telemetry: body.telemetry === true,\n emailGate: body.emailGate === true,\n emailGateRequired: body.emailGateRequired === true,\n };\n } catch {\n return DISABLED;\n }\n })();\n }\n return configPromise;\n}\n\n/**\n * Continue an existing funnel session (resume-from-email): the emailed link\n * identifies the session that already holds this person's email and reminder\n * history, so adopting its id keeps everything on one row instead of forking a\n * new one that looks like a brand-new visitor.\n */\nexport function adoptFunnelSessionId(id: string): void {\n if (!id) return;\n try {\n sessionStorage.setItem(sessionIdKey(), id);\n } catch {\n /* storage unavailable — the session stays ephemeral */\n }\n}\n\n/** Test seam: forget the cached config so the next fetch re-resolves. */\nexport function resetFunnelConfigCache(): void {\n configPromise = null;\n}\n\nconst sessionIdKey = () => `${getConfig().storagePrefix}-funnel-session`;\n\n/**\n * Stable id for this survey session, minted on first use and kept in\n * sessionStorage — a refresh continues the same session (matching the survey\n * draft's resume behavior); a new tab or browser session starts a new one.\n */\nexport function funnelSessionId(): string {\n let id: string | null = null;\n try {\n id = sessionStorage.getItem(sessionIdKey());\n } catch {\n /* storage unavailable (private mode) — fall through to ephemeral id */\n }\n if (!id) {\n id =\n typeof crypto !== 'undefined' && 'randomUUID' in crypto\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.random().toString(36).slice(2)}`;\n try {\n sessionStorage.setItem(sessionIdKey(), id);\n } catch {\n /* ephemeral it is */\n }\n }\n return id;\n}\n\n/**\n * The current survey session id, or null — WITHOUT minting one.\n *\n * `funnelSessionId()` creates an id on first read, which is right for the\n * survey (asking means a survey is starting) and wrong for anything else. Cart\n * capture uses this to say \"if this shopper also has a survey session, here it\n * is\" — letting the backend borrow the email the gate already collected —\n * without conjuring survey sessions on a storefront that never runs one.\n */\nexport function peekFunnelSessionId(): string | null {\n try {\n return sessionStorage.getItem(sessionIdKey());\n } catch {\n return null;\n }\n}\n\n/**\n * Fire-and-forget event post. `keepalive` lets the request survive a page\n * unload — which is exactly when the `abandoned` event is sent. (This is why\n * it's `fetch` and not `navigator.sendBeacon`: beacons can't carry the\n * X-Tenant-Key header the tenant-scoped mount requires.)\n */\nexport function postFunnelEvent(type: string, data?: Record<string, unknown>): void {\n try {\n const cfg = getConfig();\n void fetch(`${cfg.apiBase}/funnel/events`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n },\n body: JSON.stringify({ sessionId: funnelSessionId(), type, data }),\n }).catch(() => {});\n } catch {\n /* not configured yet — drop */\n }\n}\n\n// ── Survey drafts (cross-device resume) ─────────────────────────────────────\n\nexport interface FunnelDraftPayload {\n answers: Array<{ questionId: string; value: unknown }>;\n stepIndex: number;\n}\n\n/**\n * Save in-progress answers to Apex (through the-backend's embed proxy) and\n * return the draft id, so the next save updates the same row.\n *\n * Answers travel to the CLINICAL system — the partner backend stores only the\n * returned pointer. Returns null on any failure: a draft is best-effort, and\n * losing one costs a retype, never correctness.\n */\nexport async function saveFunnelDraft(\n draft: FunnelDraftPayload & { draftId?: string; drugIds?: string[]; templateId?: string; mode?: string },\n): Promise<string | null> {\n try {\n const cfg = getConfig();\n if (!cfg.apexEmbedApiBase) return null;\n const res = await fetch(`${cfg.apexEmbedApiBase}/v2/embed/surveys/drafts`, {\n method: 'PUT',\n headers: { 'Content-Type': 'application/json', 'X-Tenant-Key': cfg.tenantKey },\n body: JSON.stringify(draft),\n });\n if (!res.ok) return null;\n const body = (await res.json()) as { draftId?: string };\n return body.draftId ?? null;\n } catch {\n return null;\n }\n}\n\nexport interface ResumedDraft extends FunnelDraftPayload {\n sessionId: string;\n draftId: string;\n}\n\n/**\n * Exchange an emailed resume token for the saved answers.\n *\n * The token is the ONLY thing authorizing this read — the-backend verifies its\n * HMAC before fetching from Apex with credentials the browser never sees. A\n * 404 (expired, already submitted, tampered) resolves to null so the caller\n * simply starts a fresh survey.\n */\nexport async function fetchResumedDraft(token: string): Promise<ResumedDraft | null> {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/funnel/resume?token=${encodeURIComponent(token)}`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return null;\n const body = (await res.json()) as Partial<ResumedDraft>;\n if (!body.draftId || !Array.isArray(body.answers)) return null;\n return {\n sessionId: String(body.sessionId ?? ''),\n draftId: body.draftId,\n answers: body.answers,\n stepIndex: typeof body.stepIndex === 'number' ? body.stepIndex : 0,\n };\n } catch {\n return null;\n }\n}\n\n/** Read the `?resume=` token from the current URL. */\nexport function readResumeToken(): string | null {\n try {\n const token = new URLSearchParams(window.location.search).get('resume');\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop `?resume=` from the address bar once it has been redeemed.\n *\n * This token authorizes a read of someone's clinical answers, so leaving it in\n * the address bar is worse than leaving the cart's there: it gets bookmarked,\n * pasted into a support chat, or captured by whatever the patient's browser\n * syncs. The answers are mirrored into local storage on redemption, so a\n * refresh resumes from this device without it. History is replaced, not\n * pushed — the token was never a page.\n */\nexport function stripResumeToken(): void {\n try {\n const url = new URL(window.location.href);\n if (!url.searchParams.has('resume')) return;\n url.searchParams.delete('resume');\n window.history.replaceState({}, '', url.toString());\n } catch {\n /* no history API — leaving the param is harmless */\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/flows/products.ts","../../src/flows/categoryVisual.ts","../../src/flows/subscriptionIntake.ts","../../src/flows/cartCapture.ts"],"names":["createSignal","createEffect"],"mappings":";;;;;;;AAWO,SAAS,cAAA,CAAe,SAAyB,MAAA,EAA+B;AACrF,EAAA,MAAM,OAAA,GAAA,CAAW,OAAA,CAAQ,aAAA,IAAiB,EAAC,EAAG,KAAK,CAAC,CAAA,KAAM,CAAA,CAAE,MAAA,KAAW,MAAM,CAAA;AAC7E,EAAA,IAAI,OAAA,IAAW,OAAA,CAAQ,KAAA,IAAS,IAAA,SAAa,OAAA,CAAQ,KAAA;AACrD,EAAA,OAAO,OAAA,CAAQ,KAAA;AACjB;AAIO,SAAS,YA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;AACR,IAAA,OAAA,GAAU,KAAA;AAAA,EACZ,CAAA;AACF","file":"EIXZJX6R.js","sourcesContent":["import { createMemo, createResource, createSignal, type Accessor, type Resource } from 'solid-js';\nimport { productsApi, type CatalogProduct } from '../api/client';\nimport cartStore from '../stores/cart';\nimport medicationStore from '../stores/medication';\n\nexport type { CatalogProduct } from '../api/client';\n\n// ── Pricing helpers (pure) ──────────────────────────────────────────\n\n/** Effective price for a single dose: the overlay price if present, else the\n * product's base price (null when neither is set — dose not purchasable). */\nexport function priceForDosage(product: CatalogProduct, dosage: string): number | null {\n const overlay = (product.dosage_prices ?? []).find((d) => d.dosage === dosage);\n if (overlay && overlay.price != null) return overlay.price;\n return product.price;\n}\n\n/** Lowest price across the product's available doses (overlay-or-base each),\n * falling back to the product-level price. Returns null for free / unpriced products. */\nexport function lowestPrice(product: CatalogProduct): number | null {\n const available = product.available_dosages ?? [];\n if (available.length === 0) return product.price;\n let min: number | null = null;\n for (const dose of available) {\n const p = priceForDosage(product, dose);\n if (p != null && (min == null || p < min)) min = p;\n }\n return min ?? product.price;\n}\n\n/**\n * Lowest sale price for a tiered product, computed by re-deriving the same\n * percent/fixed discount the backend applied at the product level. Used so\n * the strikethrough lands on the displayed (lowest-tier) value.\n *\n * Returns null when no active sale, no discount, or insufficient data.\n */\nexport function lowestSalePrice(product: CatalogProduct, basePrice: number | null): number | null {\n if (basePrice == null || !product.activeSale) return null;\n const sale = product.activeSale;\n const baseCents = Math.round(basePrice * 100);\n if (sale.discountCents <= 0) return null;\n if (\n product.salePriceCents != null &&\n product.price != null &&\n Math.abs(product.price - basePrice) < 0.001\n ) {\n return product.salePriceCents / 100;\n }\n if (product.price != null && product.salePriceCents != null && product.price > 0) {\n const ratio = product.salePriceCents / Math.round(product.price * 100);\n return Math.max(0, basePrice * ratio);\n }\n return Math.max(0, (baseCents - sale.discountCents) / 100);\n}\n\n// ── useCatalog ──────────────────────────────────────────────────────\n\nexport interface CatalogFlow {\n products: Resource<CatalogProduct[]>;\n /** Products in the \"weight-loss\" category. */\n weightLoss: Accessor<CatalogProduct[]>;\n /** Products NOT in \"weight-loss\" (peptides, recovery, etc). */\n peptides: Accessor<CatalogProduct[]>;\n /** Filter products by an arbitrary category slug. */\n filterByCategory: (slug: string) => CatalogProduct[];\n}\n\n/** Fetches the product catalog and exposes a couple of common derivations. */\nexport function useCatalog(): CatalogFlow {\n const [products] = createResource<CatalogProduct[]>(async () => {\n try {\n const res = await productsApi.list();\n return res.products;\n } catch {\n return [];\n }\n });\n\n const weightLoss = () =>\n (products() ?? []).filter((p) => (p.categories ?? []).includes('weight-loss'));\n const peptides = () =>\n (products() ?? []).filter((p) => !(p.categories ?? []).includes('weight-loss'));\n const filterByCategory = (slug: string) =>\n (products() ?? []).filter((p) => (p.categories ?? []).includes(slug));\n\n return { products, weightLoss, peptides, filterByCategory };\n}\n\n// ── useProductDetail ────────────────────────────────────────────────\n\nexport interface ProductDetailFlow {\n product: Resource<CatalogProduct | null>;\n dosageOptions: Accessor<Array<{ dosage: string; price: number; savingsPrice: number | null }>>;\n selectedDosage: Accessor<string>;\n setSelectedDosage: (v: string) => void;\n /** Effective base price for the currently-selected dosage. */\n selectedPrice: Accessor<number | null>;\n /** Sale price for the selected dosage, if a sale is active. */\n selectedSalePrice: Accessor<number | null>;\n /** 'per_dose' (default) or 'flat_fee'. When 'flat_fee', `dosageOptions` is\n * collapsed to a single entry and consumer UI should hide the dose picker. */\n pricingMode: Accessor<'per_dose' | 'flat_fee'>;\n /** True if the product+dosage combination is already in cart. */\n inCart: Accessor<boolean>;\n addToCart: () => void;\n}\n\n/**\n * Single-product page state. Loads the catalog and finds the product by id.\n * Tracks dosage selection, derives current/sale price, exposes addToCart.\n */\nexport function useProductDetail(productId: Accessor<string>): ProductDetailFlow {\n const [product] = createResource<CatalogProduct | null, string>(productId, async (id) => {\n if (!id) return null;\n try {\n const res = await productsApi.list();\n return res.products.find((p) => p.id === id) ?? null;\n } catch {\n return null;\n }\n });\n\n const pricingMode = createMemo<'per_dose' | 'flat_fee'>(\n () => product()?.pricing_mode ?? 'per_dose',\n );\n\n const dosageOptions = createMemo(() => {\n const p = product();\n if (!p) return [];\n // Doses come from the linked Apex drug (available_dosages); dosage_prices is\n // only a price overlay. A dose with no resolvable price (no overlay + no\n // base price) is dropped — it isn't purchasable.\n const all = (p.available_dosages ?? [])\n .map((dosage) => {\n const overlay = (p.dosage_prices ?? []).find((d) => d.dosage === dosage);\n const price = overlay && overlay.price != null ? overlay.price : p.price;\n return { dosage, price, savingsPrice: overlay?.savingsPrice ?? null };\n })\n .filter((o): o is { dosage: string; price: number; savingsPrice: number | null } => o.price != null);\n if (pricingMode() !== 'flat_fee' || all.length === 0) return all;\n // flat_fee: collapse to a single entry — prefer dosage_override, else first.\n const override = p.dosage_override;\n const chosen = (override && all.find((d) => d.dosage === override)) || all[0];\n return [chosen];\n });\n const [selectedDosage, setSelectedDosage] = createSignal<string>('');\n\n // Auto-select the first dosage once options arrive\n createMemo(() => {\n const opts = dosageOptions();\n if (opts.length > 0 && !selectedDosage()) setSelectedDosage(opts[0].dosage);\n });\n\n const selectedPrice = createMemo<number | null>(() => {\n const opts = dosageOptions();\n const chosen = opts.find((d) => d.dosage === selectedDosage());\n if (chosen) return chosen.price;\n return product()?.price ?? null;\n });\n\n const selectedSalePrice = createMemo<number | null>(() => {\n const p = product();\n const base = selectedPrice();\n if (!p || base == null || !p.activeSale) return null;\n if (p.salePriceCents != null && p.price != null && p.price > 0) {\n const ratio = p.salePriceCents / Math.round(p.price * 100);\n return Math.max(0, base * ratio);\n }\n return Math.max(0, base - p.activeSale.discountCents / 100);\n });\n\n const inCart = createMemo(() => {\n const p = product();\n if (!p) return false;\n const dosage = selectedDosage() || (dosageOptions()[0]?.dosage ?? '');\n const key = cartStore.itemKey(p.id, dosage);\n return cartStore.items().some((i) => cartStore.itemKey(i.productId, i.dosage) === key);\n });\n\n function addToCart() {\n const p = product();\n if (!p) return;\n const dosage = selectedDosage() || (dosageOptions()[0]?.dosage ?? '');\n const effective = selectedSalePrice() ?? selectedPrice() ?? 0;\n const priceCents = Math.round(effective * 100);\n cartStore.add({\n productId: p.id,\n productName: p.name,\n dosage,\n quantity: 1,\n priceCents,\n drugId: p.id,\n apexDrugId: p.apex_drug_id ?? null,\n categories: p.categories ?? [],\n thumbnailUrl: p.thumbnail_url ?? undefined,\n hideDoseLabel: pricingMode() === 'flat_fee' ? true : undefined,\n isSubscription: p.is_subscription ? true : undefined,\n });\n cartStore.open();\n }\n\n return {\n product,\n dosageOptions,\n selectedDosage,\n setSelectedDosage,\n selectedPrice,\n selectedSalePrice,\n pricingMode,\n inCart,\n addToCart,\n };\n}\n\n// ── useMedicationSelect ─────────────────────────────────────────────\n\nexport interface MedicationSelectFlow {\n products: Resource<CatalogProduct[]>;\n weightLoss: Accessor<CatalogProduct[]>;\n peptides: Accessor<CatalogProduct[]>;\n /** Pick a specific product as the patient's selected medication and proceed. The site fires the navigation in the optional `onSelected` callback. */\n selectMedication: (product: CatalogProduct) => void;\n /** Pick \"general consultation\" — a null drugId, indicating no pre-selected drug. */\n selectGeneralConsultation: () => void;\n}\n\nexport interface UseMedicationSelectOptions {\n /** Called after a selection is made. Sites typically navigate to their survey route. */\n onSelected?: () => void;\n /** Override the label used for the general-consultation selection. Default \"General Consultation\". */\n generalConsultationLabel?: string;\n}\n\n/**\n * Catalog browse + select-for-survey. The selection is written to\n * medicationStore (legacy single-item flow); the site navigates afterward\n * via the onSelected callback.\n */\nexport function useMedicationSelect(\n options: UseMedicationSelectOptions = {},\n): MedicationSelectFlow {\n const catalog = useCatalog();\n\n function selectMedication(product: CatalogProduct) {\n medicationStore.select({ drugId: product.id, drugName: product.name });\n options.onSelected?.();\n }\n\n function selectGeneralConsultation() {\n medicationStore.select({\n drugId: null,\n drugName: options.generalConsultationLabel ?? 'General Consultation',\n });\n options.onSelected?.();\n }\n\n return {\n products: catalog.products,\n weightLoss: catalog.weightLoss,\n peptides: catalog.peptides,\n selectMedication,\n selectGeneralConsultation,\n };\n}\n","/**\n * Deterministic procedural color for product categories.\n *\n * Sites want a stable color per category id without curating maps. The hash\n * is stable across reloads, so the same id always picks the same slot. Sites\n * override the palette to brand-align — default palette works out of the box.\n */\n\nfunction hashId(id: string): number {\n let h = 5381;\n for (let i = 0; i < id.length; i++) h = ((h << 5) + h + id.charCodeAt(i)) | 0;\n return Math.abs(h);\n}\n\n/** Default palette. Reads on light or dark; sites that want brand alignment\n * pass their own array (e.g. CSS var refs). */\nexport const DEFAULT_COLOR_PALETTE: readonly string[] = [\n '#4f46e5', // indigo\n '#0891b2', // cyan\n '#0d9488', // teal\n '#f59e0b', // amber\n '#e11d48', // rose\n '#10b981', // emerald\n '#8b5cf6', // violet\n '#f97316', // orange\n];\n\nexport interface CategoryColorOpts {\n palette?: readonly string[];\n}\n\nexport function categoryColor(id: string, opts: CategoryColorOpts = {}): string {\n const palette = opts.palette ?? DEFAULT_COLOR_PALETTE;\n if (palette.length === 0) return 'currentColor';\n return palette[hashId(id) % palette.length];\n}\n","import { createEffect, createSignal, onMount, type Accessor } from 'solid-js';\nimport {\n promoCodesApi,\n subscriptionsApi,\n usersApi,\n newIdempotencyKey,\n ApiError,\n type PromoValidationResponse,\n type ApiResponse,\n} from '../api/client';\nimport { readPromoCode, clearPromoCode } from '../api/promoRef';\nimport authStore from '../stores/auth';\nimport { useCardTokenizer } from './_internal/cardTokenizer';\nimport { formatCardNumber, formatExpiry, formatCvv } from './checkout';\nimport { getConfig } from '../config';\nimport { useAddressPair, validateAddress, firstAddressError, type AddressPair } from './address';\nimport { isLive } from './subscriptionStatus';\n\n// ── Draft persistence ───────────────────────────────────────────────\n\nconst DRAFT_TTL_MS = 7 * 24 * 3600 * 1000;\nconst MAX_RESTORABLE_STEP = 1; // Account + Address only; never restore into Payment\n\ninterface IntakeDraft {\n step?: number;\n firstName?: string;\n lastName?: string;\n dateOfBirth?: string;\n email?: string;\n phone?: string;\n street?: string;\n city?: string;\n state?: string;\n zip?: string;\n /** Idempotency key for THIS draft's create/signup attempt. Persisted so a\n * refresh mid-submit retries with the SAME key and the backend dedupes\n * instead of double-charging; rotated after a definitive rejection. */\n idempotencyKey?: string;\n savedAt?: number;\n}\n\nfunction draftKey(): string {\n return `${getConfig().storagePrefix}-subscription-intake-draft`;\n}\n\nfunction loadDraft(): IntakeDraft {\n try {\n const raw = localStorage.getItem(draftKey());\n if (!raw) return {};\n const parsed = JSON.parse(raw) as IntakeDraft;\n if (parsed.savedAt && Date.now() - parsed.savedAt > DRAFT_TTL_MS) {\n localStorage.removeItem(draftKey());\n return {};\n }\n return parsed ?? {};\n } catch {\n return {};\n }\n}\n\nfunction saveDraft(draft: IntakeDraft) {\n try {\n localStorage.setItem(draftKey(), JSON.stringify({ ...draft, savedAt: Date.now() }));\n } catch {\n // noop\n }\n}\n\nfunction clearDraft() {\n try {\n localStorage.removeItem(draftKey());\n } catch {\n // noop\n }\n}\n\n// ── Types ───────────────────────────────────────────────────────────\n\nexport interface SurveyResult {\n surveyResponseId: string;\n /**\n * v2 survey response id. When set, the Rx is linked to the Apex survey\n * snapshot and Apex generates the prescriber case notes from it (no local\n * caseNotes synthesis). Leave unset for the legacy v1 flow.\n */\n v2SurveyResponseId?: string;\n caseNotes?: string;\n drugId: string;\n drugName: string;\n dosage: string;\n}\n\nexport interface MedicationPricing {\n productId: string;\n productName: string;\n priceCents: number;\n savingsPriceCents?: number | null;\n}\n\nexport type SubscriptionIntakeOutcome =\n | { kind: 'in_progress' }\n | { kind: 'tokenizing' }\n | { kind: 'submitting' }\n /**\n * The member already holds a live subscription, so this intake must not create\n * a second one. Emitted ONLY under `singleSubscription` — without that option\n * the flow behaves exactly as before, so existing consumers that switch on\n * 'completed' alone are unaffected.\n *\n * Deliberately NOT 'completed': that kind means *this* purchase succeeded, and\n * hosts navigate onward celebrating it. This one means the member arrived\n * already subscribed and needs telling, not congratulating.\n */\n | { kind: 'already_subscribed'; productId?: string }\n | { kind: 'completed' };\n\nexport interface UseSubscriptionIntakeFlowOptions {\n surveyResult: SurveyResult;\n pricing: MedicationPricing;\n intervalDays?: number;\n /**\n * Whether the member is enrolled in the savings program — read reactively, so\n * a verification that completes mid-intake re-quotes. When true and the\n * product defines `savingsPriceCents`, that rate is quoted instead of list.\n *\n * Must track the same member the SERVER will resolve at charge time (the\n * persisted savings link), or the quote and the charge disagree.\n */\n isSavingsMember?: () => boolean;\n /**\n * Single-subscription tenants: the site sells ONE subscription program, so a\n * member may hold at most one live subscription — of ANY product.\n *\n * Widens the mount reconcile below from \"already subscribed to THIS product\"\n * to \"already subscribed to anything\", and turns the server's\n * `SUBSCRIPTION_EXISTS` rejection into an `already_subscribed` outcome instead\n * of a raw error banner. Mirrors `features.singleSubscription` on the tenant;\n * setting it here without the tenant flag still guards the common paths, but\n * the server is what actually enforces it.\n */\n singleSubscription?: boolean;\n}\n\nexport interface PromoPricing {\n baseCents: number;\n discountCents: number;\n finalCents: number;\n promoCode?: string;\n}\n\nexport interface SubscriptionIntakeFlow {\n // Step 0 = Account, 1 = Address, 2 = Payment\n step: Accessor<number>;\n stepCount: 3;\n next: () => Promise<void>;\n back: () => void;\n\n outcome: Accessor<SubscriptionIntakeOutcome>;\n error: Accessor<string | null>;\n submitting: Accessor<boolean>;\n tokenizing: Accessor<boolean>;\n /** True once the card tokenizer is ready (config loaded; for AuthNet, Accept.js loaded too). Gate submission on this. */\n tokenizerReady: Accessor<boolean>;\n /** @deprecated alias of tokenizerReady (pre-rename name). */\n acceptJsReady: Accessor<boolean>;\n /** Non-null when payment setup failed to initialize — render as a banner. */\n /** Tokenizer init failure, or null. */\n tokenizerError: Accessor<string | null>;\n /** @deprecated alias of tokenizerError (pre-rename name). */\n acceptJsError: Accessor<string | null>;\n\n // Step 0 — Account\n firstName: Accessor<string>; setFirstName: (v: string) => void;\n lastName: Accessor<string>; setLastName: (v: string) => void;\n email: Accessor<string>; setEmail: (v: string) => void;\n password: Accessor<string>; setPassword: (v: string) => void;\n dateOfBirth: Accessor<string>; setDateOfBirth: (v: string) => void;\n phone: Accessor<string>; setPhone: (v: string) => void;\n\n // Step 1 — Address (delivery + billing override; see AddressPair).\n // `address.billingSameAsShipping` is this flow's \"billing same as delivery\".\n address: AddressPair;\n\n // Step 2 — Payment\n cardNumber: Accessor<string>; setCardNumber: (v: string) => void;\n expiry: Accessor<string>; setExpiry: (v: string) => void;\n cvv: Accessor<string>; setCvv: (v: string) => void;\n\n // Promo\n promoCode: Accessor<string>; setPromoCode: (v: string) => void;\n promoValidating: Accessor<boolean>;\n promoError: Accessor<string | null>;\n promoApplied: Accessor<PromoValidationResponse | null>;\n applyPromo: () => Promise<void>;\n clearPromo: () => void;\n\n // Pricing (reflects applied promo)\n pricing: Accessor<PromoPricing>;\n\n // Context (read-only, from options)\n surveyResult: SurveyResult;\n medication: MedicationPricing;\n\n submit: () => Promise<void>;\n}\n\n// ── Hook ────────────────────────────────────────────────────────────\n\nexport function useSubscriptionIntakeFlow(\n options: UseSubscriptionIntakeFlowOptions,\n): SubscriptionIntakeFlow {\n const accept = useCardTokenizer();\n\n let restored: IntakeDraft = {};\n if (typeof window !== 'undefined') restored = loadDraft();\n\n const [step, setStep] = createSignal(Math.min(restored.step ?? 0, MAX_RESTORABLE_STEP));\n const [error, setError] = createSignal<string | null>(null);\n const [tokenizing, setTokenizing] = createSignal(false);\n const [submitting, setSubmitting] = createSignal(false);\n const [outcome, setOutcome] = createSignal<SubscriptionIntakeOutcome>({ kind: 'in_progress' });\n\n // Account\n const [firstName, setFirstName] = createSignal(restored.firstName ?? '');\n const [lastName, setLastName] = createSignal(restored.lastName ?? '');\n const [email, setEmail] = createSignal(restored.email ?? '');\n const [password, setPassword] = createSignal('');\n const [dateOfBirth, setDateOfBirth] = createSignal(restored.dateOfBirth ?? '');\n const [phone, setPhone] = createSignal(restored.phone ?? '');\n\n // Address (delivery/shipping + billing override), backed by the shared\n // useAddressPair so validation and the same-as / copy-on-uncheck behavior\n // match the checkout flow. The individual accessors below keep this flow's\n // public interface stable for consuming storefronts (no breaking change).\n const addr = useAddressPair({\n initialShipping: {\n street: restored.street ?? '',\n city: restored.city ?? '',\n state: restored.state ?? '',\n zip: restored.zip ?? '',\n },\n });\n\n // Internal shipping getters for draft persistence + payload building; the full\n // read/write surface (incl. billing override) is exposed as `address` below.\n const street = () => addr.shipping().street;\n const city = () => addr.shipping().city;\n const state = () => addr.shipping().state;\n const zip = () => addr.shipping().zip;\n\n // Effective billing address sent as the charge's billTo.\n const effectiveBillingAddress = () => {\n const b = addr.effectiveBilling();\n return { street: b.street.trim(), city: b.city.trim(), state: b.state, zip: b.zip.trim() };\n };\n\n // Payment\n const [cardNumberRaw, setCardNumberRaw] = createSignal('', { equals: false });\n const [expiryRaw, setExpiryRaw] = createSignal('', { equals: false });\n const [cvvRaw, setCvvRaw] = createSignal('', { equals: false });\n\n // Promo\n const [promoCode, setPromoCode] = createSignal('');\n const [promoValidating, setPromoValidating] = createSignal(false);\n const [promoError, setPromoError] = createSignal<string | null>(null);\n const [promoApplied, setPromoApplied] = createSignal<PromoValidationResponse | null>(null);\n\n // ── Pre-fill from a `?promo=` landing ───────────────────────────\n //\n // A campaign link stashes its code (see api/promoRef). Being inside the\n // storage window says nothing about the CODE still being live — a sale can end\n // while the stash is fresh — so re-validate before showing it to anyone, and\n // drop it silently when the server says no. An expired or withdrawn code must\n // not greet a member with an error they did nothing to cause.\n //\n // Pre-fills ONLY: the member still presses Apply. Auto-applying would put a\n // discount on screen before they asked for it and, for a savings member handed\n // an exclusive code, would surface a refusal on arrival.\n //\n // Yields to anything already in the field. Nothing sets it before mount today\n // (the draft does not persist a promo), but a member's own entry must never be\n // overwritten by a stale link if that changes.\n onMount(async () => {\n if (promoCode().trim()) return;\n const stashed = readPromoCode();\n if (!stashed) return;\n try {\n const res = await promoCodesApi.validate(stashed, {\n productIds: [options.pricing.productId],\n subtotalCents: savingsBaseCents(),\n });\n if (res.valid) setPromoCode(stashed);\n else clearPromoCode();\n } catch {\n // Network/-server blip: leave the stash for the next visit rather than\n // discarding a code that may be perfectly good.\n }\n });\n\n // Idempotency key for the create/signup POST — restored with the draft so a\n // retry after a refresh presents the same key (see IntakeDraft.idempotencyKey).\n const [idemKey, setIdemKey] = createSignal(restored.idempotencyKey ?? '');\n\n // ── Auto-save draft ─────────────────────────────────────────────\n\n onMount(() => {\n createEffect(() => {\n saveDraft({\n step: step(),\n firstName: firstName(),\n lastName: lastName(),\n dateOfBirth: dateOfBirth(),\n email: email(),\n phone: phone(),\n street: street(),\n city: city(),\n state: state(),\n zip: zip(),\n idempotencyKey: idemKey() || undefined,\n });\n });\n });\n\n // ── Mount reconcile (authenticated re-subscribe path) ───────────\n //\n // The restored draft re-arms submit with no memory of a create that already\n // committed: if the subscription landed server-side but this client never saw\n // the response (refresh mid-submit, dropped connection), the user is invited\n // to subscribe — and be charged — again. Ask the server before offering the\n // form.\n //\n // Scope depends on the tenant's model:\n // default → THIS product only. A subscription to a different\n // medication is a legitimate separate purchase and\n // must not block this intake.\n // singleSubscription → any live subscription. The program IS the\n // subscription, so a second one of any product is a\n // double charge, not a second purchase.\n //\n // The unauthenticated path needs no reconcile (a committed signup makes the\n // email taken, so a re-submit fails instead of double-charging). Fails open —\n // the server refuses the duplicate regardless, and blocking a real intake on a\n // lookup blip costs a customer.\n onMount(async () => {\n if (!authStore.isAuthenticated()) return;\n try {\n const res = (await subscriptionsApi.list()) as {\n subscriptions?: Array<{ productId?: string; status?: string }>;\n } | null;\n const existing = res?.subscriptions?.find(\n (s) =>\n isLive(s.status) &&\n (options.singleSubscription || s.productId === options.pricing.productId),\n );\n if (existing) {\n clearDraft();\n // Same-product is the ambiguous-retry case this reconcile was built for:\n // the purchase this very flow was configured for already exists, so the\n // member is done. A DIFFERENT product means they came back to buy\n // something they can't have alongside what they hold — a distinct\n // outcome, and only reachable under singleSubscription.\n setOutcome(\n existing.productId === options.pricing.productId\n ? { kind: 'completed' }\n : { kind: 'already_subscribed', productId: existing.productId },\n );\n }\n } catch {\n // Reconcile is a guard, not a gate — never block intake on a lookup blip.\n }\n });\n\n // ── Pricing ─────────────────────────────────────────────────────\n\n /**\n * The base price to quote: the product's savings rate for an enrolled member,\n * otherwise list.\n *\n * `savingsPriceCents` was carried on MedicationPricing but never actually\n * read, so enrolled members were quoted (and charged) list price. This mirrors\n * the SERVER rule exactly — `resolveProductPricing` in the-backend keys off\n * the member's savings link and treats a null savings price as \"no savings\n * rate for this item\", never as free — because the server re-derives the\n * charge from the DB and ignores the amount posted here. If the two rules ever\n * disagree, the member sees one number and is charged another; that mismatch\n * is the whole reason this exists, so keep them in step.\n */\n const savingsBaseCents = (): number => {\n const list = options.pricing.priceCents;\n const savings = options.pricing.savingsPriceCents;\n return options.isSavingsMember?.() && savings != null ? savings : list;\n };\n\n const pricing = (): PromoPricing => {\n const baseCents = savingsBaseCents();\n const promo = promoApplied();\n if (!promo?.valid || !promo.discountCents) {\n return { baseCents, discountCents: 0, finalCents: baseCents };\n }\n const discountCents = Math.min(baseCents, promo.discountCents);\n return {\n baseCents,\n discountCents,\n finalCents: promo.finalCents ?? Math.max(0, baseCents - discountCents),\n promoCode: promo.promoCode?.code,\n };\n };\n\n // ── Promo code ──────────────────────────────────────────────────\n\n async function applyPromo() {\n const code = promoCode().trim();\n if (!code) {\n setPromoError('Enter a promo code.');\n return;\n }\n setPromoError(null);\n setPromoValidating(true);\n try {\n const res = await promoCodesApi.validate(code, {\n productIds: [options.pricing.productId],\n // The base the promo will actually be applied to. For a savings member\n // that is the savings price, not list: the server discounts the\n // savings-substituted subtotal at checkout, so quoting off list would\n // show a percentage promo as a bigger saving than it is (10% of $399\n // displayed, 10% of $280 charged). Same rule as savingsBaseCents — keep\n // the two in step.\n subtotalCents: savingsBaseCents(),\n });\n if (!res.valid) {\n setPromoError(res.error ?? 'Invalid promo code.');\n setPromoApplied(null);\n } else {\n setPromoApplied(res);\n setPromoError(null);\n }\n } catch {\n setPromoError('Could not validate promo code. Please try again.');\n setPromoApplied(null);\n } finally {\n setPromoValidating(false);\n }\n }\n\n function clearPromo() {\n setPromoCode('');\n setPromoApplied(null);\n setPromoError(null);\n }\n\n // ── Validation per step ─────────────────────────────────────────\n\n function validateStep(s: number): string | null {\n if (s === 0) {\n if (!firstName().trim()) return 'First name is required.';\n if (!lastName().trim()) return 'Last name is required.';\n // Authenticated members already have an account — they don't re-enter\n // credentials; submit() subscribes their existing account instead.\n if (!authStore.isAuthenticated()) {\n if (!email().trim()) return 'Email is required.';\n if (!password().trim()) return 'Password is required.';\n if (password().length < 8) return 'Password must be at least 8 characters.';\n }\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateOfBirth())) return 'Enter a valid date of birth.';\n const dob = new Date(dateOfBirth() + 'T00:00:00');\n if (Number.isNaN(dob.getTime())) return 'Enter a valid date of birth.';\n const age = (Date.now() - dob.getTime()) / (365.25 * 24 * 3600 * 1000);\n if (age < 18) return 'You must be at least 18 to register.';\n if (age > 120) return 'Enter a valid date of birth.';\n } else if (s === 1) {\n return firstAddressError(validateAddress(addr.shipping(), '', { enforceAvailability: true }));\n } else if (s === 2) {\n if (!cardNumberRaw().trim()) return 'Card number is required.';\n if (!expiryRaw().trim()) return 'Expiration date is required.';\n if (!cvvRaw().trim()) return 'CVV is required.';\n }\n return null;\n }\n\n // ── Navigation ───────────────────────────────────────────────────\n\n async function next() {\n const err = validateStep(step());\n if (err) {\n setError(err);\n return;\n }\n setError(null);\n setStep((s) => s + 1);\n }\n\n function back() {\n setError(null);\n if (step() > 0) setStep((s) => s - 1);\n }\n\n // ── Submit (from Payment step) ──────────────────────────────────\n\n async function submit() {\n const finalPricing = pricing();\n const isFree = finalPricing.finalCents === 0;\n\n if (!isFree) {\n const cardErr = validateStep(2);\n if (cardErr) {\n setError(cardErr);\n return;\n }\n if (addr.billingIsOverride()) {\n const bErr = firstAddressError(validateAddress(addr.billing(), 'Billing'));\n if (bErr) { setError(bErr); return; }\n }\n }\n\n setError(null);\n\n let opaque: Record<string, unknown> | undefined;\n if (!isFree) {\n setTokenizing(true);\n setOutcome({ kind: 'tokenizing' });\n try {\n opaque = await accept.tokenize({\n cardNumber: cardNumberRaw(),\n expiry: expiryRaw(),\n cvv: cvvRaw(),\n });\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Card tokenization failed.');\n setTokenizing(false);\n setOutcome({ kind: 'in_progress' });\n return;\n }\n setTokenizing(false);\n }\n\n setSubmitting(true);\n setOutcome({ kind: 'submitting' });\n\n // One key per logical purchase attempt: minted on first submit, persisted in\n // the draft (the auto-save effect tracks it), reused verbatim on retries so\n // the backend's idempotency middleware can collapse a replay of a create\n // that already committed.\n let idempotencyKey = idemKey();\n if (!idempotencyKey) {\n idempotencyKey = newIdempotencyKey();\n setIdemKey(idempotencyKey);\n }\n\n try {\n const promo = promoApplied();\n\n if (authStore.isAuthenticated()) {\n // Logged-in member (e.g. a savings member who created an account first):\n // subscribe their EXISTING account instead of creating a second one. The\n // account may be name-only, so first persist the profile entered during\n // intake, then create the subscription + Apex Rx on that account.\n await usersApi.updateProfile({\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim() || undefined,\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n });\n\n const res = await subscriptionsApi.create({\n opaqueData: opaque,\n amountCents: finalPricing.baseCents,\n intervalDays: options.intervalDays ?? 30,\n billingAddress: effectiveBillingAddress(),\n products: [{\n productId: options.pricing.productId,\n productName: options.pricing.productName,\n quantity: 1,\n dosage: options.surveyResult.dosage,\n }],\n productId: options.pricing.productId,\n promoCode: promo?.valid ? promo.promoCode?.code : undefined,\n metadata: {\n drugId: options.surveyResult.drugId,\n selectedDosage: options.surveyResult.dosage,\n caseNotes: options.surveyResult.caseNotes,\n v2SurveyResponseId: options.surveyResult.v2SurveyResponseId,\n },\n }, { idempotencyKey });\n if ((res as ApiResponse).error) {\n throw new Error((res as ApiResponse).error || 'Subscription failed. Please try again.');\n }\n } else {\n await authStore.signupAndSubscribe({\n email: email().trim(),\n password: password(),\n member: {\n firstName: firstName().trim(),\n lastName: lastName().trim(),\n dateOfBirth: dateOfBirth(),\n phone: phone().trim() || undefined,\n address1: street().trim(),\n city: city().trim(),\n state: state(),\n zip: zip().trim(),\n },\n opaqueData: opaque,\n amountCents: finalPricing.baseCents,\n intervalDays: options.intervalDays ?? 30,\n medication: options.surveyResult.drugId,\n products: [{\n productId: options.pricing.productId,\n productName: options.pricing.productName,\n quantity: 1,\n dosage: options.surveyResult.dosage,\n }],\n billingAddress: effectiveBillingAddress(),\n surveyResponseId: options.surveyResult.surveyResponseId,\n v2SurveyResponseId: options.surveyResult.v2SurveyResponseId,\n caseNotes: options.surveyResult.caseNotes,\n promoCode: promo?.valid ? promo.promoCode?.code : undefined,\n }, { idempotencyKey });\n }\n\n clearDraft();\n setOutcome({ kind: 'completed' });\n } catch (err) {\n // The server refused because this member already holds a live\n // subscription. Not an error the member can act on by retrying — nothing\n // is wrong with what they typed — so surface it as its own outcome and\n // let the host explain, rather than as a red banner over a form that will\n // never succeed. Draft cleared so a later legitimate intake (after a\n // cancellation) starts clean.\n if (err instanceof ApiError && err.code === 'SUBSCRIPTION_EXISTS') {\n clearDraft();\n setOutcome({ kind: 'already_subscribed' });\n return;\n }\n\n // A definitive rejection (4xx: decline, validation) means nothing was\n // committed — the next attempt is a NEW operation and must not be\n // deduped against this one, so rotate the key. An AMBIGUOUS failure\n // (connection dropped, 5xx) may have committed server-side: keep the key\n // so the retry collapses into the original instead of charging twice.\n const maybeCommitted = err instanceof ApiError && err.ambiguous;\n if (!maybeCommitted) setIdemKey(newIdempotencyKey());\n\n setError(err instanceof Error ? err.message : 'Registration failed. Please try again.');\n setOutcome({ kind: 'in_progress' });\n } finally {\n setSubmitting(false);\n }\n }\n\n return {\n step,\n stepCount: 3,\n next,\n back,\n\n outcome,\n error,\n submitting,\n tokenizing,\n tokenizerReady: accept.ready,\n acceptJsReady: accept.ready,\n tokenizerError: accept.error,\n acceptJsError: accept.error,\n\n firstName, setFirstName,\n lastName, setLastName,\n email, setEmail,\n password, setPassword,\n dateOfBirth, setDateOfBirth,\n phone, setPhone,\n\n address: addr,\n\n cardNumber: cardNumberRaw,\n setCardNumber: (v) => setCardNumberRaw(formatCardNumber(v)),\n expiry: expiryRaw,\n setExpiry: (v) => setExpiryRaw(formatExpiry(v)),\n cvv: cvvRaw,\n setCvv: (v) => setCvvRaw(formatCvv(v)),\n\n promoCode,\n setPromoCode,\n promoValidating,\n promoError,\n promoApplied,\n applyPromo,\n clearPromo,\n\n pricing,\n\n surveyResult: options.surveyResult,\n medication: options.pricing,\n\n submit,\n };\n}\n","import { createEffect, createRoot, on } from 'solid-js';\nimport cartStore, { type CartItem } from '../stores/cart';\nimport { promoCodesApi } from '../api/client';\nimport {\n adoptCartId,\n fetchCartConfig,\n fetchResumedCart,\n postCartSnapshot,\n readCartToken,\n resetCartId,\n stripCartToken,\n type CartSnapshotLine,\n type ResumedCart,\n} from '../api/cart';\n\n// Abandoned-cart capture, wired to the cart store.\n//\n// Two halves, both best-effort:\n//\n// - SNAPSHOT: every cart change is mirrored to the-backend (debounced, plus a\n// flush on pagehide — a shopper leaving is exactly the moment this exists\n// for). Identity only; the server re-prices.\n// - RESTORE: a `?cart=` token in the URL is traded for the saved cart and\n// rebuilt locally, so a recovery email opened on a phone brings the basket\n// with it.\n//\n// Nothing here may block, slow or break shopping. Every failure path ends in\n// \"carry on with the cart this browser already had\".\n\nexport interface CartCaptureOptions {\n /** Debounce for snapshot writes. Quantity steppers fire fast. */\n debounceMs?: number;\n /**\n * Address for an anonymous shopper, if the site collected one outside the\n * survey's email gate (e.g. checkout step 1). Logged-in shoppers need\n * nothing here — the backend reads their email off the token.\n */\n email?: () => string | null | undefined;\n}\n\nfunction toSnapshotLines(items: CartItem[]): CartSnapshotLine[] {\n return items.map((i) => ({\n productId: i.productId,\n ...(i.dosage ? { dosage: i.dosage } : {}),\n quantity: i.quantity || 1,\n }));\n}\n\n/** Rebuild the local cart from a resumed one, replacing whatever was there. */\nfunction applyResumedCart(resumed: ResumedCart): void {\n cartStore.clear();\n for (const line of resumed.items) {\n cartStore.add({\n productId: line.productId,\n productName: line.name,\n dosage: line.dosage ?? '',\n quantity: 1,\n // The sale price when one is running — same figure the catalog shows.\n priceCents: line.salePriceCents ?? line.priceCents,\n drugId: line.productId,\n apexDrugId: line.apexDrugId,\n categories: line.categories,\n thumbnailUrl: line.thumbnailUrl ?? undefined,\n hideDoseLabel: line.hideDoseLabel || undefined,\n isSubscription: line.isSubscription || undefined,\n });\n if (line.quantity > 1) {\n cartStore.setQuantity(cartStore.itemKey(line.productId, line.dosage ?? ''), line.quantity);\n }\n }\n}\n\n/**\n * Re-apply the promo code the cart was carrying when it was abandoned.\n *\n * Re-VALIDATED, never trusted: a code can expire, get revoked, or stop\n * covering the products still in the cart between abandonment and return, and\n * showing a discount the checkout won't honour is worse than showing none.\n */\nasync function restorePromo(resumed: ResumedCart): Promise<void> {\n if (!resumed.promoCode) return;\n try {\n const res = await promoCodesApi.validate(resumed.promoCode, {\n productIds: resumed.items.map((i) => i.productId),\n subtotalCents: resumed.subtotalCents,\n });\n if (!res.valid || !res.promoCode) return;\n cartStore.setPromo({\n code: res.promoCode.code,\n discountType: res.promoCode.discountType,\n discountValueCents: res.promoCode.discountValueCents,\n discountCents: res.discountCents ?? 0,\n });\n } catch {\n /* the cart is restored either way — the code is a bonus */\n }\n}\n\nlet restoreInFlight: Promise<ResumedCart | null> | null = null;\n\n/**\n * Redeem a `?cart=` token if the URL carries one.\n *\n * Exported for sites that want to act on the restore — opening their cart\n * drawer on arrival, say, or waiting for their catalog first.\n *\n * Single-flight: `startCartCapture()` restores on its own, so a site calling\n * this directly would otherwise race it — both read the token before either\n * strips it, and the cart gets rebuilt twice. Concurrent callers share one\n * restore and one result.\n */\nexport function restoreCartFromLink(): Promise<ResumedCart | null> {\n if (!restoreInFlight) {\n restoreInFlight = runRestore().finally(() => {\n restoreInFlight = null;\n });\n }\n return restoreInFlight;\n}\n\nasync function runRestore(): Promise<ResumedCart | null> {\n const token = readCartToken();\n if (!token) return null;\n\n const resumed = await fetchResumedCart(token);\n // Strip either way: a dead token that stays in the URL re-fires this on\n // every navigation and, worse, gets shared or bookmarked.\n stripCartToken();\n if (!resumed) return null;\n\n // Keep writing to the cart the email was about, not the one this browser\n // happened to mint — otherwise the reminder history and the conversion land\n // on different rows.\n adoptCartId(resumed.cartId);\n applyResumedCart(resumed);\n void restorePromo(resumed);\n return resumed;\n}\n\nlet running = false;\n\n/**\n * Start mirroring the cart. Call once at app boot; returns a disposer.\n *\n * No-ops for tenants that never opted in (`GET /config/cart`), so it is safe to\n * call unconditionally from shared site scaffolding.\n */\nexport function startCartCapture(opts: CartCaptureOptions = {}): () => void {\n if (running) return () => {};\n running = true;\n\n const debounceMs = opts.debounceMs ?? 2000;\n let enabled: boolean | null = null;\n let pending: CartItem[] | null = null;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let lastSentEmpty = true;\n\n function flush(): void {\n if (timer) clearTimeout(timer);\n timer = undefined;\n const items = pending;\n pending = null;\n if (!items || enabled !== true) return;\n\n // An empty cart is not an abandoned one: the snapshot deletes the row, and\n // the id is retired so the next basket starts a clean one. This is also the\n // post-purchase path — checkout clears the cart — which is why converting\n // doesn't need its own wiring here.\n if (items.length === 0) {\n if (lastSentEmpty) return;\n postCartSnapshot({ items: [], promoCode: null });\n resetCartId();\n lastSentEmpty = true;\n return;\n }\n\n postCartSnapshot({\n items: toSnapshotLines(items),\n promoCode: cartStore.appliedPromo()?.code ?? null,\n email: opts.email?.() ?? null,\n });\n lastSentEmpty = false;\n }\n\n function schedule(ms: number): void {\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, ms);\n }\n\n const dispose = createRoot((disposeRoot) => {\n // `defer` so merely starting capture doesn't post the cart the shopper\n // hasn't touched; the first real change schedules the first write.\n createEffect(\n on(\n cartStore.items,\n (items) => {\n pending = items;\n if (enabled === true) schedule(debounceMs);\n },\n { defer: true },\n ),\n );\n return disposeRoot;\n });\n\n void fetchCartConfig().then((cfg) => {\n enabled = cfg.snapshot;\n if (!enabled) return;\n void restoreCartFromLink();\n if (pending) schedule(0);\n });\n\n // The shopper leaving with items in the cart is the whole point; don't let a\n // pending debounce die with the page.\n const onPageHide = () => flush();\n if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {\n window.addEventListener('pagehide', onPageHide);\n }\n\n return () => {\n if (timer) clearTimeout(timer);\n if (typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {\n window.removeEventListener('pagehide', onPageHide);\n }\n dispose();\n running = false;\n };\n}\n"]}