@quantaroute/checkout 1.7.4 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -297,7 +297,7 @@ return/ipad|tablet/.test(r)?"tablet":/mobile|iphone|android/.test(r)?"mobile":"d
297
297
  return{deviceType:Ge(e),platform:"web",userAgent:e}}const Ye=["utm_source","utm_medium","utm_campaign"]
298
298
  function Xe(e){try{const r=new URL(e??("undefined"!=typeof window?window.location.href:"")),n={}
299
299
  for(const e of Ye){const a=r.searchParams.get(e)
300
- a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}function er(e){return Boolean(e.utm_source||e.utm_medium||e.utm_campaign)}const rr=({address:n,onEditAddress:a})=>e("div",{className:"qr-success",children:[r("div",{className:"qr-success__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-success__title",children:"Address Saved!"}),r("p",{className:"qr-success__address",children:n.formattedAddress}),r("div",{className:"qr-success__meta",children:e("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r("span",{className:"qr-digipin-badge__code",children:n.digipin})]})}),r("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:a,children:"Change Address"})]}),nr=({apiKey:l,apiBaseUrl:d="https://api.quantaroute.com",onComplete:u,onError:h,defaultLat:p,defaultLng:m,theme:y="light",className:f="",style:b,mapHeight:v="min(52dvh, 420px)",title:_="Add Delivery Address",mobilePresentation:g="auto",mobileStepLabels:q,indiaBoundaryUrl:w,enableSearch:N=!0,mapStyle:k,mapTheme:C,embedMode:x,mapsKey:E,enablePhoneAuth:S=!1,merchantId:L="",supabaseFunctionBaseUrl:T="",brandColor:I,logoUrl:P,headerBanner:B,onCheckoutEvent:A,enableCod:O=!1,enableServiceabilityCheck:M=!1,enableAddressIntelligence:D=!1,showIndiaPostDeliveryWarning:$=!1,serviceabilityBlockCheckout:R,codCartTotalPaise:U,codSessionToken:F="",enableEmailAuth:j=!1,variant:W,utmParams:z,enablePayment:V=!1,paymentAmountPaise:J,onPaymentComplete:H,enablePrepaidNudge:K=!1,prepaidNudgeCopy:G,prepaidNudgeCtaUrl:Q,registerController:Z,orderConfirmationUrl:Y})=>{var X
300
+ a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}function er(e){return Boolean(e.utm_source||e.utm_medium||e.utm_campaign)}const rr=({address:n,onEditAddress:a})=>e("div",{className:"qr-success",children:[r("div",{className:"qr-success__icon","aria-hidden":"true",children:e("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r("h3",{className:"qr-success__title",children:"Address Saved!"}),r("p",{className:"qr-success__address",children:n.formattedAddress}),r("div",{className:"qr-success__meta",children:e("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r("span",{className:"qr-digipin-badge__code",children:n.digipin})]})}),r("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:a,children:"Change Address"})]}),nr=({apiKey:l,apiBaseUrl:d="https://api.quantaroute.com",onComplete:u,onError:h,defaultLat:p,defaultLng:m,theme:y="light",className:f="",style:b,mapHeight:v="min(52dvh, 420px)",title:_="Add Delivery Address",mobilePresentation:g="auto",mobileStepLabels:q,indiaBoundaryUrl:w,enableSearch:N=!0,mapStyle:k,mapTheme:C,embedMode:x,mapsKey:E,enablePhoneAuth:S=!1,merchantId:L="",supabaseFunctionBaseUrl:T="https://ikfiewesidedxozotmrl.supabase.co/functions/v1",brandColor:I,logoUrl:P,headerBanner:B,onCheckoutEvent:A,enableCod:O=!1,enableServiceabilityCheck:M=!1,enableAddressIntelligence:D=!1,showIndiaPostDeliveryWarning:$=!1,serviceabilityBlockCheckout:R,codCartTotalPaise:U,codSessionToken:F="",enableEmailAuth:j=!1,variant:W,utmParams:z,enablePayment:V=!1,paymentAmountPaise:J,onPaymentComplete:H,enablePrepaidNudge:K=!1,prepaidNudgeCopy:G,prepaidNudgeCtaUrl:Q,registerController:Z,orderConfirmationUrl:Y})=>{var X
301
301
  const ee=S?"phone":j?"email":"none",ne="phone"===ee?"phone":"email"===ee?"email":"map",ae=Boolean(V&&J&&T),[te,ie]=t(ne),[le,se]=t(null),[he,pe]=t(null),[fe,ge]=t(null),[qe,we]=t(""),[Ne,ke]=t(!1),[Ce,xe]=t(!1),[Ee,Se]=t(null),[Le,Pe]=t(null),[Ae,Oe]=t(null),[Me,De]=t(null),[$e,Re]=t("form"),We=o(te),ze=c(()=>z??Xe(),[z]),He=c(()=>Ze(),[]),Ge=c(()=>({utm_source:ze.utm_source,utm_medium:ze.utm_medium,utm_campaign:ze.utm_campaign,device_type:He.deviceType,platform:He.platform,user_agent:He.userAgent,experiment_variant:W}),[ze,He,W]),Qe=c(()=>({functionBaseUrl:T,merchantId:L}),[T,L]),Ye=(null==fe?void 0:fe.sessionToken)||F
302
302
  s(()=>{We.current=te},[te])
303
303
  const er=i(e=>{const r={...e,sessionId:e.sessionId??(null==fe?void 0:fe.sessionId),buyerId:e.buyerId??(null==fe?void 0:fe.buyerId),authChannel:e.authChannel??("phone"===ee?"phone":"email"===ee?"email":"none"),deviceType:e.deviceType??He.deviceType,platform:e.platform??He.platform,userAgent:e.userAgent??He.userAgent,experimentVariant:e.experimentVariant??W,timestamp:(new Date).toISOString()}
@@ -330,7 +330,7 @@ return-1===t?0:t}(te,ee,ae),cr=function(e,r){return"none"===e?r?3:2:r?6:5}(ee,ae
330
330
  return e("div",{className:`qr-checkout qr-checkout--${y} qr-checkout--mobile-${g} ${f}`,style:tr,"data-testid":"quantaroute-checkout",children:["done"!==te&&e(n,{children:[e("div",{className:"qr-header",children:[e("div",{className:"qr-header__brand",children:[P?r("img",{src:P,alt:"",className:"qr-header__logo-img",width:28,height:28,decoding:"async"}):e("svg",{className:"qr-header__logo","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r("path",{d:"M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"}),r("circle",{cx:"12",cy:"10",r:"3"})]}),r("span",{className:"qr-header__title",children:_})]}),r("div",{className:"qr-header__progress-desktop",children:(()=>{const n=Array.from({length:cr+1},(e,r)=>r)
331
331
  return r("div",{className:"qr-progress",role:"progressbar","aria-valuenow":dr+1,"aria-valuemin":1,"aria-valuemax":cr+1,"aria-label":`Step ${dr+1} of ${cr+1}`,children:n.map(n=>e(a.Fragment,{children:[r("div",{className:"qr-progress__dot"+(dr>=n?" qr-progress__dot--active":"")}),n<cr&&r("div",{className:"qr-progress__line"+(dr>n?" qr-progress__line--active":"")})]},n))})})()})]}),r("div",{className:"qr-header__progress-mobile",children:r("div",{className:"qr-mobile-stepper",role:"list","aria-label":"Checkout progress",children:pr.map((n,t)=>e(a.Fragment,{children:[e("div",{className:`qr-mobile-stepper__item qr-mobile-stepper__item--${n.status}`,role:"listitem","aria-current":"active"===n.status?"step":void 0,children:[r("span",{className:"qr-mobile-stepper__mark","aria-hidden":"true",children:"complete"===n.status?"✓":t+1}),r("span",{className:"qr-mobile-stepper__label",children:n.label})]}),t<pr.length-1?r("span",{className:"qr-mobile-stepper__rail","aria-hidden":"true"}):null]},n.id))})}),B?r("div",{className:"qr-header-banner",role:"region","aria-label":"Merchant message",children:B}):null,Ee?e("div",{className:"qr-offer-banner",role:"region","aria-label":"Special offer",children:[Ee.banner_copy,Ee.banner_cta_url?e(n,{children:[" ",r("a",{href:Ee.banner_cta_url,target:"_blank",rel:"noopener noreferrer",children:"Learn more"})]}):null]}):null]}),"email"===te&&j&&r(Je,{onOtpSent:(e,r)=>{we(e),ke(Boolean(null==r?void 0:r.reused)),er({type:"email_otp_sent",step:"email-otp",mobile:e}),ie("email-otp")},onSkip:ir,functionBaseUrl:T,merchantId:L}),"email-otp"===te&&j&&qe&&r(Ke,{email:qe,codeReused:Ne,onVerified:(e,r,n)=>{ge({mobile:qe,sessionToken:e,sessionId:n??"",buyerId:r}),er({type:"email_verified",step:"saved",buyerId:r,sessionId:n}),ie("saved")},onBack:sr,functionBaseUrl:T,merchantId:L,sessionContext:Ge}),"phone"===te&&S&&r(Ie,{onOtpSent:e=>{ge(r=>({mobile:e,sessionToken:"",sessionId:"",buyerId:(null==r?void 0:r.buyerId)??""})),er({type:"otp_sent",step:"otp",mobile:e}),ie("otp")},onSkip:ir,functionBaseUrl:T,merchantId:L}),"otp"===te&&fe&&r(Be,{mobile:fe.mobile,onVerified:(e,r,n)=>{ge({mobile:(null==fe?void 0:fe.mobile)??"",sessionToken:e,sessionId:n??"",buyerId:r}),er({type:"phone_verified",step:"saved",buyerId:r,sessionId:n}),ie("saved")},onBack:sr,functionBaseUrl:T,merchantId:L,sessionContext:Ge}),"saved"===te&&(null==fe?void 0:fe.sessionToken)&&r(Ue,{sessionToken:fe.sessionToken,functionBaseUrl:T,merchantId:L,onSelectAddress:async e=>{if(null==fe?void 0:fe.sessionToken){try{await de(Qe,fe.sessionToken,e.id)}catch(e){return void(null==h||h(e instanceof Error?e:new Error("Failed to select address.")))}if(!e.digipin)return De(e),er({type:"saved_address_selected",step:"verify-address",buyerId:fe.buyerId}),void ie("verify-address")
332
332
  er({type:"saved_address_selected",step:ae?"payment":"done",buyerId:fe.buyerId,digipin:e.digipin}),await lr(function(e){var r
333
- return{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,division:"",locality:e.locality,pincode:e.pincode,delivery:e.delivery_status,country:"India",flatNumber:e.flat_number,floorNumber:e.floor_number,buildingName:e.building_name,streetName:e.street_name,formattedAddress:[e.flat_number,e.building_name,e.street_name,e.locality,e.district,e.state,e.pincode].filter(Boolean).join(", "),label:"work"===e.label||"other"===e.label?e.label:"home",labelText:(null==(r=e.label_text)?void 0:r.trim())||void 0,addressId:e.id}}(e),{skipCreate:!0,paymentBackStep:"saved"})}},onAddNew:()=>{De(null),se(null),ie("map")}}),"verify-address"===te&&Me&&e(n,{children:[r("div",{className:"qr-order-lock-banner",role:"status",children:"Confirm your delivery pin to complete this order"}),r(re,{onLocationConfirm:or,defaultLat:Me.lat??p,defaultLng:Me.lng??m,mapHeight:v,theme:y,indiaBoundaryUrl:w,enableSearch:N,apiKey:l,apiBaseUrl:d,brandColor:I,mapStyle:k,mapTheme:C,embedMode:x,mapsKey:E})]}),"map"===te&&r(re,{onLocationConfirm:or,defaultLat:p,defaultLng:m,mapHeight:v,theme:y,indiaBoundaryUrl:w,enableSearch:N,apiKey:l,apiBaseUrl:d,brandColor:I,mapStyle:k,mapTheme:C,embedMode:x,mapsKey:E}),"form"===te&&le&&r(Te,{digipin:le.digipin,lat:le.lat,lng:le.lng,apiKey:l,apiBaseUrl:d,onAddressComplete:async e=>{if(Me&&(null==fe?void 0:fe.sessionToken))try{await ce(Qe,fe.sessionToken,Me.id,{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,locality:e.locality,pincode:e.pincode,delivery_status:e.delivery,flat_number:e.flatNumber,floor_number:e.floorNumber,building_name:e.buildingName,street_name:e.streetName})
333
+ return{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,division:"",locality:e.locality,pincode:e.pincode,delivery:e.delivery_status,country:"India",flatNumber:e.flat_number,floorNumber:e.floor_number,buildingName:e.building_name,streetName:e.street_name,formattedAddress:[e.flat_number,e.building_name,e.street_name,e.locality,e.district,e.state,e.pincode].filter(Boolean).join(", "),label:"work"===e.label||"other"===e.label?e.label:"home",labelText:(null==(r=e.label_text)?void 0:r.trim())||void 0,addressId:e.id}}(e),{skipCreate:!0,paymentBackStep:"saved"})}},onAddNew:()=>{De(null),se(null),ie("map")}}),"verify-address"===te&&Me&&e(n,{children:[r("div",{className:"qr-order-lock-banner",role:"status",children:"Confirm your delivery pin to complete this order"}),r(re,{onLocationConfirm:or,defaultLat:Me.lat??p,defaultLng:Me.lng??m,mapHeight:v,theme:y,indiaBoundaryUrl:w,enableSearch:N,apiKey:l,apiBaseUrl:d,brandColor:I,mapStyle:k,mapTheme:C,embedMode:x,mapsKey:E??l})]}),"map"===te&&r(re,{onLocationConfirm:or,defaultLat:p,defaultLng:m,mapHeight:v,theme:y,indiaBoundaryUrl:w,enableSearch:N,apiKey:l,apiBaseUrl:d,brandColor:I,mapStyle:k,mapTheme:C,embedMode:x,mapsKey:E??l}),"form"===te&&le&&r(Te,{digipin:le.digipin,lat:le.lat,lng:le.lng,apiKey:l,apiBaseUrl:d,onAddressComplete:async e=>{if(Me&&(null==fe?void 0:fe.sessionToken))try{await ce(Qe,fe.sessionToken,Me.id,{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,locality:e.locality,pincode:e.pincode,delivery_status:e.delivery,flat_number:e.flatNumber,floor_number:e.floorNumber,building_name:e.buildingName,street_name:e.streetName})
334
334
  const r={...e,addressId:Me.id}
335
335
  De(null),await lr(r,{skipCreate:!0})}catch(e){null==h||h(e instanceof Error?e:new Error("Failed to verify delivery pin."))}else await lr(e)},onBack:sr,onError:h,theme:y,checkoutConfig:Qe,serviceabilitySessionToken:Ye,enableServiceabilityCheck:M,showIndiaPostDeliveryWarning:$,serviceabilityBlockCheckout:R,initialValues:Me?{flatNumber:Me.flat_number,floorNumber:Me.floor_number,buildingName:Me.building_name,streetName:Me.street_name,locality:Me.locality,label:"work"===Me.label||"other"===Me.label?Me.label:"home",labelText:(null==(X=Me.label_text)?void 0:X.trim())||void 0}:void 0,submitLabel:Me?"Confirm delivery pin":void 0}),"payment"===te&&ae&&Ye&&J&&r(Ve,{checkoutConfig:Qe,sessionToken:Ye,sessionId:null==fe?void 0:fe.sessionId,amountPaise:J,enableCod:O,codAllowed:Ce&&!(null==Le?void 0:Le.interventions.includes("hide_cod")),addressRisk:Le,theme:y,onComplete:({paymentMethod:e,razorpayOrderId:r,razorpayPaymentId:n})=>{Oe(e),er({type:"payment_method_selected",step:"done",paymentMethod:e}),ie("done"),he&&u(he),null==H||H({paymentMethod:e,sessionId:null==fe?void 0:fe.sessionId,razorpayOrderId:r,razorpayPaymentId:n})},onBack:sr,onEvent:(e,r)=>er({type:e,step:"payment",paymentMethod:r,buyerId:null==fe?void 0:fe.buyerId}),orderConfirmationUrl:Y}),"done"===te&&he&&e(n,{children:[r(rr,{address:he,onEditAddress:()=>{const e=null!==Ae,r=!e&&(null==fe?void 0:fe.sessionToken)?"saved":ne
336
336
  er({type:"widget_reset",step:r}),e&&(ge(null),Se(null)),ie(r),se(null),pe(null),Pe(null),De(null),Oe(null)}}),Ae?e("p",{className:"qr-cod-banner__text qr-cod-banner__text--ok",style:{textAlign:"center",margin:"8px 16px"},children:["Paid via ","cod"===Ae?"Cash on Delivery":"online payment"]}):null,O&&L&&T&&Ye?e(n,{children:[r(Fe,{checkoutConfig:Qe,sessionToken:Ye,pincode:he.pincode,cartTotalPaise:U??J,theme:y,onCodAllowedChange:xe}),K&&Ce?r(je,{copy:G??"Save more when you pay online — faster delivery & exclusive offers.",ctaUrl:Q,theme:y}):null]}):null]}),e("div",{className:"qr-footer",children:[r("span",{children:"Powered by"}),r("a",{href:"https://quantaroute.com",target:"_blank",rel:"noopener noreferrer",className:"qr-footer__link",children:"QuantaRoute"}),r("span",{className:"qr-footer__flag","aria-label":"Made in India",children:"🇮🇳"})]})]})}
@@ -295,7 +295,7 @@ return/ipad|tablet/.test(r)?"tablet":/mobile|iphone|android/.test(r)?"mobile":"d
295
295
  return{deviceType:Oe(e),platform:"web",userAgent:e}}const $e=["utm_source","utm_medium","utm_campaign"]
296
296
  function De(e){try{const r=new URL(e??("undefined"!=typeof window?window.location.href:"")),n={}
297
297
  for(const e of $e){const a=r.searchParams.get(e)
298
- a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}const Re=({address:e,onEditAddress:n})=>r.jsxs("div",{className:"qr-success",children:[r.jsx("div",{className:"qr-success__icon","aria-hidden":"true",children:r.jsxs("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r.jsx("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r.jsx("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r.jsx("h3",{className:"qr-success__title",children:"Address Saved!"}),r.jsx("p",{className:"qr-success__address",children:e.formattedAddress}),r.jsx("div",{className:"qr-success__meta",children:r.jsxs("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r.jsx("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r.jsx("span",{className:"qr-digipin-badge__code",children:e.digipin})]})}),r.jsx("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:n,children:"Change Address"})]}),Ue=({apiKey:e,apiBaseUrl:a="https://api.quantaroute.com",onComplete:t,onError:i,defaultLat:o,defaultLng:l,theme:s="light",className:d="",style:c,mapHeight:u="min(52dvh, 420px)",title:h="Add Delivery Address",mobilePresentation:p="auto",mobileStepLabels:m,indiaBoundaryUrl:y,enableSearch:f=!0,mapStyle:b,mapTheme:v,embedMode:_,mapsKey:g,enablePhoneAuth:q=!1,merchantId:w="",supabaseFunctionBaseUrl:N="",brandColor:k,logoUrl:C,headerBanner:x,onCheckoutEvent:E,enableCod:S=!1,enableServiceabilityCheck:L=!1,enableAddressIntelligence:T=!1,showIndiaPostDeliveryWarning:P=!1,serviceabilityBlockCheckout:I,codCartTotalPaise:B,codSessionToken:A="",enableEmailAuth:O=!1,variant:M,utmParams:$,enablePayment:D=!1,paymentAmountPaise:R,onPaymentComplete:U,enablePrepaidNudge:F=!1,prepaidNudgeCopy:W,prepaidNudgeCtaUrl:z,registerController:V,orderConfirmationUrl:J})=>{var K
298
+ a&&(n[e]=a.slice(0,256))}return n}catch{return{}}}const Re=({address:e,onEditAddress:n})=>r.jsxs("div",{className:"qr-success",children:[r.jsx("div",{className:"qr-success__icon","aria-hidden":"true",children:r.jsxs("svg",{viewBox:"0 0 52 52",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[r.jsx("circle",{cx:"26",cy:"26",r:"26",fill:"var(--qr-success, #10b981)",opacity:"0.12"}),r.jsx("circle",{cx:"26",cy:"26",r:"20",fill:"var(--qr-success, #10b981)"}),r.jsx("path",{d:"M15 26l8 8 14-16",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round"})]})}),r.jsx("h3",{className:"qr-success__title",children:"Address Saved!"}),r.jsx("p",{className:"qr-success__address",children:e.formattedAddress}),r.jsx("div",{className:"qr-success__meta",children:r.jsxs("span",{className:"qr-digipin-badge qr-digipin-badge--inline",children:[r.jsx("span",{className:"qr-digipin-badge__label",children:"DigiPin"}),r.jsx("span",{className:"qr-digipin-badge__code",children:e.digipin})]})}),r.jsx("button",{type:"button",className:"qr-btn qr-btn--ghost qr-btn--sm",onClick:n,children:"Change Address"})]}),Ue=({apiKey:e,apiBaseUrl:a="https://api.quantaroute.com",onComplete:t,onError:i,defaultLat:o,defaultLng:l,theme:s="light",className:d="",style:c,mapHeight:u="min(52dvh, 420px)",title:h="Add Delivery Address",mobilePresentation:p="auto",mobileStepLabels:m,indiaBoundaryUrl:y,enableSearch:f=!0,mapStyle:b,mapTheme:v,embedMode:_,mapsKey:g,enablePhoneAuth:q=!1,merchantId:w="",supabaseFunctionBaseUrl:N="https://ikfiewesidedxozotmrl.supabase.co/functions/v1",brandColor:k,logoUrl:C,headerBanner:x,onCheckoutEvent:E,enableCod:S=!1,enableServiceabilityCheck:L=!1,enableAddressIntelligence:T=!1,showIndiaPostDeliveryWarning:P=!1,serviceabilityBlockCheckout:I,codCartTotalPaise:B,codSessionToken:A="",enableEmailAuth:O=!1,variant:M,utmParams:$,enablePayment:D=!1,paymentAmountPaise:R,onPaymentComplete:U,enablePrepaidNudge:F=!1,prepaidNudgeCopy:W,prepaidNudgeCtaUrl:z,registerController:V,orderConfirmationUrl:J})=>{var K
299
299
  const G=q?"phone":O?"email":"none",X="phone"===G?"phone":"email"===G?"email":"map",ee=Boolean(D&&R&&N),[ae,le]=n.useState(X),[se,de]=n.useState(null),[ce,ue]=n.useState(null),[he,pe]=n.useState(null),[me,ye]=n.useState(""),[ve,ge]=n.useState(!1),[qe,we]=n.useState(!1),[Ne,ke]=n.useState(null),[Ce,Le]=n.useState(null),[Te,Be]=n.useState(null),[Oe,$e]=n.useState(null),[Ue,Fe]=n.useState("form"),je=n.useRef(ae),We=n.useMemo(()=>$??De(),[$]),ze=n.useMemo(()=>Me(),[]),Ve=n.useMemo(()=>({utm_source:We.utm_source,utm_medium:We.utm_medium,utm_campaign:We.utm_campaign,device_type:ze.deviceType,platform:ze.platform,user_agent:ze.userAgent,experiment_variant:M}),[We,ze,M]),Je=n.useMemo(()=>({functionBaseUrl:N,merchantId:w}),[N,w]),He=(null==he?void 0:he.sessionToken)||A
300
300
  n.useEffect(()=>{je.current=ae},[ae])
301
301
  const Ke=n.useCallback(e=>{const r={...e,sessionId:e.sessionId??(null==he?void 0:he.sessionId),buyerId:e.buyerId??(null==he?void 0:he.buyerId),authChannel:e.authChannel??("phone"===G?"phone":"email"===G?"email":"none"),deviceType:e.deviceType??ze.deviceType,platform:e.platform??ze.platform,userAgent:e.userAgent??ze.userAgent,experimentVariant:e.experimentVariant??M,timestamp:(new Date).toISOString()}
@@ -328,7 +328,7 @@ return-1===t?0:t}(ae,G,ee),ar=function(e,r){return"none"===e?r?3:2:r?6:5}(G,ee),
328
328
  return r.jsxs("div",{className:`qr-checkout qr-checkout--${s} qr-checkout--mobile-${p} ${d}`,style:Ze,"data-testid":"quantaroute-checkout",children:["done"!==ae&&r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"qr-header",children:[r.jsxs("div",{className:"qr-header__brand",children:[C?r.jsx("img",{src:C,alt:"",className:"qr-header__logo-img",width:28,height:28,decoding:"async"}):r.jsxs("svg",{className:"qr-header__logo","aria-hidden":"true",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M21 10c0 7-9 13-9 13S3 17 3 10a9 9 0 0118 0z"}),r.jsx("circle",{cx:"12",cy:"10",r:"3"})]}),r.jsx("span",{className:"qr-header__title",children:h})]}),r.jsx("div",{className:"qr-header__progress-desktop",children:(()=>{const e=Array.from({length:ar+1},(e,r)=>r)
329
329
  return r.jsx("div",{className:"qr-progress",role:"progressbar","aria-valuenow":nr+1,"aria-valuemin":1,"aria-valuemax":ar+1,"aria-label":`Step ${nr+1} of ${ar+1}`,children:e.map(e=>r.jsxs(n.Fragment,{children:[r.jsx("div",{className:"qr-progress__dot"+(nr>=e?" qr-progress__dot--active":"")}),e<ar&&r.jsx("div",{className:"qr-progress__line"+(nr>e?" qr-progress__line--active":"")})]},e))})})()})]}),r.jsx("div",{className:"qr-header__progress-mobile",children:r.jsx("div",{className:"qr-mobile-stepper",role:"list","aria-label":"Checkout progress",children:or.map((e,a)=>r.jsxs(n.Fragment,{children:[r.jsxs("div",{className:`qr-mobile-stepper__item qr-mobile-stepper__item--${e.status}`,role:"listitem","aria-current":"active"===e.status?"step":void 0,children:[r.jsx("span",{className:"qr-mobile-stepper__mark","aria-hidden":"true",children:"complete"===e.status?"✓":a+1}),r.jsx("span",{className:"qr-mobile-stepper__label",children:e.label})]}),a<or.length-1?r.jsx("span",{className:"qr-mobile-stepper__rail","aria-hidden":"true"}):null]},e.id))})}),x?r.jsx("div",{className:"qr-header-banner",role:"region","aria-label":"Merchant message",children:x}):null,Ne?r.jsxs("div",{className:"qr-offer-banner",role:"region","aria-label":"Special offer",children:[Ne.banner_copy,Ne.banner_cta_url?r.jsxs(r.Fragment,{children:[" ",r.jsx("a",{href:Ne.banner_cta_url,target:"_blank",rel:"noopener noreferrer",children:"Learn more"})]}):null]}):null]}),"email"===ae&&O&&r.jsx(Ie,{onOtpSent:(e,r)=>{ye(e),ge(Boolean(null==r?void 0:r.reused)),Ke({type:"email_otp_sent",step:"email-otp",mobile:e}),le("email-otp")},onSkip:Ye,functionBaseUrl:N,merchantId:w}),"email-otp"===ae&&O&&me&&r.jsx(Ae,{email:me,codeReused:ve,onVerified:(e,r,n)=>{pe({mobile:me,sessionToken:e,sessionId:n??"",buyerId:r}),Ke({type:"email_verified",step:"saved",buyerId:r,sessionId:n}),le("saved")},onBack:rr,functionBaseUrl:N,merchantId:w,sessionContext:Ve}),"phone"===ae&&q&&r.jsx(be,{onOtpSent:e=>{pe(r=>({mobile:e,sessionToken:"",sessionId:"",buyerId:(null==r?void 0:r.buyerId)??""})),Ke({type:"otp_sent",step:"otp",mobile:e}),le("otp")},onSkip:Ye,functionBaseUrl:N,merchantId:w}),"otp"===ae&&he&&r.jsx(_e,{mobile:he.mobile,onVerified:(e,r,n)=>{pe({mobile:(null==he?void 0:he.mobile)??"",sessionToken:e,sessionId:n??"",buyerId:r}),Ke({type:"phone_verified",step:"saved",buyerId:r,sessionId:n}),le("saved")},onBack:rr,functionBaseUrl:N,merchantId:w,sessionContext:Ve}),"saved"===ae&&(null==he?void 0:he.sessionToken)&&r.jsx(xe,{sessionToken:he.sessionToken,functionBaseUrl:N,merchantId:w,onSelectAddress:async e=>{if(null==he?void 0:he.sessionToken){try{await Q(Je,he.sessionToken,e.id)}catch(e){return void(null==i||i(e instanceof Error?e:new Error("Failed to select address.")))}if(!e.digipin)return $e(e),Ke({type:"saved_address_selected",step:"verify-address",buyerId:he.buyerId}),void le("verify-address")
330
330
  Ke({type:"saved_address_selected",step:ee?"payment":"done",buyerId:he.buyerId,digipin:e.digipin}),await er(function(e){var r
331
- return{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,division:"",locality:e.locality,pincode:e.pincode,delivery:e.delivery_status,country:"India",flatNumber:e.flat_number,floorNumber:e.floor_number,buildingName:e.building_name,streetName:e.street_name,formattedAddress:[e.flat_number,e.building_name,e.street_name,e.locality,e.district,e.state,e.pincode].filter(Boolean).join(", "),label:"work"===e.label||"other"===e.label?e.label:"home",labelText:(null==(r=e.label_text)?void 0:r.trim())||void 0,addressId:e.id}}(e),{skipCreate:!0,paymentBackStep:"saved"})}},onAddNew:()=>{$e(null),de(null),le("map")}}),"verify-address"===ae&&Oe&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"qr-order-lock-banner",role:"status",children:"Confirm your delivery pin to complete this order"}),r.jsx(j,{onLocationConfirm:Xe,defaultLat:Oe.lat??o,defaultLng:Oe.lng??l,mapHeight:u,theme:s,indiaBoundaryUrl:y,enableSearch:f,apiKey:e,apiBaseUrl:a,brandColor:k,mapStyle:b,mapTheme:v,embedMode:_,mapsKey:g})]}),"map"===ae&&r.jsx(j,{onLocationConfirm:Xe,defaultLat:o,defaultLng:l,mapHeight:u,theme:s,indiaBoundaryUrl:y,enableSearch:f,apiKey:e,apiBaseUrl:a,brandColor:k,mapStyle:b,mapTheme:v,embedMode:_,mapsKey:g}),"form"===ae&&se&&r.jsx(fe,{digipin:se.digipin,lat:se.lat,lng:se.lng,apiKey:e,apiBaseUrl:a,onAddressComplete:async e=>{if(Oe&&(null==he?void 0:he.sessionToken))try{await Z(Je,he.sessionToken,Oe.id,{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,locality:e.locality,pincode:e.pincode,delivery_status:e.delivery,flat_number:e.flatNumber,floor_number:e.floorNumber,building_name:e.buildingName,street_name:e.streetName})
331
+ return{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,division:"",locality:e.locality,pincode:e.pincode,delivery:e.delivery_status,country:"India",flatNumber:e.flat_number,floorNumber:e.floor_number,buildingName:e.building_name,streetName:e.street_name,formattedAddress:[e.flat_number,e.building_name,e.street_name,e.locality,e.district,e.state,e.pincode].filter(Boolean).join(", "),label:"work"===e.label||"other"===e.label?e.label:"home",labelText:(null==(r=e.label_text)?void 0:r.trim())||void 0,addressId:e.id}}(e),{skipCreate:!0,paymentBackStep:"saved"})}},onAddNew:()=>{$e(null),de(null),le("map")}}),"verify-address"===ae&&Oe&&r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"qr-order-lock-banner",role:"status",children:"Confirm your delivery pin to complete this order"}),r.jsx(j,{onLocationConfirm:Xe,defaultLat:Oe.lat??o,defaultLng:Oe.lng??l,mapHeight:u,theme:s,indiaBoundaryUrl:y,enableSearch:f,apiKey:e,apiBaseUrl:a,brandColor:k,mapStyle:b,mapTheme:v,embedMode:_,mapsKey:g??e})]}),"map"===ae&&r.jsx(j,{onLocationConfirm:Xe,defaultLat:o,defaultLng:l,mapHeight:u,theme:s,indiaBoundaryUrl:y,enableSearch:f,apiKey:e,apiBaseUrl:a,brandColor:k,mapStyle:b,mapTheme:v,embedMode:_,mapsKey:g??e}),"form"===ae&&se&&r.jsx(fe,{digipin:se.digipin,lat:se.lat,lng:se.lng,apiKey:e,apiBaseUrl:a,onAddressComplete:async e=>{if(Oe&&(null==he?void 0:he.sessionToken))try{await Z(Je,he.sessionToken,Oe.id,{digipin:e.digipin,lat:e.lat,lng:e.lng,state:e.state,district:e.district,locality:e.locality,pincode:e.pincode,delivery_status:e.delivery,flat_number:e.flatNumber,floor_number:e.floorNumber,building_name:e.buildingName,street_name:e.streetName})
332
332
  const r={...e,addressId:Oe.id}
333
333
  $e(null),await er(r,{skipCreate:!0})}catch(e){null==i||i(e instanceof Error?e:new Error("Failed to verify delivery pin."))}else await er(e)},onBack:rr,onError:i,theme:s,checkoutConfig:Je,serviceabilitySessionToken:He,enableServiceabilityCheck:L,showIndiaPostDeliveryWarning:P,serviceabilityBlockCheckout:I,initialValues:Oe?{flatNumber:Oe.flat_number,floorNumber:Oe.floor_number,buildingName:Oe.building_name,streetName:Oe.street_name,locality:Oe.locality,label:"work"===Oe.label||"other"===Oe.label?Oe.label:"home",labelText:(null==(K=Oe.label_text)?void 0:K.trim())||void 0}:void 0,submitLabel:Oe?"Confirm delivery pin":void 0}),"payment"===ae&&ee&&He&&R&&r.jsx(Pe,{checkoutConfig:Je,sessionToken:He,sessionId:null==he?void 0:he.sessionId,amountPaise:R,enableCod:S,codAllowed:qe&&!(null==Ce?void 0:Ce.interventions.includes("hide_cod")),addressRisk:Ce,theme:s,onComplete:({paymentMethod:e,razorpayOrderId:r,razorpayPaymentId:n})=>{Be(e),Ke({type:"payment_method_selected",step:"done",paymentMethod:e}),le("done"),ce&&t(ce),null==U||U({paymentMethod:e,sessionId:null==he?void 0:he.sessionId,razorpayOrderId:r,razorpayPaymentId:n})},onBack:rr,onEvent:(e,r)=>Ke({type:e,step:"payment",paymentMethod:r,buyerId:null==he?void 0:he.buyerId}),orderConfirmationUrl:J}),"done"===ae&&ce&&r.jsxs(r.Fragment,{children:[r.jsx(Re,{address:ce,onEditAddress:()=>{const e=null!==Te,r=!e&&(null==he?void 0:he.sessionToken)?"saved":X
334
334
  Ke({type:"widget_reset",step:r}),e&&(pe(null),ke(null)),le(r),de(null),ue(null),Le(null),$e(null),Be(null)}}),Te?r.jsxs("p",{className:"qr-cod-banner__text qr-cod-banner__text--ok",style:{textAlign:"center",margin:"8px 16px"},children:["Paid via ","cod"===Te?"Cash on Delivery":"online payment"]}):null,S&&w&&N&&He?r.jsxs(r.Fragment,{children:[r.jsx(Ee,{checkoutConfig:Je,sessionToken:He,pincode:ce.pincode,cartTotalPaise:B??R,theme:s,onCodAllowedChange:we}),F&&qe?r.jsx(Se,{copy:W??"Save more when you pay online — faster delivery & exclusive offers.",ctaUrl:z,theme:s}):null]}):null]}),r.jsxs("div",{className:"qr-footer",children:[r.jsx("span",{children:"Powered by"}),r.jsx("a",{href:"https://quantaroute.com",target:"_blank",rel:"noopener noreferrer",className:"qr-footer__link",children:"QuantaRoute"}),r.jsx("span",{className:"qr-footer__flag","aria-label":"Made in India",children:"🇮🇳"})]})]})}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@quantaroute/checkout",
3
- "version": "1.7.4",
4
- "description": "Embeddable DigiPin-powered smart address checkout widget — React (web), React Native & Expo (iOS/Android)",
3
+ "version": "1.8.1",
4
+ "description": "Verified-address checkout step for Indian e-commerce: DigiPin, map pin, shopper sign-in and funnel events. Script tag for any website, React, and Expo (iOS/Android).",
5
5
  "main": "./dist/lib/quantaroute-checkout.umd.js",
6
6
  "module": "./dist/lib/quantaroute-checkout.es.js",
7
7
  "types": "./dist/lib/index.d.ts",
@@ -17,11 +17,14 @@
17
17
  "./plugin": {
18
18
  "default": "./expo-plugin.js"
19
19
  },
20
- "./style.css": "./dist/style.css"
20
+ "./style.css": "./dist/style.css",
21
+ "./embed": "./dist/embed/quantaroute-checkout.js"
21
22
  },
