@apextelemed/partner-core 0.17.0-dev.52 → 0.17.0-dev.53

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 (40) hide show
  1. package/dist/api/index.d.ts +1 -1
  2. package/dist/api/index.js +3 -3
  3. package/dist/api/index.jsx +3 -3
  4. package/dist/chunk/{TLDELI22.jsx → 2PME7R6L.jsx} +11 -5
  5. package/dist/chunk/{A6FJGQIS.js → 3VBKKYOR.js} +3 -3
  6. package/dist/chunk/{A6FJGQIS.js.map → 3VBKKYOR.js.map} +1 -1
  7. package/dist/chunk/{FXRGPBYU.js → 3VUCQNOR.js} +3 -3
  8. package/dist/chunk/{FXRGPBYU.js.map → 3VUCQNOR.js.map} +1 -1
  9. package/dist/chunk/{6V7RVUXX.js → COIUOQOE.js} +3 -3
  10. package/dist/chunk/{6V7RVUXX.js.map → COIUOQOE.js.map} +1 -1
  11. package/dist/chunk/{BYDMO5RM.js → DETBZTGQ.js} +12 -6
  12. package/dist/chunk/DETBZTGQ.js.map +1 -0
  13. package/dist/chunk/{O7H7DAWO.js → FDCDDUB6.js} +282 -236
  14. package/dist/chunk/FDCDDUB6.js.map +1 -0
  15. package/dist/chunk/{2HDMTWLH.js → JDCV4T6O.js} +6 -6
  16. package/dist/chunk/{2HDMTWLH.js.map → JDCV4T6O.js.map} +1 -1
  17. package/dist/chunk/{RDZDD5UW.js → NQLBWDE3.js} +2 -2
  18. package/dist/chunk/{RDZDD5UW.js.map → NQLBWDE3.js.map} +1 -1
  19. package/dist/chunk/{BJXD2NQQ.jsx → OOCYQ4I6.jsx} +2 -2
  20. package/dist/chunk/{37UEVJEC.jsx → PDK3JMIW.jsx} +1 -1
  21. package/dist/chunk/{5HQAA4UO.jsx → PW7F2JMV.jsx} +2 -2
  22. package/dist/chunk/{FTZ52PMM.jsx → XGCOWLXF.jsx} +2 -2
  23. package/dist/chunk/{IQDVS3XA.jsx → XZJASVNG.jsx} +5 -5
  24. package/dist/chunk/{T37L6JE6.jsx → Z745N7NE.jsx} +53 -23
  25. package/dist/{client-BLh8hFAu.d.ts → client-JZfa9Gbp.d.ts} +14 -1
  26. package/dist/flows/index.d.ts +12 -3
  27. package/dist/flows/index.js +6 -6
  28. package/dist/flows/index.jsx +6 -6
  29. package/dist/index/index.d.ts +1 -1
  30. package/dist/index/index.js +7 -7
  31. package/dist/index/index.jsx +7 -7
  32. package/dist/pages/index.d.ts +1 -1
  33. package/dist/pages/index.js +5 -5
  34. package/dist/pages/index.jsx +5 -5
  35. package/dist/stores/index.d.ts +1 -1
  36. package/dist/stores/index.js +2 -2
  37. package/dist/stores/index.jsx +2 -2
  38. package/package.json +1 -1
  39. package/dist/chunk/BYDMO5RM.js.map +0 -1
  40. package/dist/chunk/O7H7DAWO.js.map +0 -1
@@ -1,4 +1,4 @@
1
- export { A as AddPharmacyBody, a as AddPharmacyDoseMatch, b as AddPharmacyDoseOption, c as AddPharmacyFinding, d as AddPharmacyMatchQuestion, e as AddPharmacyMatchSource, f as AddPharmacyPlan, g as AddPharmacyPrice, h as AddPharmacyResult, i as AddPharmacyStrengthAfter, j as AddPharmacyStrengthBefore, k as AddressVerifyResult, l as AdminApexDrug, m as AdminApexItemStatus, n as AdminBillingAttempt, o as AdminCategory, p as AdminCategoryInput, q as AdminCategoryUpdate, r as AdminCustomer, s as AdminCustomerFacts, t as AdminCustomerFunnel, u as AdminCustomerListParams, v as AdminCustomerOverview, w as AdminCustomerProfile, x as AdminCustomerRequest, y as AdminCustomerRow, z as AdminCustomerSupport, B as AdminCustomerSupportThread, C as AdminDashboardStats, D as AdminLifecycle, E as AdminLifecycleBucket, F as AdminListParams, G as AdminOffer, H as AdminOfferBase, I as AdminOfferGrant, J as AdminOfferGrantBase, K as AdminOfferInput, L as AdminOrderSummary, M as AdminOrphanReason, N as AdminOrphanedDosePrice, O as AdminPayment, P as AdminPaymentDetail, Q as AdminProduct, R as AdminProductOverlayField, S as AdminProductPharmacy, T as AdminProductStrength, U as AdminPromoCode, V as AdminPromoCodeInput, W as AdminRecurringPricePoint, X as AdminRecurringRevenue, Y as AdminRefundResult, Z as AdminSale, _ as AdminSaleInput, $ as AdminScheduledRefund, a0 as AdminScheduledRefundProblem, a1 as AdminSubscription, a2 as AdminSubscriptionDetail, a3 as AdminSubscriptionPatch, a4 as AdminSubscriptionWriteResult, a5 as AdminSupportCustomer, a6 as AdminSupportStats, a7 as AdminSupportThread, a8 as AdminWebhookEvent, a9 as Affiliate, aa as AffiliateAuthTokens, ab as AffiliateClickRecord, ac as AffiliateConversion, ad as AffiliateDashboardLinks, ae as AffiliateDashboardProfile, af as AffiliateDashboardStats, ag as AffiliateDownlineMember, ah as AffiliateEarningsBreakdown, ai as AffiliatePaymentMethod, aj as AffiliateProgram, ak as AffiliateRegisterInput, al as AffiliateRegisterResponse, am as AffiliateSession, an as AffiliateStatsResponse, ao as AffiliateStatus, ap as AffiliateTrackResponse, aq as ApiError, ar as ApiResponse, as as AttributionMethod, at as AuthTokens, au as BillingReminderSettings, av as CatalogAvailabilityItem, aw as CatalogAvailabilityReason, ax as CatalogAvailabilityResult, ay as CatalogClassification, az as CatalogConversionChoice, aA as CatalogConversionCommitResult, aB as CatalogConversionDose, aC as CatalogConversionDoseMatch, aD as CatalogConversionFinding, aE as CatalogConversionPointers, aF as CatalogConversionPrepareResult, aG as CatalogConversionPreview, aH as CatalogConversionRun, aI as CatalogConversionSource, aJ as CatalogConversionStage, aK as CatalogConversionTarget, aL as CatalogConversionUndoOptions, aM as CatalogConversionUndoResult, aN as CatalogDose, aO as CatalogDoseInput, aP as CatalogDoseModel, aQ as CatalogDoseSuggestion, aR as CatalogDoseSuggestions, aS as CatalogEquivalentSuggestions, aT as CatalogFulfillment, aU as CatalogFulfillmentInput, aV as CatalogItem, aW as CatalogItemInput, aX as CatalogMappableDrug, aY as CatalogMatrixCell, aZ as CatalogProduct, a_ as CatalogReadiness, a$ as CategoryMetadata, b0 as CheckoutAddress, b1 as CheckoutPayload, b2 as CheckoutResult, b3 as CommissionConfig, b4 as CommissionStatus, b5 as CompleteSurveyPayload, b6 as CreateAffiliatePayload, b7 as CreateAffiliateProgramPayload, b8 as CreateOrderPayload, b9 as CreateRequestPayload, ba as CreateSubscriptionPayload, bb as CustomTemplate, bc as CustomTemplateInput, bd as CustomerDiscountConfig, be as DeliveryInfo, bf as DiscountType, bg as EmailNotificationSettings, bh as EmailTemplatesMap, bi as LoginPayload, bj as MemberOffer, bk as MemberPrescriptionRequest, bl as MemberSurveyMode, bm as MemberSurveyResponseSummary, bn as MemberSurveyTranscript, bo as MemberSurveyTranscriptItem, bp as MemberSurveyTranscriptSection, bq as MembersMeResponse, br as OfferGrantState, bs as Order, bt as OrderItemInput, bu as PaginationParams, bv as PaymentCallbackPayload, bw as PaymentInitiatePayload, bx as PaymentType, by as PendingRenewalSurvey, bz as Placeholder, bA as PlaceholderKind, bB as ProductSaleSummary, bC as ProductStrengthMatches, bD as PromoValidationResponse, bE as PublicCategory, bF as RegisterAndSubscribePayload, bG as RegisterPayload, bH as RenewalStatus, bI as SUPPORT_ATTACHMENT_MAX_BYTES, bJ as SUPPORT_ATTACHMENT_MIME_TYPES, bK as SelectDrugPayload, bL as SendMessagePayload, bM as SendToPharmacyPayload, bN as StrengthMatchBody, bO as StrengthMatchDoseOption, bP as StrengthMatchRow, bQ as SubscriptionPreview, bR as SubscriptionPreviewLine, bS as SubscriptionPreviewPayload, bT as SupportAttachment, bU as SupportChannel, bV as SupportChannelSettings, bW as SupportMessage, bX as SupportRealtimeToken, bY as SupportThread, bZ as SupportThreadCategory, b_ as SupportThreadStatus, b$ as SurveySubmitPayload, c0 as TemplatePlaceholdersMap, c1 as TemplateText, c2 as TenantFeature, c3 as TenantFeatureAccess, c4 as TokenTrackName, c5 as UpdateAffiliatePayload, c6 as UpdateAffiliateProgramPayload, c7 as UpdatePaymentMethodPayload, c8 as UpdateProfilePayload, c9 as User, ca as addressesApi, cb as adminAffiliatesApi, cc as adminApi, cd as adminCatalogApi, ce as adminCatalogConversionApi, cf as adminProductPharmaciesApi, cg as adminProductStrengthMatchesApi, ch as affiliateAuthStorageKey, ci as affiliatePortalApi, cj as apexApi, ck as apiFetch, cl as authApi, cm as authStorageKey, cn as catalogApi, co as clearAffiliateTokens, cp as clearTokens, cq as getAffiliateTokens, cr as getTokens, cs as membersApi, ct as messagesApi, cu as newIdempotencyKey, cv as offersApi, cw as onTokensCleared, cx as ordersApi, cy as paymentsApi, cz as productsApi, cA as promoCodesApi, cB as setAffiliateTokens, cC as setTokens, cD as subscriptionsApi, cE as supportApi, cF as usersApi } from '../client-BLh8hFAu.js';
1
+ export { A as AddPharmacyBody, a as AddPharmacyDoseMatch, b as AddPharmacyDoseOption, c as AddPharmacyFinding, d as AddPharmacyMatchQuestion, e as AddPharmacyMatchSource, f as AddPharmacyPlan, g as AddPharmacyPrice, h as AddPharmacyResult, i as AddPharmacyStrengthAfter, j as AddPharmacyStrengthBefore, k as AddressVerifyResult, l as AdminApexDrug, m as AdminApexItemStatus, n as AdminBillingAttempt, o as AdminCategory, p as AdminCategoryInput, q as AdminCategoryUpdate, r as AdminCustomer, s as AdminCustomerFacts, t as AdminCustomerFunnel, u as AdminCustomerListParams, v as AdminCustomerOverview, w as AdminCustomerProfile, x as AdminCustomerRequest, y as AdminCustomerRow, z as AdminCustomerSupport, B as AdminCustomerSupportThread, C as AdminDashboardStats, D as AdminLifecycle, E as AdminLifecycleBucket, F as AdminListParams, G as AdminOffer, H as AdminOfferBase, I as AdminOfferGrant, J as AdminOfferGrantBase, K as AdminOfferInput, L as AdminOrderSummary, M as AdminOrphanReason, N as AdminOrphanedDosePrice, O as AdminPayment, P as AdminPaymentDetail, Q as AdminProduct, R as AdminProductOverlayField, S as AdminProductPharmacy, T as AdminProductStrength, U as AdminPromoCode, V as AdminPromoCodeInput, W as AdminRecurringPricePoint, X as AdminRecurringRevenue, Y as AdminRefundResult, Z as AdminSale, _ as AdminSaleInput, $ as AdminScheduledRefund, a0 as AdminScheduledRefundProblem, a1 as AdminSubscription, a2 as AdminSubscriptionDetail, a3 as AdminSubscriptionPatch, a4 as AdminSubscriptionWriteResult, a5 as AdminSupportCustomer, a6 as AdminSupportStats, a7 as AdminSupportThread, a8 as AdminWebhookEvent, a9 as Affiliate, aa as AffiliateAuthTokens, ab as AffiliateClickRecord, ac as AffiliateConversion, ad as AffiliateDashboardLinks, ae as AffiliateDashboardProfile, af as AffiliateDashboardStats, ag as AffiliateDownlineMember, ah as AffiliateEarningsBreakdown, ai as AffiliatePaymentMethod, aj as AffiliateProgram, ak as AffiliateRegisterInput, al as AffiliateRegisterResponse, am as AffiliateSession, an as AffiliateStatsResponse, ao as AffiliateStatus, ap as AffiliateTrackResponse, aq as ApiError, ar as ApiResponse, as as AttributionMethod, at as AuthTokens, au as BillingReminderSettings, av as CatalogAvailabilityItem, aw as CatalogAvailabilityReason, ax as CatalogAvailabilityResult, ay as CatalogClassification, az as CatalogConversionChoice, aA as CatalogConversionCommitResult, aB as CatalogConversionDose, aC as CatalogConversionDoseMatch, aD as CatalogConversionFinding, aE as CatalogConversionPointers, aF as CatalogConversionPrepareResult, aG as CatalogConversionPreview, aH as CatalogConversionRun, aI as CatalogConversionSource, aJ as CatalogConversionStage, aK as CatalogConversionTarget, aL as CatalogConversionUndoOptions, aM as CatalogConversionUndoResult, aN as CatalogDose, aO as CatalogDoseInput, aP as CatalogDoseModel, aQ as CatalogDoseSuggestion, aR as CatalogDoseSuggestions, aS as CatalogEquivalentSuggestions, aT as CatalogFulfillment, aU as CatalogFulfillmentInput, aV as CatalogItem, aW as CatalogItemInput, aX as CatalogMappableDrug, aY as CatalogMatrixCell, aZ as CatalogProduct, a_ as CatalogReadiness, a$ as CategoryMetadata, b0 as CheckoutAddress, b1 as CheckoutPayload, b2 as CheckoutResult, b3 as CommissionConfig, b4 as CommissionStatus, b5 as CompleteSurveyPayload, b6 as CreateAffiliatePayload, b7 as CreateAffiliateProgramPayload, b8 as CreateOrderPayload, b9 as CreateRequestPayload, ba as CreateSubscriptionPayload, bb as CustomTemplate, bc as CustomTemplateInput, bd as CustomerDiscountConfig, be as DeliveryInfo, bf as DiscountType, bg as EmailNotificationSettings, bh as EmailTemplatesMap, bi as LoginPayload, bj as MemberOffer, bk as MemberPrescriptionRequest, bl as MemberSurveyMode, bm as MemberSurveyResponseSummary, bn as MemberSurveyTranscript, bo as MemberSurveyTranscriptItem, bp as MemberSurveyTranscriptSection, bq as MembersMeResponse, br as OfferGrantState, bs as Order, bt as OrderItemInput, bu as PaginationParams, bv as PaymentCallbackPayload, bw as PaymentInitiatePayload, bx as PaymentType, by as PendingRenewalSurvey, bz as Placeholder, bA as PlaceholderKind, bB as ProductSaleSummary, bC as ProductStrengthMatches, bD as PromoValidationResponse, bE as PublicCategory, bF as RegisterAndSubscribePayload, bG as RegisterPayload, bH as RenewalStatus, bI as SUPPORT_ATTACHMENT_MAX_BYTES, bJ as SUPPORT_ATTACHMENT_MIME_TYPES, bK as SelectDrugPayload, bL as SendMessagePayload, bM as SendToPharmacyPayload, bN as StrengthMatchBody, bO as StrengthMatchDoseOption, bP as StrengthMatchRow, bQ as SubscriptionPreview, bR as SubscriptionPreviewLine, bS as SubscriptionPreviewPayload, bT as SupportAttachment, bU as SupportChannel, bV as SupportChannelSettings, bW as SupportMessage, bX as SupportRealtimeToken, bY as SupportThread, bZ as SupportThreadCategory, b_ as SupportThreadStatus, b$ as SurveySubmitPayload, c0 as TemplatePlaceholdersMap, c1 as TemplateText, c2 as TenantFeature, c3 as TenantFeatureAccess, c4 as TokenTrackName, c5 as UpdateAffiliatePayload, c6 as UpdateAffiliateProgramPayload, c7 as UpdatePaymentMethodPayload, c8 as UpdateProfilePayload, c9 as User, ca as addressesApi, cb as adminAffiliatesApi, cc as adminApi, cd as adminCatalogApi, ce as adminCatalogConversionApi, cf as adminProductPharmaciesApi, cg as adminProductStrengthMatchesApi, ch as affiliateAuthStorageKey, ci as affiliatePortalApi, cj as apexApi, ck as apiFetch, cl as authApi, cm as authStorageKey, cn as catalogApi, co as clearAffiliateTokens, cp as clearTokens, cq as getAffiliateTokens, cr as getTokens, cs as membersApi, ct as messagesApi, cu as newIdempotencyKey, cv as offersApi, cw as onTokensCleared, cx as ordersApi, cy as paymentsApi, cz as productsApi, cA as promoCodesApi, cB as setAffiliateTokens, cC as setTokens, cD as subscriptionsApi, cE as supportApi, cF as usersApi } from '../client-JZfa9Gbp.js';
2
2
  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';