22
23
  "files": [
23
24
  "src",
25
+ "!src/**/*.test.ts",
24
26
  "dist/lib",
27
+ "dist/embed",
25
28
  "dist/style.css",
26
29
  "expo-plugin.js",
27
30
  "babel.config.js",
@@ -31,7 +34,7 @@
31
34
  ],
32
35
  "scripts": {
33
36
  "dev": "vite",
34
- "build": "npm run build:lib && npm run build:demo",
37
+ "build": "npm run build:lib && npm run build:embed && npm run build:demo",
35
38
  "build:lib": "vite build --config vite.lib.config.ts",
36
39
  "build:demo": "vite build",
37
40
  "preview": "vite preview --outDir dist/demo",
@@ -39,7 +42,9 @@
39
42
  "type-check:native": "tsc --project tsconfig.native.json --noEmit",
40
43
  "verify:digipin": "npx tsx scripts/verify-digipin-formats.mjs",
41
44
  "verify:locality": "npx tsx scripts/verify-locality-names.mjs",
42
- "prepublishOnly": "npm run type-check && npm run type-check:native && npm run build:lib"
45
+ "prepublishOnly": "npm run type-check && npm run type-check:native && npm run test && npm run build:lib && npm run build:embed",
46
+ "build:embed": "vite build --config vite.embed.config.ts",
47
+ "test": "node --test src/embed/*.test.ts"
43
48
  },
44
49
  "keywords": [
45
50
  "digipin",
@@ -63,13 +68,6 @@
63
68
  "name": "QuantaRoute",
64
69
  "url": "https://quantaroute.com"
65
70
  },
66
- "repository": {
67
- "type": "git",
68
- "url": "https://github.com/quantaroute/checkout.git"
69
- },
70
- "bugs": {
71
- "url": "https://github.com/quantaroute/checkout/issues"
72
- },
73
71
  "homepage": "https://developers.quantaroute.com",
74
72
  "publishConfig": {
75
73
  "access": "public",
@@ -136,5 +134,7 @@
136
134
  "typescript": "^5.6.3",
137
135
  "vite": "^6.4.3",
138
136
  "vite-plugin-dts": "^4.3.0"
139
- }
137
+ },
138
+ "jsdelivr": "./dist/embed/quantaroute-checkout.js",
139
+ "unpkg": "./dist/embed/quantaroute-checkout.js"
140
140
  }
@@ -14,6 +14,7 @@ import AddressForm from './AddressForm.native';
14
14
  import type { CheckoutEvent, CheckoutWidgetProps, CompleteAddress } from '../core/types';
15
15
  import CodAvailabilityBanner from './CodAvailabilityBanner';
16
16
  import { styles, COLORS } from '../styles/checkout.native';