3
3
  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';
4
4
 
package/dist/api/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import '../chunk/JSHO46VZ.js';
2
- export { adoptCartId, capturePromoCode, cartId, clearPromoCode, fetchCartConfig, fetchResumedCart, postCartSnapshot, readCartToken, readPromoCode, resetCartConfigCache, resetCartId, stripCartToken } from '../chunk/FXRGPBYU.js';
2
+ export { adoptCartId, capturePromoCode, cartId, clearPromoCode, fetchCartConfig, fetchResumedCart, postCartSnapshot, readCartToken, readPromoCode, resetCartConfigCache, resetCartId, stripCartToken } from '../chunk/3VUCQNOR.js';
3
3
  export { EmbedApiError2 as ApexV2ApiError, EmbedApiError, createEmbedApiClient, disqualificationReasonText, disqualifiedDrugIds, qualifiedDrugIds } from '../chunk/LZWA44KD.js';
4
- export { adoptFunnelSessionId, captureAuthHeader, fetchFunnelConfig, fetchResumedDraft, funnelSessionId, peekFunnelSessionId, postFunnelEvent, readResumeToken, resetFunnelConfigCache, saveFunnelDraft, stripResumeToken } from '../chunk/6V7RVUXX.js';
5
- export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, adminCatalogApi, adminCatalogConversionApi, adminProductPharmaciesApi, adminProductStrengthMatchesApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, catalogApi, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, offersApi, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi } from '../chunk/RDZDD5UW.js';
4
+ export { adoptFunnelSessionId, captureAuthHeader, fetchFunnelConfig, fetchResumedDraft, funnelSessionId, peekFunnelSessionId, postFunnelEvent, readResumeToken, resetFunnelConfigCache, saveFunnelDraft, stripResumeToken } from '../chunk/COIUOQOE.js';
5
+ export { ApiError, SUPPORT_ATTACHMENT_MAX_BYTES, SUPPORT_ATTACHMENT_MIME_TYPES, addressesApi, adminAffiliatesApi, adminApi, adminCatalogApi, adminCatalogConversionApi, adminProductPharmaciesApi, adminProductStrengthMatchesApi, affiliateAuthStorageKey, affiliatePortalApi, apexApi, apiFetch, authApi, authStorageKey, captureAffiliateRef, catalogApi, clearAffiliateRef, clearAffiliateTokens, clearTokens, getAffiliateTokens, getTokens, membersApi, messagesApi, newIdempotencyKey, offersApi, onTokensCleared, ordersApi, paymentsApi, productsApi, promoCodesApi, readAffiliateRef, setAffiliateTokens, setTokens, subscriptionsApi, supportApi, usersApi } from '../chunk/NQLBWDE3.js';
6
6
  import '../chunk/2IFPDU4D.js';
7
7
  //# sourceMappingURL=index.js.map
8
8
  //# sourceMappingURL=index.js.map
@@ -12,7 +12,7 @@ import {
12
12
  resetCartConfigCache,
13
13
  resetCartId,
14
14
  stripCartToken
15
- } from "../chunk/FTZ52PMM.jsx";
15
+ } from "../chunk/XGCOWLXF.jsx";
16
16
  import {
17
17
  EmbedApiError,
18
18
  EmbedApiError2,
@@ -33,7 +33,7 @@ import {
33
33
  resetFunnelConfigCache,
34
34
  saveFunnelDraft,
35
35
  stripResumeToken
36
- } from "../chunk/5HQAA4UO.jsx";
36
+ } from "../chunk/PW7F2JMV.jsx";
37
37
  import {
38
38
  ApiError,
39
39
  SUPPORT_ATTACHMENT_MAX_BYTES,
@@ -73,7 +73,7 @@ import {
73
73
  subscriptionsApi,
74
74
  supportApi,
75
75
  usersApi
76
- } from "../chunk/37UEVJEC.jsx";
76
+ } from "../chunk/PDK3JMIW.jsx";
77
77
  import "../chunk/QVZ7BRNO.jsx";
78
78
  export {
79
79
  EmbedApiError2 as ApexV2ApiError,
@@ -6,13 +6,13 @@ import {
6
6
  readResumeToken,
7
7
  saveFunnelDraft,
8
8
  stripResumeToken
9
- } from "./5HQAA4UO.jsx";
9
+ } from "./PW7F2JMV.jsx";
10
10
  import {
11
11
  affiliateAuth_default,
12
12
  auth_default,
13
13
  cart_default,
14
14
  medication_default
15
- } from "./BJXD2NQQ.jsx";
15
+ } from "./OOCYQ4I6.jsx";
16
16
  import {
17
17
  ApiError,
18
18
  addressesApi,
@@ -34,7 +34,7 @@ import {
34
34
  subscriptionsApi,
35
35
  supportApi,
36
36
  usersApi
37
- } from "./37UEVJEC.jsx";
37
+ } from "./PDK3JMIW.jsx";
38
38
  import {
39
39
  getConfig
40
40
  } from "./QVZ7BRNO.jsx";
@@ -6374,7 +6374,7 @@ function useAddPharmacy(opts) {
6374
6374
  // src/flows/strengthMatches.ts
6375
6375
  import { createEffect as createEffect11, createMemo as createMemo4, createSignal as createSignal16, on as on5, onCleanup as onCleanup6 } from "solid-js";
6376
6376
  function wantsStrengthMatches(product, enabled) {
6377
- return enabled && !!product && product.pricingMode !== "flat_fee";
6377
+ return enabled && !!product;
6378
6378
  }
6379
6379
  function matchBody(dosage, doseId, carryPrice) {
6380
6380
  return { dosage, doseId, ...carryPrice === void 0 ? {} : { carryPrice } };
@@ -6382,6 +6382,7 @@ function matchBody(dosage, doseId, carryPrice) {
6382
6382
  var matchValue = (row) => row.doseId ?? "";
6383
6383
  var doseIdOf = (value) => value === "" ? null : value;
6384
6384
  var isLeftForReview = (row) => row.doseId === null;
6385
+ var isFlatFee = (raw) => raw?.flatFee === true;
6385
6386
  function normalizeMatches(raw) {
6386
6387
  return {
6387
6388
  rows: Array.isArray(raw?.rows) ? raw.rows : [],
@@ -6417,6 +6418,7 @@ function classifyStrengthMatchError(err, doseId) {
6417
6418
  }
6418
6419
  function useStrengthMatches(opts) {
6419
6420
  const [status, setStatus] = createSignal16("idle");
6421
+ const [flatFee, setFlatFee] = createSignal16(false);
6420
6422
  const [rows, setRows] = createSignal16([]);
6421
6423
  const [doseOptions, setDoseOptions] = createSignal16([]);
6422
6424
  const [pending, setPending] = createSignal16(null);
@@ -6438,6 +6440,7 @@ function useStrengthMatches(opts) {
6438
6440
  });
6439
6441
  const adopt = (raw) => {
6440
6442
  const next = normalizeMatches(raw);
6443
+ setFlatFee(isFlatFee(raw));
6441
6444
  setRows(next.rows);
6442
6445
  setDoseOptions(next.doseOptions);
6443
6446
  const p = pending();
@@ -6450,6 +6453,7 @@ function useStrengthMatches(opts) {
6450
6453
  const seq = ++loadSeq;
6451
6454
  const product = opts.product();
6452
6455
  if (!wantsStrengthMatches(product, opts.enabled())) {
6456
+ setFlatFee(false);
6453
6457
  setRows([]);
6454
6458
  setDoseOptions([]);
6455
6459
  setStatus("idle");
@@ -6484,6 +6488,7 @@ function useStrengthMatches(opts) {
6484
6488
  on5(key, () => {
6485
6489
  generation++;
6486
6490
  loadSeq++;
6491
+ setFlatFee(false);
6487
6492
  setRows([]);
6488
6493
  setDoseOptions([]);
6489
6494
  setPending(null);
@@ -6542,6 +6547,7 @@ function useStrengthMatches(opts) {
6542
6547
  };
6543
6548
  return {
6544
6549
  status,
6550
+ flatFee,
6545
6551
  rows,
6546
6552
  doseOptions,
6547
6553
  pending,
@@ -6729,4 +6735,4 @@ export {
6729
6735
  classifyStrengthMatchError,
6730
6736
  useStrengthMatches
6731
6737
  };
6732
- //# sourceMappingURL=TLDELI22.jsx.map
6738
+ //# sourceMappingURL=2PME7R6L.jsx.map
@@ -1,4 +1,4 @@
1
- import { onTokensCleared, authStorageKey, getTokens, usersApi, ApiError, affiliateAuthStorageKey, getAffiliateTokens, affiliatePortalApi, clearTokens, authApi, clearAffiliateTokens, setTokens, setAffiliateTokens } from './RDZDD5UW.js';
1
+ import { onTokensCleared, authStorageKey, getTokens, usersApi, ApiError, affiliateAuthStorageKey, getAffiliateTokens, affiliatePortalApi, clearTokens, authApi, clearAffiliateTokens, setTokens, setAffiliateTokens } from './NQLBWDE3.js';
2
2
  import { onConfigured, getConfig } from './2IFPDU4D.js';
3
3
  import { createRoot, createSignal, createMemo, batch } from 'solid-js';
4
4
 
@@ -382,5 +382,5 @@ var medicationStore = createRoot(createMedicationStore);
382
382
  var medication_default = medicationStore;
383
383
 
384
384
  export { affiliateAuth_default, auth_default, cart_default, medication_default };
385
- //# sourceMappingURL=A6FJGQIS.js.map
386
- //# sourceMappingURL=A6FJGQIS.js.map
385
+ //# sourceMappingURL=3VBKKYOR.js.map
386
+ //# sourceMappingURL=3VBKKYOR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/stores/cart.ts","../../src/stores/auth.ts","../../src/stores/affiliateAuth.ts","../../src/stores/medication.ts"],"names":["createSignal","createRoot","batch"],"mappings":";;;;AAGA,IAAM,cAAA,GAAiB,MAAM,CAAA,EAAG,SAAA,GAAY,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CAAW,IAAI,CAAA;AAAA,IACjB;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,SAAA;AAAA,IACA,eAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA;AAAA,IACA,QAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF;AAEA,IAAM,kBAAA,GAAqBD,WAAW,wBAAwB,CAAA;AAC9D,IAAO,qBAAA,GAAQ;AC5Jf,SAAS,qBAAA,GAAwB;AAC/B,EAAA,MAAM,CAAC,QAAA,EAAU,WAAW,CAAA,GAAID,aAAyC,IAAI,CAAA;AAE7E,EAAA,SAAS,OAAO,UAAA,EAAiC;AAC/C,IAAA,WAAA,CAAY,UAAU,CAAA;AAAA,EACxB;AAEA,EAAA,SAAS,KAAA,GAAQ;AACf,IAAA,WAAA,CAAY,IAAI,CAAA;AAAA,EAClB;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,MAAA,EAAQ,KAAA,EAAM;AACnC;AAEA,IAAM,eAAA,GAAkBC,WAAW,qBAAqB,CAAA;AACxD,IAAO,kBAAA,GAAQ","file":"A6FJGQIS.js","sourcesContent":["import { createSignal, createRoot } from 'solid-js';\nimport { getConfig } from '../config';\n\nconst cartStorageKey = () => `${getConfig().storagePrefix}-cart`;\nconst promoStorageKey = () => `${getConfig().storagePrefix}-cart-promo`;\n\nexport interface CartItem {\n productId: string;\n productName: string;\n dosage: string;\n /** Dose redesign (Phase 8): optional patient-requested intake hints, mirroring\n * Apex intake — `requestedSku` is the binding patient-bought SKU,\n * `requestedClinicalDose` is the advisory dose. Default undefined; carried\n * through to the /apex/requests medications payload. Nothing sets these yet. */\n requestedSku?: string;\n /** SKU identity S4: the stable, opaque `skus[].id` form of `requestedSku`\n * (from Apex's /v1/drugs catalog). Preferred over the label — survives a\n * relabel. Additive; carried through to the medications payload. */\n requestedSkuId?: string;\n requestedClinicalDose?: { value: number; unit: string };\n quantity: number;\n priceCents: number;\n drugId: string | null;\n /** The linked Apex drug id, copied from the catalog product. Matches the id\n * the survey qualification verdict (`drugResults[].drugId`) is keyed on, so\n * request creation can gate out drugs the survey marked ineligible. Null/\n * undefined for non-Apex products or carts saved before this field existed. */\n apexDrugId?: string | null;\n categories: string[];\n thumbnailUrl?: string;\n /** True when the product uses flat_fee pricing. The dosage is still set\n * (Apex needs it for the prescription) but consumer cart drawers should\n * skip rendering the dose suffix. */\n hideDoseLabel?: boolean;\n /** Copied from the catalog's `is_subscription` at add-time. The one-time\n * checkout flow excludes subscription items (the backend 400s a\n * /payments/checkout containing one, and stays the authority). Undefined —\n * legacy persisted carts, non-catalog adds — is treated as one-time-purchasable. */\n isSubscription?: boolean;\n}\n\nexport interface AppliedPromoCode {\n code: string;\n discountType: 'percent' | 'fixed';\n discountValueCents: number;\n discountCents: number;\n}\n\nfunction itemKey(productId: string, dosage: string): string {\n return `${productId}::${dosage}`;\n}\n\nfunction loadInitial(): CartItem[] {\n try {\n const raw = localStorage.getItem(cartStorageKey());\n if (!raw) return [];\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n // Preserve a sane persisted quantity (set via setQuantity); anything else\n // — legacy carts, tampered storage — normalizes back to 1.\n return parsed.map((i: CartItem) => ({\n ...i,\n quantity: Number.isInteger(i.quantity) && i.quantity > 0 ? i.quantity : 1,\n }));\n } catch {\n return [];\n }\n}\n\nfunction loadInitialPromo(): AppliedPromoCode | null {\n try {\n const raw = localStorage.getItem(promoStorageKey());\n if (!raw) return null;\n return JSON.parse(raw) as AppliedPromoCode;\n } catch {\n return null;\n }\n}\n\nfunction persist(items: CartItem[]) {\n try {\n localStorage.setItem(cartStorageKey(), JSON.stringify(items));\n } catch {\n // noop\n }\n}\n\nfunction persistPromo(promo: AppliedPromoCode | null) {\n try {\n if (promo) localStorage.setItem(promoStorageKey(), JSON.stringify(promo));\n else localStorage.removeItem(promoStorageKey());\n } catch {\n // noop\n }\n}\n\nfunction createCartStore() {\n const [items, setItems] = createSignal<CartItem[]>(loadInitial());\n const [isOpen, setIsOpen] = createSignal(false);\n const [appliedPromo, setAppliedPromo] = createSignal<AppliedPromoCode | null>(loadInitialPromo());\n\n function write(next: CartItem[]) {\n setItems(next);\n persist(next);\n }\n\n function count() {\n return items().length;\n }\n\n function subtotalCents() {\n return items().reduce((sum, i) => sum + i.priceCents * (i.quantity || 1), 0);\n }\n\n function add(item: CartItem) {\n const key = itemKey(item.productId, item.dosage);\n const current = items();\n if (current.some(i => itemKey(i.productId, i.dosage) === key)) return;\n write([...current, { ...item, quantity: 1 }]);\n }\n\n function remove(key: string) {\n write(items().filter(i => itemKey(i.productId, i.dosage) !== key));\n }\n\n /** Set an item's quantity (floored, clamped to ≥1 — removing is `remove`'s\n * job). Non-finite input and unknown keys are ignored. `add` still starts\n * every item at 1; this is the only quantity mutator. */\n function setQuantity(key: string, quantity: number) {\n if (!Number.isFinite(quantity)) return;\n const clamped = Math.max(1, Math.floor(quantity));\n const current = items();\n if (!current.some(i => itemKey(i.productId, i.dosage) === key)) return;\n write(current.map(i => (itemKey(i.productId, i.dosage) === key ? { ...i, quantity: clamped } : i)));\n }\n\n /**\n * Replace the whole cart in one write. For catalog reconciliation\n * (`flows/cartReconcile`), which drops lines the catalog no longer offers and\n * refreshes the snapshots of the ones it does — neither expressible as\n * add/remove, and both must land as a single persist so a half-written cart\n * can never be read back. Quantities are taken as given (unlike `add`, which\n * always starts at 1).\n */\n function replace(next: CartItem[]) {\n write(next);\n }\n\n function clear() {\n // Preserve the applied promo across cart resets — the survey submission\n // clears the cart but the customer still expects the code they entered to\n // apply to subsequent prescription purchases. Removing the promo is an\n // explicit action via the cart drawer's \"remove\" link.\n write([]);\n }\n\n function hasGlp1() {\n return items().some(i =>\n i.categories.some(c => c.toLowerCase().includes('weight') || c.toLowerCase().includes('glp')),\n );\n }\n\n function isMultiItem() {\n return items().length > 1;\n }\n\n function setPromo(promo: AppliedPromoCode | null) {\n setAppliedPromo(promo);\n persistPromo(promo);\n }\n\n return {\n items,\n count,\n subtotalCents,\n add,\n remove,\n setQuantity,\n replace,\n clear,\n hasGlp1,\n isMultiItem,\n itemKey,\n isOpen,\n open: () => setIsOpen(true),\n close: () => setIsOpen(false),\n toggle: () => setIsOpen(v => !v),\n appliedPromo,\n setPromo,\n };\n}\n\nconst cartStore = createRoot(createCartStore);\nexport default cartStore;\n","import { createSignal, createMemo, createRoot, batch } from 'solid-js';\nimport { onConfigured } from '../config';\nimport {\n authApi,\n getTokens,\n setTokens,\n clearTokens,\n usersApi,\n ApiError,\n onTokensCleared,\n authStorageKey,\n type User,\n type AuthTokens,\n type RegisterPayload,\n type RegisterAndSubscribePayload,\n} from '../api/client';\nimport cartStore from './cart';\n\nfunction createAuthStore() {\n // ── Signals ─────────────────────────────────────────────────────\n\n const [tokens, _setTokens] = createSignal<AuthTokens | null>(null);\n const [user, setUser] = createSignal<User | null>(null);\n const [isAuthenticated, setIsAuthenticated] = createSignal(false);\n const [loading, setLoading] = createSignal(false);\n\n // Derived, not a second signal: admin-ness must never be observable out of\n // step with the user it describes. As separate writes, Solid flushed\n // dependents between setUser and setIsAdmin, so an admin gate combining\n // \"hydrated\" (user() !== null) with isAdmin() saw \"hydrated but not admin\"\n // for one tick on every hard load of /admin and bounced to the fallback\n // route.\n const isAdmin = createMemo(() => user()?.role === 'admin');\n\n // ── Internal helpers ────────────────────────────────────────────\n\n /** Reset the in-memory session signals WITHOUT touching token storage.\n * Used by the token-cleared/storage listeners, where storage is already\n * gone (writing it back would re-notify and loop). */\n function dropSession() {\n batch(() => {\n _setTokens(null);\n setIsAuthenticated(false);\n setUser(null);\n });\n }\n\n function syncTokens(t: AuthTokens | null) {\n _setTokens(t);\n if (t) {\n setTokens(t);\n setIsAuthenticated(true);\n } else {\n clearTokens();\n dropSession();\n // Kiosk/shared-browser hygiene: ending the session must not hand the\n // next visitor the previous member's cart + promo (audit cart.ts:4).\n // Done HERE — not in dropSession — so an explicit logout or definitive\n // auth rejection wipes them, while an out-of-band token expiry in the\n // middle of an active shopper's visit leaves their cart alone.\n // Deliberately NOT userId-namespaced: the cart is populated anonymously\n // pre-signup and must survive the anonymous→signup transition.\n cartStore.clear();\n cartStore.setPromo(null);\n }\n }\n\n // The transport clears tokens out-of-band (refresh failure, post-refresh\n // 401). Without this subscription isAuthenticated() stayed true and the\n // chrome kept rendering an authenticated shell whose every request 401s\n // until a hard reload (audit auth.ts:26).\n onTokensCleared('patient', dropSession);\n\n // Cross-tab convergence: logout (or login) in another tab updates shared\n // localStorage but fires no event in-store — converge on the peer's state.\n // The `storage` event never fires in the acting tab, which is why the\n // same-tab path above is a separate, direct subscription.\n if (typeof window !== 'undefined') {\n window.addEventListener('storage', (e) => {\n let key: string;\n try {\n key = authStorageKey();\n } catch {\n return; // not configured yet — nothing to converge on\n }\n if (e.key !== null && e.key !== key) return; // null key = storage.clear()\n const stored = getTokens();\n if (stored?.accessToken) {\n const wasAuthenticated = isAuthenticated();\n batch(() => {\n _setTokens(stored);\n setIsAuthenticated(true);\n });\n if (!wasAuthenticated) void fetchProfile();\n } else {\n dropSession();\n }\n });\n }\n\n async function fetchProfile() {\n try {\n const res = await usersApi.getProfile();\n if (res.data) {\n setUser(res.data);\n }\n } catch (err) {\n // Only a definitive auth rejection ends the session. The transport has\n // already refreshed-and-retried before a 401 reaches here (and cleared\n // the stored tokens itself); a transient 5xx / network blip during a\n // reload must NOT destroy a valid refresh token and force-log-out a\n // returning member (audit auth.ts:46). The profile simply stays\n // unhydrated and can be fetched again later.\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n syncTokens(null);\n }\n }\n }\n\n // ── Initialize ──────────────────────────────────────────────────\n\n // Hydrate from token storage AFTER `configure()` runs. The store is a\n // singleton created at import time (see `createRoot` below), which is before\n // the host site calls `configure()`; reading `getTokens()` then would route\n // through `getConfig()` and throw, leaving a returning member rendered\n // logged-out until their first live API call. `onConfigured` defers this.\n let hydrated = false;\n function hydrate() {\n if (hydrated) return;\n hydrated = true;\n const stored = getTokens();\n if (stored?.accessToken) {\n _setTokens(stored);\n setIsAuthenticated(true);\n // Fire-and-forget profile hydration\n fetchProfile();\n }\n }\n onConfigured(hydrate);\n\n // ── Public API ──────────────────────────────────────────────────\n\n async function login(email: string, password: string) {\n setLoading(true);\n try {\n const res = await authApi.login({ email, password });\n if (res.data) {\n syncTokens({\n accessToken: res.data.accessToken,\n refreshToken: res.data.refreshToken,\n userId: res.data.userId,\n });\n // Backend login doesn't return full user profile — fetch it\n await fetchProfile();\n }\n } finally {\n setLoading(false);\n }\n }\n\n async function signup(payload: RegisterPayload) {\n setLoading(true);\n try {\n const res = await authApi.register(payload);\n if (res.data) {\n syncTokens({\n accessToken: res.data.accessToken,\n refreshToken: res.data.refreshToken,\n userId: res.data.userId,\n });\n await fetchProfile();\n }\n } finally {\n setLoading(false);\n }\n }\n\n async function signupAndSubscribe(\n payload: RegisterAndSubscribePayload,\n opts?: { idempotencyKey?: string },\n ) {\n setLoading(true);\n try {\n const res = await authApi.registerAndSubscribe(payload, opts);\n if (res.data) {\n syncTokens({\n accessToken: res.data.accessToken,\n refreshToken: res.data.refreshToken,\n userId: res.data.userId,\n });\n await fetchProfile();\n return res.data;\n }\n } finally {\n setLoading(false);\n }\n }\n\n function logout() {\n syncTokens(null);\n }\n\n return {\n // Reactive getters\n tokens,\n user,\n isAuthenticated,\n isAdmin,\n loading,\n // Actions\n login,\n signup,\n signupAndSubscribe,\n logout,\n fetchProfile,\n };\n}\n\n// Singleton store created inside a reactive root\nconst authStore = createRoot(createAuthStore);\nexport default authStore;\n","import { createSignal, createRoot, batch } from 'solid-js';\nimport { onConfigured } from '../config';\nimport {\n affiliatePortalApi,\n getAffiliateTokens,\n setAffiliateTokens,\n clearAffiliateTokens,\n ApiError,\n onTokensCleared,\n affiliateAuthStorageKey,\n type Affiliate,\n type AffiliateAuthTokens,\n type AffiliateRegisterInput,\n} from '../api/client';\n\nfunction createAffiliateAuthStore() {\n const [tokens, _setTokens] = createSignal<AffiliateAuthTokens | null>(null);\n const [affiliate, setAffiliate] = createSignal<Affiliate | null>(null);\n const [isAuthenticated, setIsAuthenticated] = createSignal(false);\n const [isHydrated, setIsHydrated] = createSignal(false);\n const [loading, setLoading] = createSignal(false);\n\n /** Reset in-memory session signals WITHOUT touching token storage (see\n * stores/auth.ts dropSession — same loop-avoidance rationale). */\n function dropSession() {\n // Batched so a consumer combining these signals can never observe a\n // half-dropped session between flushes (same class of glitch as the\n // patient store's setUser→setIsAdmin admin-gate race).\n batch(() => {\n _setTokens(null);\n setIsAuthenticated(false);\n setAffiliate(null);\n });\n }\n\n function syncTokens(t: AffiliateAuthTokens | null) {\n _setTokens(t);\n if (t) {\n setAffiliateTokens(t);\n setIsAuthenticated(true);\n } else {\n clearAffiliateTokens();\n dropSession();\n }\n }\n\n // Same-tab: the transport's refresh-failure path clears affiliate tokens\n // out-of-band — flip the store immediately instead of rendering a stuck\n // authenticated-but-empty portal until a manual reload (audit client.ts:1682).\n onTokensCleared('affiliate', dropSession);\n\n // Cross-tab: converge on a peer tab's logout/login (audit affiliateAuth.ts:16).\n if (typeof window !== 'undefined') {\n window.addEventListener('storage', (e) => {\n let key: string;\n try {\n key = affiliateAuthStorageKey();\n } catch {\n return; // not configured yet\n }\n if (e.key !== null && e.key !== key) return; // null key = storage.clear()\n const stored = getAffiliateTokens();\n if (stored?.accessToken) {\n const wasAuthenticated = isAuthenticated();\n _setTokens(stored);\n setIsAuthenticated(true);\n if (!wasAuthenticated) void fetchProfile();\n } else {\n dropSession();\n }\n });\n }\n\n async function fetchProfile() {\n try {\n const res = await affiliatePortalApi.getProfile();\n setAffiliate(res.affiliate);\n } catch (err) {\n // Clear only on a definitive auth rejection (the transport has already\n // refreshed-and-retried before a 401 surfaces here). A transient\n // 5xx/network blip during hydration or right after login() must not\n // erase a valid refresh token — that logged out every affiliate loading\n // the app during a backend hiccup, and made login() resolve into an\n // instantly-dead session (audit affiliateAuth.ts:43 + :59). On a\n // transient failure the session stands; the profile stays null and can\n // be re-fetched.\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n syncTokens(null);\n }\n } finally {\n setIsHydrated(true);\n }\n }\n\n // Hydrate from token storage after `configure()` (see stores/auth.ts for the\n // boot-ordering rationale). fetchProfile() flips isHydrated in its finally;\n // the no-session branch flips it here.\n let hydrated = false;\n function hydrate() {\n if (hydrated) return;\n hydrated = true;\n const stored = getAffiliateTokens();\n if (stored?.accessToken) {\n _setTokens(stored);\n setIsAuthenticated(true);\n fetchProfile();\n } else {\n setIsHydrated(true);\n }\n }\n onConfigured(hydrate);\n\n async function login(email: string, password: string) {\n setLoading(true);\n try {\n const session = await affiliatePortalApi.login(email, password);\n syncTokens({\n accessToken: session.idToken,\n refreshToken: session.refreshToken,\n affiliateId: session.affiliateId,\n });\n setIsHydrated(false);\n await fetchProfile();\n } finally {\n setLoading(false);\n }\n }\n\n async function register(input: AffiliateRegisterInput) {\n setLoading(true);\n try {\n await affiliatePortalApi.register(input);\n // Backend register does NOT return tokens — new affiliates start as\n // 'pending' and must be approved by an admin before they can log in.\n // We surface the affiliate ID via the resolved promise so the page\n // can show a \"pending approval\" success state without logging in.\n } finally {\n setLoading(false);\n }\n }\n\n async function logout() {\n try {\n await affiliatePortalApi.logout();\n } finally {\n syncTokens(null);\n }\n }\n\n return {\n tokens,\n affiliate,\n isAuthenticated,\n isHydrated,\n loading,\n login,\n register,\n logout,\n fetchProfile,\n };\n}\n\nconst affiliateAuthStore = createRoot(createAffiliateAuthStore);\nexport default affiliateAuthStore;\n","import { createSignal, createRoot } from 'solid-js';\n\nexport interface MedicationSelection {\n drugId: string | null; // null = general consultation\n drugName: string;\n}\n\nfunction createMedicationStore() {\n const [selected, setSelected] = createSignal<MedicationSelection | null>(null);\n\n function select(medication: MedicationSelection) {\n setSelected(medication);\n }\n\n function clear() {\n setSelected(null);\n }\n\n return { selected, select, clear };\n}\n\nconst medicationStore = createRoot(createMedicationStore);\nexport default medicationStore;\n"]}
1
+ {"version":3,"sources":["../../src/stores/cart.ts","../../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B;AAAA,EACF;AAEA,EAAA,eAAe,MAAA,GAAS;AACtB,IAAA,IAAI;AACF,MAAA,MAAM,mBAAmB,MAAA,EAAO;AAAA,IAClC,CAAA,SAAE;AACA,MAAA,UAAA,CAAW,IAAI,CAAA;AAAA,IACjB;AAAA,EACF;AAEA,EAAA,OAAO;AAAA,IACL,MAAA;AAAA,IACA,SAAA;AAAA,IACA,eAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,KAAA;AAAA,IACA,QAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF;AAEA,IAAM,kBAAA,GAAqBD,WAAW,wBAAwB,CAAA;AAC9D,IAAO,qBAAA,GAAQ;AC5Jf,SAAS,qBAAA,GAAwB;AAC/B,EAAA,MAAM,CAAC,QAAA,EAAU,WAAW,CAAA,GAAID,aAAyC,IAAI,CAAA;AAE7E,EAAA,SAAS,OAAO,UAAA,EAAiC;AAC/C,IAAA,WAAA,CAAY,UAAU,CAAA;AAAA,EACxB;AAEA,EAAA,SAAS,KAAA,GAAQ;AACf,IAAA,WAAA,CAAY,IAAI,CAAA;AAAA,EAClB;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,MAAA,EAAQ,KAAA,EAAM;AACnC;AAEA,IAAM,eAAA,GAAkBC,WAAW,qBAAqB,CAAA;AACxD,IAAO,kBAAA,GAAQ","file":"3VBKKYOR.js","sourcesContent":["import { createSignal, createRoot } from 'solid-js';\nimport { getConfig } from '../config';\n\nconst cartStorageKey = () => `${getConfig().storagePrefix}-cart`;\nconst promoStorageKey = () => `${getConfig().storagePrefix}-cart-promo`;\n\nexport interface CartItem {\n productId: string;\n productName: string;\n dosage: string;\n /** Dose redesign (Phase 8): optional patient-requested intake hints, mirroring\n * Apex intake — `requestedSku` is the binding patient-bought SKU,\n * `requestedClinicalDose` is the advisory dose. Default undefined; carried\n * through to the /apex/requests medications payload. Nothing sets these yet. */\n requestedSku?: string;\n /** SKU identity S4: the stable, opaque `skus[].id` form of `requestedSku`\n * (from Apex's /v1/drugs catalog). Preferred over the label — survives a\n * relabel. Additive; carried through to the medications payload. */\n requestedSkuId?: string;\n requestedClinicalDose?: { value: number; unit: string };\n quantity: number;\n priceCents: number;\n drugId: string | null;\n /** The linked Apex drug id, copied from the catalog product. Matches the id\n * the survey qualification verdict (`drugResults[].drugId`) is keyed on, so\n * request creation can gate out drugs the survey marked ineligible. Null/\n * undefined for non-Apex products or carts saved before this field existed. */\n apexDrugId?: string | null;\n categories: string[];\n thumbnailUrl?: string;\n /** True when the product uses flat_fee pricing. The dosage is still set\n * (Apex needs it for the prescription) but consumer cart drawers should\n * skip rendering the dose suffix. */\n hideDoseLabel?: boolean;\n /** Copied from the catalog's `is_subscription` at add-time. The one-time\n * checkout flow excludes subscription items (the backend 400s a\n * /payments/checkout containing one, and stays the authority). Undefined —\n * legacy persisted carts, non-catalog adds — is treated as one-time-purchasable. */\n isSubscription?: boolean;\n}\n\nexport interface AppliedPromoCode {\n code: string;\n discountType: 'percent' | 'fixed';\n discountValueCents: number;\n discountCents: number;\n}\n\nfunction itemKey(productId: string, dosage: string): string {\n return `${productId}::${dosage}`;\n}\n\nfunction loadInitial(): CartItem[] {\n try {\n const raw = localStorage.getItem(cartStorageKey());\n if (!raw) return [];\n const parsed = JSON.parse(raw);\n if (!Array.isArray(parsed)) return [];\n // Preserve a sane persisted quantity (set via setQuantity); anything else\n // — legacy carts, tampered storage — normalizes back to 1.\n return parsed.map((i: CartItem) => ({\n ...i,\n quantity: Number.isInteger(i.quantity) && i.quantity > 0 ? i.quantity : 1,\n }));\n } catch {\n return [];\n }\n}\n\nfunction loadInitialPromo(): AppliedPromoCode | null {\n try {\n const raw = localStorage.getItem(promoStorageKey());\n if (!raw) return null;\n return JSON.parse(raw) as AppliedPromoCode;\n } catch {\n return null;\n }\n}\n\nfunction persist(items: CartItem[]) {\n try {\n localStorage.setItem(cartStorageKey(), JSON.stringify(items));\n } catch {\n // noop\n }\n}\n\nfunction persistPromo(promo: AppliedPromoCode | null) {\n try {\n if (promo) localStorage.setItem(promoStorageKey(), JSON.stringify(promo));\n else localStorage.removeItem(promoStorageKey());\n } catch {\n // noop\n }\n}\n\nfunction createCartStore() {\n const [items, setItems] = createSignal<CartItem[]>(loadInitial());\n const [isOpen, setIsOpen] = createSignal(false);\n const [appliedPromo, setAppliedPromo] = createSignal<AppliedPromoCode | null>(loadInitialPromo());\n\n function write(next: CartItem[]) {\n setItems(next);\n persist(next);\n }\n\n function count() {\n return items().length;\n }\n\n function subtotalCents() {\n return items().reduce((sum, i) => sum + i.priceCents * (i.quantity || 1), 0);\n }\n\n function add(item: CartItem) {\n const key = itemKey(item.productId, item.dosage);\n const current = items();\n if (current.some(i => itemKey(i.productId, i.dosage) === key)) return;\n write([...current, { ...item, quantity: 1 }]);\n }\n\n function remove(key: string) {\n write(items().filter(i => itemKey(i.productId, i.dosage) !== key));\n }\n\n /** Set an item's quantity (floored, clamped to ≥1 — removing is `remove`'s\n * job). Non-finite input and unknown keys are ignored. `add` still starts\n * every item at 1; this is the only quantity mutator. */\n function setQuantity(key: string, quantity: number) {\n if (!Number.isFinite(quantity)) return;\n const clamped = Math.max(1, Math.floor(quantity));\n const current = items();\n if (!current.some(i => itemKey(i.productId, i.dosage) === key)) return;\n write(current.map(i => (itemKey(i.productId, i.dosage) === key ? { ...i, quantity: clamped } : i)));\n }\n\n /**\n * Replace the whole cart in one write. For catalog reconciliation\n * (`flows/cartReconcile`), which drops lines the catalog no longer offers and\n * refreshes the snapshots of the ones it does — neither expressible as\n * add/remove, and both must land as a single persist so a half-written cart\n * can never be read back. Quantities are taken as given (unlike `add`, which\n * always starts at 1).\n */\n function replace(next: CartItem[]) {\n write(next);\n }\n\n function clear() {\n // Preserve the applied promo across cart resets — the survey submission\n // clears the cart but the customer still expects the code they entered to\n // apply to subsequent prescription purchases. Removing the promo is an\n // explicit action via the cart drawer's \"remove\" link.\n write([]);\n }\n\n function hasGlp1() {\n return items().some(i =>\n i.categories.some(c => c.toLowerCase().includes('weight') || c.toLowerCase().includes('glp')),\n );\n }\n\n function isMultiItem() {\n return items().length > 1;\n }\n\n function setPromo(promo: AppliedPromoCode | null) {\n setAppliedPromo(promo);\n persistPromo(promo);\n }\n\n return {\n items,\n count,\n subtotalCents,\n add,\n remove,\n setQuantity,\n replace,\n clear,\n hasGlp1,\n isMultiItem,\n itemKey,\n isOpen,\n open: () => setIsOpen(true),\n close: () => setIsOpen(false),\n toggle: () => setIsOpen(v => !v),\n appliedPromo,\n setPromo,\n };\n}\n\nconst cartStore = createRoot(createCartStore);\nexport default cartStore;\n","import { createSignal, createMemo, createRoot, batch } from 'solid-js';\nimport { onConfigured } from '../config';\nimport {\n authApi,\n getTokens,\n setTokens,\n clearTokens,\n usersApi,\n ApiError,\n onTokensCleared,\n authStorageKey,\n type User,\n type AuthTokens,\n type RegisterPayload,\n type RegisterAndSubscribePayload,\n} from '../api/client';\nimport cartStore from './cart';\n\nfunction createAuthStore() {\n // ── Signals ─────────────────────────────────────────────────────\n\n const [tokens, _setTokens] = createSignal<AuthTokens | null>(null);\n const [user, setUser] = createSignal<User | null>(null);\n const [isAuthenticated, setIsAuthenticated] = createSignal(false);\n const [loading, setLoading] = createSignal(false);\n\n // Derived, not a second signal: admin-ness must never be observable out of\n // step with the user it describes. As separate writes, Solid flushed\n // dependents between setUser and setIsAdmin, so an admin gate combining\n // \"hydrated\" (user() !== null) with isAdmin() saw \"hydrated but not admin\"\n // for one tick on every hard load of /admin and bounced to the fallback\n // route.\n const isAdmin = createMemo(() => user()?.role === 'admin');\n\n // ── Internal helpers ────────────────────────────────────────────\n\n /** Reset the in-memory session signals WITHOUT touching token storage.\n * Used by the token-cleared/storage listeners, where storage is already\n * gone (writing it back would re-notify and loop). */\n function dropSession() {\n batch(() => {\n _setTokens(null);\n setIsAuthenticated(false);\n setUser(null);\n });\n }\n\n function syncTokens(t: AuthTokens | null) {\n _setTokens(t);\n if (t) {\n setTokens(t);\n setIsAuthenticated(true);\n } else {\n clearTokens();\n dropSession();\n // Kiosk/shared-browser hygiene: ending the session must not hand the\n // next visitor the previous member's cart + promo (audit cart.ts:4).\n // Done HERE — not in dropSession — so an explicit logout or definitive\n // auth rejection wipes them, while an out-of-band token expiry in the\n // middle of an active shopper's visit leaves their cart alone.\n // Deliberately NOT userId-namespaced: the cart is populated anonymously\n // pre-signup and must survive the anonymous→signup transition.\n cartStore.clear();\n cartStore.setPromo(null);\n }\n }\n\n // The transport clears tokens out-of-band (refresh failure, post-refresh\n // 401). Without this subscription isAuthenticated() stayed true and the\n // chrome kept rendering an authenticated shell whose every request 401s\n // until a hard reload (audit auth.ts:26).\n onTokensCleared('patient', dropSession);\n\n // Cross-tab convergence: logout (or login) in another tab updates shared\n // localStorage but fires no event in-store — converge on the peer's state.\n // The `storage` event never fires in the acting tab, which is why the\n // same-tab path above is a separate, direct subscription.\n if (typeof window !== 'undefined') {\n window.addEventListener('storage', (e) => {\n let key: string;\n try {\n key = authStorageKey();\n } catch {\n return; // not configured yet — nothing to converge on\n }\n if (e.key !== null && e.key !== key) return; // null key = storage.clear()\n const stored = getTokens();\n if (stored?.accessToken) {\n const wasAuthenticated = isAuthenticated();\n batch(() => {\n _setTokens(stored);\n setIsAuthenticated(true);\n });\n if (!wasAuthenticated) void fetchProfile();\n } else {\n dropSession();\n }\n });\n }\n\n async function fetchProfile() {\n try {\n const res = await usersApi.getProfile();\n if (res.data) {\n setUser(res.data);\n }\n } catch (err) {\n // Only a definitive auth rejection ends the session. The transport has\n // already refreshed-and-retried before a 401 reaches here (and cleared\n // the stored tokens itself); a transient 5xx / network blip during a\n // reload must NOT destroy a valid refresh token and force-log-out a\n // returning member (audit auth.ts:46). The profile simply stays\n // unhydrated and can be fetched again later.\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n syncTokens(null);\n }\n }\n }\n\n // ── Initialize ──────────────────────────────────────────────────\n\n // Hydrate from token storage AFTER `configure()` runs. The store is a\n // singleton created at import time (see `createRoot` below), which is before\n // the host site calls `configure()`; reading `getTokens()` then would route\n // through `getConfig()` and throw, leaving a returning member rendered\n // logged-out until their first live API call. `onConfigured` defers this.\n let hydrated = false;\n function hydrate() {\n if (hydrated) return;\n hydrated = true;\n const stored = getTokens();\n if (stored?.accessToken) {\n _setTokens(stored);\n setIsAuthenticated(true);\n // Fire-and-forget profile hydration\n fetchProfile();\n }\n }\n onConfigured(hydrate);\n\n // ── Public API ──────────────────────────────────────────────────\n\n async function login(email: string, password: string) {\n setLoading(true);\n try {\n const res = await authApi.login({ email, password });\n if (res.data) {\n syncTokens({\n accessToken: res.data.accessToken,\n refreshToken: res.data.refreshToken,\n userId: res.data.userId,\n });\n // Backend login doesn't return full user profile — fetch it\n await fetchProfile();\n }\n } finally {\n setLoading(false);\n }\n }\n\n async function signup(payload: RegisterPayload) {\n setLoading(true);\n try {\n const res = await authApi.register(payload);\n if (res.data) {\n syncTokens({\n accessToken: res.data.accessToken,\n refreshToken: res.data.refreshToken,\n userId: res.data.userId,\n });\n await fetchProfile();\n }\n } finally {\n setLoading(false);\n }\n }\n\n async function signupAndSubscribe(\n payload: RegisterAndSubscribePayload,\n opts?: { idempotencyKey?: string },\n ) {\n setLoading(true);\n try {\n const res = await authApi.registerAndSubscribe(payload, opts);\n if (res.data) {\n syncTokens({\n accessToken: res.data.accessToken,\n refreshToken: res.data.refreshToken,\n userId: res.data.userId,\n });\n await fetchProfile();\n return res.data;\n }\n } finally {\n setLoading(false);\n }\n }\n\n function logout() {\n syncTokens(null);\n }\n\n return {\n // Reactive getters\n tokens,\n user,\n isAuthenticated,\n isAdmin,\n loading,\n // Actions\n login,\n signup,\n signupAndSubscribe,\n logout,\n fetchProfile,\n };\n}\n\n// Singleton store created inside a reactive root\nconst authStore = createRoot(createAuthStore);\nexport default authStore;\n","import { createSignal, createRoot, batch } from 'solid-js';\nimport { onConfigured } from '../config';\nimport {\n affiliatePortalApi,\n getAffiliateTokens,\n setAffiliateTokens,\n clearAffiliateTokens,\n ApiError,\n onTokensCleared,\n affiliateAuthStorageKey,\n type Affiliate,\n type AffiliateAuthTokens,\n type AffiliateRegisterInput,\n} from '../api/client';\n\nfunction createAffiliateAuthStore() {\n const [tokens, _setTokens] = createSignal<AffiliateAuthTokens | null>(null);\n const [affiliate, setAffiliate] = createSignal<Affiliate | null>(null);\n const [isAuthenticated, setIsAuthenticated] = createSignal(false);\n const [isHydrated, setIsHydrated] = createSignal(false);\n const [loading, setLoading] = createSignal(false);\n\n /** Reset in-memory session signals WITHOUT touching token storage (see\n * stores/auth.ts dropSession — same loop-avoidance rationale). */\n function dropSession() {\n // Batched so a consumer combining these signals can never observe a\n // half-dropped session between flushes (same class of glitch as the\n // patient store's setUser→setIsAdmin admin-gate race).\n batch(() => {\n _setTokens(null);\n setIsAuthenticated(false);\n setAffiliate(null);\n });\n }\n\n function syncTokens(t: AffiliateAuthTokens | null) {\n _setTokens(t);\n if (t) {\n setAffiliateTokens(t);\n setIsAuthenticated(true);\n } else {\n clearAffiliateTokens();\n dropSession();\n }\n }\n\n // Same-tab: the transport's refresh-failure path clears affiliate tokens\n // out-of-band — flip the store immediately instead of rendering a stuck\n // authenticated-but-empty portal until a manual reload (audit client.ts:1682).\n onTokensCleared('affiliate', dropSession);\n\n // Cross-tab: converge on a peer tab's logout/login (audit affiliateAuth.ts:16).\n if (typeof window !== 'undefined') {\n window.addEventListener('storage', (e) => {\n let key: string;\n try {\n key = affiliateAuthStorageKey();\n } catch {\n return; // not configured yet\n }\n if (e.key !== null && e.key !== key) return; // null key = storage.clear()\n const stored = getAffiliateTokens();\n if (stored?.accessToken) {\n const wasAuthenticated = isAuthenticated();\n _setTokens(stored);\n setIsAuthenticated(true);\n if (!wasAuthenticated) void fetchProfile();\n } else {\n dropSession();\n }\n });\n }\n\n async function fetchProfile() {\n try {\n const res = await affiliatePortalApi.getProfile();\n setAffiliate(res.affiliate);\n } catch (err) {\n // Clear only on a definitive auth rejection (the transport has already\n // refreshed-and-retried before a 401 surfaces here). A transient\n // 5xx/network blip during hydration or right after login() must not\n // erase a valid refresh token — that logged out every affiliate loading\n // the app during a backend hiccup, and made login() resolve into an\n // instantly-dead session (audit affiliateAuth.ts:43 + :59). On a\n // transient failure the session stands; the profile stays null and can\n // be re-fetched.\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n syncTokens(null);\n }\n } finally {\n setIsHydrated(true);\n }\n }\n\n // Hydrate from token storage after `configure()` (see stores/auth.ts for the\n // boot-ordering rationale). fetchProfile() flips isHydrated in its finally;\n // the no-session branch flips it here.\n let hydrated = false;\n function hydrate() {\n if (hydrated) return;\n hydrated = true;\n const stored = getAffiliateTokens();\n if (stored?.accessToken) {\n _setTokens(stored);\n setIsAuthenticated(true);\n fetchProfile();\n } else {\n setIsHydrated(true);\n }\n }\n onConfigured(hydrate);\n\n async function login(email: string, password: string) {\n setLoading(true);\n try {\n const session = await affiliatePortalApi.login(email, password);\n syncTokens({\n accessToken: session.idToken,\n refreshToken: session.refreshToken,\n affiliateId: session.affiliateId,\n });\n setIsHydrated(false);\n await fetchProfile();\n } finally {\n setLoading(false);\n }\n }\n\n async function register(input: AffiliateRegisterInput) {\n setLoading(true);\n try {\n await affiliatePortalApi.register(input);\n // Backend register does NOT return tokens — new affiliates start as\n // 'pending' and must be approved by an admin before they can log in.\n // We surface the affiliate ID via the resolved promise so the page\n // can show a \"pending approval\" success state without logging in.\n } finally {\n setLoading(false);\n }\n }\n\n async function logout() {\n try {\n await affiliatePortalApi.logout();\n } finally {\n syncTokens(null);\n }\n }\n\n return {\n tokens,\n affiliate,\n isAuthenticated,\n isHydrated,\n loading,\n login,\n register,\n logout,\n fetchProfile,\n };\n}\n\nconst affiliateAuthStore = createRoot(createAffiliateAuthStore);\nexport default affiliateAuthStore;\n","import { createSignal, createRoot } from 'solid-js';\n\nexport interface MedicationSelection {\n drugId: string | null; // null = general consultation\n drugName: string;\n}\n\nfunction createMedicationStore() {\n const [selected, setSelected] = createSignal<MedicationSelection | null>(null);\n\n function select(medication: MedicationSelection) {\n setSelected(medication);\n }\n\n function clear() {\n setSelected(null);\n }\n\n return { selected, select, clear };\n}\n\nconst medicationStore = createRoot(createMedicationStore);\nexport default medicationStore;\n"]}
@@ -1,4 +1,4 @@
1
- import { peekFunnelSessionId, captureAuthHeader } from './6V7RVUXX.js';
1
+ import { peekFunnelSessionId, captureAuthHeader } from './COIUOQOE.js';
2
2
  import { getConfig } from './2IFPDU4D.js';
3
3
 
4
4
  // src/api/promoRef.ts
@@ -156,5 +156,5 @@ function stripCartToken() {
156
156
  }
157
157
 
158
158
  export { adoptCartId, capturePromoCode, cartId, clearPromoCode, fetchCartConfig, fetchResumedCart, postCartSnapshot, readCartToken, readPromoCode, resetCartConfigCache, resetCartId, stripCartToken };
159
- //# sourceMappingURL=FXRGPBYU.js.map
160
- //# sourceMappingURL=FXRGPBYU.js.map
159
+ //# sourceMappingURL=3VUCQNOR.js.map
160
+ //# sourceMappingURL=3VUCQNOR.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/promoRef.ts","../../src/api/cart.ts"],"names":[],"mappings":";;;;AAiBA,IAAM,MAAA,GAAS,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,GAAA;AAEnC,IAAM,UAAA,GAAa,MAAM,CAAA,EAAG,SAAA,GAAY,aAAa,CAAA,WAAA,CAAA;AAQ9C,SAAS,iBAAiB,IAAA,EAAoB;AACnD,EAAA,IAAI,OAAO,iBAAiB,WAAA,EAAa;AACzC,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,IAAI,CAAC,OAAA,EAAS;AACd,EAAA,IAAI;AACF,IAAA,MAAM,QAAqB,EAAE,IAAA,EAAM,SAAS,EAAA,EAAI,IAAA,CAAK,KAAI,EAAE;AAC3D,IAAA,YAAA,CAAa,QAAQ,UAAA,EAAW,EAAG,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,EAC1D,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AASO,SAAS,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AA,CAAa,GAAA,CAAI,MAAM,CAAA,EAAG;AACnC,IAAA,GAAA,CAAI,YAAA,CAAa,OAAO,MAAM,CAAA;AAC9B,IAAA,MAAA,CAAO,QAAQ,YAAA,CAAa,IAAI,EAAA,EAAI,GAAA,CAAI,UAAU,CAAA;AAAA,EACpD,CAAA,CAAA,MAAQ;AAAA,EAER;AACF","file":"FXRGPBYU.js","sourcesContent":["// ── First-party promo-code capture from a `?promo=` landing ──────────\n//\n// A campaign link can carry its own code (`/?promo=TRUE10`) so the member does\n// not have to type it. Stashed in the storefront's own localStorage and read\n// back when the intake reaches the promo field.\n//\n// Mirrors `affiliateRef` deliberately — same storage shape, same 30-day window —\n// but is a SEPARATE concern: an affiliate ref attributes a sale to a partner and\n// is validated server-side at checkout, while this only pre-fills an input the\n// member still has to submit.\n\nimport { getConfig } from '../config';\n\n// Matches the affiliate-ref window. A stash that outlives the promo it carries\n// is not a correctness problem — the code is re-validated before it is used,\n// and silently dropped if it has expired — but there is no reason to keep one\n// around longer than a campaign plausibly runs.\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst storageKey = () => `${getConfig().storagePrefix}-promo-code`;\n\ninterface StoredPromo {\n code: string;\n ts: number;\n}\n\n/** Persist a promo code from a `?promo=` landing. No-op for empty input. */\nexport function capturePromoCode(code: string): void {\n if (typeof localStorage === 'undefined') return;\n const trimmed = code.trim();\n if (!trimmed) return;\n try {\n const entry: StoredPromo = { code: trimmed, ts: Date.now() };\n localStorage.setItem(storageKey(), JSON.stringify(entry));\n } catch {\n // storage unavailable (private mode / quota) — non-fatal\n }\n}\n\n/**\n * Read the stored promo code, or null if absent or past the storage window.\n *\n * Being within the window says nothing about whether the CODE is still valid —\n * a campaign can end while the stash is fresh. The caller re-validates against\n * the server before showing it to anyone.\n */\nexport function readPromoCode(): string | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(storageKey());\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<StoredPromo>;\n if (!parsed.code || typeof parsed.ts !== 'number') return null;\n if (Date.now() - parsed.ts > TTL_MS) {\n localStorage.removeItem(storageKey());\n return null;\n }\n return parsed.code;\n } catch {\n return null;\n }\n}\n\n/** Drop the stored promo code. */\nexport function clearPromoCode(): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.removeItem(storageKey());\n } catch {\n // non-fatal\n }\n}\n","import { getConfig } from '../config';\nimport { captureAuthHeader, peekFunnelSessionId } from './funnel';\n\n// ── Abandoned-cart transport ────────────────────────────────────────────────\n//\n// Thin client for the-backend's cart-capture endpoints:\n// GET /config/cart → whether this tenant mirrors carts at all\n// POST /cart/snapshot → server-side mirror of the browser's cart\n// GET /cart/resume → trade an emailed token for the saved cart\n//\n// Sibling of ./funnel, and the same posture: fire-and-forget, fail-silent.\n// Cart capture is marketing instrumentation and must never break, block or\n// slow down shopping.\n\nexport interface CartCaptureConfig {\n /** Tenant opted in (features.cartRecovery); false = never send anything. */\n snapshot: boolean;\n}\n\nconst DISABLED: CartCaptureConfig = { snapshot: false };\n\nlet configPromise: Promise<CartCaptureConfig> | null = null;\n\n/**\n * The tenant's cart-capture posture, fetched once per page load and cached.\n * Fails closed: any error reads as \"off\".\n */\nexport function fetchCartConfig(): Promise<CartCaptureConfig> {\n if (!configPromise) {\n configPromise = (async () => {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/config/cart`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return DISABLED;\n const body = (await res.json()) as Partial<CartCaptureConfig>;\n return { snapshot: body.snapshot === true };\n } catch {\n return DISABLED;\n }\n })();\n }\n return configPromise;\n}\n\n/** Test seam: forget the cached config so the next fetch re-resolves. */\nexport function resetCartConfigCache(): void {\n configPromise = null;\n}\n\nconst cartIdKey = () => `${getConfig().storagePrefix}-cart-id`;\n\n/**\n * Stable id for this shopper's cart, minted on first use and kept in\n * localStorage — NOT sessionStorage like the survey session.\n *\n * A cart outlives the tab it was filled in: someone adds items, closes the\n * browser, comes back tomorrow and finds the cart still there (the cart store\n * itself persists the same way). The id has to survive with it, or every visit\n * would look like a brand-new abandoned cart and one shopper would accumulate\n * a row — and a reminder track — per session.\n */\nexport function cartId(): string {\n let id: string | null = null;\n try {\n id = localStorage.getItem(cartIdKey());\n } catch {\n /* storage unavailable (private mode) — fall through to an 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 localStorage.setItem(cartIdKey(), id);\n } catch {\n /* ephemeral it is */\n }\n }\n return id;\n}\n\n/**\n * Continue the cart a recovery email points at, instead of the one this browser\n * happens to hold. Adopting the emailed id keeps the reminder history, the\n * email address and the eventual conversion on ONE row.\n */\nexport function adoptCartId(id: string): void {\n if (!id) return;\n try {\n localStorage.setItem(cartIdKey(), id);\n } catch {\n /* storage unavailable — the adoption is ephemeral */\n }\n}\n\n/**\n * Start a fresh cart id. Called after a purchase: the old id is stamped\n * converted server-side and must never be written to again, or a new cart\n * would inherit a bought cart's row (and its silence — converted rows are\n * never nudged).\n */\nexport function resetCartId(): void {\n try {\n localStorage.removeItem(cartIdKey());\n } catch {\n /* nothing to clear */\n }\n}\n\nexport interface CartSnapshotLine {\n productId: string;\n dosage?: string;\n quantity: number;\n}\n\n/**\n * Mirror the cart server-side. Identity only — the backend re-prices from the\n * catalog and ignores anything else we send, so there is no point shipping\n * names or prices.\n *\n * `keepalive` lets the request survive the page unload that so often IS the\n * abandonment.\n *\n * The bearer token, when there is one, is how a signed-in shopper's cart gets\n * their user id: the endpoint takes identity from the token and never from the\n * body (`optionalAuth`), so omitting it left every logged-in cart anonymous —\n * joinable only by whatever email happened to be attached.\n */\nexport function postCartSnapshot(params: {\n items: CartSnapshotLine[];\n promoCode?: string | null;\n email?: string | null;\n}): void {\n try {\n const cfg = getConfig();\n void fetch(`${cfg.apiBase}/cart/snapshot`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n ...captureAuthHeader(),\n },\n body: JSON.stringify({\n cartId: cartId(),\n items: params.items,\n promoCode: params.promoCode ?? null,\n ...(params.email ? { email: params.email } : {}),\n // Only when a survey session already exists: it lets the backend reuse\n // the address the pre-survey email gate collected, which is often the\n // only handle we have on an anonymous shopper.\n ...(peekFunnelSessionId() ? { sessionId: peekFunnelSessionId() } : {}),\n }),\n }).catch(() => {});\n } catch {\n /* not configured yet — drop */\n }\n}\n\n/** A resumed cart line, already re-priced against today's catalog. */\nexport interface ResumedCartLine {\n productId: string;\n dosage?: string;\n quantity: number;\n name: string;\n priceCents: number;\n salePriceCents: number | null;\n thumbnailUrl: string | null;\n isSubscription: boolean;\n apexDrugId: string | null;\n categories: string[];\n hideDoseLabel: boolean;\n}\n\nexport interface ResumedCart {\n cartId: string;\n items: ResumedCartLine[];\n /** Lines whose product has since been discontinued or deactivated. */\n unavailable: Array<{ productId: string; dosage?: string; quantity: number }>;\n promoCode: string | null;\n subtotalCents: number;\n}\n\n/**\n * Exchange an emailed recovery token for the saved cart.\n *\n * The token is the ONLY thing authorizing this read — the-backend verifies its\n * HMAC before returning anything. A 404 (expired, already bought, tampered, or\n * every product gone) resolves to null so the caller simply keeps whatever cart\n * this browser already had.\n */\nexport async function fetchResumedCart(token: string): Promise<ResumedCart | null> {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/cart/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<ResumedCart>;\n if (!body.cartId || !Array.isArray(body.items) || body.items.length === 0) return null;\n return {\n cartId: body.cartId,\n items: body.items,\n unavailable: Array.isArray(body.unavailable) ? body.unavailable : [],\n promoCode: body.promoCode ?? null,\n subtotalCents: typeof body.subtotalCents === 'number' ? body.subtotalCents : 0,\n };\n } catch {\n return null;\n }\n}\n\n/** Read the `?cart=` token from the current URL. */\nexport function readCartToken(): string | null {\n try {\n const token = new URLSearchParams(window.location.search).get('cart');\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop `?cart=` from the address bar once it's been redeemed, so a refresh (or\n * a shared URL) doesn't re-run the restore over a cart the shopper has since\n * edited. History is replaced, not pushed — the token was never a page.\n */\nexport function stripCartToken(): void {\n try {\n const url = new URL(window.location.href);\n if (!url.searchParams.has('cart')) return;\n url.searchParams.delete('cart');\n window.history.replaceState({}, '', url.toString());\n } catch {\n /* no history API — leaving the param is harmless */\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/api/promoRef.ts","../../src/api/cart.ts"],"names":[],"mappings":";;;;AAiBA,IAAM,MAAA,GAAS,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,GAAA;AAEnC,IAAM,UAAA,GAAa,MAAM,CAAA,EAAG,SAAA,GAAY,aAAa,CAAA,WAAA,CAAA;AAQ9C,SAAS,iBAAiB,IAAA,EAAoB;AACnD,EAAA,IAAI,OAAO,iBAAiB,WAAA,EAAa;AACzC,EAAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,EAAA,IAAI,CAAC,OAAA,EAAS;AACd,EAAA,IAAI;AACF,IAAA,MAAM,QAAqB,EAAE,IAAA,EAAM,SAAS,EAAA,EAAI,IAAA,CAAK,KAAI,EAAE;AAC3D,IAAA,YAAA,CAAa,QAAQ,UAAA,EAAW,EAAG,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAAA,EAC1D,CAAA,CAAA,MAAQ;AAAA,EAER;AACF;AASO,SAAS,aAAA,GAA+B;AAC7C,EAAA,IAAI,OAAO,YAAA,KAAiB,WAAA,EAAa,OAAO,IAAA;AAChD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,YAAA,CAAa,OAAA,CAAQ,UAAA,EAAY,CAAA;AAC7C,IAAA,IAAI,CAAC,KAAK,OAAO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A,MAAQ;AAAA,EAER;AACF","file":"3VUCQNOR.js","sourcesContent":["// ── First-party promo-code capture from a `?promo=` landing ──────────\n//\n// A campaign link can carry its own code (`/?promo=TRUE10`) so the member does\n// not have to type it. Stashed in the storefront's own localStorage and read\n// back when the intake reaches the promo field.\n//\n// Mirrors `affiliateRef` deliberately — same storage shape, same 30-day window —\n// but is a SEPARATE concern: an affiliate ref attributes a sale to a partner and\n// is validated server-side at checkout, while this only pre-fills an input the\n// member still has to submit.\n\nimport { getConfig } from '../config';\n\n// Matches the affiliate-ref window. A stash that outlives the promo it carries\n// is not a correctness problem — the code is re-validated before it is used,\n// and silently dropped if it has expired — but there is no reason to keep one\n// around longer than a campaign plausibly runs.\nconst TTL_MS = 30 * 24 * 60 * 60 * 1000;\n\nconst storageKey = () => `${getConfig().storagePrefix}-promo-code`;\n\ninterface StoredPromo {\n code: string;\n ts: number;\n}\n\n/** Persist a promo code from a `?promo=` landing. No-op for empty input. */\nexport function capturePromoCode(code: string): void {\n if (typeof localStorage === 'undefined') return;\n const trimmed = code.trim();\n if (!trimmed) return;\n try {\n const entry: StoredPromo = { code: trimmed, ts: Date.now() };\n localStorage.setItem(storageKey(), JSON.stringify(entry));\n } catch {\n // storage unavailable (private mode / quota) — non-fatal\n }\n}\n\n/**\n * Read the stored promo code, or null if absent or past the storage window.\n *\n * Being within the window says nothing about whether the CODE is still valid —\n * a campaign can end while the stash is fresh. The caller re-validates against\n * the server before showing it to anyone.\n */\nexport function readPromoCode(): string | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(storageKey());\n if (!raw) return null;\n const parsed = JSON.parse(raw) as Partial<StoredPromo>;\n if (!parsed.code || typeof parsed.ts !== 'number') return null;\n if (Date.now() - parsed.ts > TTL_MS) {\n localStorage.removeItem(storageKey());\n return null;\n }\n return parsed.code;\n } catch {\n return null;\n }\n}\n\n/** Drop the stored promo code. */\nexport function clearPromoCode(): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.removeItem(storageKey());\n } catch {\n // non-fatal\n }\n}\n","import { getConfig } from '../config';\nimport { captureAuthHeader, peekFunnelSessionId } from './funnel';\n\n// ── Abandoned-cart transport ────────────────────────────────────────────────\n//\n// Thin client for the-backend's cart-capture endpoints:\n// GET /config/cart → whether this tenant mirrors carts at all\n// POST /cart/snapshot → server-side mirror of the browser's cart\n// GET /cart/resume → trade an emailed token for the saved cart\n//\n// Sibling of ./funnel, and the same posture: fire-and-forget, fail-silent.\n// Cart capture is marketing instrumentation and must never break, block or\n// slow down shopping.\n\nexport interface CartCaptureConfig {\n /** Tenant opted in (features.cartRecovery); false = never send anything. */\n snapshot: boolean;\n}\n\nconst DISABLED: CartCaptureConfig = { snapshot: false };\n\nlet configPromise: Promise<CartCaptureConfig> | null = null;\n\n/**\n * The tenant's cart-capture posture, fetched once per page load and cached.\n * Fails closed: any error reads as \"off\".\n */\nexport function fetchCartConfig(): Promise<CartCaptureConfig> {\n if (!configPromise) {\n configPromise = (async () => {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/config/cart`, {\n headers: { 'X-Tenant-Key': cfg.tenantKey },\n });\n if (!res.ok) return DISABLED;\n const body = (await res.json()) as Partial<CartCaptureConfig>;\n return { snapshot: body.snapshot === true };\n } catch {\n return DISABLED;\n }\n })();\n }\n return configPromise;\n}\n\n/** Test seam: forget the cached config so the next fetch re-resolves. */\nexport function resetCartConfigCache(): void {\n configPromise = null;\n}\n\nconst cartIdKey = () => `${getConfig().storagePrefix}-cart-id`;\n\n/**\n * Stable id for this shopper's cart, minted on first use and kept in\n * localStorage — NOT sessionStorage like the survey session.\n *\n * A cart outlives the tab it was filled in: someone adds items, closes the\n * browser, comes back tomorrow and finds the cart still there (the cart store\n * itself persists the same way). The id has to survive with it, or every visit\n * would look like a brand-new abandoned cart and one shopper would accumulate\n * a row — and a reminder track — per session.\n */\nexport function cartId(): string {\n let id: string | null = null;\n try {\n id = localStorage.getItem(cartIdKey());\n } catch {\n /* storage unavailable (private mode) — fall through to an 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 localStorage.setItem(cartIdKey(), id);\n } catch {\n /* ephemeral it is */\n }\n }\n return id;\n}\n\n/**\n * Continue the cart a recovery email points at, instead of the one this browser\n * happens to hold. Adopting the emailed id keeps the reminder history, the\n * email address and the eventual conversion on ONE row.\n */\nexport function adoptCartId(id: string): void {\n if (!id) return;\n try {\n localStorage.setItem(cartIdKey(), id);\n } catch {\n /* storage unavailable — the adoption is ephemeral */\n }\n}\n\n/**\n * Start a fresh cart id. Called after a purchase: the old id is stamped\n * converted server-side and must never be written to again, or a new cart\n * would inherit a bought cart's row (and its silence — converted rows are\n * never nudged).\n */\nexport function resetCartId(): void {\n try {\n localStorage.removeItem(cartIdKey());\n } catch {\n /* nothing to clear */\n }\n}\n\nexport interface CartSnapshotLine {\n productId: string;\n dosage?: string;\n quantity: number;\n}\n\n/**\n * Mirror the cart server-side. Identity only — the backend re-prices from the\n * catalog and ignores anything else we send, so there is no point shipping\n * names or prices.\n *\n * `keepalive` lets the request survive the page unload that so often IS the\n * abandonment.\n *\n * The bearer token, when there is one, is how a signed-in shopper's cart gets\n * their user id: the endpoint takes identity from the token and never from the\n * body (`optionalAuth`), so omitting it left every logged-in cart anonymous —\n * joinable only by whatever email happened to be attached.\n */\nexport function postCartSnapshot(params: {\n items: CartSnapshotLine[];\n promoCode?: string | null;\n email?: string | null;\n}): void {\n try {\n const cfg = getConfig();\n void fetch(`${cfg.apiBase}/cart/snapshot`, {\n method: 'POST',\n keepalive: true,\n headers: {\n 'Content-Type': 'application/json',\n 'X-Tenant-Key': cfg.tenantKey,\n ...captureAuthHeader(),\n },\n body: JSON.stringify({\n cartId: cartId(),\n items: params.items,\n promoCode: params.promoCode ?? null,\n ...(params.email ? { email: params.email } : {}),\n // Only when a survey session already exists: it lets the backend reuse\n // the address the pre-survey email gate collected, which is often the\n // only handle we have on an anonymous shopper.\n ...(peekFunnelSessionId() ? { sessionId: peekFunnelSessionId() } : {}),\n }),\n }).catch(() => {});\n } catch {\n /* not configured yet — drop */\n }\n}\n\n/** A resumed cart line, already re-priced against today's catalog. */\nexport interface ResumedCartLine {\n productId: string;\n dosage?: string;\n quantity: number;\n name: string;\n priceCents: number;\n salePriceCents: number | null;\n thumbnailUrl: string | null;\n isSubscription: boolean;\n apexDrugId: string | null;\n categories: string[];\n hideDoseLabel: boolean;\n}\n\nexport interface ResumedCart {\n cartId: string;\n items: ResumedCartLine[];\n /** Lines whose product has since been discontinued or deactivated. */\n unavailable: Array<{ productId: string; dosage?: string; quantity: number }>;\n promoCode: string | null;\n subtotalCents: number;\n}\n\n/**\n * Exchange an emailed recovery token for the saved cart.\n *\n * The token is the ONLY thing authorizing this read — the-backend verifies its\n * HMAC before returning anything. A 404 (expired, already bought, tampered, or\n * every product gone) resolves to null so the caller simply keeps whatever cart\n * this browser already had.\n */\nexport async function fetchResumedCart(token: string): Promise<ResumedCart | null> {\n try {\n const cfg = getConfig();\n const res = await fetch(`${cfg.apiBase}/cart/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<ResumedCart>;\n if (!body.cartId || !Array.isArray(body.items) || body.items.length === 0) return null;\n return {\n cartId: body.cartId,\n items: body.items,\n unavailable: Array.isArray(body.unavailable) ? body.unavailable : [],\n promoCode: body.promoCode ?? null,\n subtotalCents: typeof body.subtotalCents === 'number' ? body.subtotalCents : 0,\n };\n } catch {\n return null;\n }\n}\n\n/** Read the `?cart=` token from the current URL. */\nexport function readCartToken(): string | null {\n try {\n const token = new URLSearchParams(window.location.search).get('cart');\n return token && token.length > 0 ? token : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Drop `?cart=` from the address bar once it's been redeemed, so a refresh (or\n * a shared URL) doesn't re-run the restore over a cart the shopper has since\n * edited. History is replaced, not pushed — the token was never a page.\n */\nexport function stripCartToken(): void {\n try {\n const url = new URL(window.location.href);\n if (!url.searchParams.has('cart')) return;\n url.searchParams.delete('cart');\n window.history.replaceState({}, '', url.toString());\n } catch {\n /* no history API — leaving the param is harmless */\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { getTokens } from './RDZDD5UW.js';
1
+ import { getTokens } from './NQLBWDE3.js';
2
2
  import { getConfig } from './2IFPDU4D.js';
3
3
 
4
4
  // src/api/funnel.ts
@@ -138,5 +138,5 @@ function stripResumeToken() {
138
138
  }
139
139
 
140
140
  export { adoptFunnelSessionId, captureAuthHeader, fetchFunnelConfig, fetchResumedDraft, funnelSessionId, peekFunnelSessionId, postFunnelEvent, readResumeToken, resetFunnelConfigCache, saveFunnelDraft, stripResumeToken };
141
- //# sourceMappingURL=6V7RVUXX.js.map
142
- //# sourceMappingURL=6V7RVUXX.js.map
141
+ //# sourceMappingURL=COIUOQOE.js.map
142
+ //# sourceMappingURL=COIUOQOE.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/api/funnel.ts"],"names":[],"mappings":";;;;AAmBA,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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AAW,OAAO,IAAA,CAAK,SAAA,KAAc,QAAA,GAAW,KAAK,SAAA,GAAY;AAAA,KACnE;AAAA,EACF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAGO,SAAS,eAAA,GAAiC;AAC/C,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,GAAQ,IAAI,eAAA,CAAgB,MAAA,CAAO,SAAS,MAAM,CAAA,CAAE,IAAI,QAAQ,CAAA;AACtE,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":"6V7RVUXX.js","sourcesContent":["import { getConfig } from '../config';\nimport { getTokens } from './client';\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 * The member's access token, when this browser has one.\n *\n * Read raw and never refreshed: these are fire-and-forget telemetry posts, and\n * a token refresh is a real network round-trip on the unload path. An expired\n * token is not a failure either — the sinks take it with `optionalAuth`, so a\n * stale one simply reads as an anonymous visitor, which is what we had before.\n */\nexport function captureAuthHeader(): Record<string, string> {\n try {\n const token = getTokens()?.accessToken;\n return token ? { Authorization: `Bearer ${token}` } : {};\n } catch {\n return {};\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 — nor the bearer token\n * below.)\n *\n * The token identifies a signed-in member to the sink. Without it a member's\n * session is stored anonymously, and the pre-survey email gate — the only\n * other writer of a session's identity — is deliberately never shown to\n * someone already signed in, so their drop-off could never be attributed to\n * them. That is the whole population of a site where the account is created\n * before the questionnaire (savings-program signups, returning members\n * starting a second intake).\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 ...captureAuthHeader(),\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
+ {"version":3,"sources":["../../src/api/funnel.ts"],"names":[],"mappings":";;;;AAmBA,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,GAAA,CAAI,IAAA,EAAK;AAC7B,QAAA,OAAO;AAAA,UACL,SAAA,EAAW,KAAK,SAAA,KAAc,IAAA;AAAA,UAC9B,SAAA,EAAW,KAAK,SAAA,KAAc,IAAA;AAAA,UAC9B,iBAAA,EAAmB,KAAK,iBAAA,KAAsB;AAAA,SAChD;AAAA,MACF,CAAA,CAAA,MAAQ;AACN,QAAA,OAAO,QAAA;AAAA,MACT;AAAA,IACF,CAAA,GAAG;AAAA,EACL;AACA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AS,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":"COIUOQOE.js","sourcesContent":["import { getConfig } from '../config';\nimport { getTokens } from './client';\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 * The member's access token, when this browser has one.\n *\n * Read raw and never refreshed: these are fire-and-forget telemetry posts, and\n * a token refresh is a real network round-trip on the unload path. An expired\n * token is not a failure either — the sinks take it with `optionalAuth`, so a\n * stale one simply reads as an anonymous visitor, which is what we had before.\n */\nexport function captureAuthHeader(): Record<string, string> {\n try {\n const token = getTokens()?.accessToken;\n return token ? { Authorization: `Bearer ${token}` } : {};\n } catch {\n return {};\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 — nor the bearer token\n * below.)\n *\n * The token identifies a signed-in member to the sink. Without it a member's\n * session is stored anonymously, and the pre-survey email gate — the only\n * other writer of a session's identity — is deliberately never shown to\n * someone already signed in, so their drop-off could never be attributed to\n * them. That is the whole population of a site where the account is created\n * before the questionnaire (savings-program signups, returning members\n * starting a second intake).\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 ...captureAuthHeader(),\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,6 +1,6 @@
1
- import { fetchFunnelConfig, postFunnelEvent, readResumeToken, fetchResumedDraft, stripResumeToken, adoptFunnelSessionId, saveFunnelDraft } from './6V7RVUXX.js';
2
- import { cart_default, medication_default, auth_default, affiliateAuth_default } from './A6FJGQIS.js';
3
- import { newIdempotencyKey, apexApi, usersApi, addressesApi, catalogApi, paymentsApi, subscriptionsApi, membersApi, supportApi, productsApi, affiliatePortalApi, adminApi, adminCatalogApi, adminProductPharmaciesApi, ApiError, ordersApi, adminCatalogConversionApi, messagesApi, authApi, adminProductStrengthMatchesApi } from './RDZDD5UW.js';
1
+ import { fetchFunnelConfig, postFunnelEvent, readResumeToken, fetchResumedDraft, stripResumeToken, adoptFunnelSessionId, saveFunnelDraft } from './COIUOQOE.js';
2
+ import { cart_default, medication_default, auth_default, affiliateAuth_default } from './3VBKKYOR.js';
3
+ import { newIdempotencyKey, apexApi, usersApi, addressesApi, catalogApi, paymentsApi, subscriptionsApi, membersApi, supportApi, productsApi, affiliatePortalApi, adminApi, adminCatalogApi, adminProductPharmaciesApi, ApiError, ordersApi, adminCatalogConversionApi, messagesApi, authApi, adminProductStrengthMatchesApi } from './NQLBWDE3.js';
4
4
  import { getConfig } from './2IFPDU4D.js';
5
5
  import { createSignal, onMount, createEffect, on, onCleanup, createResource, createMemo } from 'solid-js';
6
6
  import { useSurveyV2Flow as useSurveyV2Flow$1 } from '@apextelemed/survey-solid';
@@ -6276,7 +6276,7 @@ function useAddPharmacy(opts) {
6276
6276
  };
6277
6277
  }
6278
6278
  function wantsStrengthMatches(product, enabled) {
6279
- return enabled && !!product && product.pricingMode !== "flat_fee";
6279
+ return enabled && !!product;
6280
6280
  }
6281
6281
  function matchBody(dosage, doseId, carryPrice) {
6282
6282
  return { dosage, doseId, ...carryPrice === void 0 ? {} : { carryPrice } };
@@ -6284,6 +6284,7 @@ function matchBody(dosage, doseId, carryPrice) {
6284
6284
  var matchValue = (row) => row.doseId ?? "";
6285
6285
  var doseIdOf = (value) => value === "" ? null : value;
6286
6286
  var isLeftForReview = (row) => row.doseId === null;
6287
+ var isFlatFee = (raw) => raw?.flatFee === true;
6287
6288
  function normalizeMatches(raw) {
6288
6289
  return {
6289
6290
  rows: Array.isArray(raw?.rows) ? raw.rows : [],
@@ -6319,6 +6320,7 @@ function classifyStrengthMatchError(err, doseId) {
6319
6320
  }
6320
6321
  function useStrengthMatches(opts) {
6321
6322
  const [status, setStatus] = createSignal("idle");
6323
+ const [flatFee, setFlatFee] = createSignal(false);
6322
6324
  const [rows, setRows] = createSignal([]);
6323
6325
  const [doseOptions, setDoseOptions] = createSignal([]);
6324
6326
  const [pending, setPending] = createSignal(null);
@@ -6340,6 +6342,7 @@ function useStrengthMatches(opts) {
6340
6342
  });
6341
6343
  const adopt = (raw) => {
6342
6344
  const next = normalizeMatches(raw);
6345
+ setFlatFee(isFlatFee(raw));
6343
6346
  setRows(next.rows);
6344
6347
  setDoseOptions(next.doseOptions);
6345
6348
  const p = pending();
@@ -6352,6 +6355,7 @@ function useStrengthMatches(opts) {
6352
6355
  const seq = ++loadSeq;
6353
6356
  const product = opts.product();
6354
6357
  if (!wantsStrengthMatches(product, opts.enabled())) {
6358
+ setFlatFee(false);
6355
6359
  setRows([]);
6356
6360
  setDoseOptions([]);
6357
6361
  setStatus("idle");
@@ -6386,6 +6390,7 @@ function useStrengthMatches(opts) {
6386
6390
  on(key, () => {
6387
6391
  generation++;
6388
6392
  loadSeq++;
6393
+ setFlatFee(false);
6389
6394
  setRows([]);
6390
6395
  setDoseOptions([]);
6391
6396
  setPending(null);
@@ -6444,6 +6449,7 @@ function useStrengthMatches(opts) {
6444
6449
  };
6445
6450
  return {
6446
6451
  status,
6452
+ flatFee,
6447
6453
  rows,
6448
6454
  doseOptions,
6449
6455
  pending,
@@ -6479,5 +6485,5 @@ function useStrengthMatches(opts) {
6479
6485
  }
6480
6486
 
6481
6487
  export { ACCOUNT_SOURCE_LABEL, DEFAULT_COLOR_PALETTE, LIFECYCLE_BUCKETS, LIFECYCLE_LABEL, LIFECYCLE_TONE, LIVE_SUBSCRIPTION_STATUSES, MATCH_DEPENDENT_WARNINGS, MATCH_HOW_LABEL, ORPHAN_REASON, READINESS_LABEL, SOURCE_FIELD_NOTE, SUPPORT_CATEGORIES, TERMINAL_SUBSCRIPTION_STATUSES, US_STATES, US_STATE_OPTIONS, accountSource, addCatalogItemAsProduct, applyPriceDrafts, availableStateOptions, availableStates, bestOfferDiscount, buildFulfillmentRows, buildMatrixView, buildRefillView, buildSaveBody, buildStrengthRows, buildTimeline, buildTrackerView, buildTrackingUrl, canLeaveUnmatched, canOfferConversion, captureFunnelEmail, catalogUnavailableMessage, categoryColor, categoryLabel, classifyAddPharmacyError, classifyCatalogError, classifyConversionError, classifyStrengthMatchError, compareStrengths, createCatalogProduct, createFunnelTelemetry, decisionFromDetails, deriveAttention, deriveCatalogAvailabilityDecision, deriveJourney, describeConversion, doseIdOf, emailGateAnswered, explainFinding, findStoredDosePrice, firstAddressError, flaggedSubscribers, fmtDay, formatCalendarDate, formatCardNumber, formatConversationTime, formatCvv, formatEventDate, formatExpiry, formatMessageTime, formatRelativeTime, formatStageDate, groupDrugsByPharmacy, hasBlockers, hasConversion, hasErrors, hasStateRestrictions, initialMatches, intakeEvidence, invalidDraftKeys, isCatalogItemId, isCssColorValue, isImageAttachment, isLeftForReview, isLive, isQuestionVisible, isReconcilable, lifecycleReason, liveDoses, lowestPrice, lowestSalePrice, markEmailGateAnswered, matchBody, matchKey, matchProblem, matchValue, matchesComplete, missingPrices, moveInOrder, needsReview, normalizeMatches, normalizeState, normalizeStates, offerBeatsPromo, offerDurationText, offerSummaryText, orphanKey, parseMoney, pharmacyIsOnProduct, pharmacyLabel, primarySubscription, readinessStatus, reconcileCartAgainstCatalog, reconcileCartLines, redeemResumeLink, removeStoredDosePrice, resetResumeRedemption, resolveCategoryColor, resolveStrengthPrices, resolveSurveyV2DrugIntent, salePriceForBase, skuBindingModeFor, sourceKey, sourceLabel, stateAvailabilityNote, strengthsChanged, subscribeToSupportTopic, toChoices, toTrackerRequest, uploadPrescriptionPhoto, upsertDosePrice, useAddPharmacy, useAddressPair, useAffiliateConversions, useAffiliateDownline, useAffiliateLinks, useAffiliateStats, useCardTokenizer, useCartCheckoutFlow, useCartReconcile, useCatalog, useCatalogAvailability, useCatalogConversion, useCheckoutFlow, useDashboardData, useMedicationSelect, useMemberPortalData, useMessagesThread, useProductCatalogEditor, useProductDetail, useRegisterFlow, useSignupFlow, useStrengthMatches, useSubscribeFlow, useSurveyFlow, useSurveyV2Flow, useUpdatePaymentMethodFlow, validateAddress, visibleWarnings, wantsStrengthMatches };
6482
- //# sourceMappingURL=BYDMO5RM.js.map
6483
- //# sourceMappingURL=BYDMO5RM.js.map
6488
+ //# sourceMappingURL=DETBZTGQ.js.map
6489
+ //# sourceMappingURL=DETBZTGQ.js.map