17
+ import { DEFAULT_CHECKOUT_FUNCTIONS_URL } from '../core/map-runtime';
17
18
 
18
19
  // ─── Types ────────────────────────────────────────────────────────────────────
19
20
 
@@ -81,6 +82,7 @@ const SuccessScreen: React.FC<SuccessScreenProps> = ({ address, onEditAddress, i
81
82
  */
82
83
  const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
83
84
  apiKey,
85
+ mapsKey,
84
86
  apiBaseUrl = 'https://api.quantaroute.com',
85
87
  onComplete,
86
88
  onError,
@@ -95,7 +97,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
95
97
  headerBanner,
96
98
  onCheckoutEvent,
97
99
  merchantId = '',
98
- supabaseFunctionBaseUrl = '',
100
+ supabaseFunctionBaseUrl = DEFAULT_CHECKOUT_FUNCTIONS_URL,
99
101
  enableCod = false,
100
102
  enableServiceabilityCheck = false,
101
103
  showIndiaPostDeliveryWarning = false,
@@ -231,6 +233,10 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
231
233
  mapHeight={mapHeight}
232
234
  theme={theme}
233
235
  brandColor={brandColor}
236
+ apiKey={apiKey}
237
+ apiBaseUrl={apiBaseUrl}
238
+ // The public dp_ key carries the maps scope; without it maps.quantaroute.com answers 403.
239
+ mapsKey={mapsKey ?? apiKey}
234
240
  />
235
241
  ) : null}
236
242
 
@@ -29,6 +29,7 @@ import EmailOtpStep from './EmailOtpStep';
29
29
  import { getWebDeviceContext } from '../core/device';
30
30
  import { captureUtmFromUrl } from '../core/utm';
31
31
  import '../styles/checkout.css';
32
+ import { DEFAULT_CHECKOUT_FUNCTIONS_URL } from '../core/map-runtime';
32
33
 
33
34
  // ─── Types ────────────────────────────────────────────────────────────────────
34
35
 
@@ -218,7 +219,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
218
219
  mapsKey,
219
220
  enablePhoneAuth = false,
220
221
  merchantId = '',
221
- supabaseFunctionBaseUrl = '',
222
+ supabaseFunctionBaseUrl = DEFAULT_CHECKOUT_FUNCTIONS_URL,
222
223
  brandColor,
223
224
  logoUrl,
224
225
  headerBanner,
@@ -980,7 +981,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
980
981
  mapStyle={mapStyle}
981
982
  mapTheme={mapTheme}
982
983
  embedMode={embedMode}
983
- mapsKey={mapsKey}
984
+ mapsKey={mapsKey ?? apiKey}
984
985
  />
985
986
  </>
986
987
  )}
@@ -1001,7 +1002,7 @@ const CheckoutWidget: React.FC<CheckoutWidgetProps> = ({
1001
1002
  mapStyle={mapStyle}
1002
1003
  mapTheme={mapTheme}
1003
1004
  embedMode={embedMode}
1004
- mapsKey={mapsKey}
1005
+ mapsKey={mapsKey ?? apiKey}
1005
1006
  />
1006
1007
  )}
1007
1008
 
@@ -16,7 +16,7 @@ import { getDigiPin, getLatLngFromDigiPin, formatDigiPin, isWithinIndia } from '
16
16
  import { autocompleteAddress, looksLikeDigiPin, couldBeDigiPinInput } from '../core/api';
17
17
  import type { AutocompleteSuggestion } from '../core/api';
18
18
  import type { MapPinSelectorProps } from '../core/types';
19
- import { QUANTAROUTE_MAP_STYLE_URL, withMapsKey } from '../core/map-runtime';
19
+ import { CARTO_POSITRON_STYLE_URL, QUANTAROUTE_MAP_STYLE_URL, withMapsKey } from '../core/map-runtime';
20
20
  import { styles, COLORS } from '../styles/checkout.native';
21
21
 
22
22
  // ─── Constants ────────────────────────────────────────────────────────────────
@@ -59,7 +59,8 @@ function computeDigiPinSafe(lat: number, lng: number): string | null {
59
59
 
60
60
  /**
61
61
  * Native (iOS/Android) map pin selector.
62
- * Uses expo-osm-sdk's OSMView with a draggable marker over Carto Positron tiles.
62
+ * Uses expo-osm-sdk's OSMView with a draggable marker over the QuantaRoute basemap
63
+ * (Carto Positron only when no maps key is given).
63
64
  * Metro resolves this file on native; MapPinSelector.tsx is used on web.
64
65
  */
65
66
  const MapPinSelector: React.FC<MapPinSelectorProps> = ({
@@ -323,7 +324,11 @@ const MapPinSelector: React.FC<MapPinSelectorProps> = ({
323
324
  style={{ flex: 1 }}
324
325
  initialCenter={{ latitude: initLat, longitude: initLng }}
325
326
  initialZoom={hasDefault ? STREET_ZOOM : OVERVIEW_ZOOM}
326
- styleUrl={withMapsKey(QUANTAROUTE_MAP_STYLE_URL, mapsKey)}
327
+ styleUrl={
328
+ mapsKey
329
+ ? withMapsKey(QUANTAROUTE_MAP_STYLE_URL, mapsKey)
330
+ : CARTO_POSITRON_STYLE_URL
331
+ }
327
332
  markers={pinMarkers}
328
333
  showUserLocation={false}
329
334
  scrollEnabled
@@ -193,3 +193,7 @@ export function waitForExternalMapRuntime(
193
193
  if (retryTimer !== null) window.clearTimeout(retryTimer);
194
194
  };
195
195
  }
196
+
197
+ /** Hosted QuantaRoute checkout functions. Every merchant uses these; override only for testing. */
198
+ export const DEFAULT_CHECKOUT_FUNCTIONS_URL =
199
+ 'https://ikfiewesidedxozotmrl.supabase.co/functions/v1';
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Pure helpers for the script-tag embed. No DOM and no React, so they can be
3
+ * unit tested on their own.
4
+ */
5
+
6
+ /** What the embed hands to the merchant when the shopper finishes. */
7
+ export type HandoffPayload = {
8
+ /** Checkout session id. Verify it on your server with the admin API. */
9
+ sessionId: string;
10
+ digipin: string;
11
+ lat: number;
12
+ lng: number;
13
+ pincode: string;
14
+ state: string;
15
+ district: string;
16
+ locality: string;
17
+ flatNumber: string;
18
+ floorNumber: string;
19
+ buildingName: string;
20
+ streetName: string;
21
+ formattedAddress: string;
22
+ addressId?: string;
23
+ };
24
+
25
+ const PLACEHOLDER = /\{\{\s*([a-zA-Z]+)\s*\}\}|\{\s*([a-zA-Z]+)\s*\}/g;
26
+
27
+ /**
28
+ * Fill `{name}` or `{{name}}` placeholders in a redirect URL with the
29
+ * (URL-encoded) handoff values. Unknown placeholders are left empty.
30
+ *
31
+ * Example: https://shop.example/pay?sid={sessionId}&pin={pincode}
32
+ */
33
+ export function buildRedirectUrl(
34
+ template: string,
35
+ payload: Partial<HandoffPayload> & Record<string, unknown>
36
+ ): string {
37
+ return template.replace(PLACEHOLDER, (_match, doubleKey: string, singleKey: string) => {
38
+ const value = payload[doubleKey ?? singleKey];
39
+ return value === undefined || value === null ? '' : encodeURIComponent(String(value));
40
+ });
41
+ }
42
+
43
+ /** `"#a, .b"` -> `["#a", ".b"]`. Selectors may themselves contain commas inside brackets. */
44
+ export function parseSelectors(value: string | string[] | undefined | null): string[] {
45
+ if (!value) return [];
46
+ const list = Array.isArray(value) ? value : splitTopLevel(value);
47
+ return list.map((item) => item.trim()).filter(Boolean);
48
+ }
49
+
50
+ function splitTopLevel(value: string): string[] {
51
+ const out: string[] = [];
52
+ let depth = 0;
53
+ let quote: string | null = null;
54
+ let current = '';
55
+ for (const char of value) {
56
+ if (quote) {
57
+ current += char;
58
+ if (char === quote) quote = null;
59
+ continue;
60
+ }
61
+ if (char === '"' || char === "'") {
62
+ quote = char;
63
+ current += char;
64
+ } else if (char === '[' || char === '(') {
65
+ depth += 1;
66
+ current += char;
67
+ } else if (char === ']' || char === ')') {
68
+ depth = Math.max(0, depth - 1);
69
+ current += char;
70
+ } else if (char === ',' && depth === 0) {
71
+ out.push(current);
72
+ current = '';
73
+ } else {
74
+ current += char;
75
+ }
76
+ }
77
+ out.push(current);
78
+ return out;
79
+ }
80
+
81
+ export type ScriptConfig = {
82
+ merchantId?: string;
83
+ apiKey?: string;
84
+ mapsKey?: string;
85
+ functionsUrl?: string;
86
+ triggers?: string[];
87
+ redirectUrl?: string;
88
+ brandColor?: string;
89
+ theme?: 'light' | 'dark';
90
+ title?: string;
91
+ logoUrl?: string;
92
+ authMode?: 'email' | 'phone' | 'none';
93
+ autoInit: boolean;
94
+ };
95
+
96
+ const truthy = (value: string | undefined) =>
97
+ value !== undefined && !['false', '0', 'no', 'off'].includes(value.toLowerCase());
98
+
99
+ /**
100
+ * Read embed options from the data-* attributes of the script tag:
101
+ *
102
+ * <script src=".../quantaroute-checkout.js"
103
+ * data-merchant-id="…" data-api-key="dp_…" data-maps-key="dp_…"
104
+ * data-trigger="#checkout-button" data-redirect-url="https://shop/pay?sid={sessionId}">
105
+ * </script>
106
+ *
107
+ * `autoInit` is true when the tag carries enough to start (a merchant id and
108
+ * an API key); otherwise call QuantaRouteCheckout.init() yourself.
109
+ */
110
+ export function readScriptConfig(data: Record<string, string | undefined>): ScriptConfig {
111
+ const authMode = (data.auth ?? data.authMode ?? '').toLowerCase();
112
+ const theme = (data.theme ?? '').toLowerCase();
113
+ const config: ScriptConfig = {
114
+ merchantId: data.merchantId,
115
+ apiKey: data.apiKey,
116
+ mapsKey: data.mapsKey,
117
+ functionsUrl: data.functionsUrl,
118
+ triggers: parseSelectors(data.trigger ?? data.triggers),
119
+ redirectUrl: data.redirectUrl,
120
+ brandColor: data.brandColor,
121
+ theme: theme === 'dark' ? 'dark' : theme === 'light' ? 'light' : undefined,
122
+ title: data.title,
123
+ logoUrl: data.logoUrl,
124
+ authMode:
125
+ authMode === 'phone' || authMode === 'none' || authMode === 'email' ? authMode : undefined,
126
+ autoInit: false,
127
+ };
128
+ config.autoInit =
129
+ Boolean(config.merchantId && config.apiKey) && truthy(data.autoInit ?? 'true');
130
+ return config;
131
+ }