@kanorio/elements 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/CustomerAccountPanel-FXJEOS4F.js +2 -0
- package/dist/CustomerAccountPanel-LK4GSYYU.js +2 -0
- package/dist/{FormAddressField-QR7ZCH77.js → FormAddressField-NH5LD6K7.js} +2 -2
- package/dist/{FormAddressField-C6VN7J6I.js → FormAddressField-Z5XT2ELO.js} +2 -2
- package/dist/FormFileField-5YFTKIRZ.js +2 -0
- package/dist/FormFileField-D2XIGIML.js +2 -0
- package/dist/{FormTaxIdField-K34MDUPW.js → FormTaxIdField-GGBQOVZE.js} +2 -2
- package/dist/{FormTaxIdField-XMK5WRQO.js → FormTaxIdField-XJSMW3II.js} +2 -2
- package/dist/KanorioAccount-BGIMYMGL.js +2 -0
- package/dist/KanorioAccount-E3NDKUX5.js +2 -0
- package/dist/KanorioAnalytics-CNEIZ4VZ.js +2 -0
- package/dist/KanorioAnalytics-RTCJ62AP.js +2 -0
- package/dist/KanorioCurriculum-CDHXCPSI.js +2 -0
- package/dist/KanorioCurriculum-JIKUHPOJ.js +2 -0
- package/dist/KanorioForm-QU243SAP.js +2 -0
- package/dist/KanorioForm-W6XBJW74.js +2 -0
- package/dist/KanorioLightbox-2YTEYM57.js +2 -0
- package/dist/KanorioLightbox-WCQ4NW5Z.js +2 -0
- package/dist/KanorioLogin-CDSAAJJE.js +2 -0
- package/dist/KanorioLogin-OYIESFJL.js +2 -0
- package/dist/KanorioMedia-BEFSUKSN.js +2 -0
- package/dist/KanorioMedia-ZGHENDE3.js +2 -0
- package/dist/KanorioReviews-O67GJZ24.js +2 -0
- package/dist/KanorioReviews-V5RUA2TV.js +2 -0
- package/dist/KanorioUnit-2FXOUNOP.js +2 -0
- package/dist/KanorioUnit-AIM4O7QI.js +2 -0
- package/dist/{MediaPlayer-F43FPK4E.js → MediaPlayer-C5KI6N5V.js} +2 -2
- package/dist/{MediaPlayer-JHFZFOOG.js → MediaPlayer-PMAEZSCZ.js} +2 -2
- package/dist/{PDFViewerFull-INVHZL4V.js → PDFViewerFull-6MZJTHN2.js} +2 -2
- package/dist/{PDFViewerFull-CB44M7GW.js → PDFViewerFull-P3HCVGDZ.js} +2 -2
- package/dist/account.d.ts +3 -2
- package/dist/account.js +1 -1
- package/dist/analytics.js +1 -1
- package/dist/ar-JXAEXYYY.js +2 -0
- package/dist/ar-UXUCJCPY.js +2 -0
- package/dist/bg-EUIPVVBX.js +2 -0
- package/dist/bg-HEU3KGAJ.js +2 -0
- package/dist/{bn-BHRS66N3.js → bn-L35GOE5D.js} +2 -2
- package/dist/{bn-DM5WNGJ5.js → bn-LMQOF3SO.js} +2 -2
- package/dist/bot-protection.d.ts +67 -36
- package/dist/bot-protection.js +1 -1
- package/dist/chunk-2H3LTDAA.js +2 -0
- package/dist/chunk-3NXF6SCJ.js +2 -0
- package/dist/{chunk-EE4S6NRV.js → chunk-4OC7BRQS.js} +2 -2
- package/dist/{chunk-DTBRUBPG.js → chunk-56UUP6CI.js} +2 -2
- package/dist/{chunk-IAXVJLJ3.js → chunk-65RP744E.js} +2 -2
- package/dist/chunk-73S6VKNV.js +2 -0
- package/dist/{chunk-4MOCTNN7.js → chunk-7UCZ56EJ.js} +2 -2
- package/dist/{chunk-FQCA2VGY.js → chunk-A4ZGBTRT.js} +2 -2
- package/dist/chunk-APWDEDWM.js +2 -0
- package/dist/{chunk-WM5S3YN5.js → chunk-CTMHQZAU.js} +2 -2
- package/dist/chunk-D4KDA3KL.js +2 -0
- package/dist/{chunk-2ONAW3CA.js → chunk-DIHLDYIG.js} +2 -2
- package/dist/chunk-EGMCB2MQ.js +3 -0
- package/dist/{chunk-LWRWKZBC.js → chunk-FFSPNYLJ.js} +2 -2
- package/dist/chunk-FXDWRWZ3.js +3 -0
- package/dist/chunk-I6KLZIN6.js +2 -0
- package/dist/{chunk-NGRNPVON.js → chunk-II7PVZWZ.js} +2 -2
- package/dist/chunk-J24HGQ7U.js +2 -0
- package/dist/{chunk-4KA3HSRQ.js → chunk-JYBSXLT3.js} +2 -2
- package/dist/{chunk-N5PIQM4L.js → chunk-KW2CH7SS.js} +2 -2
- package/dist/chunk-KYXZNMNA.js +2 -0
- package/dist/{chunk-QOQQCCID.js → chunk-L3BUSP27.js} +2 -2
- package/dist/{chunk-B7KLKVIM.js → chunk-L66F3USG.js} +2 -2
- package/dist/{chunk-36YEGBKK.js → chunk-N4Y3DCC6.js} +2 -2
- package/dist/{chunk-NBDRYQZV.js → chunk-OLGITMLA.js} +2 -2
- package/dist/{chunk-5HWAL7VK.js → chunk-OSXFUIAV.js} +2 -2
- package/dist/chunk-Q4APVE7S.js +2 -0
- package/dist/chunk-QF55WZDP.js +2 -0
- package/dist/chunk-QYTK2CW3.js +2 -0
- package/dist/chunk-RNRIZCZS.js +2 -0
- package/dist/{chunk-K4VRRKYJ.js → chunk-UDNUWN4W.js} +2 -2
- package/dist/{chunk-AF46NLXK.js → chunk-UITC3NFQ.js} +2 -2
- package/dist/chunk-UWRJBUJY.js +2 -0
- package/dist/chunk-VGQ2N7JH.js +2 -0
- package/dist/{chunk-H7VP4BYY.js → chunk-VRD67HVO.js} +2 -2
- package/dist/chunk-VT2B53EX.js +2 -0
- package/dist/{chunk-BGVTMWPN.js → chunk-W5QS3RHM.js} +2 -2
- package/dist/chunk-WJPCDZSL.js +2 -0
- package/dist/chunk-XJPS3G7J.js +3 -0
- package/dist/{chunk-Z4OV6QHI.js → chunk-Y5JA6B5O.js} +2 -2
- package/dist/cs-LY4LE4NI.js +2 -0
- package/dist/cs-MGLMNU2K.js +2 -0
- package/dist/curriculum.d.ts +3 -2
- package/dist/curriculum.js +1 -1
- package/dist/da-LQTLZNBW.js +2 -0
- package/dist/da-X5HKEDEL.js +2 -0
- package/dist/de-M3M4VBDR.js +2 -0
- package/dist/de-Y5ELIZBU.js +2 -0
- package/dist/{deliverables-C5RD2ASE.js → deliverables-EOIAZFWB.js} +25 -25
- package/dist/{deliverables-BDS7WMBC.js → deliverables-NO5NEFRM.js} +2 -2
- package/dist/{el-SMBF7FG4.js → el-7YYYEHW6.js} +2 -2
- package/dist/{el-G2AWU43W.js → el-YZGS3PLP.js} +2 -2
- package/dist/elements.css +1 -1
- package/dist/en-AU-IUEA3YQP.js +2 -0
- package/dist/en-AU-RQ2DVIXE.js +2 -0
- package/dist/en-CA-OFK46Q44.js +2 -0
- package/dist/en-CA-QDP57WHG.js +2 -0
- package/dist/en-GB-URCOTEDK.js +2 -0
- package/dist/en-GB-VNG2IO2E.js +2 -0
- package/dist/en-JSBHSC4K.js +2 -0
- package/dist/en-MCRNEXQP.js +2 -0
- package/dist/en-US-5RT4SJ3V.js +2 -0
- package/dist/en-US-IWMVMSUT.js +2 -0
- package/dist/es-419-53Z5HI6Z.js +2 -0
- package/dist/es-419-JFUQ3D4V.js +2 -0
- package/dist/es-ES-BMD6JJEO.js +2 -0
- package/dist/es-ES-PBIVNTAT.js +2 -0
- package/dist/fa-57P7R77M.js +2 -0
- package/dist/{fa-OYP2Q5EV.js → fa-NE4XJTHW.js} +2 -2
- package/dist/fi-G5MG7VJ2.js +2 -0
- package/dist/fi-SCTIKRMX.js +2 -0
- package/dist/form.d.ts +393 -23
- package/dist/form.js +1 -1
- package/dist/{forms-answers-address-7P6EVFY5.js → forms-answers-address-5MXQYIH3.js} +2 -2
- package/dist/{forms-answers-address-IQV2Y56H.js → forms-answers-address-BGBI445K.js} +2 -2
- package/dist/{forms-answers-tax-id-WJD7K3PG.js → forms-answers-tax-id-3AYXCNP5.js} +2 -2
- package/dist/{forms-answers-tax-id-D4GOUC6N.js → forms-answers-tax-id-LSWOEHJ4.js} +2 -2
- package/dist/fr-CA-4X7URW4M.js +2 -0
- package/dist/fr-CA-RQDI3NIQ.js +2 -0
- package/dist/fr-FR-EDVHTVOW.js +2 -0
- package/dist/fr-FR-KGXOTINP.js +2 -0
- package/dist/{gu-BREQK3GJ.js → gu-7AJCL43I.js} +2 -2
- package/dist/{gu-RNCZTEOA.js → gu-QE53XIWR.js} +2 -2
- package/dist/he-UWYKIUPF.js +2 -0
- package/dist/he-VLGZUN42.js +2 -0
- package/dist/{hi-DKG5TPYX.js → hi-5M4U37GW.js} +2 -2
- package/dist/{hi-F7Y62LAZ.js → hi-KXKJMKZF.js} +2 -2
- package/dist/{hu-3Y5YEIFL.js → hu-JU7V3YQX.js} +2 -2
- package/dist/{hu-L6W5O2G5.js → hu-YRF3KPIJ.js} +2 -2
- package/dist/id-IRL2KCIE.js +2 -0
- package/dist/id-SXO4Z54V.js +2 -0
- package/dist/index.d.ts +5 -3
- package/dist/index.js +1 -1
- package/dist/it-55QCLHB7.js +2 -0
- package/dist/it-RBRELRA3.js +2 -0
- package/dist/ja-2WRUVHKU.js +2 -0
- package/dist/ja-3HZPHYZS.js +2 -0
- package/dist/kanorio-elements.js +1 -1
- package/dist/{km-HPCMYWAG.js → km-EW4ISUB7.js} +2 -2
- package/dist/{km-PHVYTPLT.js → km-SL6MZB3H.js} +2 -2
- package/dist/{kn-QAWBGLHG.js → kn-RUSRJNGR.js} +2 -2
- package/dist/kn-YGEU3PSD.js +2 -0
- package/dist/ko-2GI6Z5YH.js +2 -0
- package/dist/ko-QK33QMU2.js +2 -0
- package/dist/{lightbox-DEvsB5dB.d.ts → lightbox-BmkHgtZg.d.ts} +1 -1
- package/dist/lightbox.d.ts +4 -3
- package/dist/lightbox.js +1 -1
- package/dist/{lo-JNUKFIQV.js → lo-PPDKXTQQ.js} +2 -2
- package/dist/{lo-YRHYLRZC.js → lo-ZRV6OAH6.js} +2 -2
- package/dist/login.d.ts +3 -2
- package/dist/login.js +1 -1
- package/dist/media.d.ts +3 -2
- package/dist/media.js +1 -1
- package/dist/{ml-QO64O4H6.js → ml-BIZEFHNR.js} +2 -2
- package/dist/{ml-3LXSDTNF.js → ml-KO2JGAL5.js} +2 -2
- package/dist/{mr-PLM72664.js → mr-J4AGQFC7.js} +2 -2
- package/dist/{mr-5WLN37JQ.js → mr-PZNRW5MW.js} +2 -2
- package/dist/{ms-PIAATVMD.js → ms-NYWKJQEQ.js} +2 -2
- package/dist/{ms-N544Y63H.js → ms-OMUKF5WC.js} +2 -2
- package/dist/{my-3J665CWK.js → my-FHI5JEQF.js} +2 -2
- package/dist/{my-6IKSM3XW.js → my-R4OXNUDW.js} +2 -2
- package/dist/nb-EC6AP76Y.js +2 -0
- package/dist/nb-U4QN5GJE.js +2 -0
- package/dist/{ne-ASFNHMO3.js → ne-DRPNDCZH.js} +2 -2
- package/dist/ne-J3XQJZAY.js +2 -0
- package/dist/nl-BE-QIH5K6WQ.js +2 -0
- package/dist/nl-BE-VHBDCIRF.js +2 -0
- package/dist/nl-NL-FZMZRVH4.js +2 -0
- package/dist/nl-NL-USXHXD5U.js +2 -0
- package/dist/nn-IPL74C6S.js +2 -0
- package/dist/nn-UCSEDGDB.js +2 -0
- package/dist/{pa-P2GAYL5A.js → pa-LTF7CWS2.js} +2 -2
- package/dist/{pa-VX5TUNDP.js → pa-NTK4KSUF.js} +2 -2
- package/dist/{phone-input-Q5AV6KSW.js → phone-input-DOL46AIF.js} +2 -2
- package/dist/{phone-input-T6QX2TDS.js → phone-input-PXLNDXAB.js} +2 -2
- package/dist/pl-6FXX3WNC.js +2 -0
- package/dist/pl-YWCG2YWW.js +2 -0
- package/dist/{provider-CMLzyAjJ.d.ts → provider-BYGVc6kS.d.ts} +3 -1
- package/dist/provider.d.ts +3 -2
- package/dist/provider.js +1 -1
- package/dist/pt-BR-5JRKIQVH.js +2 -0
- package/dist/pt-BR-CIJCMCLE.js +2 -0
- package/dist/pt-PT-A7F2KKCY.js +2 -0
- package/dist/pt-PT-Y2UCAKHP.js +2 -0
- package/dist/reviews.d.ts +3 -2
- package/dist/reviews.js +1 -1
- package/dist/ro-6MQF2KY2.js +2 -0
- package/dist/ro-YISUN7LU.js +2 -0
- package/dist/ru-KGU3SC3S.js +2 -0
- package/dist/ru-RMPFJQSL.js +2 -0
- package/dist/{si-5VUM5FGR.js → si-CTQN6I2M.js} +2 -2
- package/dist/{si-5F7RWQIE.js → si-N5U32GIL.js} +2 -2
- package/dist/sv-36EB3HIA.js +2 -0
- package/dist/sv-QGZRDKBJ.js +2 -0
- package/dist/sw-CWIRVHYD.js +2 -0
- package/dist/sw-OUQYTLJF.js +2 -0
- package/dist/{ta-MNWTH3F5.js → ta-E3ZBHC6A.js} +2 -2
- package/dist/{ta-R73RBA23.js → ta-N7BHKWBO.js} +2 -2
- package/dist/{te-5SBVH4OF.js → te-7JC2KGAU.js} +2 -2
- package/dist/{te-GVW56XDM.js → te-CTCZQKFU.js} +2 -2
- package/dist/{th-G6SY3D2Q.js → th-AN5CLQP6.js} +2 -2
- package/dist/{th-2GWK7DBB.js → th-JVK4E2AJ.js} +2 -2
- package/dist/tl-BSWGJB7O.js +2 -0
- package/dist/tl-X72423V3.js +2 -0
- package/dist/tr-22NUPSET.js +2 -0
- package/dist/tr-AZ2PLRZY.js +2 -0
- package/dist/{uk-PGHXMWJR.js → uk-POKPJJDZ.js} +2 -2
- package/dist/uk-UOTQJ3E7.js +2 -0
- package/dist/unit.d.ts +3 -1
- package/dist/unit.js +1 -1
- package/dist/{ur-4CR64XUI.js → ur-6LBRTMAE.js} +2 -2
- package/dist/{ur-J5HV4NTW.js → ur-NRHFTLO5.js} +2 -2
- package/dist/vi-3ZVAOXIJ.js +2 -0
- package/dist/vi-XC4CGJHX.js +2 -0
- package/dist/web-components.js +1 -1
- package/dist/zh-CN-EKEY2CLM.js +2 -0
- package/dist/zh-CN-XW3PLUG5.js +2 -0
- package/dist/zh-HK-25OZZBHO.js +2 -0
- package/dist/zh-HK-EPQAUBL3.js +2 -0
- package/dist/zh-Hant-LFJZCOMK.js +2 -0
- package/dist/zh-Hant-RQMTFZSE.js +2 -0
- package/package.json +2 -2
- package/dist/CustomerAccountPanel-DJKV7LT4.js +0 -2
- package/dist/CustomerAccountPanel-RWEHWBJY.js +0 -2
- package/dist/FormFileField-LZDCXI2Z.js +0 -2
- package/dist/FormFileField-ONL4Q55V.js +0 -2
- package/dist/KanorioAccount-EN3TM67X.js +0 -2
- package/dist/KanorioAccount-XGVSGVYN.js +0 -2
- package/dist/KanorioAnalytics-NEKTFQEE.js +0 -2
- package/dist/KanorioAnalytics-UMCUWQM7.js +0 -2
- package/dist/KanorioCurriculum-3QSCOHK7.js +0 -2
- package/dist/KanorioCurriculum-RUIGZ5X7.js +0 -2
- package/dist/KanorioForm-GUA5GEJY.js +0 -2
- package/dist/KanorioForm-KXV7D2TU.js +0 -2
- package/dist/KanorioLightbox-M72HNQQX.js +0 -2
- package/dist/KanorioLightbox-TQ3Q73TD.js +0 -2
- package/dist/KanorioLogin-5XFN3YEE.js +0 -2
- package/dist/KanorioLogin-AJHHVQGV.js +0 -2
- package/dist/KanorioMedia-ADKUDH5C.js +0 -2
- package/dist/KanorioMedia-DLBSXCKA.js +0 -2
- package/dist/KanorioReviews-42FZSXTI.js +0 -2
- package/dist/KanorioReviews-7LD5WKFG.js +0 -2
- package/dist/KanorioUnit-NWBX5DEI.js +0 -2
- package/dist/KanorioUnit-SIM3344J.js +0 -2
- package/dist/ar-3VA7IUCO.js +0 -2
- package/dist/ar-AUQCHHZG.js +0 -2
- package/dist/bg-IRGRVWOG.js +0 -2
- package/dist/bg-QWC2KG3G.js +0 -2
- package/dist/chunk-4BBERZ6T.js +0 -2
- package/dist/chunk-5AUWUK5R.js +0 -2
- package/dist/chunk-66XN5RR4.js +0 -2
- package/dist/chunk-EZMTUAQX.js +0 -2
- package/dist/chunk-FSY5GB5E.js +0 -3
- package/dist/chunk-G4U6BFZY.js +0 -2
- package/dist/chunk-GJY6AQIS.js +0 -2
- package/dist/chunk-IXDKZO42.js +0 -2
- package/dist/chunk-MIQK3T3Y.js +0 -2
- package/dist/chunk-QGR3QAQB.js +0 -3
- package/dist/chunk-SUXTLVTX.js +0 -2
- package/dist/chunk-UIHBR4NU.js +0 -3
- package/dist/chunk-WXIUWMFR.js +0 -2
- package/dist/cs-3IX2ZQKJ.js +0 -2
- package/dist/cs-NZW6FBFY.js +0 -2
- package/dist/da-AFMLFM32.js +0 -2
- package/dist/da-PZ32KKTE.js +0 -2
- package/dist/de-5JPEK4HF.js +0 -2
- package/dist/de-MVL4XGYR.js +0 -2
- package/dist/en-AIAENVLI.js +0 -2
- package/dist/en-AU-LB5UVGIW.js +0 -2
- package/dist/en-AU-Q2O2HPJ2.js +0 -2
- package/dist/en-CA-AZDOY7PW.js +0 -2
- package/dist/en-CA-PVKXM3WS.js +0 -2
- package/dist/en-GB-2N4WB6SL.js +0 -2
- package/dist/en-GB-Y5QRPC7S.js +0 -2
- package/dist/en-SAXQF5YW.js +0 -2
- package/dist/en-US-74L4OI3J.js +0 -2
- package/dist/en-US-EKS52JBW.js +0 -2
- package/dist/es-419-Q5IH6W5F.js +0 -2
- package/dist/es-419-VSZWGONE.js +0 -2
- package/dist/es-ES-7L55KPLO.js +0 -2
- package/dist/es-ES-ETSYFLPQ.js +0 -2
- package/dist/fa-WRJCKGS3.js +0 -2
- package/dist/fi-44ST6B6Q.js +0 -2
- package/dist/fi-J6NJBPNK.js +0 -2
- package/dist/fr-CA-KXRNFZBP.js +0 -2
- package/dist/fr-CA-PWWAPLBH.js +0 -2
- package/dist/fr-FR-FMLQPLOD.js +0 -2
- package/dist/fr-FR-MQAFE7IX.js +0 -2
- package/dist/he-GNC45OCB.js +0 -2
- package/dist/he-VXZCGAHY.js +0 -2
- package/dist/id-7DWHYYFC.js +0 -2
- package/dist/id-DCV57AQB.js +0 -2
- package/dist/it-7RASZ4SK.js +0 -2
- package/dist/it-JICU5WVL.js +0 -2
- package/dist/ja-4V7QJLTM.js +0 -2
- package/dist/ja-52MBIM3T.js +0 -2
- package/dist/kn-5DYCOYAN.js +0 -2
- package/dist/ko-55JV4VQK.js +0 -2
- package/dist/ko-FZIJZG6K.js +0 -2
- package/dist/nb-345ACUTX.js +0 -2
- package/dist/nb-F33WYJ6T.js +0 -2
- package/dist/ne-AAIECB2W.js +0 -2
- package/dist/nl-BE-SHZLAL5T.js +0 -2
- package/dist/nl-BE-WK4C6XRZ.js +0 -2
- package/dist/nl-NL-2YLHGJZL.js +0 -2
- package/dist/nl-NL-PHRY43UB.js +0 -2
- package/dist/nn-I5A2LCBH.js +0 -2
- package/dist/nn-S3SNETRB.js +0 -2
- package/dist/pl-4Y4BWTLT.js +0 -2
- package/dist/pl-SGPLZAER.js +0 -2
- package/dist/pt-BR-CW3MRSRP.js +0 -2
- package/dist/pt-BR-WKEKB5CG.js +0 -2
- package/dist/pt-PT-AJZQS2C6.js +0 -2
- package/dist/pt-PT-ZTPCI2K6.js +0 -2
- package/dist/ro-ANISGUFX.js +0 -2
- package/dist/ro-HRV64STT.js +0 -2
- package/dist/ru-7U566HR4.js +0 -2
- package/dist/ru-PKSZKOLH.js +0 -2
- package/dist/sv-HZVCM7LG.js +0 -2
- package/dist/sv-UOGO55PW.js +0 -2
- package/dist/sw-5XU65KFC.js +0 -2
- package/dist/sw-KVAYRFED.js +0 -2
- package/dist/tl-OCD2O6J3.js +0 -2
- package/dist/tl-PZNXANIM.js +0 -2
- package/dist/tr-2BDM6H5Q.js +0 -2
- package/dist/tr-VFMHVRQX.js +0 -2
- package/dist/uk-OQRACKKD.js +0 -2
- package/dist/vi-MQSOSIUY.js +0 -2
- package/dist/vi-U7OT2LM7.js +0 -2
- package/dist/zh-CN-CCYHPSVA.js +0 -2
- package/dist/zh-CN-RNW2BEY7.js +0 -2
- package/dist/zh-HK-HE2T63O2.js +0 -2
- package/dist/zh-HK-RKREDSAO.js +0 -2
- package/dist/zh-Hant-GBQLGJDF.js +0 -2
- package/dist/zh-Hant-T6KHSA5B.js +0 -2
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{CUSTOMER_SESSION_HINT_COOKIE_NAME,CustomerAccountPanel,createHostedCustomerAuthTransport,customerButtonClass,normalizeCustomerAuthMethods}from"./chunk-4OC7BRQS.js";import{composeRefs}from"./chunk-AQ6F6MIJ.js";import{useHydrated}from"./chunk-63XJWMJG.js";import{completeHostedCustomerLogin,startHostedCustomerLogin}from"./chunk-UWRJBUJY.js";import{onDemand}from"./chunk-E77WGXYW.js";import{LOGIN_EVENT,LOGOUT_EVENT}from"./chunk-LWKCGUHS.js";import{BotProtectionConfigProvider,parsePublicBotProtectionConfig}from"./chunk-KYXZNMNA.js";import{useSiteChrome}from"./chunk-Z4A5NQWJ.js";import{lockPageScroll}from"./chunk-HFYLTH5B.js";import{LoaderCircle,X}from"./chunk-33AQQY6T.js";import{clsx,cn}from"./chunk-VUTODQFX.js";import{ElementsRoot}from"./chunk-7UCZ56EJ.js";import{fillLabel}from"./chunk-KNNN5V3T.js";import{useSiteLabels}from"./chunk-U7H3W23Q.js";import{KanorioApiError,createCustomerClient,useElementContext}from"./chunk-73S6VKNV.js";import{useEffect as useEffect4,useMemo as useMemo2,useState as useState2}from"react";import{jsx,jsxs}from"react/jsx-runtime";import{jsx as jsx2}from"react/jsx-runtime";import{jsx as jsx3,jsxs as jsxs2}from"react/jsx-runtime";import{useEffect,useRef}from"react";import{jsx as jsx4,jsxs as jsxs3}from"react/jsx-runtime";import{createContext,useCallback as useCallback2,useContext,useEffect as useEffect3,useMemo,useRef as useRef3,useState}from"react";import{useCallback,useEffect as useEffect2,useRef as useRef2}from"react";import{createPortal}from"react-dom";import{jsx as jsx5,jsxs as jsxs4}from"react/jsx-runtime";var FOCUSABLE_SELECTOR='a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';function SiteResponsiveModal({open,onClose,title,closeLabel,children,footer,showHeader=true,dismissible=true,desktopZIndexClassName="z-[var(--z-dialog,200)]",drawerZIndexClassName="z-[var(--z-dialog,200)]",maxWidthClassName="max-w-lg",desktopVariant="dialog",surface="glass",headerSlot,subheader,bodyClassName,footerClassName,id}){const isSide=desktopVariant==="side";const chrome=useSiteChrome();const mounted=useHydrated();const onCloseRef=useRef2(onClose);const dismissibleRef=useRef2(dismissible);useEffect2(()=>{onCloseRef.current=onClose;dismissibleRef.current=dismissible});useEffect2(()=>{if(!open)return;const releaseScrollLock=lockPageScroll();const onKeyDown=e=>{if(e.key==="Escape"&&dismissibleRef.current)onCloseRef.current()};document.addEventListener("keydown",onKeyDown);return()=>{releaseScrollLock();document.removeEventListener("keydown",onKeyDown)}},[open]);const sheetRef=useRef2(null);const subheaderRef=useRef2(null);const bodyRef=useRef2(null);const dragZoneRef=useRef2(null);const dragStartY=useRef2(null);const dragDelta=useRef2(0);const portalTarget=chrome?chrome.slots.modal:mounted?document.body:null;const rendered=open&&!!portalTarget;useEffect2(()=>{if(!rendered)return;const sheet=sheetRef.current;if(!sheet)return;const previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null;const focusables=()=>Array.from(sheet.querySelectorAll(FOCUSABLE_SELECTOR)).filter(el=>!el.hasAttribute("disabled")&&el.getAttribute("aria-hidden")!=="true");const firstInSubheader=subheaderRef.current?.querySelector(FOCUSABLE_SELECTOR);const firstInBody=bodyRef.current?.querySelector(FOCUSABLE_SELECTOR);(firstInSubheader??firstInBody??focusables()[0]??sheet).focus({preventScroll:true});const onKeyDown=e=>{if(e.key!=="Tab")return;const list=focusables();if(list.length===0){e.preventDefault();sheet.focus();return}const first=list[0];const last=list[list.length-1];const active=document.activeElement;const inside=active instanceof Node&&sheet.contains(active);if(e.shiftKey){if(!inside||active===first||active===sheet){e.preventDefault();last.focus()}}else if(!inside||active===last){e.preventDefault();first.focus()}};document.addEventListener("keydown",onKeyDown);return()=>{document.removeEventListener("keydown",onKeyDown);if(previouslyFocused&&previouslyFocused.isConnected){previouslyFocused.focus({preventScroll:true})}}},[rendered]);const onTouchStart=useCallback(e=>{if(!dismissibleRef.current)return;const target=e.target instanceof Node?e.target:null;const fromDragZone=!!target&&!!dragZoneRef.current?.contains(target);const bodyAtTop=(bodyRef.current?.scrollTop??0)<=0;if(!fromDragZone&&!bodyAtTop)return;dragStartY.current=e.touches[0].clientY;dragDelta.current=0},[]);const onTouchMove=useCallback(e=>{if(dragStartY.current==null)return;const delta=e.touches[0].clientY-dragStartY.current;if(delta<0&&(bodyRef.current?.scrollTop??0)>0){dragStartY.current=null;if(sheetRef.current)sheetRef.current.style.transform="";return}dragDelta.current=delta;if(delta>0&&sheetRef.current){sheetRef.current.style.transform=`translateY(${delta}px)`}},[]);const onTouchEnd=useCallback(()=>{if(dragStartY.current==null)return;if(sheetRef.current){sheetRef.current.style.transform=""}if(dragDelta.current>100&&dismissibleRef.current){onCloseRef.current()}dragStartY.current=null;dragDelta.current=0},[]);if(!rendered)return null;const headerCloseButton=jsx5("button",{type:"button",onClick:onClose,className:"relative h-10 w-10 flex items-center justify-center rounded-full text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors before:absolute before:-inset-0.5 before:content-['']","aria-label":closeLabel,children:jsx5(X,{className:"h-5 w-5"})});const floatingCloseButton=jsx5("button",{type:"button",onClick:onClose,className:"absolute right-2 top-2 z-10 h-9 w-9 flex items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-sm hover:bg-black/60 transition-colors before:absolute before:-inset-1 before:content-['']","aria-label":closeLabel,children:jsx5(X,{className:"h-5 w-5"})});return createPortal(jsxs4("div",{className:cn("pointer-events-auto fixed inset-0 flex items-end justify-center",isSide?"md:items-stretch md:justify-end":"md:items-center md:p-4",desktopZIndexClassName,drawerZIndexClassName),role:"dialog","aria-modal":"true","aria-label":title,children:[jsx5("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:dismissible?onClose:void 0,"aria-hidden":"true"}),jsxs4("div",{id,ref:sheetRef,tabIndex:-1,onTouchStart,onTouchMove,onTouchEnd,className:cn("relative flex w-full flex-col overflow-hidden outline-none transition-transform duration-150 ease-out","max-h-[90dvh] rounded-t-[var(--site-radius-card)]",isSide?"animate-site-side-panel md:h-full md:max-h-full md:rounded-none md:rounded-l-[var(--site-radius-card)] md:border-y-0 md:border-r-0":"animate-site-sheet-up md:max-h-[80vh] md:rounded-[var(--site-radius-card)]",surface==="glass"?"glass-card":"border border-zinc-200/50 bg-white shadow-2xl shadow-black/20 dark:border-zinc-700/50 dark:bg-zinc-900 dark:shadow-black/40","max-md:max-w-none",maxWidthClassName),children:[jsxs4("div",{ref:dragZoneRef,className:"flex shrink-0 flex-col",children:[dismissible&&jsx5("button",{type:"button",onClick:onClose,className:"mx-auto mt-1.5 mb-0.5 flex h-4 w-14 shrink-0 items-center justify-center md:hidden","aria-label":closeLabel,children:jsx5("span",{className:"h-1 w-full rounded-full bg-zinc-400 dark:bg-zinc-500"})}),showHeader?jsxs4("div",{className:"flex flex-shrink-0 items-center justify-between border-b border-zinc-200/50 px-4 py-2 dark:border-zinc-700/50",children:[headerSlot??jsx5("h2",{className:"text-lg font-semibold text-zinc-900 dark:text-zinc-50",children:title}),headerSlot&&jsx5("h2",{className:"sr-only",children:title}),dismissible&&headerCloseButton]}):dismissible&&floatingCloseButton]}),subheader&&jsx5("div",{ref:subheaderRef,className:"shrink-0",children:subheader}),jsx5("div",{ref:bodyRef,className:cn("min-h-0 flex-1 overflow-y-auto overscroll-contain kano-scrollbar",showHeader?"p-4":"p-0",bodyClassName),children}),footer&&jsx5("div",{className:cn("flex-shrink-0 border-t border-zinc-200/50 p-4 dark:border-zinc-700/50",footerClassName),children:footer})]})]}),portalTarget)}import*as React2 from"react";import*as React from"react";import{Fragment as Fragment2,jsx as jsx6}from"react/jsx-runtime";var REACT_LAZY_TYPE=Symbol.for("react.lazy");var use=React[" use ".trim().toString()];function isPromiseLike(value){return typeof value==="object"&&value!==null&&"then"in value}function isLazyComponent(element){return element!=null&&typeof element==="object"&&"$$typeof"in element&&element.$$typeof===REACT_LAZY_TYPE&&"_payload"in element&&isPromiseLike(element._payload)}function createSlot(ownerName){const SlotClone=createSlotClone(ownerName);const Slot2=React.forwardRef((props,forwardedRef)=>{let{children,...slotProps}=props;if(isLazyComponent(children)&&typeof use==="function"){children=use(children._payload)}const childrenArray=React.Children.toArray(children);const slottable=childrenArray.find(isSlottable);if(slottable){const newElement=slottable.props.children;const newChildren=childrenArray.map(child=>{if(child===slottable){if(React.Children.count(newElement)>1)return React.Children.only(null);return React.isValidElement(newElement)?newElement.props.children:null}else{return child}});return jsx6(SlotClone,{...slotProps,ref:forwardedRef,children:React.isValidElement(newElement)?React.cloneElement(newElement,void 0,newChildren):null})}return jsx6(SlotClone,{...slotProps,ref:forwardedRef,children})});Slot2.displayName=`${ownerName}.Slot`;return Slot2}var Slot=createSlot("Slot");function createSlotClone(ownerName){const SlotClone=React.forwardRef((props,forwardedRef)=>{let{children,...slotProps}=props;if(isLazyComponent(children)&&typeof use==="function"){children=use(children._payload)}if(React.isValidElement(children)){const childrenRef=getElementRef(children);const props2=mergeProps(slotProps,children.props);if(children.type!==React.Fragment){props2.ref=forwardedRef?composeRefs(forwardedRef,childrenRef):childrenRef}return React.cloneElement(children,props2)}return React.Children.count(children)>1?React.Children.only(null):null});SlotClone.displayName=`${ownerName}.SlotClone`;return SlotClone}var SLOTTABLE_IDENTIFIER=Symbol("radix.slottable");function isSlottable(child){return React.isValidElement(child)&&typeof child.type==="function"&&"__radixId"in child.type&&child.type.__radixId===SLOTTABLE_IDENTIFIER}function mergeProps(slotProps,childProps){const overrideProps={...childProps};for(const propName in childProps){const slotPropValue=slotProps[propName];const childPropValue=childProps[propName];const isHandler=/^on[A-Z]/.test(propName);if(isHandler){if(slotPropValue&&childPropValue){overrideProps[propName]=(...args)=>{const result=childPropValue(...args);slotPropValue(...args);return result}}else if(slotPropValue){overrideProps[propName]=slotPropValue}}else if(propName==="style"){overrideProps[propName]={...slotPropValue,...childPropValue}}else if(propName==="className"){overrideProps[propName]=[slotPropValue,childPropValue].filter(Boolean).join(" ")}}return{...slotProps,...overrideProps}}function getElementRef(element){let getter=Object.getOwnPropertyDescriptor(element.props,"ref")?.get;let mayWarn=getter&&"isReactWarning"in getter&&getter.isReactWarning;if(mayWarn){return element.ref}getter=Object.getOwnPropertyDescriptor(element,"ref")?.get;mayWarn=getter&&"isReactWarning"in getter&&getter.isReactWarning;if(mayWarn){return element.props.ref}return element.props.ref||element.ref}var falsyToString=value=>typeof value==="boolean"?`${value}`:value===0?"0":value;var cx=clsx;var cva=(base,config)=>props=>{var _config_compoundVariants;if((config===null||config===void 0?void 0:config.variants)==null)return cx(base,props===null||props===void 0?void 0:props.class,props===null||props===void 0?void 0:props.className);const{variants,defaultVariants}=config;const getVariantClassNames=Object.keys(variants).map(variant=>{const variantProp=props===null||props===void 0?void 0:props[variant];const defaultVariantProp=defaultVariants===null||defaultVariants===void 0?void 0:defaultVariants[variant];if(variantProp===null)return null;const variantKey=falsyToString(variantProp)||falsyToString(defaultVariantProp);return variants[variant][variantKey]});const propsWithoutUndefined=props&&Object.entries(props).reduce((acc,param)=>{let[key,value]=param;if(value===void 0){return acc}acc[key]=value;return acc},{});const getCompoundVariantClassNames=config===null||config===void 0?void 0:(_config_compoundVariants=config.compoundVariants)===null||_config_compoundVariants===void 0?void 0:_config_compoundVariants.reduce((acc,param)=>{let{class:cvClass,className:cvClassName,...compoundVariantOptions}=param;return Object.entries(compoundVariantOptions).every(param2=>{let[key,value]=param2;return Array.isArray(value)?value.includes({...defaultVariants,...propsWithoutUndefined}[key]):{...defaultVariants,...propsWithoutUndefined}[key]===value})?[...acc,cvClass,cvClassName]:acc},[]);return cx(base,getVariantClassNames,getCompoundVariantClassNames,props===null||props===void 0?void 0:props.class,props===null||props===void 0?void 0:props.className)};import{jsx as jsx7}from"react/jsx-runtime";var buttonVariants=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-200 hover:scale-[1.02] hover:shadow-md active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 disabled:hover:scale-100 disabled:hover:shadow-none [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-11 rounded-[var(--site-radius-button)] px-4 py-2",sm:"h-9 rounded-[var(--site-radius-button)] px-3",lg:"h-14 rounded-[var(--site-radius-button)] px-8",icon:"h-11 w-11 rounded-full"}},defaultVariants:{variant:"default",size:"default"}});var Button=React2.forwardRef(({className,variant,size,asChild=false,...props},ref)=>{const Comp=asChild?Slot:"button";return jsx7(Comp,{className:cn(buttonVariants({variant,size,className})),ref,...props})});Button.displayName="Button";import{jsx as jsx8,jsxs as jsxs5}from"react/jsx-runtime";var CustomerAccountPanel2=onDemand(()=>import("./CustomerAccountPanel-LK4GSYYU.js").then(m=>m.CustomerAccountPanel),()=>jsx8("div",{className:"flex min-h-40 items-center justify-center","aria-busy":"true",children:jsx8(LoaderCircle,{className:"h-5 w-5 animate-spin opacity-50"})}));function hasCustomerSessionHint(){if(typeof document==="undefined")return false;return document.cookie.split(";").some(part=>part.trim().startsWith(`${CUSTOMER_SESSION_HINT_COOKIE_NAME}=`))}function clearCustomerSessionHint(){if(typeof document==="undefined")return;document.cookie=`${CUSTOMER_SESSION_HINT_COOKIE_NAME}=; Max-Age=0; Path=/; SameSite=Lax`}var overviewCacheKey=siteId=>`knr_customer_overview:${siteId}`;function sessionFingerprint(sessionKey){if(sessionKey===null)return"";let hash=2166136261;for(let index=0;index<sessionKey.length;index+=1){hash^=sessionKey.charCodeAt(index);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)}function readCachedOverview(siteId,sessionKey){try{const raw=typeof sessionStorage==="undefined"?null:sessionStorage.getItem(overviewCacheKey(siteId));if(!raw)return null;const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||!parsed.contact||parsed.session!==sessionFingerprint(sessionKey))return null;return parsed}catch{return null}}function writeCachedOverview(siteId,overview,sessionKey){try{if(typeof sessionStorage==="undefined")return;if(overview){const{id,email,name}=overview.contact;const cached={session:sessionFingerprint(sessionKey),contact:{id,email,name},sections:overview.sections,landing:overview.landing};sessionStorage.setItem(overviewCacheKey(siteId),JSON.stringify(cached))}else sessionStorage.removeItem(overviewCacheKey(siteId))}catch{}}var SESSION_RETRY_DELAYS_MS=[1e3,3e3,1e4];var CustomerAuthContext=createContext(null);function CustomerAuthProvider({config,children}){const[user,setUser]=useState(null);const[sections,setSections]=useState([]);const[landing,setLanding]=useState(null);const[check,setCheck]=useState("pending");const[hinted,setHinted]=useState(false);const[panelOpen,setPanelOpen]=useState(false);const[refreshTick,setRefreshTick]=useState(0);const transport=useMemo(()=>config?.transport??createHostedCustomerAuthTransport(),[config?.transport]);const sessionHint=config?.sessionHint??hasCustomerSessionHint;const siteId=config?.siteId??null;const sessionKey=config?.sessionKey??null;const lastCheckRef=useRef3(null);const sessionKeyRef=useRef3(sessionKey);sessionKeyRef.current=sessionKey;const applySession=useCallback2(overview=>{if(siteId)writeCachedOverview(siteId,overview,sessionKeyRef.current);setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done");if(!overview)setRefreshTick(tick=>tick+1)},[siteId]);const retrySession=useCallback2(()=>{setCheck("pending");setRefreshTick(tick=>tick+1)},[]);useEffect3(()=>{if(siteId===null)return;const previous=lastCheckRef.current;lastCheckRef.current={siteId,sessionKey};if(!sessionHint()){writeCachedOverview(siteId,null,sessionKey);setHinted(false);setUser(null);setSections([]);setLanding(null);setCheck("done");return}setHinted(true);if(previous===null||previous.siteId!==siteId||previous.sessionKey!==sessionKey)setCheck("pending");const cached=readCachedOverview(siteId,sessionKey);if(cached){setUser(cached.contact);setSections(cached.sections??[]);setLanding(cached.landing??null)}else if(previous!==null&&(previous.siteId!==siteId||previous.sessionKey!==null&&previous.sessionKey!==sessionKey)){setUser(null);setSections([]);setLanding(null)}let cancelled=false;let retryTimer=null;const ask=attempt=>{transport.session().then(overview=>{if(cancelled)return;writeCachedOverview(siteId,overview,sessionKey);if(!overview)clearCustomerSessionHint();setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done")}).catch(()=>{if(cancelled)return;const delay=SESSION_RETRY_DELAYS_MS[attempt];if(delay!==void 0){retryTimer=setTimeout(()=>ask(attempt+1),delay);return}setCheck(current=>current==="pending"?"failed":current)})};ask(0);return()=>{cancelled=true;if(retryTimer!==null)clearTimeout(retryTimer)}},[siteId,sessionKey,transport,refreshTick]);useEffect3(()=>{if(!config||typeof document==="undefined")return;const sync=()=>{if(document.visibilityState!=="visible")return;const hint=sessionHint();if(hint&&user===null)setRefreshTick(tick=>tick+1);if(!hint&&user!==null){writeCachedOverview(config.siteId,null,sessionKey);setUser(null);setSections([]);setLanding(null);setCheck("done")}};document.addEventListener("visibilitychange",sync);window.addEventListener("focus",sync);return()=>{document.removeEventListener("visibilitychange",sync);window.removeEventListener("focus",sync)}},[config,user]);const refresh=useCallback2(async()=>{let overview;try{overview=await transport.session()}catch{setCheck("done");return}if(siteId)writeCachedOverview(siteId,overview,sessionKeyRef.current);setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done")},[transport,siteId]);const signOut=useCallback2(async()=>{await transport.signOut();if(siteId)writeCachedOverview(siteId,null,sessionKeyRef.current);clearCustomerSessionHint();setUser(null);setSections([]);setLanding(null);setCheck("done")},[transport,siteId]);const openPanel=useCallback2(()=>setPanelOpen(true),[]);const closePanel=useCallback2(()=>setPanelOpen(false),[]);const value=useMemo(()=>config?{siteId:config.siteId,siteName:config.siteName,locale:config.locale,siteLocale:config.siteLocale,accountBaseUrl:config.accountBaseUrl,showNavEntry:config.showNavEntry,allowSignup:config.allowSignup,methods:config.methods,messages:config.messages,transport,user,sections,landing,checked:check!=="pending",pending:hinted&&check==="pending"&&user===null,sessionUnavailable:hinted&&check==="failed"&&user===null,retrySession,applySession,refresh,signOut,panelOpen,openPanel,closePanel}:null,[config,transport,user,sections,landing,check,hinted,applySession,retrySession,refresh,signOut,panelOpen,openPanel,closePanel]);return jsxs5(CustomerAuthContext.Provider,{value,children:[children,value?jsx8(CustomerAccountModal,{auth:value}):null]})}function useCustomerAuth(){return useContext(CustomerAuthContext)}function CustomerAccountModal({auth}){const{ui}=useSiteLabels();const title=auth.user||auth.pending?ui.myAccount:fillLabel(auth.messages.signInTitle,{siteName:auth.siteName});return jsx8(SiteResponsiveModal,{id:"customer-account-panel",open:auth.panelOpen,onClose:auth.closePanel,title,closeLabel:ui.close,maxWidthClassName:"max-w-md",surface:"solid",bodyClassName:"p-5 sm:p-6",children:jsx8(CustomerAccountPanel2,{variant:"panel",auth,onNavigate:auth.closePanel})})}import{Fragment as Fragment3,jsx as jsx9,jsxs as jsxs6}from"react/jsx-runtime";function loginReturnTo(returnTo){if(returnTo?.startsWith("/"))return returnTo;if(typeof window==="undefined")return void 0;const url=new URL(window.location.href);for(const key of["token","handoff","error","verify","email"])url.searchParams.delete(key);return`${url.pathname}${url.search}`}function failure(error){if(error instanceof KanorioApiError)return{ok:false,code:error.code??"SERVER_ERROR"};return{ok:false,code:"NETWORK_ERROR"}}var sessionRequests=new Map;function createBearerCustomerAuthTransport(params){return bearerTransport(params,false)}function bearerTransport(params,strictSession){const siteUrl=params.siteUrl.replace(/\/+$/,"");const client=createCustomerClient({siteUrl,token:params.token});const post=async(path,body)=>{try{const data=await client.post(path,{body});return{ok:true,...data}}catch(error){return failure(error)}};const get=async path=>{try{const data=await client.get(path,{});return{ok:true,...data}}catch(error){return failure(error)}};const grant=result=>{if(result.ok&&result.sessionToken)params.onToken(result.sessionToken);return result};return{altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`,challengeUrl:`${siteUrl}/api/form-protection/challenge`,requestChallenge:({email,locale,returnTo,protection})=>post("/auth/challenge",{email,locale,returnTo,...protection}),verifyCode:async({email,code})=>grant(await post("/auth/verify",{method:"code",email,code,channel:"bearer"})),verifyToken:async({method,token})=>grant(await post("/auth/verify",{method,token,channel:"bearer"})),startOauth:({method,returnTo,locale})=>post("/auth/oauth/start",{method,returnTo,locale}),passkeyLoginOptions:()=>post("/auth/passkey/options",{origin:typeof window==="undefined"?void 0:window.location.origin}),passkeyLoginVerify:async input=>grant(await post("/auth/passkey/verify",{...input,channel:"bearer"})),listPasskeys:()=>get("/passkeys"),passkeyRegisterOptions:()=>post("/passkeys/register/options",{origin:typeof window==="undefined"?void 0:window.location.origin}),passkeyRegister:input=>post("/passkeys/register",input),session:()=>{const token=params.token();if(!token)return Promise.resolve(null);const key=`${siteUrl}
|
|
2
|
+
${token}`;const running=sessionRequests.get(key);const request=running??createCustomerClient({siteUrl,token}).get("/me").then(data=>{const overview=data;if(!overview.contact)return null;const{id,email,name}=overview.contact;return{contact:{id,email,name},sections:overview.sections??[],landing:overview.landing??"/account"}},error=>{if(error instanceof KanorioApiError&&error.status===401)return null;throw error});if(!running){sessionRequests.set(key,request);void request.then(()=>sessionRequests.delete(key),()=>sessionRequests.delete(key))}return strictSession?request:request.catch(()=>null)},signOut:async()=>{try{await client.delete("/session",{body:{mode:"current"}})}catch{}params.onToken(null)}}}var hostedExchanges=new Map;function hostedExchange(siteUrl,clientId){const key=`${siteUrl}|${clientId}`;const running=hostedExchanges.get(key);if(running)return running;if(!new URLSearchParams(window.location.search).has("code"))return null;const exchange={result:completeHostedCustomerLogin({siteUrl,clientId}),signedIn:false};hostedExchanges.set(key,exchange);void exchange.result.then(()=>hostedExchanges.delete(key),()=>hostedExchanges.delete(key));return exchange}function KanorioAccount({siteName,mode="direct",redirectUri,returnTo,onLogin,onLogout,renderSignedIn,className,...config}){const ctx=useElementContext(config,{needsSite:true});const site=ctx.site;const[redirectState,setRedirectState]=useState2({busy:false,error:null});const siteId=site?.id??"";const setToken=ctx.setToken;useEffect4(()=>{if(mode!=="redirect"||!siteId||typeof window==="undefined")return;const exchange=hostedExchange(ctx.siteUrl,siteId);if(!exchange)return;let cancelled=false;setRedirectState({busy:true,error:null});exchange.result.then(grant=>{if(cancelled)return;if(grant&&!exchange.signedIn){exchange.signedIn=true;setToken(grant.accessToken);const session={token:grant.accessToken,contactId:grant.contactId,expiresAt:grant.expiresAt};onLogin?.(session);window.dispatchEvent(new CustomEvent(LOGIN_EVENT,{detail:session}))}setRedirectState({busy:false,error:null})}).catch(error=>{if(cancelled)return;setRedirectState({busy:false,error:error instanceof KanorioApiError?error.code:"NETWORK_ERROR"})});return()=>{cancelled=true}},[mode,siteId,ctx.siteUrl,setToken]);const[initial]=useState2(()=>{if(typeof window==="undefined")return{};const params=new URLSearchParams(window.location.search);return{email:params.get("email")??void 0,token:params.get("token")??void 0,handoff:params.get("handoff")??void 0,verify:params.get("verify")==="1",error:params.get("error")??void 0}});const tokenRef=useLatest(ctx.token);const transport=useMemo2(()=>bearerTransport({siteUrl:ctx.siteUrl,token:()=>tokenRef.current,onToken:token=>{tokenRef.current=token;setToken(token)}},true),[ctx.siteUrl,setToken,tokenRef]);const resolvedSiteName=siteName??site?.brand?.displayName??site?.name??"";const authConfig=useMemo2(()=>site&&ctx.messages?{siteId:site.id,siteName:resolvedSiteName,locale:ctx.locale,siteLocale:site.locale??ctx.locale,accountBaseUrl:ctx.siteUrl,showNavEntry:site.customerAccess?.showNavEntry===true,allowSignup:site.customerAccess?.allowSignup===true,methods:normalizeCustomerAuthMethods(site.customerAccess?.methods),messages:ctx.messages.account,transport,sessionHint:()=>Boolean(tokenRef.current),sessionKey:ctx.token}:null,[site,ctx.messages,ctx.locale,ctx.siteUrl,ctx.token,resolvedSiteName,transport,tokenRef]);if(!ctx.messages)return jsx9(ElementsRoot,{context:ctx,className,loading:true});return jsx9(ElementsRoot,{context:ctx,className,children:jsx9(BotProtectionConfigProvider,{value:parsePublicBotProtectionConfig(site?.botProtection),children:jsx9(CustomerAuthProvider,{config:authConfig,children:mode==="redirect"?jsx9(RedirectBody,{siteUrl:ctx.siteUrl,siteId,siteName:resolvedSiteName,redirectUri,busy:redirectState.busy,error:redirectState.error,messages:ctx.messages.account,onLogout,renderSignedIn}):jsx9(AccountBody,{returnTo:loginReturnTo(returnTo),initial,onLogin,onLogout,renderSignedIn})})})})}function RedirectBody({siteUrl,siteId,siteName,redirectUri,busy,error,messages,onLogout,renderSignedIn}){const auth=useCustomerAuth();const[starting,setStarting]=useState2(false);if(!auth)return jsx9("div",{"aria-busy":"true"});if(auth.user){if(renderSignedIn)return jsx9(Fragment3,{children:renderSignedIn(()=>void auth.signOut().then(()=>emitLogout(onLogout)))});return jsx9("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:jsx9(CustomerAccountPanel,{variant:"panel",auth,onSignedOut:()=>emitLogout(onLogout)})})}const start=async()=>{if(!siteId)return;setStarting(true);try{await startHostedCustomerLogin({siteUrl,clientId:siteId,redirectUri})}catch{setStarting(false)}};if(auth.sessionUnavailable){return jsxs6("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[jsx9("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:messages.errorServiceUnavailable}),jsx9("button",{type:"button",className:customerButtonClass({block:true}),onClick:auth.retrySession,children:messages.contentRetry})]})}return jsxs6("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[error?jsx9("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:messages.errorGeneric}):null,jsx9("button",{type:"button",className:customerButtonClass({block:true}),onClick:()=>void start(),disabled:starting||busy||auth.pending||!siteId,"aria-busy":busy||auth.pending||void 0,children:busy||auth.pending?messages.sessionChecking:fillLabel(messages.signInTitle,{siteName})})]})}function AccountBody({returnTo,initial,onLogin,onLogout,renderSignedIn}){const auth=useCustomerAuth();if(!auth)return jsx9("div",{"aria-busy":"true"});if(auth.user&&renderSignedIn){return jsx9(Fragment3,{children:renderSignedIn(()=>void auth.signOut().then(()=>emitLogout(onLogout)))})}return jsx9("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:jsx9(CustomerAccountPanel,{variant:"panel",auth,initial,returnTo,onSignedIn:grant=>{if(!grant.sessionToken)return;const session={token:grant.sessionToken,contactId:grant.contactId??"",expiresAt:grant.expiresAt??""};onLogin?.(session);window.dispatchEvent(new CustomEvent(LOGIN_EVENT,{detail:session}))},onSignedOut:()=>emitLogout(onLogout)})})}function emitLogout(onLogout){onLogout?.();window.dispatchEvent(new CustomEvent(LOGOUT_EVENT))}function useLatest(value){const ref=useState2(()=>({current:value}))[0];useEffect4(()=>{ref.current=value},[ref,value]);ref.current=value;return ref}export{createBearerCustomerAuthTransport,KanorioAccount};
|
|
3
|
+
//# sourceMappingURL=chunk-FXDWRWZ3.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as a,d as l}from"./chunk-XJPS3G7J.js";var c="kanorio.customer.pkce";function h(e){return{accessToken:e.access_token,tokenType:e.token_type,expiresIn:e.expires_in,expiresAt:e.expires_at,refreshToken:e.refresh_token,refreshTokenExpiresIn:e.refresh_token_expires_in,contactId:e.contactId}}function g(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function d(e=32){let t=new Uint8Array(e);return crypto.getRandomValues(t),g(t)}async function y(){let e=d(32),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return{verifier:e,challenge:g(new Uint8Array(t)),method:"S256"}}function m(e){let t=e.siteUrl.replace(/\/+$/,""),r=new URL(`${t}${e.localeRoot??""}/account/login`);return r.searchParams.set("client_id",e.clientId),r.searchParams.set("redirect_uri",e.redirectUri),r.searchParams.set("code_challenge",e.codeChallenge),r.searchParams.set("code_challenge_method","S256"),r.searchParams.set("state",e.state),r.toString()}function E(){let e=new URL(window.location.href);return e.searchParams.delete("code"),e.searchParams.delete("state"),e.hash="",e.toString()}async function f(e){let t=e.storage??sessionStorage,r=e.redirectUri??E(),n=await y(),i=d(16);t.setItem(c,JSON.stringify({verifier:n.verifier,state:i,redirectUri:r}));let s=m({siteUrl:e.siteUrl,clientId:e.clientId,redirectUri:r,codeChallenge:n.challenge,state:i,localeRoot:e.localeRoot});(e.navigate??(o=>window.location.assign(o)))(s)}async function _(e){let t=new URL(window.location.href),r=t.searchParams.get("code"),n=t.searchParams.get("state");if(!r)return null;let i=e.storage??sessionStorage,s=i.getItem(c);i.removeItem(c);let o=s?JSON.parse(s):null;if(!o||o.state!==n)throw new Error("Hosted sign-in state mismatch; start the sign-in again.");e.cleanUrl!==!1&&(t.searchParams.delete("code"),t.searchParams.delete("state"),window.history.replaceState(window.history.state,"",t.toString()));let p=await u({siteUrl:e.siteUrl,clientId:e.clientId,code:r,codeVerifier:o.verifier,redirectUri:o.redirectUri});return e.storeToken!==!1&&l(p.accessToken),p}async function u(e){let r=await a({siteUrl:e.siteUrl,serverKey:e.serverKey,visitorIp:e.visitorIp}).post("/auth/oauth2/token",{body:{grant_type:"authorization_code",code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri,client_id:e.clientId}});return h(r)}export{f as a,_ as b};
|
|
2
|
+
//# sourceMappingURL=chunk-I6KLZIN6.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as ot,b as st,c as at,d as lt,e as ct,f as ut,g as z,h as mt,j as dt,l as pt,m as j,o as gt,p as ft,q as xt,r as ht}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as ot,b as st,c as at,d as lt,e as ct,f as ut,g as z,h as mt,j as dt,l as pt,m as j,o as gt,p as ft,q as xt,r as ht}from"./chunk-65RP744E.js";import{ba as f}from"./chunk-S2NFWI7C.js";import{a as k}from"./chunk-OU4IOHLN.js";import{a as rt}from"./chunk-6LGTFWQS.js";import{c as T}from"./chunk-CDG7S4P5.js";var x=T(rt());var Mt=T(k()),Wt={},G=(0,x.createContext)(Wt);function Kt({facts:n,children:t}){let i=(0,x.useContext)(G),r=(0,x.useMemo)(()=>!n||Object.keys(n).length===0?i:Object.keys(i).length===0?n:{...i,...n},[i,n]);return(0,Mt.jsx)(G.Provider,{value:r,children:t})}function Tt(n){return dt((0,x.useContext)(G),n)}var W=T(rt());var _t=125;function bt(n,t,i,r){let s=r&&r.length>0?r[0].trim():null,m=t?.trim()||"",l=i?.trim()||"";return n==="logo"?m||l||"logo":m?s&&!m.includes(s)?`${s} ${m}`:m:l?s&&!l.includes(s)?`${s} ${l}`:l:s||"image"}function Ft(n,t,i,r){return`${bt(n,i,void 0,r)} (${t+1})`}function St(n){let{explicitAlt:t,assetAltText:i,type:r,name:s,fallback:m,index:l,seoKeywords:A,websiteName:X}=n,p=M=>M.length<=_t?M:M.slice(0,_t);if(t&&t.trim().length>0)return p(t.trim());if(r!=="logo"&&i&&i.trim().length>0)return p(i.trim());let a=s?.trim()||m||X?.trim(),d;return l!=null?d=Ft(r,l,a||void 0,A):d=bt(r,a||void 0,void 0,A),p(d)}var o=T(k());function Ht(n){return n.includes("imagedelivery.net")||n.includes("/cdn-cgi/imagedelivery/")}function Rt(n){let t=at(n)??{x:0,y:0,w:1,h:1},i=r=>`${Math.round(r*1e4)/100}%`;return{left:i(-t.x/t.w),top:i(-t.y/t.h),width:i(1/t.w),height:i(1/t.h)}}var Ut=[{device:"mobile",suffix:"m",position:{crop:"absolute",flow:"relative"}},{device:"tablet",suffix:"t",position:{crop:"md:absolute",flow:"md:relative"}},{device:"desktop",suffix:"d",position:{crop:"lg:absolute",flow:"lg:relative"}}],zt="max-h-none max-w-none left-[var(--crop-l-m)] top-[var(--crop-t-m)] w-[var(--crop-w-m)] h-[var(--crop-h-m)] md:left-[var(--crop-l-t)] md:top-[var(--crop-t-t)] md:w-[var(--crop-w-t)] md:h-[var(--crop-h-t)] lg:left-[var(--crop-l-d)] lg:top-[var(--crop-t-d)] lg:w-[var(--crop-w-d)] lg:h-[var(--crop-h-d)]",jt=(0,W.forwardRef)(function({src:t,alt:i,altType:r,altName:s,explicitAlt:m,index:l,seoKeywords:A,websiteName:X,useCase:p="general",width:a,height:d,fit:M,responsive:Ct=!1,sizes:_,fill:c=!1,objectFit:F="cover",framing:g,deviceRatios:u,tabletInherits:v="desktop",priority:K=!1,containBackdrop:Et,className:b,style:S,onError:Pt,...D},It){let[At,vt]=(0,W.useState)(null),w=Tt({url:t}),C=c?u&&ot(u)?st(u):"absolute inset-0 h-full w-full":void 0;if(!t||At===t)return(0,o.jsx)("span",{"aria-hidden":"true",className:f("block bg-zinc-100 dark:bg-zinc-800",C,b),style:{aspectRatio:a&&d?`${a} / ${d}`:"4 / 3",...S}});let Dt=i??(r?St({explicitAlt:m,assetAltText:w?.altText,type:r,name:s,index:l,seoKeywords:A,websiteName:X}):""),B=!Ht(t),N=pt(t),E=g?.fitMode==="contain",Y=E?"contain":F,q=E?"scale-down":M,h=E?null:ct(g),H=E?"single":ft({src:t,framing:g,deviceRatios:u,tabletInherits:v}),O={ref:It,alt:Dt,loading:K?"eager":"lazy",fetchPriority:K?"high":"auto",decoding:"async",draggable:!1,onError:e=>{vt(t),Pt?.(e)}};if(H==="picture"&&u){let e=ht({src:t,useCase:p,ratios:u,framing:g,tabletInherits:v,sizes:_?{desktop:_,tablet:_,mobile:_}:void 0,maxWidth:a});if(e)return(0,o.jsxs)("picture",{className:f(c&&f("block",C)),children:[(0,o.jsx)("source",{media:e.mobile.media,srcSet:e.mobile.srcSet,sizes:e.mobile.sizes}),e.tablet?(0,o.jsx)("source",{media:e.tablet.media,srcSet:e.tablet.srcSet,sizes:e.tablet.sizes}):null,(0,o.jsx)("img",{...O,src:e.desktop.src,srcSet:e.desktop.srcSet,sizes:e.desktop.sizes,width:c?void 0:e.desktop.width,height:c?void 0:e.desktop.height??void 0,className:f(C,b),style:{objectFit:F,...S},...D})]})}if(H==="single-trim"&&u?.desktop){let e=xt({src:t,useCase:p,width:a,ratio:u.desktop,framing:g,tabletInherits:v});return(0,o.jsx)("img",{...O,src:e.src,width:c?void 0:e.width,height:c?void 0:e.height,className:f(C,b),style:{objectFit:F,...S},...D})}if(H==="css-fallback"&&c&&u){let e={},Q=[],tt=null;for(let{device:et,suffix:L,position:kt}of Ut){let nt=u[et],I={left:"0%",top:"0%",width:"100%",height:"auto"},$="flow";if(nt){$="crop";let it=ut({framing:g,device:et,targetRatio:nt,tabletInherits:v,source:g?.source??null});I=it.derived?{left:"0%",top:"0%",width:"100%",height:"100%"}:Rt(it.rect)}e[`--crop-l-${L}`]=I.left,e[`--crop-t-${L}`]=I.top,e[`--crop-w-${L}`]=I.width,e[`--crop-h-${L}`]=I.height,$!==tt&&Q.push(kt[$]),tt=$}let $t=N?t:j(t,{useCase:p,...a!=null?{width:a}:{}});return(0,o.jsx)("img",{...O,src:$t,referrerPolicy:B?"no-referrer":void 0,className:f(Q,zt,b),style:{...e,objectFit:"cover",...h?{objectPosition:z(h)}:{},...S},...D})}let P={useCase:p};a!=null&&(P.width=a),d!=null&&(P.height=d),q!=null&&(P.fit=q),h&&(P.focus=h);let R=Ct&&!N?gt(t):null,wt=N?t:R?.src??j(t,P),Nt=R?.srcSet,Ot=_??R?.sizes,Z=Et??(c&&Y==="contain"||E),y=mt(w?.edgeColor),yt=lt(g?.padColor),U=Z?yt??(y&&y!=="transparent"?y:void 0):void 0,V=Z&&!U&&!y&&w?.lqip&&!N?w.lqip:void 0,Lt={objectFit:Y,...h?{objectPosition:z(h)}:{},...U?{backgroundColor:U}:{},...S},J=(0,o.jsx)("img",{...O,src:wt,srcSet:Nt,sizes:Ot,width:c?void 0:a,height:c?void 0:d,referrerPolicy:B?"no-referrer":void 0,className:f(C,b),style:Lt,...D});return V?(0,o.jsxs)(o.Fragment,{children:[(0,o.jsx)("span",{"aria-hidden":"true","data-testid":"site-image-blur-backdrop",className:"pointer-events-none absolute inset-0 overflow-hidden",children:(0,o.jsx)("img",{src:V,alt:"",className:"h-full w-full scale-125 object-cover blur-xl"})}),J]}):J});jt.displayName="SiteImage";export{Kt as a,Tt as b,jt as c};
|
|
2
|
+
//# sourceMappingURL=chunk-II7PVZWZ.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{NO_HEAVY_FIELD_VALIDATORS,OTHER_OPTION_PLACEHOLDER,countAnswered,hasVisibilityRules,ownFieldValue,resolveFormPhoneCountry,resolveVisibleFieldIds,sanitizeFormSubmitResponse,validateFormAnswerWith,validateFormAnswersWith}from"./chunk-D4KDA3KL.js";import{checkFormFile,uploadFormFile}from"./chunk-QF55WZDP.js";import{FORM_ACCENT_ICON,FORM_DANGER,FORM_FG,FORM_FG_MUTED,FORM_FIELD_CLASS,FORM_FIELD_INVALID_CLASS,FORM_SUBMIT_COLORS}from"./chunk-SVWEVSYJ.js";import{FORM_REDIRECT_EXPANDED_URL_MAX,isKnownFormFieldType,parseFormRedirectUrl,resolveConsentLabel,resolveFormAvailability,resolveFormDateBound}from"./chunk-APWDEDWM.js";import{onDemand}from"./chunk-E77WGXYW.js";import{useAdoptTypedOnMount,useComposingEnterGuard,useControlRef}from"./chunk-C7HUM2EN.js";import{FORM_SUBMIT_EVENT}from"./chunk-LWKCGUHS.js";import{KanorioBotProtection}from"./chunk-VT2B53EX.js";import{BotProtectionChallenge,BotProtectionConfigProvider,BotProtectionFields,parsePublicBotProtectionConfig,useBotProtection}from"./chunk-KYXZNMNA.js";import{TONE_BG_TINT,TONE_BG_TINT_STRONG_HOVER,TONE_BORDER_STRONG,TONE_TEXT_FAINT}from"./chunk-RKEHHJDU.js";import{EMPTY_VALUE,dateTimeFormat}from"./chunk-4BEKWYEW.js";import{clampText}from"./chunk-O2SYHUQF.js";import{CircleCheck,Heart,LoaderCircle,Star,ThumbsUp}from"./chunk-33AQQY6T.js";import{cn}from"./chunk-VUTODQFX.js";import{ElementsRoot}from"./chunk-7UCZ56EJ.js";import{loadSiteMeta,useElementContext}from"./chunk-73S6VKNV.js";import{useEffect,useMemo,useState}from"react";var SITE_RETRY_DELAYS_MS=[1e3,3e3,1e4];function useDefinitionByContent(definition){const content=definition?JSON.stringify(definition):null;return useMemo(()=>definition??null,[content])}function useKanorioFormSetup(config,formId,initialDefinition,labels){const ctx=useElementContext(config,{needsSite:true});const{site,siteError,siteUrl}=ctx;const given=useDefinitionByContent(initialDefinition);const[read,setRead]=useState(null);const siteMissing=!site&&siteError;const[siteRetries,setSiteRetries]=useState({siteUrl,count:0});const retried=siteRetries.siteUrl===siteUrl?siteRetries.count:0;useEffect(()=>{if(!siteMissing)return;const delay=SITE_RETRY_DELAYS_MS[retried];if(delay===void 0)return;const timer=setTimeout(()=>{void loadSiteMeta(siteUrl).then(meta=>{if(meta===null)setSiteRetries({siteUrl,count:retried+1})})},delay);return()=>clearTimeout(timer)},[siteMissing,siteUrl,retried]);useEffect(()=>{if(given||!formId)return;let cancelled=false;fetch(`${siteUrl}/api/v1/forms/${encodeURIComponent(formId)}`).then(res=>res.ok?res.json():Promise.reject(new Error(`HTTP ${res.status}`))).then(data=>{if(cancelled)return;const resolved=data&&typeof data==="object"&&"fields"in data?data:data?.form??null;setRead({siteUrl,formId,form:resolved??null})}).catch(()=>{if(!cancelled)setRead({siteUrl,formId,form:null})});return()=>{cancelled=true}},[siteUrl,formId,given]);const current=read!==null&&read.siteUrl===siteUrl&&read.formId===formId?read:null;const form=given??current?.form??null;const siteText=ctx.messages?.form;const mergedLabels=useMemo(()=>siteText||labels?{...siteText??{},...labels??{}}:void 0,[siteText,labels]);return{ctx,form,loadFailed:!given&¤t!==null&¤t.form===null,siteUnavailable:Boolean(siteMissing)&&retried>=SITE_RETRY_DELAYS_MS.length,textUnavailable:ctx.messages===null&&ctx.messagesError,mergedLabels,ready:Boolean(form&&ctx.messages&&site)}}import{useContext as useContext2}from"react";import{useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";function SiteChoiceInput({type,className,...props}){const inputRef=useRef(null);useAdoptTypedOnMount(inputRef,props.onChange);return jsxs("span",{className:cn("relative inline-grid h-[18px] w-[18px] shrink-0 place-items-center",className),children:[jsx("input",{ref:inputRef,type,className:cn("peer col-start-1 row-start-1 m-0 h-[18px] w-[18px] cursor-pointer appearance-none border-2 transition-colors","bg-transparent "+TONE_BORDER_STRONG,"checked:border-[var(--site-cta-brand-bg,var(--brand-color,#FF5733))] checked:bg-[var(--site-cta-brand-bg,var(--brand-color,#FF5733))]","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))]","disabled:cursor-not-allowed disabled:opacity-50",type==="radio"?"rounded-full":"rounded-[4px]"),...props}),type==="checkbox"?jsx("svg",{"aria-hidden":true,viewBox:"0 0 16 16",fill:"none",className:"pointer-events-none col-start-1 row-start-1 h-3.5 w-3.5 text-[var(--site-cta-brand-fg,var(--brand-foreground,#ffffff))] opacity-0 peer-checked:opacity-100 peer-disabled:peer-checked:opacity-50",children:jsx("path",{d:"M3.5 8.5l3 3 6-6.5",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"})}):jsx("span",{"aria-hidden":true,className:"pointer-events-none col-start-1 row-start-1 h-2 w-2 rounded-full bg-[var(--site-cta-brand-fg,var(--brand-foreground,#ffffff))] opacity-0 peer-checked:opacity-100 peer-disabled:peer-checked:opacity-50"})]})}var MAX_COLUMNS_FALLBACK={mobile:1,tablet:2,desktop:2};var GRID_COLS={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6"};var SM_GRID_COLS={1:"sm:grid-cols-1",2:"sm:grid-cols-2",3:"sm:grid-cols-3",4:"sm:grid-cols-4",5:"sm:grid-cols-5",6:"sm:grid-cols-6"};var MD_GRID_COLS={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4",5:"md:grid-cols-5",6:"md:grid-cols-6"};function clampColumn(value){const n=Math.max(1,Math.min(6,Math.round(value)));return n}function getGridColumnsClass(maxColumns,itemCount){const resolve=raw=>{const capped=clampColumn(raw);if(itemCount==null)return capped;return clampColumn(Math.min(capped,Math.max(1,itemCount)))};const mobile=resolve(maxColumns?.mobile??MAX_COLUMNS_FALLBACK.mobile);const tablet=resolve(maxColumns?.tablet??MAX_COLUMNS_FALLBACK.tablet);const desktop=resolve(maxColumns?.desktop??MAX_COLUMNS_FALLBACK.desktop);return`${GRID_COLS[mobile]} ${SM_GRID_COLS[tablet]} ${MD_GRID_COLS[desktop]}`}import{createContext}from"react";var FormFieldComponentsContext=createContext(null);var FormFieldUnavailableLabelContext=createContext("");import{useContext}from"react";import{jsx as jsx2,jsxs as jsxs2}from"react/jsx-runtime";function FieldLoading({failed,props}){const unavailableLabel=useContext(FormFieldUnavailableLabelContext);const{inputId}=props;return jsxs2("div",{children:[jsx2("div",{id:inputId,tabIndex:inputId?-1:void 0,className:cn("h-11 w-full",FORM_FIELD_CLASS),"aria-busy":failed?void 0:"true","data-field-unavailable":failed?"":void 0}),failed&&unavailableLabel&&jsx2("p",{role:"alert",className:cn("mt-1.5 text-xs",FORM_DANGER),children:unavailableLabel})]})}var ON_DEMAND_FORM_FIELDS={PhoneInput:onDemand(()=>import("./phone-input-DOL46AIF.js").then(m=>m.PhoneInput),FieldLoading),FormAddressField:onDemand(()=>import("./FormAddressField-NH5LD6K7.js").then(m=>m.FormAddressField),FieldLoading),FormTaxIdField:onDemand(()=>import("./FormTaxIdField-XJSMW3II.js").then(m=>m.FormTaxIdField),FieldLoading),FormFileField:onDemand(()=>import("./FormFileField-5YFTKIRZ.js").then(m=>m.FormFileField),FieldLoading),FormChoiceDropdown:onDemand(()=>import("./FormChoiceDropdown-U3NIOOHG.js").then(m=>m.FormChoiceDropdown),FieldLoading)};var FORM_LIFECYCLE_EVENT="kanorio:form-event";import{useCallback,useEffect as useEffect2,useId,useMemo as useMemo2,useRef as useRef2,useState as useState2}from"react";var DATE_PRESETS={date:{dateStyle:"medium"},dateLong:{dateStyle:"long"},dateTime:{dateStyle:"medium",timeStyle:"short"},dateTimeFull:{dateStyle:"full",timeStyle:"short"},time:{timeStyle:"short"},monthDay:{month:"short",day:"numeric"},monthDayTime:{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"},monthYear:{year:"numeric",month:"long"},dateWithZone:{year:"numeric",month:"long",day:"numeric",timeZoneName:"short"}};var CALENDAR_DATE=/^\d{4}-\d{2}-\d{2}$/;function isCalendarDate(value){return typeof value==="string"&&CALENDAR_DATE.test(value)}function toDate(value){if(value==null||value==="")return null;const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?null:date}function formatCalendarDate(value,preset="date",options){if(!isCalendarDate(value))return EMPTY_VALUE;const date=new Date(`${value}T00:00:00Z`);if(Number.isNaN(date.getTime()))return EMPTY_VALUE;return dateTimeFormat(options.locale,{...DATE_PRESETS[preset],timeZone:"UTC"}).format(date)}function toCalendarDateIn(value,timeZone){const date=toDate(value);if(!date)return"";return dateTimeFormat("en-CA",{year:"numeric",month:"2-digit",day:"2-digit",timeZone}).format(date)}var MINUTE=6e4;var HOUR=60*MINUTE;var DAY=24*HOUR;var loaded={...NO_HEAVY_FIELD_VALIDATORS};var pending=new Map;var LOADERS={phone:()=>import("./forms-answers-phone-2VZ46OME.js").then(m=>void(loaded.phone=m.validatePhoneAnswer)),address:()=>import("./forms-answers-address-5MXQYIH3.js").then(m=>void(loaded.address=m.validateAddressAnswer)),tax_id:()=>import("./forms-answers-tax-id-3AYXCNP5.js").then(m=>void(loaded.tax_id=m.validateTaxIdAnswer))};function isHeavyFieldType(type){return Object.hasOwn(LOADERS,type)}function loadedFormFieldValidators(){return loaded}function canValidateFormField(type){return!isHeavyFieldType(type)||loaded[type]!==null}function hasFormFieldValidators(types){for(const type of types)if(!canValidateFormField(type))return false;return true}function loadFormFieldValidators(types){const waits=[];for(const type of new Set(types)){if(!isHeavyFieldType(type)||loaded[type])continue;let wait=pending.get(type);if(!wait){wait=LOADERS[type]().finally(()=>pending.delete(type));pending.set(type,wait)}waits.push(wait)}return Promise.all(waits).then(()=>loaded)}var PAGEVIEW_ATTRIBUTION_PARAMS=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gclid","fbclid","oppref"];var MAX_ATTRIBUTION_VALUE_LENGTH=200;var ATTRIBUTION_VALUE_ALLOWED=/[^\p{L}\p{N} _\-./:+%()&=|]/gu;function sanitizePageviewAttribution(read){const utm={};for(const key of PAGEVIEW_ATTRIBUTION_PARAMS){const raw=read(key);if(typeof raw!=="string"||!raw)continue;const val=clampText(raw.replace(ATTRIBUTION_VALUE_ALLOWED,"").trim(),MAX_ATTRIBUTION_VALUE_LENGTH);if(val)utm[key]=val}return Object.keys(utm).length>0?utm:null}var HOST_RE=/^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/;var LANDING_PATH_MAX=500;function sanitizeHost(raw){if(typeof raw!=="string")return void 0;const host=raw.trim().toLowerCase();return HOST_RE.test(host)?host:void 0}function sanitizeLandingPath(raw){if(typeof raw!=="string")return void 0;const path=raw.trim().split(/[?#]/)[0]??"";if(!path.startsWith("/")||path.startsWith("//")||/[\s\\\0]/.test(path))return void 0;return path.slice(0,LANDING_PATH_MAX)}function sanitizeFormAttribution(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;const input=raw;const utmInput=input.utm&&typeof input.utm==="object"&&!Array.isArray(input.utm)?input.utm:{};const utm=sanitizePageviewAttribution(key=>utmInput[key]);const referrerHost=sanitizeHost(input.referrerHost);const landingPath=sanitizeLandingPath(input.landingPath);const out={};if(utm)out.utm=utm;if(referrerHost)out.referrerHost=referrerHost;if(landingPath)out.landingPath=landingPath;return Object.keys(out).length>0?out:null}function buildFormAttribution(input){let utm=null;try{const params=new URLSearchParams(input.search??"");utm=sanitizePageviewAttribution(key=>params.get(key))}catch{utm=null}let referrerHost;try{referrerHost=input.referrer?new URL(input.referrer).hostname:void 0}catch{referrerHost=void 0}return sanitizeFormAttribution({utm:utm??void 0,referrerHost,landingPath:input.path??void 0})}var SESSION_ATTRIBUTION_KEY="kano-session-attribution";function readSessionAttribution(){if(typeof window==="undefined")return null;try{const raw=window.sessionStorage.getItem(SESSION_ATTRIBUTION_KEY);return raw?sanitizeFormAttribution(JSON.parse(raw)):null}catch{return null}}function currentFormAttribution(){if(typeof window==="undefined")return null;const stored=readSessionAttribution();if(stored)return stored;let referrer=null;try{referrer=document.referrer&&new URL(document.referrer).hostname.toLowerCase()!==window.location.hostname.toLowerCase()?document.referrer:null}catch{referrer=null}return buildFormAttribution({search:window.location.search,referrer,path:window.location.pathname})}var VALIDATOR_WAIT_MS=4e3;var DEFAULT_FORM_LABELS={submit:"Submit",submitting:"Submitting\u2026",success:"Thanks! We\u2019ll be in touch soon.",error:"Something went wrong. Please try again.",required:"This field is required.",invalidEmail:"Please enter a valid email address.",invalidPhone:"Please enter a valid phone number.",invalidDate:"Please enter a valid date.",invalidTime:"Please enter a valid time.",tooLong:"This answer is too long.",otherRequired:"Please specify your answer.",duplicate:"This email or phone number has already been used. Only one response per person is allowed.",temporarilyUnavailable:"This form isn\u2019t accepting responses right now. Please try again later.",rateLimited:"Too many submissions. Please wait a moment and try again.",verificationExpired:"Verification expired. Please verify again and resubmit.",outdated:"This form has changed since you opened it. Please refresh the page and submit again.",edgeChallenge:"Your browser didn\u2019t pass this site\u2019s security check. Please reload the page and submit again.",tooLarge:"Your answers are too long to send. Please shorten them and try again.",redirecting:"Taking you to the next page\u2026",invalid:"Please check this answer.",tooShort:"Please enter at least {min} characters.",invalidNumber:"Please enter a number.",notInteger:"Please enter a whole number.",numberMin:"Please enter {min} or more.",numberMax:"Please enter {max} or less.",numberRange:"Please enter a number from {min} to {max}.",invalidUrl:"Please enter a web address, such as example.com.",dateMin:"Please choose {min} or later.",dateMax:"Please choose {max} or earlier.",dateRange:"Please choose a date from {min} to {max}.",tooFewOptions:"Please select {min} or more.",tooManyOptions:"Please select no more than {max}.",selectPlaceholder:"Select an option",invalidAddress:"Please complete the address.",invalidTaxId:"Please check this tax ID.",taxIdChecking:"Looking up the public registry\u2026",taxIdRegisteredName:"Registered name: {name}",taxIdInactive:"The registry shows this business as suspended or closed. Please check the tax ID.",taxIdSource:"Source: {provider}",invalidPostalCode:"Please check the postal code.",addressCountry:"Country or region",addressRecipient:"Recipient name",addressLine1:"Address",addressLine2:"Apartment, suite, etc. (optional)",addressPostal_postal:"Postal code",addressPostal_zip:"ZIP code",addressPostal_pin:"PIN code",addressPostal_eircode:"Eircode",addressLocality_city:"City",addressLocality_district:"District",addressLocality_post_town:"Town or city",addressLocality_suburb:"Suburb",addressRegion_area:"Area",addressRegion_county:"County",addressRegion_department:"Department",addressRegion_district:"District",addressRegion_do_si:"Province or city",addressRegion_emirate:"Emirate",addressRegion_island:"Island",addressRegion_oblast:"Oblast",addressRegion_parish:"Parish",addressRegion_prefecture:"Prefecture",addressRegion_province:"Province",addressRegion_state:"State",marketingOptIn:"I\u2019d like to receive news and offers from {siteName} by email. I can unsubscribe from any email with one click.",subscribeOnSubmit:"By clicking \u201C{button}\u201D, you agree to receive news and offers from {siteName} by email. You can unsubscribe from any email with one click.",otherOption:"Other",otherPlaceholder:"Please specify",closed:"This form is closed.",notOpenYet:"This form isn\u2019t open yet.",full:"All spots have been filled. Thank you for your interest.",fileChoose:"Choose a file",fileLimitHint:"Up to {max} file(s), {size} each.",fileWaiting:"Waiting for verification\u2026",fileUploading:"Uploading\u2026",fileUploadFailed:"Upload failed. Please try again.",fileTooLarge:"This file is too large.",fileTypeNotAllowed:"This file type isn\u2019t supported.",fileUnavailable:"Attachments can\u2019t be uploaded right now. You can still submit the form.",fileRemove:"Remove",noFormSelected:"Select a form in the panel to display it here.",formNotFound:"The selected form no longer exists.",previewNotice:"Preview only \u2014 submissions are disabled here."};function fill(template,values){return template.replaceAll("{min}",String(values.min??"")).replaceAll("{max}",String(values.max??""))}function errorLabel(code,field,{labels,today,locale}){switch(code){case"invalid_email":return labels.invalidEmail;case"invalid_phone":return labels.invalidPhone;case"invalid_date":return labels.invalidDate;case"invalid_time":return labels.invalidTime;case"too_long":return labels.tooLong;case"too_short":return(field.type==="short_text"||field.type==="long_text")&&field.minLength!==void 0?fill(labels.tooShort,{min:field.minLength}):labels.invalid;case"invalid_format":return field.type==="short_text"&&field.patternMessage?field.patternMessage:labels.invalid;case"other_required":return labels.otherRequired;case"too_few_options":return field.type==="choice"&&field.minSelections!==void 0?fill(labels.tooFewOptions,{min:field.minSelections}):labels.invalid;case"too_many_options":return field.type==="choice"&&field.maxSelections!==void 0?fill(labels.tooManyOptions,{max:field.maxSelections}):labels.invalid;case"invalid_number":return labels.invalidNumber;case"not_integer":return labels.notInteger;case"out_of_range":{if(field.type!=="number")return labels.invalid;const{min,max}=field;if(min!==void 0&&max!==void 0)return fill(labels.numberRange,{min,max});if(min!==void 0)return fill(labels.numberMin,{min});if(max!==void 0)return fill(labels.numberMax,{max});return labels.invalid}case"invalid_url":return labels.invalidUrl;case"date_out_of_range":{if(field.type!=="date")return labels.invalid;const min=resolveFormDateBound(field.range?.min,today);const max=resolveFormDateBound(field.range?.max,today);const show=date=>formatCalendarDate(date,"date",{locale});if(min&&max)return fill(labels.dateRange,{min:show(min),max:show(max)});if(min)return fill(labels.dateMin,{min:show(min)});if(max)return fill(labels.dateMax,{max:show(max)});return labels.invalid}case"invalid_address":return labels.invalidAddress;case"invalid_tax_id":return labels.invalidTaxId;case"invalid_postal_code":return labels.invalidPostalCode;case"invalid":return labels.invalid;case"required":case"invalid_option":return labels.required}}function todayIn(timeZone){const now=new Date;if(timeZone){try{const date=toCalendarDateIn(now,timeZone);if(date)return date}catch{}}const pad=n=>String(n).padStart(2,"0");return`${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`}function submitErrorLabel(error,labels){switch(error){case"outdated":return labels.outdated;case"edge_challenge":return labels.edgeChallenge;case"duplicate":return labels.duplicate;case"daily_limit":case"temporarily_unavailable":return labels.temporarilyUnavailable;case"rate_limited":return labels.rateLimited;case"verification_expired":return labels.verificationExpired;case"too_large":return labels.tooLarge;case"invalid_answers":case"server_error":return labels.error}}function cssAttributeValue(value){return value.replace(/["\\]/g,"\\$&")}function dispatchLifecycle(detail){if(typeof window==="undefined")return;window.dispatchEvent(new CustomEvent(FORM_LIFECYCLE_EVENT,{detail}))}function singleLineInputProps(field,today){switch(field.type){case"short_text":return{type:"text",maxLength:field.maxLength,autoComplete:field.contactMapping==="name"?"name":void 0};case"email":return{type:"email",inputMode:"email",autoComplete:"email"};case"date":return{type:"date",min:resolveFormDateBound(field.range?.min,today)??void 0,max:resolveFormDateBound(field.range?.max,today)??void 0};case"time":return{type:"time"};case"number":return{type:"text",inputMode:field.integer&&(field.min??-1)>=0?"numeric":"decimal",autoComplete:"off"};case"url":return{type:"url",inputMode:"url",autoComplete:"url",autoCapitalize:"none",spellCheck:false,placeholder:"https://"};default:return null}}function useFormController(options){const{form,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect=true,hiddenValues:hiddenValuesProp,isEditing=false,labels:labelsProp,locale,websiteName,botProtectionConfig,botProtectionPending=false}=options;const formId=form?.id??options.formId??"";const labels=useMemo2(()=>({...DEFAULT_FORM_LABELS,...labelsProp}),[labelsProp]);const formFields=form?.fields;const fields=useMemo2(()=>(formFields??[]).filter(field=>isKnownFormFieldType(field.type)),[formFields]);const consentLabel=form?resolveConsentLabel(form.settings,labels,websiteName):null;const canSubmit=Boolean(submitUrl)&&!isEditing&&form!==null;const[serverState,setServerState]=useState2(null);const availability=serverState??(form?resolveFormAvailability(form):"open");const isClosed=availability!=="open";const[answers,setAnswers]=useState2({});const[otherText,setOtherText]=useState2({});const answersRef=useRef2(answers);const otherTextRef=useRef2(otherText);const marketingOptInRef=useRef2(false);const updateAnswers=useCallback(update=>{const next=update(answersRef.current);if(next===answersRef.current)return;answersRef.current=next;setAnswers(next)},[]);const[uploadUnavailable,setUploadUnavailable]=useState2({});const[uploadBusy,setUploadBusy]=useState2({});const anyUploadBusy=Object.values(uploadBusy).some(Boolean);const uploadsInFlightRef=useRef2({});const hasUploadInFlight=useCallback(()=>Object.values(uploadsInFlightRef.current).some(count=>count>0),[]);const consentMode=form?.settings.marketingConsent??"off";const[marketingOptIn,setMarketingOptInState]=useState2(false);const setMarketingOptIn=useCallback(checked=>{marketingOptInRef.current=checked;setMarketingOptInState(checked)},[]);const[errors,setErrors]=useState2({});const[submitError,setSubmitError]=useState2(null);const[status,setStatusState]=useState2("idle");const statusRef=useRef2("idle");const setStatus=useCallback(next=>{statusRef.current=next;setStatusState(next)},[]);const[result,setResult]=useState2(null);const[altchaKey,setAltchaKey]=useState2(0);const[redirecting,setRedirecting]=useState2(false);const declaredHiddenFields=form?.settings.hiddenFields;const hiddenFields=useMemo2(()=>declaredHiddenFields??[],[declaredHiddenFields]);const[urlHiddenValues,setUrlHiddenValues]=useState2({});const hiddenFieldIds=JSON.stringify(hiddenFields.map(hidden=>hidden.id));useEffect2(()=>{const ids=JSON.parse(hiddenFieldIds);if(ids.length===0||typeof window==="undefined")return;const params=new URLSearchParams(window.location.search);const next={};for(const id of ids){const value=params.get(id);if(value)next[id]=value}setUrlHiddenValues(next)},[hiddenFieldIds]);const hiddenValues=useMemo2(()=>({...urlHiddenValues,...hiddenValuesProp??{}}),[urlHiddenValues,hiddenValuesProp]);const hasRules=useMemo2(()=>hasVisibilityRules(fields),[fields]);const visibleFieldsFor=useCallback(current=>{if(!hasRules)return fields;const visible=resolveVisibleFieldIds(fields,{...hiddenValues,...current});return fields.filter(field=>visible.has(field.id))},[hasRules,fields,hiddenValues]);const visibleFields=useMemo2(()=>visibleFieldsFor(answers),[visibleFieldsFor,answers]);const startedRef=useRef2(false);const viewedRef=useRef2(false);const rootRef=useRef2(null);const[rootElement,setRootElement]=useState2(null);const setRoot=useCallback(element=>{rootRef.current=element;setRootElement(element)},[]);const fieldIdPrefix=`form-${useId().replace(/[^A-Za-z0-9_-]/g,"")}-field`;const inputIdOf=useCallback(fieldId=>`${fieldIdPrefix}-${fieldId}`,[fieldIdPrefix]);const protection=useBotProtection({variant:"full",context:formId,entry:"forms",needsUploadToken:fields.some(field=>field.type==="file"||field.type==="tax_id"),...challengeUrl?{challengeUrl}:{},...altchaChallengeUrl?{altchaChallengeUrl}:{},...botProtectionConfig!==void 0?{config:botProtectionConfig}:{}});const protectionSubmittable=protection.isSubmittable&&!botProtectionPending;const uploadReady=protection.isUploadReady&&!botProtectionPending;const uploadUrl=canSubmit&&submitUrl?submitUrl.replace(/\/submit$/,"/upload-request"):null;const taxIdLookupUrl=canSubmit&&submitUrl?submitUrl.replace(/\/submit$/,"/tax-id-lookup"):null;const taxIdLookupReady=Boolean(taxIdLookupUrl)&&uploadReady;const getUploadProtectionData=protection.getUploadProtectionData;const lookupTaxId=useCallback(async(fieldId,input)=>{if(!taxIdLookupUrl)return null;try{const res=await fetch(taxIdLookupUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fieldId,...input,...getUploadProtectionData()})});if(!res.ok)return null;const data=await res.json();if(!data||data.ok===false||typeof data.status!=="string")return null;return{...data,ok:true}}catch{return null}},[taxIdLookupUrl,getUploadProtectionData]);useEffect2(()=>{if(!canSubmit||viewedRef.current||!rootElement)return;const el=rootElement;if(typeof IntersectionObserver==="undefined"){viewedRef.current=true;dispatchLifecycle({type:"form_view",formId});return}const io=new IntersectionObserver(entries=>{if(entries.some(e=>e.isIntersecting)&&!viewedRef.current){viewedRef.current=true;dispatchLifecycle({type:"form_view",formId});io.disconnect()}},{threshold:.3});io.observe(el);return()=>io.disconnect()},[canSubmit,formId,rootElement]);const lastFieldRef=useRef2(null);const abandonRef=useRef2({status,visibleFields,answers});useEffect2(()=>{abandonRef.current={status,visibleFields,answers}},[status,visibleFields,answers]);useEffect2(()=>{if(!canSubmit||typeof window==="undefined")return;let sent=false;const onPageHide=()=>{const latest=abandonRef.current;if(sent||!startedRef.current||latest.status==="success")return;sent=true;dispatchLifecycle({type:"form_abandon",formId,lastFieldId:lastFieldRef.current,answeredCount:countAnswered(latest.visibleFields,latest.answers)})};window.addEventListener("pagehide",onPageHide);return()=>window.removeEventListener("pagehide",onPageHide)},[canSubmit,formId]);const markStarted=useCallback(()=>{protection.registerFocus();if(startedRef.current||!canSubmit)return;startedRef.current=true;dispatchLifecycle({type:"form_start",formId})},[protection,canSubmit,formId]);const focusField=useCallback(fieldId=>{lastFieldRef.current=fieldId;markStarted()},[markStarted]);const clearError=useCallback(id=>{setErrors(prev=>{if(!ownFieldValue(prev,id))return prev;const next={...prev};delete next[id];return next})},[]);const setAnswer=useCallback((id,value)=>{lastFieldRef.current=id;updateAnswers(prev=>({...prev,[id]:value}));clearError(id);setSubmitError(null)},[clearError,updateAnswers]);const setOtherAnswer=useCallback((id,text)=>{otherTextRef.current={...otherTextRef.current,[id]:text};setOtherText(otherTextRef.current);clearError(id)},[clearError]);const[today,setToday]=useState2(null);const timezone=form?.timezone;useEffect2(()=>{setToday(todayIn(timezone))},[timezone]);const fieldTypes=useMemo2(()=>Array.from(new Set(fields.map(field=>field.type))),[fields]);useEffect2(()=>{loadFormFieldValidators(fieldTypes).catch(()=>void 0)},[fieldTypes]);const[preparing,setPreparing]=useState2(false);const preparingRef=useRef2(false);const resendSameRef=useRef2(false);const defaultPhoneCountry=form?.defaultPhoneCountry;const validationCtx=useMemo2(()=>({defaultPhoneCountry,fileRequired:{exempt:Object.keys(uploadUnavailable).filter(id=>uploadUnavailable[id])},today}),[defaultPhoneCountry,uploadUnavailable,today]);const errorCtx=useMemo2(()=>({labels,today:today??todayIn(timezone),locale:locale||(typeof navigator!=="undefined"?navigator.language:"en")}),[labels,today,timezone,locale]);const validateOne=useCallback(field=>{if(!canValidateFormField(field.type))return;const code=validateFormAnswerWith(loadedFormFieldValidators(),field,{answers:answersRef.current,otherText:otherTextRef.current},validationCtx);if(code&&code!=="required")setErrors(prev=>({...prev,[field.id]:code}));else clearError(field.id)},[validationCtx,clearError]);const validateField=useCallback(fieldId=>{const field=fields.find(f=>f.id===fieldId);if(field)validateOne(field)},[fields,validateOne]);const focusFirstError=useCallback(errorIds=>{const root=rootRef.current;if(!root)return;for(const field of fields){if(!errorIds.includes(field.id))continue;const el=root.querySelector(`[id="${cssAttributeValue(inputIdOf(field.id))}"]`);if(!el)continue;el.scrollIntoView?.({behavior:"smooth",block:"center"});el.focus({preventScroll:true});return}},[fields,inputIdOf]);const submitAnswers=useCallback(async validators=>{if(!canSubmit||!form||statusRef.current!=="idle"||isClosed||anyUploadBusy||hasUploadInFlight())return;const current=answersRef.current;const optedIn=marketingOptInRef.current;const validated=validateFormAnswersWith(validators,fields,{answers:{...hiddenValues,...current},otherText:otherTextRef.current},{...validationCtx,hiddenFields});if(!validated.ok){setErrors(validated.errors);focusFirstError(Object.keys(validated.errors));return}setStatus("submitting");setSubmitError(null);let sent=false;try{if(!resendSameRef.current)await protection.prepare();sent=true;const res=await fetch(submitUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:validated.answers,...consentMode==="submit"?{consent:"submit_statement",consentTextId:form.consentTextId}:consentMode==="checkbox"&&optedIn?{consent:"checked",consentTextId:form.consentTextId}:{},locale:typeof navigator!=="undefined"?navigator.language:void 0,...locale?{pageLocale:locale}:{},pagePath:typeof window!=="undefined"?window.location.pathname:void 0,attribution:currentFormAttribution()??void 0,...protection.getProtectionData()})});if(res.headers.get("cf-mitigated")==="challenge"){setStatus("idle");setSubmitError("edge_challenge");resendSameRef.current=false;protection.renewCaptcha();return}const data=sanitizeFormSubmitResponse(res.status===429?{ok:false,error:"rate_limited"}:res.status===503?{ok:false,error:"temporarily_unavailable"}:await res.json().catch(()=>null));setStatus("idle");const resendSame=!data.ok&&data.error==="temporarily_unavailable";resendSameRef.current=resendSame;if(data.ok?Boolean(data.state):!resendSame){protection.renewCaptcha()}if(data.ok){if(data.state){setServerState(data.state);return}setStatus("success");const redirectUrl=data.redirectUrl??parseFormRedirectUrl(form.redirectUrl,{maxLength:FORM_REDIRECT_EXPANDED_URL_MAX})?.url;const detail={formId:form.id,...redirectUrl?{redirectUrl}:{},...data.submissionId?{submissionId:data.submissionId}:{}};setResult({...redirectUrl?{redirectUrl}:{},...data.submissionId?{submissionId:data.submissionId}:{}});onSuccess?.(detail);if(redirectUrl&&followRedirect){setRedirecting(true);window.location.assign(redirectUrl)}return}const errorIds=data.error==="invalid_answers"&&data.errors?Object.keys(data.errors):[];const renderedIds=new Set(visibleFieldsFor(current).map(f=>f.id));setSubmitError(errorIds.some(id=>!renderedIds.has(id))?"outdated":data.error);if(errorIds.length>0){setErrors(data.errors);focusFirstError(errorIds)}if(data.error==="verification_expired"||data.error==="duplicate")setAltchaKey(k=>k+1)}catch{setStatus("idle");setSubmitError("server_error");if(sent)resendSameRef.current=true;else protection.renewCaptcha()}},[canSubmit,form,setStatus,isClosed,anyUploadBusy,hasUploadInFlight,validationCtx,focusFirstError,fields,visibleFieldsFor,hiddenFields,hiddenValues,followRedirect,submitUrl,consentMode,locale,protection,onSuccess]);const submitAnswersRef=useRef2(submitAnswers);useEffect2(()=>{submitAnswersRef.current=submitAnswers},[submitAnswers]);const handleSubmit=useCallback(async e=>{e?.preventDefault();if(!canSubmit||statusRef.current!=="idle"||isClosed||anyUploadBusy||hasUploadInFlight()||preparingRef.current||!protectionSubmittable)return;if(hasFormFieldValidators(fieldTypes))return submitAnswers(loadedFormFieldValidators());preparingRef.current=true;setPreparing(true);let timer;try{await Promise.race([loadFormFieldValidators(fieldTypes),new Promise(resolve=>timer=setTimeout(resolve,VALIDATOR_WAIT_MS))])}catch{}finally{clearTimeout(timer);preparingRef.current=false;setPreparing(false)}await submitAnswersRef.current(loadedFormFieldValidators())},[canSubmit,isClosed,anyUploadBusy,hasUploadInFlight,protectionSubmittable,fieldTypes,submitAnswers]);const autofilledRef=useRef2({});const fillCompanyName=useCallback((targetId,name)=>{updateAnswers(prev=>{const currentValue=prev[targetId];const text=typeof currentValue==="string"?currentValue:"";if(text.trim()!==""&&text!==autofilledRef.current[targetId])return prev;autofilledRef.current[targetId]=name;return{...prev,[targetId]:name}})},[updateAnswers]);const setUnavailable=useCallback((id,unavailable)=>{setUploadUnavailable(prev=>prev[id]===unavailable?prev:{...prev,[id]:unavailable})},[]);const setBusy=useCallback((id,busy)=>{setUploadBusy(prev=>prev[id]===busy?prev:{...prev,[id]:busy})},[]);const uploadFile=useCallback(async(fieldId,file,uploadOptions={})=>{const field=fields.find(f=>f.id===fieldId);if(!field||field.type!=="file")return{ok:false,reason:"not_a_file_question"};focusField(fieldId);if(!uploadUrl||!uploadReady)return{ok:false,reason:"not_ready"};const current=ownFieldValue(answersRef.current,fieldId);const accepted=Array.isArray(current)?current.length:0;const inFlight=ownFieldValue(uploadsInFlightRef.current,fieldId)??0;if(accepted+inFlight>=field.maxFiles)return{ok:false,reason:"too_many_files"};const problem=checkFormFile(field,file);if(problem)return{ok:false,reason:problem};uploadsInFlightRef.current={...uploadsInFlightRef.current,[fieldId]:inFlight+1};setBusy(fieldId,true);try{const uploaded=await uploadFormFile({uploadUrl,fieldId,file,protection:getUploadProtectionData(),onProgress:uploadOptions.onProgress,signal:uploadOptions.signal});if(uploaded.ok){updateAnswers(prev=>{const ids=Array.isArray(prev[fieldId])?prev[fieldId]:[];return{...prev,[fieldId]:[...ids,uploaded.uploadId]}});clearError(fieldId);setSubmitError(null)}else if(uploaded.reason==="unavailable"){setUnavailable(fieldId,true)}return uploaded}finally{const left=Math.max(0,(ownFieldValue(uploadsInFlightRef.current,fieldId)??1)-1);uploadsInFlightRef.current={...uploadsInFlightRef.current,[fieldId]:left};if(left===0)setBusy(fieldId,false)}},[fields,uploadUrl,uploadReady,focusField,setBusy,getUploadProtectionData,updateAnswers,clearError,setUnavailable]);const errorMessage=useCallback(fieldId=>{const code=ownFieldValue(errors,fieldId);if(!code)return void 0;const field=fields.find(f=>f.id===fieldId);return field?errorLabel(code,field,errorCtx):labels.invalid},[errors,fields,errorCtx,labels.invalid]);return{form,formId,labels,fields,visibleFields,canSubmit,availability,isClosed,status,preparing,redirecting,result,successMessage:form?.settings.successMessage||labels.success,answers,setAnswer,otherText,setOtherAnswer,errors,errorMessage,validateField,validateOne,submitError,submitErrorMessage:submitError?submitErrorLabel(submitError,labels):null,consentMode,consentLabel,marketingOptIn,setMarketingOptIn,protection,altchaKey,today,inputIdOf,setRoot,markStarted,focusField,handleSubmit,submitDisabled:!canSubmit||status==="submitting"||preparing||!protectionSubmittable||anyUploadBusy,uploadUrl,uploadReady,getUploadProtectionData,setUploadUnavailable:setUnavailable,setUploadBusy:setBusy,uploadFile,lookupTaxId:taxIdLookupReady?lookupTaxId:null,fillCompanyName,phoneCountryOf:field=>field.type==="phone"?resolveFormPhoneCountry(field,form?.defaultPhoneCountry):null,siteCountry:form?.defaultPhoneCountry??null}}import{forwardRef}from"react";import{jsx as jsx3}from"react/jsx-runtime";var NativeInput=forwardRef(function NativeInput2({onKeyDown,onCompositionStart,onCompositionEnd,...props},forwarded){const ime=useComposingEnterGuard({onKeyDown,onCompositionStart,onCompositionEnd});const{ref,setRef}=useControlRef(forwarded);useAdoptTypedOnMount(ref,props.onChange);return jsx3("input",{...ime.props,...props,ref:setRef})});var NativeTextarea=forwardRef(function NativeTextarea2({onKeyDown,onCompositionStart,onCompositionEnd,...props},forwarded){const ime=useComposingEnterGuard({onKeyDown,onCompositionStart,onCompositionEnd});const{ref,setRef}=useControlRef(forwarded);useAdoptTypedOnMount(ref,props.onChange);return jsx3("textarea",{...ime.props,...props,ref:setRef})});import{jsx as jsx4,jsxs as jsxs3}from"react/jsx-runtime";function shouldSpanFullRow(field){return field.type==="long_text"||field.type==="file"||field.type==="statement"||field.type==="address"}function onGroupBlur(onBlur){return e=>{if(e.relatedTarget&&e.currentTarget.contains(e.relatedTarget))return;onBlur()}}var INPUT_CLASS=cn("w-full py-2.5",FORM_FIELD_CLASS);function FormWidget({form,maxColumns,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect=true,hiddenValues,isEditing=false,labels:labelsProp,locale,websiteName,captchaTheme}){const controller=useFormController({form,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect,hiddenValues,isEditing,labels:labelsProp,locale,websiteName});const{labels,visibleFields,availability,isClosed,status,preparing,redirecting,answers,otherText,consentMode,consentLabel,marketingOptIn,setMarketingOptIn,protection,altchaKey,today,submitError,submitErrorMessage,uploadUrl,lookupTaxId}=controller;const gridClass=getGridColumnsClass(maxColumns,visibleFields.length);const isPreview=isEditing&&submitUrl===void 0;return jsx4(FormFieldUnavailableLabelContext.Provider,{value:labels.error,children:jsx4("div",{ref:controller.setRoot,className:"w-full min-w-0",children:isClosed?jsx4("p",{className:cn("rounded-lg px-4 py-6 text-center text-sm",TONE_BG_TINT,FORM_FG_MUTED),children:availability==="not_open"?labels.notOpenYet:availability==="full"?labels.full:labels.closed}):status==="success"?jsxs3("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[jsx4(CircleCheck,{className:cn("h-10 w-10",FORM_ACCENT_ICON)}),jsx4("p",{className:cn("whitespace-pre-wrap text-base",FORM_FG),children:controller.successMessage}),redirecting&&jsx4("p",{className:cn("text-sm",FORM_FG_MUTED),children:labels.redirecting})]}):jsxs3("form",{onSubmit:controller.handleSubmit,noValidate:true,className:cn("grid gap-x-8 gap-y-7",gridClass),children:[jsx4(BotProtectionFields,{...protection.fieldProps,renderAltcha:false}),visibleFields.map(field=>jsx4(FieldRow,{inputId:controller.inputIdOf(field.id),className:shouldSpanFullRow(field)?"col-span-full":void 0,field,value:ownFieldValue(answers,field.id)??null,otherText:ownFieldValue(otherText,field.id)??"",onOtherTextChange:v=>controller.setOtherAnswer(field.id,v),error:controller.errorMessage(field.id),labels,today,phoneCountry:controller.phoneCountryOf(field),siteCountry:controller.siteCountry,onChange:v=>controller.setAnswer(field.id,v),onFocus:()=>controller.focusField(field.id),onBlur:()=>controller.validateOne(field),upload:{url:uploadUrl,ready:controller.uploadReady,getProtectionData:controller.getUploadProtectionData,onUnavailableChange:u=>controller.setUploadUnavailable(field.id,u),onBusyChange:b=>controller.setUploadBusy(field.id,b)},taxId:field.type==="tax_id"?{lookup:lookupTaxId?input=>lookupTaxId(field.id,input):void 0,onRegistryName:field.companyNameFieldId?name=>controller.fillCompanyName(field.companyNameFieldId,name):void 0}:void 0},field.id)),consentMode==="checkbox"&&jsxs3("label",{className:cn("col-span-full flex cursor-pointer items-start gap-2.5 pt-1 text-sm",FORM_FG),children:[jsx4(SiteChoiceInput,{type:"checkbox",className:"mt-0.5",checked:marketingOptIn,onFocus:controller.markStarted,onChange:e=>setMarketingOptIn(e.target.checked)}),jsx4("span",{children:consentLabel})]}),jsx4(BotProtectionChallenge,{...protection.challengeProps,locale,theme:captchaTheme,className:"col-span-full sm:max-w-sm"},altchaKey),submitError&&jsx4("p",{role:"alert",className:cn("col-span-full text-sm",FORM_DANGER),children:submitErrorMessage}),jsxs3("div",{className:"col-span-full flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4",children:[jsxs3("button",{type:"submit",disabled:controller.submitDisabled,className:cn("inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-lg px-5 py-2.5 text-[15px] font-medium transition sm:w-auto",FORM_SUBMIT_COLORS,"shadow-md hover:brightness-110 hover:shadow-lg","disabled:cursor-not-allowed disabled:opacity-60"),children:[(status==="submitting"||preparing)&&jsx4(LoaderCircle,{className:"h-4 w-4 animate-spin"}),status==="submitting"||preparing?labels.submitting:form.settings.submitLabel||labels.submit]}),isPreview&&jsx4("p",{className:cn("text-xs",FORM_FG_MUTED),children:labels.previewNotice})]}),consentMode==="submit"&&jsx4("p",{className:cn("col-span-full -mt-4 text-xs leading-relaxed",FORM_FG_MUTED),children:consentLabel})]})})})}function FieldRow({field,inputId,className,value,otherText,onOtherTextChange,error,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}){const errorId=`${inputId}-error`;const describedBy=error?errorId:void 0;if(field.type==="statement"){return jsxs3("div",{className:cn("min-w-0 space-y-1.5",className),children:[jsx4("p",{className:cn("text-base font-semibold leading-snug",FORM_FG),children:field.label}),field.description&&jsx4("p",{className:cn("whitespace-pre-wrap text-sm leading-relaxed",FORM_FG_MUTED),children:field.description})]})}return jsxs3("div",{className:cn("min-w-0 space-y-2",className),children:[jsxs3("label",{htmlFor:inputId,className:cn("block text-base font-semibold leading-snug",FORM_FG),children:[field.label,field.required&&jsx4("span",{"aria-hidden":true,className:cn("ml-0.5",FORM_DANGER),children:"*"})]}),field.description&&jsx4("p",{className:cn("text-sm",FORM_FG_MUTED),children:field.description}),jsx4(FieldInput,{field,inputId,describedBy,invalid:Boolean(error),value,otherText,onOtherTextChange,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}),error&&jsx4("p",{id:errorId,role:"alert",className:cn("text-xs",FORM_DANGER),children:error})]})}function OtherTextInput({className,placeholder,value,onFocus,onChange}){return jsx4("input",{type:"text",className:cn(INPUT_CLASS,className),placeholder,"aria-label":placeholder,value,onFocus,onChange:e=>onChange(e.target.value)})}function FieldInput({field,inputId,describedBy,invalid,value,otherText,onOtherTextChange,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}){const{PhoneInput,FormAddressField,FormTaxIdField,FormFileField,FormChoiceDropdown}=useContext2(FormFieldComponentsContext)??ON_DEMAND_FORM_FIELDS;const common={id:inputId,"aria-describedby":describedBy,"aria-invalid":invalid||void 0,onFocus,onBlur,required:field.required,className:cn(INPUT_CLASS,invalid&&FORM_FIELD_INVALID_CLASS)};const singleLine=singleLineInputProps(field,today);if(singleLine){return jsx4(NativeInput,{...common,...singleLine,value:typeof value==="string"?value:typeof value==="number"?String(value):"",onChange:e=>onChange(e.target.value)})}switch(field.type){case"short_text":case"email":case"date":case"time":case"number":case"url":return null;case"long_text":return jsx4(NativeTextarea,{...common,rows:4,maxLength:field.maxLength,value:typeof value==="string"?value:"",onChange:e=>onChange(e.target.value)});case"phone":return jsx4("div",{id:inputId,onFocus,onBlur:onGroupBlur(onBlur),tabIndex:-1,className:"outline-none",children:jsx4(PhoneInput,{value:typeof value==="string"?value:"",onChange:v=>onChange(v??null),defaultCountry:phoneCountry,error:invalid,controlClassName:cn(FORM_FIELD_CLASS,invalid&&FORM_FIELD_INVALID_CLASS)})});case"statement":return null;case"tax_id":return jsx4(FormTaxIdField,{field,inputId,describedBy,invalid,value,labels,siteCountry,controlClassName:FORM_FIELD_CLASS,lookup:taxId?.lookup,onRegistryName:taxId?.onRegistryName,onChange,onFocus,onBlur});case"address":return jsx4(FormAddressField,{field,inputId,describedBy,invalid,value,labels,siteCountry,controlClassName:FORM_FIELD_CLASS,onChange,onFocus,onBlur});case"choice":{const selected=Array.isArray(value)?value:typeof value==="string"&&value?[value]:[];const options=[...field.options.map(o=>({id:o.id,label:o.label})),...field.allowOther?[{id:OTHER_OPTION_PLACEHOLDER,label:labels.otherOption}]:[]];const showOther=field.allowOther&&selected.includes(OTHER_OPTION_PLACEHOLDER);if(field.display==="dropdown"&&!field.allowMultiple){return jsxs3("div",{className:"space-y-2.5",onBlur:onGroupBlur(onBlur),children:[jsx4(FormChoiceDropdown,{inputId,describedBy,invalid,value:selected[0]||void 0,options,placeholder:labels.selectPlaceholder,onChange,onFocus}),showOther&&jsx4(OtherTextInput,{placeholder:labels.otherPlaceholder,value:otherText,onFocus,onChange:onOtherTextChange})]})}return jsxs3("div",{role:field.allowMultiple?"group":"radiogroup","aria-describedby":describedBy,className:"space-y-2.5 pt-0.5",onBlur:onGroupBlur(onBlur),children:[options.map((opt,i)=>{const checked=selected.includes(opt.id);return jsxs3("label",{className:cn("flex cursor-pointer items-center gap-2.5 text-[15px]",FORM_FG),children:[jsx4(SiteChoiceInput,{id:i===0?inputId:void 0,type:field.allowMultiple?"checkbox":"radio",name:inputId,checked,onFocus,onChange:()=>{if(field.allowMultiple){onChange(checked?selected.filter(x=>x!==opt.id):[...selected,opt.id])}else{onChange(opt.id)}}}),jsx4("span",{children:opt.label})]},opt.id)}),showOther&&jsx4(OtherTextInput,{className:"mt-1",placeholder:labels.otherPlaceholder,value:otherText,onFocus,onChange:onOtherTextChange})]})}case"rating":{const Icon=field.icon==="heart"?Heart:field.icon==="thumb"?ThumbsUp:Star;const current=typeof value==="number"?value:0;return jsx4("div",{role:"radiogroup","aria-describedby":describedBy,className:"flex flex-wrap gap-1.5",onBlur:onGroupBlur(onBlur),children:Array.from({length:field.max},(_,i)=>i+1).map(n=>{const active=n<=current;return jsx4("button",{type:"button",role:"radio","aria-checked":current===n,"aria-label":String(n),id:n===1?inputId:void 0,onFocus,onClick:()=>onChange(current===n?null:n),className:cn("flex h-10 w-10 items-center justify-center rounded-lg transition",TONE_BG_TINT_STRONG_HOVER),children:jsx4(Icon,{className:cn("h-6 w-6 transition",active?"fill-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))] text-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))]":TONE_TEXT_FAINT)})},n)})})}case"file":return jsx4(FormFileField,{field,inputId,describedBy,invalid,labels,uploadUrl:upload.url,protectionReady:upload.ready,getProtectionData:upload.getProtectionData,onChange,onUnavailableChange:upload.onUnavailableChange,onBusyChange:upload.onBusyChange,onFocus})}}import{createElement,useCallback as useCallback2,useMemo as useMemo3}from"react";function useKanorioForm(options){const{formId,definition,siteName,labels,hiddenValues,followRedirect,onSuccess,siteUrl:siteUrlOption,locale:localeOption}=options;const setup=useKanorioFormSetup({siteUrl:siteUrlOption,locale:localeOption},formId,definition,labels);const{ctx,form}=setup;const site=ctx.site;const botProtectionConfig=useMemo3(()=>site?parsePublicBotProtectionConfig(site.botProtection):null,[site]);const handleSuccess=useCallback2(detail=>{if(typeof window!=="undefined")window.dispatchEvent(new CustomEvent(FORM_SUBMIT_EVENT,{detail}));onSuccess?.(detail)},[onSuccess]);const submitUrl=form?`${ctx.siteUrl}/api/v1/forms/${encodeURIComponent(form.id)}/submit`:null;const controller=useFormController({form:setup.ready?form:null,formId,submitUrl,challengeUrl:`${ctx.siteUrl}/api/form-protection/challenge`,altchaChallengeUrl:`${ctx.siteUrl}/api/form-protection/altcha`,onSuccess:handleSuccess,followRedirect,hiddenValues,labels:setup.mergedLabels,locale:ctx.locale,websiteName:siteName??null,botProtectionConfig,botProtectionPending:site===null});const{inputIdOf,answers,errors,today,setAnswer,focusField,validateField}=controller;const getInputProps=useCallback2(fieldId=>{const field=controller.fields.find(f=>f.id===fieldId);const inputId=inputIdOf(fieldId);const value=ownFieldValue(answers,fieldId);const typed=field?singleLineInputProps(field,today)??(field.type==="long_text"?{maxLength:field.maxLength}:{}):{};return{...typed,id:inputId,name:fieldId,value:typeof value==="string"?value:typeof value==="number"?String(value):"",required:Boolean(field&&"required"in field&&field.required),...ownFieldValue(errors,fieldId)?{"aria-invalid":true,"aria-describedby":`${inputId}-error`}:{},onChange:event=>setAnswer(fieldId,event.target.value),onFocus:()=>focusField(fieldId),onBlur:()=>validateField(fieldId)}},[controller.fields,inputIdOf,answers,today,errors,setAnswer,focusField,validateField]);const pending2=site===null;const captcha=controller.protection.challengeProps.captcha;const botProtection=createElement(KanorioBotProtection,{key:controller.altchaKey,...controller.protection.fieldProps,captcha,pending:pending2,locale:ctx.locale});const status=setup.loadFailed||setup.siteUnavailable||setup.textUnavailable?"unavailable":!setup.ready?"loading":controller.status==="success"?"success":controller.status==="submitting"||controller.preparing?"submitting":"ready";return{status,definition:setup.ready?form:null,fields:controller.visibleFields,availability:controller.availability,values:answers,setValue:setAnswer,otherText:controller.otherText,setOtherText:controller.setOtherAnswer,errors,errorMessage:controller.errorMessage,validateField,getInputProps,getErrorProps:fieldId=>({id:`${inputIdOf(fieldId)}-error`,role:"alert"}),formProps:{ref:controller.setRoot,onSubmit:event=>void controller.handleSubmit(event),onFocus:controller.markStarted,noValidate:true},botProtection,consent:{mode:controller.consentMode,text:form?.consentText??controller.consentLabel,checked:controller.marketingOptIn,setChecked:controller.setMarketingOptIn},canSubmit:status==="ready"&&!controller.isClosed&&!controller.submitDisabled,submit:()=>controller.handleSubmit(),submitError:controller.submitError,submitErrorMessage:controller.submitErrorMessage,result:controller.result,successMessage:controller.successMessage,uploadReady:controller.uploadReady&&status==="ready",uploadFile:controller.uploadFile,lookupTaxId:(fieldId,input)=>controller.lookupTaxId?controller.lookupTaxId(fieldId,input):Promise.resolve(null),labels:controller.labels}}import{jsx as jsx5}from"react/jsx-runtime";function KanorioForm({formId,definition:initialDefinition,maxColumns,siteName,labels,onSuccess,followRedirect,hiddenValues,className,...config}){const{ctx,form,loadFailed,siteUnavailable,mergedLabels,ready}=useKanorioFormSetup(config,formId,initialDefinition,labels);const site=ctx.site;const siteUrl=ctx.siteUrl;if(loadFailed){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-error":"load_failed",children:mergedLabels?.temporarilyUnavailable??"This form isn\u2019t accepting responses right now."})}if(siteUnavailable){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-error":"site_unavailable",children:mergedLabels?.temporarilyUnavailable??"This form isn\u2019t accepting responses right now."})}if(!ready||!form||!site){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-loading":"",loading:true})}return jsx5(ElementsRoot,{context:ctx,className,children:jsx5(BotProtectionConfigProvider,{value:parsePublicBotProtectionConfig(site.botProtection),children:jsx5(FormWidget,{form,maxColumns,submitUrl:`${siteUrl}/api/v1/forms/${encodeURIComponent(form.id)}/submit`,challengeUrl:`${siteUrl}/api/form-protection/challenge`,altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`,locale:ctx.locale,websiteName:siteName,captchaTheme:ctx.theme,labels:mergedLabels,followRedirect,hiddenValues,onSuccess:detail=>{if(typeof window!=="undefined"){window.dispatchEvent(new CustomEvent(FORM_SUBMIT_EVENT,{detail}))}onSuccess?.(detail)}})})})}export{SITE_RETRY_DELAYS_MS,useKanorioForm,KanorioForm};
|
|
2
|
+
//# sourceMappingURL=chunk-J24HGQ7U.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{deliverablePlayerLabels}from"./chunk-MC63CLSM.js";import{LazyDeliverablePlayer}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{deliverablePlayerLabels}from"./chunk-MC63CLSM.js";import{LazyDeliverablePlayer}from"./chunk-UITC3NFQ.js";import{ElementsRoot}from"./chunk-7UCZ56EJ.js";import{KanorioApiError,createCustomerClient,useKanorio}from"./chunk-73S6VKNV.js";import{useEffect,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";function playerLabelsFrom(messages){return deliverablePlayerLabels(messages.account)}function KanorioUnit({deliverable,unit,onUnitChange,onProgress,renderUnauthenticated,tree:givenTree,client:givenClient,className,...config}){const ctx=useKanorio(config);const injected=Boolean(givenTree&&givenClient);const[state,setState]=useState(()=>givenTree&&givenClient?{status:"ready",tree:givenTree}:{status:"loading"});useEffect(()=>{let cancelled=false;if(injected){setState({status:"ready",tree:givenTree});return}if(!ctx.token){setState({status:"unauthenticated"});return}setState({status:"loading"});const client2=createCustomerClient({siteUrl:ctx.siteUrl,token:ctx.token});client2.get("/deliverables/{deliverableId}",{params:{deliverableId:deliverable},query:{locale:ctx.locale}}).then(res=>{if(!cancelled)setState({status:"ready",tree:res.deliverable})}).catch(error=>{if(cancelled)return;if(error instanceof KanorioApiError&&error.status===401){setState({status:"unauthenticated"});return}setState({status:"error",code:error instanceof KanorioApiError?error.code:"NETWORK_ERROR"})});return()=>{cancelled=true}},[ctx.siteUrl,ctx.token,deliverable,injected,givenTree]);const baseClient=givenClient??ctx.client;const client=useMemo(()=>{if(!onProgress)return baseClient;return{openUnit:baseClient.openUnit,submitQuiz:async input=>{const res=await baseClient.submitQuiz(input);if(res.ok)onProgress({unitId:input.unitId,percent:res.deliverable.percent,completed:res.deliverable.completed,deliverableJustCompleted:res.deliverableJustCompleted,coveredPercent:null});return res},getCertificate:baseClient.getCertificate,getTranscript:baseClient.getTranscript,reportProgress:async input=>{const res=await baseClient.reportProgress(input);if(res.ok&&res.deliverable)onProgress({unitId:input.unitId,percent:res.deliverable.percent,completed:res.deliverable.completed,deliverableJustCompleted:res.deliverableJustCompleted,coveredPercent:res.unitCoveredPercent??null});return res}}},[baseClient,onProgress]);if(!ctx.messages||state.status==="loading"){return jsx(ElementsRoot,{context:ctx,className,loading:true,children:jsx("div",{className:"h-64 w-full animate-pulse rounded-(--media-radius,12px) bg-(--media-surface)"})})}const a=ctx.messages.account;if(state.status==="unauthenticated"){return jsx(ElementsRoot,{context:ctx,className,children:renderUnauthenticated?renderUnauthenticated():jsx("p",{className:"rounded-(--media-radius,12px) bg-(--media-surface) p-4 text-sm text-(--media-surface-fg)",children:a.contentLocked})})}if(state.status==="error"){return jsx(ElementsRoot,{context:ctx,className,children:jsx("p",{role:"alert",className:"rounded-(--media-radius,12px) bg-(--media-surface) p-4 text-sm text-(--media-surface-fg)",children:state.code==="DELIVERABLE_NOT_FOUND"?a.contentEmptyTitle:a.contentLoadError})})}return jsx(ElementsRoot,{context:ctx,className,children:jsx(LazyDeliverablePlayer,{tree:state.tree,client,labels:playerLabelsFrom(ctx.messages),locale:ctx.locale,timeZone:ctx.timeZone,initialUnitId:unit??null,onUnitChange})})}export{playerLabelsFrom,KanorioUnit};
|
|
2
|
+
//# sourceMappingURL=chunk-JYBSXLT3.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{e as bt,f as Ct,g as yt}from"./chunk-EZMTUAQX.js";import{a as ft,b as mt,c as gt}from"./chunk-VYSRVTYI.js";import{e as ht,f as re}from"./chunk-2LOQXVFI.js";import{b as te}from"./chunk-2E6RCDAA.js";import{A as ct,C as dt,Q as pt,U as fe,b as st,ba as m,d as at,g as Te,p as lt,u as _e,y as ut}from"./chunk-S2NFWI7C.js";import{a as L}from"./chunk-OU4IOHLN.js";import{a as pe}from"./chunk-6LGTFWQS.js";import{c as k}from"./chunk-CDG7S4P5.js";var u=k(pe());var B="text-[var(--site-fg,#18181b)]",D="text-[var(--site-fg-muted,#71717a)]",At=`mb-1.5 block text-sm font-medium ${B}`,H=`text-sm ${D}`,St="mt-1 text-sm text-red-600 dark:text-red-400",br="min-h-11 rounded-[var(--site-radius-lg,0.5rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] px-3 text-[length:var(--site-input-text,16px)] text-[var(--site-fg,#18181b)] outline-none transition placeholder:text-[var(--site-fg-muted,#71717a)] focus:border-[var(--site-fg-muted,#71717a)] focus:ring-2 focus:ring-[color-mix(in_srgb,var(--brand-color,#18181b)_35%,transparent)] disabled:cursor-not-allowed disabled:opacity-60",Cr=`w-full ${br}`,yr="border-red-400 hover:border-red-400 focus:border-red-400 dark:border-red-500 dark:hover:border-red-500 dark:focus:border-red-500";function Et(e,t){return m(Cr,e&&yr,t)}var Ar="inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-[var(--site-radius-button,0.75rem)] text-sm font-semibold transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand-color,#18181b)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--site-surface,#ffffff)] disabled:cursor-not-allowed disabled:opacity-60",Sr={primary:"bg-[var(--brand-color,#18181b)] text-[var(--brand-foreground,#ffffff)] hover:brightness-110",secondary:"border border-[var(--site-border,rgba(0,0,0,0.12))] bg-transparent text-[var(--site-fg,#18181b)] "+re,ghost:"bg-transparent text-[var(--site-fg-muted,#71717a)] hover:text-[var(--site-fg,#18181b)] "+re,danger:"border border-red-300 bg-transparent text-red-700 hover:bg-red-50 dark:border-red-800 dark:text-red-300 dark:hover:bg-red-950/40"},Er={md:"min-h-11 px-4",lg:"min-h-12 px-5"};function me(e){return[Ar,Sr[e?.variant??"primary"],Er[e?.size??"md"],e?.block?"flex w-full":"",e?.extra??""].filter(Boolean).join(" ")}var Rt="rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] text-[var(--site-fg,#18181b)]",ge="border-t border-[var(--site-border,rgba(0,0,0,0.12))]",Ie="rounded-[var(--site-radius-lg,0.5rem)] border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-900 dark:bg-red-950/40 dark:text-red-300",Rr={neutral:"text-[var(--site-fg,#18181b)] "+ht,success:"bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300",warning:"bg-amber-50 text-amber-800 dark:bg-amber-950/40 dark:text-amber-300",danger:"bg-red-50 text-red-700 dark:bg-red-950/40 dark:text-red-300",info:"bg-sky-50 text-sky-700 dark:bg-sky-950/40 dark:text-sky-300",brand:"bg-[var(--brand-color,#18181b)] text-[var(--brand-foreground,#ffffff)]"};function wt(e="neutral"){return`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${Rr[e]}`}var Pe=`inline-flex cursor-pointer items-center gap-1.5 text-sm font-medium transition hover:text-[var(--site-fg,#18181b)] disabled:cursor-not-allowed disabled:opacity-60 ${D}`;var kt=k(pe());var he=k(L()),U=(0,kt.forwardRef)(function({variant:t,size:r,block:o,loading:i,leading:a,className:p,disabled:g,type:c="button",children:l,...h},d){return(0,he.jsxs)("button",{ref:d,type:c,disabled:g||i,"aria-busy":i||void 0,className:me({variant:t,size:r,block:o,extra:p}),...h,children:[i?(0,he.jsx)(ct,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):a,l]})});var K=k(pe());var z=k(L());function vt({length:e=6,value:t,onChange:r,onComplete:o,disabled:i,invalid:a,autoFocus:p,label:g,id:c,className:l}){let h=(0,K.useId)(),d=c??h,x=(0,K.useRef)(null),[O,A]=(0,K.useState)(!1),W=(0,K.useRef)(null),b=t.replace(/\D/g,"").slice(0,e);(0,K.useEffect)(()=>{b.length===e&&W.current!==b&&(W.current=b,o?.(b)),b.length<e&&(W.current=null)},[b,e,o]);let v=E=>{let T=E.clipboardData.getData("text").replace(/\D/g,"").slice(0,e);T&&(E.preventDefault(),r(T))},oe=E=>{E.key},Ee=Array.from({length:e},(E,T)=>b[T]??""),Re=Math.min(b.length,e-1);return(0,z.jsxs)("div",{className:m("relative",l),onClick:()=>x.current?.focus(),children:[(0,z.jsx)("div",{className:"flex gap-2","aria-hidden":"true",children:Ee.map((E,T)=>{let y=O&&T===Re&&!i;return(0,z.jsx)("div",{className:m("flex h-12 min-w-0 flex-1 items-center justify-center rounded-[var(--site-radius-lg,0.5rem)] border bg-[var(--site-surface,#ffffff)] font-mono text-xl font-semibold text-[var(--site-fg,#18181b)] transition",a?"border-red-400 dark:border-red-500":y?"border-[var(--brand-color,#18181b)] ring-2 ring-[color-mix(in_srgb,var(--brand-color,#18181b)_35%,transparent)]":"border-[var(--site-border,rgba(0,0,0,0.12))]",i&&"opacity-60"),children:E||(y?(0,z.jsx)("span",{className:"h-6 w-px animate-pulse bg-[var(--site-fg,#18181b)]"}):null)},T)})}),(0,z.jsx)("input",{ref:x,id:d,type:"text",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"one-time-code",maxLength:e,value:b,disabled:i,autoFocus:p,"aria-label":g,"aria-invalid":a||void 0,onChange:E=>r(E.target.value.replace(/\D/g,"").slice(0,e)),onPaste:v,onKeyDown:oe,onFocus:()=>A(!0),onBlur:()=>A(!1),className:"absolute inset-0 h-full w-full cursor-text opacity-0"})]})}var be=k(pe());var F=k(L());function Tt({label:e,hint:t,error:r,labelTrailing:o,htmlFor:i,className:a,children:p}){return(0,F.jsxs)("div",{className:a,children:[(0,F.jsxs)("div",{className:"mb-1.5 flex items-center justify-between gap-2",children:[(0,F.jsx)("label",{htmlFor:i,className:m(At,"mb-0"),children:e}),o]}),p,r?(0,F.jsx)("p",{className:St,role:"alert",children:r}):t?(0,F.jsx)("p",{className:m(H,"mt-1"),children:t}):null]})}var _t=(0,be.forwardRef)(function({invalid:t,className:r,id:o,onKeyDown:i,onCompositionStart:a,onCompositionEnd:p,...g},c){let l=(0,be.useId)(),h=ft({onKeyDown:i,onCompositionStart:a,onCompositionEnd:p}),d=gt(c);return mt(d.ref,g.onChange),(0,F.jsx)("input",{ref:d.setRef,id:o??l,"aria-invalid":t||void 0,className:Et(t,r),...h.props,...g})});var J=k(L());function It({className:e}){return(0,J.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",className:e,role:"img","aria-label":"Google",children:[(0,J.jsx)("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"var(--platform-icon-mono, #4285F4)"}),(0,J.jsx)("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"var(--platform-icon-mono, #34A853)"}),(0,J.jsx)("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"var(--platform-icon-mono, #FBBC05)"}),(0,J.jsx)("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"var(--platform-icon-mono, #EA4335)"})]})}var _={index:"/account",login:"/account/login",orders:"/account/orders",order:e=>`/account/orders/${e}`,content:"/account/content",contentItem:e=>`/account/content/${encodeURIComponent(e)}`,courses:"/account/courses",settings:"/account/settings",profile:"/account/profile",devices:"/account/devices",apiSession:"/account/api/session",apiChallenge:"/account/api/challenge",apiVerify:"/account/api/verify",apiOauthStart:"/account/api/oauth/start",apiOauth2Authorize:"/account/api/oauth2/authorize",apiPasskeyLoginOptions:"/account/api/auth/passkey/options",apiPasskeyLoginVerify:"/account/api/auth/passkey/verify",apiPasskeys:"/account/api/passkeys",apiPasskey:e=>`/account/api/passkeys/${encodeURIComponent(e)}`,apiPasskeyRegisterOptions:"/account/api/passkeys/register/options",apiPasskeyRegister:"/account/api/passkeys/register",apiProfile:"/account/api/profile",apiEmailChange:"/account/api/email-change",apiEmailChangeVerify:"/account/api/email-change/verify",apiAddresses:"/account/api/addresses",apiAddress:e=>`/account/api/addresses/${encodeURIComponent(e)}`,apiAddressDefault:e=>`/account/api/addresses/${encodeURIComponent(e)}/default`,apiTaxIdentities:"/account/api/tax-identities",apiTaxIdentity:e=>`/account/api/tax-identities/${encodeURIComponent(e)}`,apiConsents:"/account/api/consents",apiData:"/account/api/data",apiErasure:"/account/api/erasure",apiContentOpen:e=>`/account/api/content/${encodeURIComponent(e)}/open`,apiContentQuiz:e=>`/account/api/content/${encodeURIComponent(e)}/quiz`,apiContentTranscript:e=>`/account/api/content/${encodeURIComponent(e)}/transcript`,apiProgress:"/account/api/progress",apiCertificate:e=>`/account/api/deliverables/${encodeURIComponent(e)}/certificate`,apiOrderReceipt:e=>`/account/api/orders/${encodeURIComponent(e)}/receipt`};var gn="knr_customer";var Pt=["passkey","google","apple","line","kakao","external_oidc","email_code","email_link"],wr=["passkey","google","email_code","email_link"],kr="email_code",vr=["email_code","email_link"];function xe(e){return typeof e=="string"&&Pt.includes(e)}function hn(e){let t=new Set(Array.isArray(e)?e.filter(xe).filter(r=>wr.includes(r)):vr);return t.add(kr),Pt.filter(r=>t.has(r))}function Oe(e,t=_.index){if(typeof e!="string")return t;let r=e.trim();return!r||r.length>512||!r.startsWith("/")||r.startsWith("//")||r.startsWith("/\\")||/[\r\n\0]/.test(r)||/^[a-z][a-z0-9+.-]*:/i.test(r)?t:r}var Tr=[{id:"orders",order:10,route:_.orders,navLabelKey:"orders",icon:"shopping-bag",apiResourcePrefixes:["/orders","/reviews"],visibility:"capability"},{id:"content",order:20,route:_.content,navLabelKey:"content",icon:"book-open",apiResourcePrefixes:["/deliverables","/units","/progress","/access"],visibility:"capability"},{id:"account",order:90,route:_.settings,navLabelKey:"account",icon:"user",apiResourcePrefixes:["/me","/session","/sessions","/email-change","/addresses","/tax-identities","/consents","/passkeys","/data","/erasure"],visibility:"always"}];function xt(e){let t=new Set(e.filter(r=>r.visible).map(r=>r.id));return[...Tr].filter(r=>t.has(r.id)).sort((r,o)=>r.order-o.order)}function _r(e,t){let r=e?.get("utm_source")?.toLowerCase()??"";if(/^(ig|instagram|threads|fb|facebook)/.test(r))return!0;let o=(t??"").toLowerCase();return[/threads\.net/i,/threads\.com/i,/instagram\.com/i,/m\.facebook\.com/i,/l\.facebook\.com/i,/lm\.facebook\.com/i].some(a=>a.test(o))}function Ot(e){if(typeof navigator>"u")return!1;let t=navigator.userAgent?.toLowerCase()??"";return!!([/\bbarcelona\b/i,/fban|fbav/i,/fb_iab/i,/fb_iab\/threads|fban\/threads|fbios.*threads/i,/instagram/i,/threads/i,/fbios/i,/line\//i,/wechat/i,/micromessenger/i,/twitter/i,/linkedin/i,/reddit/i,/pinterest/i,/discord/i,/snapchat/i,/tiktok/i,/kakaotalk/i,/naver/i,/webview/i].some(o=>o.test(t))||e&&_r(e.searchParams,e.referrer))}var Ce="NETWORK_ERROR";async function Nt(e,t){let r=await e.json().catch(()=>null);return!e.ok||!r?.ok?{ok:!1,code:r?.code??t,...typeof r?.retryAfter=="number"?{retryAfter:r.retryAfter}:{}}:r}async function G(e,t,r){try{let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(t??{})});return await Nt(o,r)}catch{return{ok:!1,code:Ce}}}function En(){let e=_;return{altchaChallengeUrl:"/api/form-protection/altcha",challengeUrl:"/api/form-protection/challenge",requestChallenge:({email:t,locale:r,returnTo:o,protection:i})=>G(e.apiChallenge,{email:t,locale:r,returnTo:o,...i},"SERVER_ERROR"),verifyCode:({email:t,code:r})=>G(e.apiVerify,{method:"code",email:t,code:r},"INVALID_CODE"),verifyToken:({method:t,token:r})=>G(e.apiVerify,{method:t,token:r},"CODE_EXPIRED"),startOauth:({method:t,returnTo:r,locale:o})=>G(e.apiOauthStart,{method:t,returnTo:r,locale:o},"METHOD_DISABLED"),passkeyLoginOptions:()=>G(e.apiPasskeyLoginOptions,{},"SERVER_ERROR"),passkeyLoginVerify:t=>G(e.apiPasskeyLoginVerify,t,"PASSKEY_FAILED"),listPasskeys:async()=>{try{let t=await fetch(e.apiPasskeys,{credentials:"same-origin"});return await Nt(t,"UNAUTHENTICATED")}catch{return{ok:!1,code:Ce}}},passkeyRegisterOptions:()=>G(e.apiPasskeyRegisterOptions,{},"SERVER_ERROR"),passkeyRegister:t=>G(e.apiPasskeyRegister,t,"PASSKEY_FAILED"),session:async()=>{let t=await fetch(e.apiSession,{credentials:"same-origin"});if(t.status===401)return null;if(!t.ok)throw new Error(`HTTP ${t.status}`);let r=await t.json();return!r?.ok||!r.contact?null:{contact:r.contact,sections:r.sections??[],landing:r.landing??e.index}},signOut:async()=>{await fetch(e.apiSession,{method:"DELETE",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({mode:"current"})}).catch(()=>{})}}}var Lt=new Set(["PASSKEY_CANCELLED"]);function Ne(e,t){switch((e??"").toUpperCase()){case"INVALID_EMAIL":return t.errorInvalidEmail;case"INVALID_CODE":return t.errorInvalidCode;case"CODE_EXPIRED":return t.errorCodeExpired;case"TOO_MANY_ATTEMPTS":return t.errorTooManyAttempts;case"ACCOUNT_BLOCKED":return t.errorAccountBlocked;case"RATE_LIMITED":return t.errorRateLimited;case"BOT_PROTECTION_FAILED":return t.errorBotProtection;case"SIGNUP_DISABLED":return t.errorSignupDisabled;case"SEND_FAILED":return t.errorSendFailed;case"METHOD_DISABLED":return t.errorMethodDisabled;case"EMAIL_NOT_VERIFIED":return t.errorEmailNotVerified;case"NO_EMAIL":return t.errorNoEmail;case"PROVIDER_DENIED":case"TOKEN_EXCHANGE_FAILED":case"INVALID_ID_TOKEN":case"INVALID_STATE":return t.errorProviderFailed;case"PASSKEY_UNSUPPORTED":return t.errorPasskeyUnsupported;case"PASSKEY_FAILED":case"NOT_FOUND":case"VERIFY_FAILED":case"CHALLENGE_EXPIRED":case"NO_HOST":return t.errorPasskeyFailed;case"ALREADY_REGISTERED":return t.errorPasskeyAlreadyRegistered;case"SERVICE_UNAVAILABLE":return t.errorServiceUnavailable;case"SHARED_SENDER_PAUSED":return t.errorEmailSignInPaused;case Ce:default:return t.errorGeneric}}function I(e){let t=new Uint8Array(e),r="";for(let i of t)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function q(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4,o=t.padEnd(t.length+r,"="),i=atob(o),a=new ArrayBuffer(i.length),p=new Uint8Array(a);for(let g=0;g<i.length;g++)p[g]=i.charCodeAt(g);return a}function M(){return Ir.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var Ir={stubThis:e=>e};function ye(e){let{id:t}=e;return{...e,id:q(t),transports:e.transports,type:e.type}}function ne(e){return e==="localhost"||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var C=class extends Error{constructor({message:t,code:r,cause:o,name:i}){super(t,{cause:o}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i??o.name,this.code=r}};function Dt({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new C({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(r.authenticatorSelection?.requireResidentKey===!0)return new C({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&r.authenticatorSelection?.userVerification==="required")return new C({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(r.authenticatorSelection?.userVerification==="required")return new C({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new C({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new C({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return r.pubKeyCredParams.filter(i=>i.type==="public-key").length===0?new C({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new C({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){let o=globalThis.location.hostname;if(ne(o)){if(r.rp.id!==o)return new C({message:`The RP ID "${r.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new C({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(r.user.id.byteLength<1||r.user.id.byteLength>64)return new C({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new C({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}var Le=class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){let t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}},Q=new Le;var Pr=["cross-platform","platform"];function Ae(e){if(e&&!(Pr.indexOf(e)<0))return e}async function Ut(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:r=!1}=e;if(!M())throw new Error("WebAuthn is not supported in this browser");let o={...t,challenge:q(t.challenge),user:{...t.user,id:q(t.user.id)},excludeCredentials:t.excludeCredentials?.map(ye)},i={};r&&(i.mediation="conditional"),i.publicKey=o,i.signal=Q.createNewAbortSignal();let a;try{a=await navigator.credentials.create(i)}catch(A){throw Dt({error:A,options:i})}if(!a)throw new Error("Registration was not completed");let{id:p,rawId:g,response:c,type:l}=a,h;typeof c.getTransports=="function"&&(h=c.getTransports());let d;if(typeof c.getPublicKeyAlgorithm=="function")try{d=c.getPublicKeyAlgorithm()}catch(A){De("getPublicKeyAlgorithm()",A)}let x;if(typeof c.getPublicKey=="function")try{let A=c.getPublicKey();A!==null&&(x=I(A))}catch(A){De("getPublicKey()",A)}let O;if(typeof c.getAuthenticatorData=="function")try{O=I(c.getAuthenticatorData())}catch(A){De("getAuthenticatorData()",A)}return{id:p,rawId:I(g),response:{attestationObject:I(c.attestationObject),clientDataJSON:I(c.clientDataJSON),transports:h,publicKeyAlgorithm:d,publicKey:x,authenticatorData:O},type:l,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:Ae(a.authenticatorAttachment)}}function De(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.
|
|
1
|
+
import{g as bt,h as Ct,i as yt}from"./chunk-WJPCDZSL.js";import{a as ft,b as mt,c as gt}from"./chunk-VYSRVTYI.js";import{e as ht,f as re}from"./chunk-2LOQXVFI.js";import{b as te}from"./chunk-2E6RCDAA.js";import{A as ct,C as dt,Q as pt,U as fe,b as st,ba as m,d as at,g as Te,p as lt,u as _e,y as ut}from"./chunk-S2NFWI7C.js";import{a as L}from"./chunk-OU4IOHLN.js";import{a as pe}from"./chunk-6LGTFWQS.js";import{c as k}from"./chunk-CDG7S4P5.js";var u=k(pe());var B="text-[var(--site-fg,#18181b)]",D="text-[var(--site-fg-muted,#71717a)]",At=`mb-1.5 block text-sm font-medium ${B}`,H=`text-sm ${D}`,St="mt-1 text-sm text-red-600 dark:text-red-400",br="min-h-11 rounded-[var(--site-radius-lg,0.5rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] px-3 text-[length:var(--site-input-text,16px)] text-[var(--site-fg,#18181b)] outline-none transition placeholder:text-[var(--site-fg-muted,#71717a)] focus:border-[var(--site-fg-muted,#71717a)] focus:ring-2 focus:ring-[color-mix(in_srgb,var(--brand-color,#18181b)_35%,transparent)] disabled:cursor-not-allowed disabled:opacity-60",Cr=`w-full ${br}`,yr="border-red-400 hover:border-red-400 focus:border-red-400 dark:border-red-500 dark:hover:border-red-500 dark:focus:border-red-500";function Et(e,t){return m(Cr,e&&yr,t)}var Ar="inline-flex cursor-pointer items-center justify-center gap-2 whitespace-nowrap rounded-[var(--site-radius-button,0.75rem)] text-sm font-semibold transition focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--brand-color,#18181b)] focus-visible:ring-offset-2 focus-visible:ring-offset-[var(--site-surface,#ffffff)] disabled:cursor-not-allowed disabled:opacity-60",Sr={primary:"bg-[var(--brand-color,#18181b)] text-[var(--brand-foreground,#ffffff)] hover:brightness-110",secondary:"border border-[var(--site-border,rgba(0,0,0,0.12))] bg-transparent text-[var(--site-fg,#18181b)] "+re,ghost:"bg-transparent text-[var(--site-fg-muted,#71717a)] hover:text-[var(--site-fg,#18181b)] "+re,danger:"border border-red-300 bg-transparent text-red-700 hover:bg-red-50 dark:border-red-800 dark:text-red-300 dark:hover:bg-red-950/40"},Er={md:"min-h-11 px-4",lg:"min-h-12 px-5"};function me(e){return[Ar,Sr[e?.variant??"primary"],Er[e?.size??"md"],e?.block?"flex w-full":"",e?.extra??""].filter(Boolean).join(" ")}var Rt="rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] text-[var(--site-fg,#18181b)]",ge="border-t border-[var(--site-border,rgba(0,0,0,0.12))]",Ie="rounded-[var(--site-radius-lg,0.5rem)] border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700 dark:border-red-900 dark:bg-red-950/40 dark:text-red-300",Rr={neutral:"text-[var(--site-fg,#18181b)] "+ht,success:"bg-emerald-50 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-300",warning:"bg-amber-50 text-amber-800 dark:bg-amber-950/40 dark:text-amber-300",danger:"bg-red-50 text-red-700 dark:bg-red-950/40 dark:text-red-300",info:"bg-sky-50 text-sky-700 dark:bg-sky-950/40 dark:text-sky-300",brand:"bg-[var(--brand-color,#18181b)] text-[var(--brand-foreground,#ffffff)]"};function wt(e="neutral"){return`inline-flex items-center gap-1 rounded-full px-2.5 py-0.5 text-xs font-medium ${Rr[e]}`}var Pe=`inline-flex cursor-pointer items-center gap-1.5 text-sm font-medium transition hover:text-[var(--site-fg,#18181b)] disabled:cursor-not-allowed disabled:opacity-60 ${D}`;var kt=k(pe());var he=k(L()),U=(0,kt.forwardRef)(function({variant:t,size:r,block:o,loading:i,leading:a,className:p,disabled:g,type:c="button",children:l,...h},d){return(0,he.jsxs)("button",{ref:d,type:c,disabled:g||i,"aria-busy":i||void 0,className:me({variant:t,size:r,block:o,extra:p}),...h,children:[i?(0,he.jsx)(ct,{className:"h-4 w-4 animate-spin","aria-hidden":"true"}):a,l]})});var K=k(pe());var z=k(L());function vt({length:e=6,value:t,onChange:r,onComplete:o,disabled:i,invalid:a,autoFocus:p,label:g,id:c,className:l}){let h=(0,K.useId)(),d=c??h,x=(0,K.useRef)(null),[O,A]=(0,K.useState)(!1),W=(0,K.useRef)(null),b=t.replace(/\D/g,"").slice(0,e);(0,K.useEffect)(()=>{b.length===e&&W.current!==b&&(W.current=b,o?.(b)),b.length<e&&(W.current=null)},[b,e,o]);let v=E=>{let T=E.clipboardData.getData("text").replace(/\D/g,"").slice(0,e);T&&(E.preventDefault(),r(T))},oe=E=>{E.key},Ee=Array.from({length:e},(E,T)=>b[T]??""),Re=Math.min(b.length,e-1);return(0,z.jsxs)("div",{className:m("relative",l),onClick:()=>x.current?.focus(),children:[(0,z.jsx)("div",{className:"flex gap-2","aria-hidden":"true",children:Ee.map((E,T)=>{let y=O&&T===Re&&!i;return(0,z.jsx)("div",{className:m("flex h-12 min-w-0 flex-1 items-center justify-center rounded-[var(--site-radius-lg,0.5rem)] border bg-[var(--site-surface,#ffffff)] font-mono text-xl font-semibold text-[var(--site-fg,#18181b)] transition",a?"border-red-400 dark:border-red-500":y?"border-[var(--brand-color,#18181b)] ring-2 ring-[color-mix(in_srgb,var(--brand-color,#18181b)_35%,transparent)]":"border-[var(--site-border,rgba(0,0,0,0.12))]",i&&"opacity-60"),children:E||(y?(0,z.jsx)("span",{className:"h-6 w-px animate-pulse bg-[var(--site-fg,#18181b)]"}):null)},T)})}),(0,z.jsx)("input",{ref:x,id:d,type:"text",inputMode:"numeric",pattern:"[0-9]*",autoComplete:"one-time-code",maxLength:e,value:b,disabled:i,autoFocus:p,"aria-label":g,"aria-invalid":a||void 0,onChange:E=>r(E.target.value.replace(/\D/g,"").slice(0,e)),onPaste:v,onKeyDown:oe,onFocus:()=>A(!0),onBlur:()=>A(!1),className:"absolute inset-0 h-full w-full cursor-text opacity-0"})]})}var be=k(pe());var F=k(L());function Tt({label:e,hint:t,error:r,labelTrailing:o,htmlFor:i,className:a,children:p}){return(0,F.jsxs)("div",{className:a,children:[(0,F.jsxs)("div",{className:"mb-1.5 flex items-center justify-between gap-2",children:[(0,F.jsx)("label",{htmlFor:i,className:m(At,"mb-0"),children:e}),o]}),p,r?(0,F.jsx)("p",{className:St,role:"alert",children:r}):t?(0,F.jsx)("p",{className:m(H,"mt-1"),children:t}):null]})}var _t=(0,be.forwardRef)(function({invalid:t,className:r,id:o,onKeyDown:i,onCompositionStart:a,onCompositionEnd:p,...g},c){let l=(0,be.useId)(),h=ft({onKeyDown:i,onCompositionStart:a,onCompositionEnd:p}),d=gt(c);return mt(d.ref,g.onChange),(0,F.jsx)("input",{ref:d.setRef,id:o??l,"aria-invalid":t||void 0,className:Et(t,r),...h.props,...g})});var J=k(L());function It({className:e}){return(0,J.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",className:e,role:"img","aria-label":"Google",children:[(0,J.jsx)("path",{d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z",fill:"var(--platform-icon-mono, #4285F4)"}),(0,J.jsx)("path",{d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z",fill:"var(--platform-icon-mono, #34A853)"}),(0,J.jsx)("path",{d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z",fill:"var(--platform-icon-mono, #FBBC05)"}),(0,J.jsx)("path",{d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z",fill:"var(--platform-icon-mono, #EA4335)"})]})}var _={index:"/account",login:"/account/login",orders:"/account/orders",order:e=>`/account/orders/${e}`,content:"/account/content",contentItem:e=>`/account/content/${encodeURIComponent(e)}`,courses:"/account/courses",settings:"/account/settings",profile:"/account/profile",devices:"/account/devices",apiSession:"/account/api/session",apiChallenge:"/account/api/challenge",apiVerify:"/account/api/verify",apiOauthStart:"/account/api/oauth/start",apiOauth2Authorize:"/account/api/oauth2/authorize",apiPasskeyLoginOptions:"/account/api/auth/passkey/options",apiPasskeyLoginVerify:"/account/api/auth/passkey/verify",apiPasskeys:"/account/api/passkeys",apiPasskey:e=>`/account/api/passkeys/${encodeURIComponent(e)}`,apiPasskeyRegisterOptions:"/account/api/passkeys/register/options",apiPasskeyRegister:"/account/api/passkeys/register",apiProfile:"/account/api/profile",apiEmailChange:"/account/api/email-change",apiEmailChangeVerify:"/account/api/email-change/verify",apiAddresses:"/account/api/addresses",apiAddress:e=>`/account/api/addresses/${encodeURIComponent(e)}`,apiAddressDefault:e=>`/account/api/addresses/${encodeURIComponent(e)}/default`,apiTaxIdentities:"/account/api/tax-identities",apiTaxIdentity:e=>`/account/api/tax-identities/${encodeURIComponent(e)}`,apiConsents:"/account/api/consents",apiData:"/account/api/data",apiErasure:"/account/api/erasure",apiContentOpen:e=>`/account/api/content/${encodeURIComponent(e)}/open`,apiContentQuiz:e=>`/account/api/content/${encodeURIComponent(e)}/quiz`,apiContentTranscript:e=>`/account/api/content/${encodeURIComponent(e)}/transcript`,apiProgress:"/account/api/progress",apiCertificate:e=>`/account/api/deliverables/${encodeURIComponent(e)}/certificate`,apiOrderReceipt:e=>`/account/api/orders/${encodeURIComponent(e)}/receipt`};var gn="knr_customer";var Pt=["passkey","google","apple","line","kakao","external_oidc","email_code","email_link"],wr=["passkey","google","email_code","email_link"],kr="email_code",vr=["email_code","email_link"];function xe(e){return typeof e=="string"&&Pt.includes(e)}function hn(e){let t=new Set(Array.isArray(e)?e.filter(xe).filter(r=>wr.includes(r)):vr);return t.add(kr),Pt.filter(r=>t.has(r))}function Oe(e,t=_.index){if(typeof e!="string")return t;let r=e.trim();return!r||r.length>512||!r.startsWith("/")||r.startsWith("//")||r.startsWith("/\\")||/[\r\n\0]/.test(r)||/^[a-z][a-z0-9+.-]*:/i.test(r)?t:r}var Tr=[{id:"orders",order:10,route:_.orders,navLabelKey:"orders",icon:"shopping-bag",apiResourcePrefixes:["/orders","/reviews"],visibility:"capability"},{id:"content",order:20,route:_.content,navLabelKey:"content",icon:"book-open",apiResourcePrefixes:["/deliverables","/units","/progress","/access"],visibility:"capability"},{id:"account",order:90,route:_.settings,navLabelKey:"account",icon:"user",apiResourcePrefixes:["/me","/session","/sessions","/email-change","/addresses","/tax-identities","/consents","/passkeys","/data","/erasure"],visibility:"always"}];function xt(e){let t=new Set(e.filter(r=>r.visible).map(r=>r.id));return[...Tr].filter(r=>t.has(r.id)).sort((r,o)=>r.order-o.order)}function _r(e,t){let r=e?.get("utm_source")?.toLowerCase()??"";if(/^(ig|instagram|threads|fb|facebook)/.test(r))return!0;let o=(t??"").toLowerCase();return[/threads\.net/i,/threads\.com/i,/instagram\.com/i,/m\.facebook\.com/i,/l\.facebook\.com/i,/lm\.facebook\.com/i].some(a=>a.test(o))}function Ot(e){if(typeof navigator>"u")return!1;let t=navigator.userAgent?.toLowerCase()??"";return!!([/\bbarcelona\b/i,/fban|fbav/i,/fb_iab/i,/fb_iab\/threads|fban\/threads|fbios.*threads/i,/instagram/i,/threads/i,/fbios/i,/line\//i,/wechat/i,/micromessenger/i,/twitter/i,/linkedin/i,/reddit/i,/pinterest/i,/discord/i,/snapchat/i,/tiktok/i,/kakaotalk/i,/naver/i,/webview/i].some(o=>o.test(t))||e&&_r(e.searchParams,e.referrer))}var Ce="NETWORK_ERROR";async function Nt(e,t){let r=await e.json().catch(()=>null);return!e.ok||!r?.ok?{ok:!1,code:r?.code??t,...typeof r?.retryAfter=="number"?{retryAfter:r.retryAfter}:{}}:r}async function G(e,t,r){try{let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify(t??{})});return await Nt(o,r)}catch{return{ok:!1,code:Ce}}}function En(){let e=_;return{altchaChallengeUrl:"/api/form-protection/altcha",challengeUrl:"/api/form-protection/challenge",requestChallenge:({email:t,locale:r,returnTo:o,protection:i})=>G(e.apiChallenge,{email:t,locale:r,returnTo:o,...i},"SERVER_ERROR"),verifyCode:({email:t,code:r})=>G(e.apiVerify,{method:"code",email:t,code:r},"INVALID_CODE"),verifyToken:({method:t,token:r})=>G(e.apiVerify,{method:t,token:r},"CODE_EXPIRED"),startOauth:({method:t,returnTo:r,locale:o})=>G(e.apiOauthStart,{method:t,returnTo:r,locale:o},"METHOD_DISABLED"),passkeyLoginOptions:()=>G(e.apiPasskeyLoginOptions,{},"SERVER_ERROR"),passkeyLoginVerify:t=>G(e.apiPasskeyLoginVerify,t,"PASSKEY_FAILED"),listPasskeys:async()=>{try{let t=await fetch(e.apiPasskeys,{credentials:"same-origin"});return await Nt(t,"UNAUTHENTICATED")}catch{return{ok:!1,code:Ce}}},passkeyRegisterOptions:()=>G(e.apiPasskeyRegisterOptions,{},"SERVER_ERROR"),passkeyRegister:t=>G(e.apiPasskeyRegister,t,"PASSKEY_FAILED"),session:async()=>{let t=await fetch(e.apiSession,{credentials:"same-origin"});if(t.status===401)return null;if(!t.ok)throw new Error(`HTTP ${t.status}`);let r=await t.json();return!r?.ok||!r.contact?null:{contact:r.contact,sections:r.sections??[],landing:r.landing??e.index}},signOut:async()=>{await fetch(e.apiSession,{method:"DELETE",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({mode:"current"})}).catch(()=>{})}}}var Lt=new Set(["PASSKEY_CANCELLED"]);function Ne(e,t){switch((e??"").toUpperCase()){case"INVALID_EMAIL":return t.errorInvalidEmail;case"INVALID_CODE":return t.errorInvalidCode;case"CODE_EXPIRED":return t.errorCodeExpired;case"TOO_MANY_ATTEMPTS":return t.errorTooManyAttempts;case"ACCOUNT_BLOCKED":return t.errorAccountBlocked;case"RATE_LIMITED":return t.errorRateLimited;case"BOT_PROTECTION_FAILED":return t.errorBotProtection;case"SIGNUP_DISABLED":return t.errorSignupDisabled;case"SEND_FAILED":return t.errorSendFailed;case"METHOD_DISABLED":return t.errorMethodDisabled;case"EMAIL_NOT_VERIFIED":return t.errorEmailNotVerified;case"NO_EMAIL":return t.errorNoEmail;case"PROVIDER_DENIED":case"TOKEN_EXCHANGE_FAILED":case"INVALID_ID_TOKEN":case"INVALID_STATE":return t.errorProviderFailed;case"PASSKEY_UNSUPPORTED":return t.errorPasskeyUnsupported;case"PASSKEY_FAILED":case"NOT_FOUND":case"VERIFY_FAILED":case"CHALLENGE_EXPIRED":case"NO_HOST":return t.errorPasskeyFailed;case"ALREADY_REGISTERED":return t.errorPasskeyAlreadyRegistered;case"SERVICE_UNAVAILABLE":return t.errorServiceUnavailable;case"SHARED_SENDER_PAUSED":return t.errorEmailSignInPaused;case Ce:default:return t.errorGeneric}}function I(e){let t=new Uint8Array(e),r="";for(let i of t)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function q(e){let t=e.replace(/-/g,"+").replace(/_/g,"/"),r=(4-t.length%4)%4,o=t.padEnd(t.length+r,"="),i=atob(o),a=new ArrayBuffer(i.length),p=new Uint8Array(a);for(let g=0;g<i.length;g++)p[g]=i.charCodeAt(g);return a}function M(){return Ir.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential=="function")}var Ir={stubThis:e=>e};function ye(e){let{id:t}=e;return{...e,id:q(t),transports:e.transports,type:e.type}}function ne(e){return e==="localhost"||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var C=class extends Error{constructor({message:t,code:r,cause:o,name:i}){super(t,{cause:o}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=i??o.name,this.code=r}};function Dt({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new C({message:"Registration ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else if(e.name==="ConstraintError"){if(r.authenticatorSelection?.requireResidentKey===!0)return new C({message:"Discoverable credentials were required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT",cause:e});if(t.mediation==="conditional"&&r.authenticatorSelection?.userVerification==="required")return new C({message:"User verification was required during automatic registration but it could not be performed",code:"ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE",cause:e});if(r.authenticatorSelection?.userVerification==="required")return new C({message:"User verification was required but no available authenticator supported it",code:"ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT",cause:e})}else{if(e.name==="InvalidStateError")return new C({message:"The authenticator was previously registered",code:"ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED",cause:e});if(e.name==="NotAllowedError")return new C({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="NotSupportedError")return r.pubKeyCredParams.filter(i=>i.type==="public-key").length===0?new C({message:'No entry in pubKeyCredParams was of type "public-key"',code:"ERROR_MALFORMED_PUBKEYCREDPARAMS",cause:e}):new C({message:"No available authenticator supported any of the specified pubKeyCredParams algorithms",code:"ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG",cause:e});if(e.name==="SecurityError"){let o=globalThis.location.hostname;if(ne(o)){if(r.rp.id!==o)return new C({message:`The RP ID "${r.rp.id}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new C({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="TypeError"){if(r.user.id.byteLength<1||r.user.id.byteLength>64)return new C({message:"User ID was not between 1 and 64 characters",code:"ERROR_INVALID_USER_ID_LENGTH",cause:e})}else if(e.name==="UnknownError")return new C({message:"The authenticator was unable to process the specified options, or could not create a new credential",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}var Le=class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let r=new Error("Cancelling existing WebAuthn API call for new one");r.name="AbortError",this.controller.abort(r)}let t=new AbortController;return this.controller=t,t.signal}cancelCeremony(){if(this.controller){let t=new Error("Manually cancelling existing WebAuthn API call");t.name="AbortError",this.controller.abort(t),this.controller=void 0}}},Q=new Le;var Pr=["cross-platform","platform"];function Ae(e){if(e&&!(Pr.indexOf(e)<0))return e}async function Ut(e){!e.optionsJSON&&e.challenge&&(console.warn("startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:r=!1}=e;if(!M())throw new Error("WebAuthn is not supported in this browser");let o={...t,challenge:q(t.challenge),user:{...t.user,id:q(t.user.id)},excludeCredentials:t.excludeCredentials?.map(ye)},i={};r&&(i.mediation="conditional"),i.publicKey=o,i.signal=Q.createNewAbortSignal();let a;try{a=await navigator.credentials.create(i)}catch(A){throw Dt({error:A,options:i})}if(!a)throw new Error("Registration was not completed");let{id:p,rawId:g,response:c,type:l}=a,h;typeof c.getTransports=="function"&&(h=c.getTransports());let d;if(typeof c.getPublicKeyAlgorithm=="function")try{d=c.getPublicKeyAlgorithm()}catch(A){De("getPublicKeyAlgorithm()",A)}let x;if(typeof c.getPublicKey=="function")try{let A=c.getPublicKey();A!==null&&(x=I(A))}catch(A){De("getPublicKey()",A)}let O;if(typeof c.getAuthenticatorData=="function")try{O=I(c.getAuthenticatorData())}catch(A){De("getAuthenticatorData()",A)}return{id:p,rawId:I(g),response:{attestationObject:I(c.attestationObject),clientDataJSON:I(c.clientDataJSON),transports:h,publicKeyAlgorithm:d,publicKey:x,authenticatorData:O},type:l,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:Ae(a.authenticatorAttachment)}}function De(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.
|
|
2
2
|
`,t)}function Se(){if(!M())return Ue.stubThis(new Promise(t=>t(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?Ue.stubThis(new Promise(t=>t(!1))):Ue.stubThis(e.isConditionalMediationAvailable())}var Ue={stubThis:e=>e};function Mt({error:e,options:t}){let{publicKey:r}=t;if(!r)throw Error("options was missing required publicKey property");if(e.name==="AbortError"){if(t.signal instanceof AbortSignal)return new C({message:"Authentication ceremony was sent an abort signal",code:"ERROR_CEREMONY_ABORTED",cause:e})}else{if(e.name==="NotAllowedError")return new C({message:e.message,code:"ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY",cause:e});if(e.name==="SecurityError"){let o=globalThis.location.hostname;if(ne(o)){if(r.rpId!==o)return new C({message:`The RP ID "${r.rpId}" is invalid for this domain`,code:"ERROR_INVALID_RP_ID",cause:e})}else return new C({message:`${globalThis.location.hostname} is an invalid domain`,code:"ERROR_INVALID_DOMAIN",cause:e})}else if(e.name==="UnknownError")return new C({message:"The authenticator was unable to process the specified options, or could not create a new assertion signature",code:"ERROR_AUTHENTICATOR_GENERAL_ERROR",cause:e})}return e}async function Bt(e){!e.optionsJSON&&e.challenge&&(console.warn("startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information."),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:r=!1,verifyBrowserAutofillInput:o=!0}=e;if(!M())throw new Error("WebAuthn is not supported in this browser");let i;t.allowCredentials?.length!==0&&(i=t.allowCredentials?.map(ye));let a={...t,challenge:q(t.challenge),allowCredentials:i},p={};if(r){if(!await Se())throw Error("Browser does not support WebAuthn autofill");if(document.querySelectorAll("input[autocomplete$='webauthn']").length<1&&o)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');p.mediation="conditional",a.allowCredentials=[]}p.publicKey=a,p.signal=Q.createNewAbortSignal();let g;try{g=await navigator.credentials.get(p)}catch(O){throw Mt({error:O,options:p})}if(!g)throw new Error("Authentication was not completed");let{id:c,rawId:l,response:h,type:d}=g,x;return h.userHandle&&(x=I(h.userHandle)),{id:c,rawId:I(l),response:{authenticatorData:I(h.authenticatorData),clientDataJSON:I(h.clientDataJSON),signature:I(h.signature),userHandle:x},type:d,clientExtensionResults:g.getClientExtensionResults(),authenticatorAttachment:Ae(g.authenticatorAttachment)}}async function Me(){if(typeof PublicKeyCredential.getClientCapabilities=="function"){let e=await PublicKeyCredential.getClientCapabilities(),t=V(e.userVerifyingPlatformAuthenticator);t==="unknown"&&typeof PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable=="function"&&(await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()?t="supported":t="unsupported");let r=V(e.conditionalGet);return r==="unknown"&&typeof PublicKeyCredential.isConditionalMediationAvailable=="function"&&(await PublicKeyCredential.isConditionalMediationAvailable()?r="supported":r="unsupported"),Kt.stubThis({conditionalCreate:V(e.conditionalCreate),conditionalGet:r,hybridTransport:V(e.hybridTransport),passkeyPlatformAuthenticator:V(e.passkeyPlatformAuthenticator),userVerifyingPlatformAuthenticator:t,relatedOrigins:V(e.relatedOrigins),signalAllAcceptedCredentials:V(e.signalAllAcceptedCredentials),signalCurrentUserDetails:V(e.signalCurrentUserDetails),signalUnknownCredential:V(e.signalUnknownCredential)})}return Kt.stubThis({conditionalCreate:"unknown",conditionalGet:"unknown",hybridTransport:"unknown",passkeyPlatformAuthenticator:"unknown",userVerifyingPlatformAuthenticator:"unknown",relatedOrigins:"unknown",signalAllAcceptedCredentials:"unknown",signalCurrentUserDetails:"unknown",signalUnknownCredential:"unknown"})}function V(e){if(e===!0)return"supported";if(e===!1)return"unsupported";if(typeof e>"u")return"unknown";throw new Error("Unexpected capability value:",e)}var Kt={stubThis:e=>e};function Vt(){return typeof window<"u"&&M()}function $t(){return Vt()?Se().catch(()=>!1):Promise.resolve(!1)}async function Ht(){if(!Vt())return!1;try{return(await Me()).userVerifyingPlatformAuthenticator==="supported"}catch{return!1}}function Ft(e){return e instanceof C?e.code==="ERROR_CEREMONY_ABORTED":e instanceof Error&&(e.name==="NotAllowedError"||e.name==="AbortError")}function Z(){Q.cancelCeremony()}async function Gt(e,t){let r=await e.passkeyLoginOptions();if(!r.ok)return r;let o;try{o=await Bt({optionsJSON:r.options,useBrowserAutofill:t.useBrowserAutofill??!1})}catch(i){return{ok:!1,code:Ft(i)?"PASSKEY_CANCELLED":"PASSKEY_FAILED"}}return t.onAssertion?.(),e.passkeyLoginVerify({challengeId:r.challengeId,response:o,returnTo:t.returnTo,locale:t.locale})}async function Wt(e,t={}){let r=await e.passkeyRegisterOptions();if(!r.ok)return r;let o;try{o=await Ut({optionsJSON:r.options})}catch(i){return i instanceof C&&i.code==="ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED"?{ok:!1,code:"ALREADY_REGISTERED"}:{ok:!1,code:Ft(i)?"PASSKEY_CANCELLED":"PASSKEY_FAILED"}}return e.passkeyRegister({response:o,name:t.name})}var Yt="kanorio.customer.last-method",Be="kanorio.customer.passkey-offer",zt=2;function Jt(e){try{return typeof localStorage>"u"?null:localStorage.getItem(e)}catch{return null}}function Ke(e,t){try{if(typeof localStorage>"u")return;t===null?localStorage.removeItem(e):localStorage.setItem(e,t)}catch{}}function Ve(e){let t=Jt(`${Yt}:${e}`);return xe(t)?t:null}function $e(e,t){Ke(`${Yt}:${e}`,t)}function qt(e){let t=Number(Jt(`${Be}:${e}`)??"0");return Number.isFinite(t)&&t>0?t:0}function jt(e){Ke(`${Be}:${e}`,String(qt(e)+1))}function Xt(e){Ke(`${Be}:${e}`,String(zt))}function Qt(e){return qt(e)>=zt}var n=k(L()),xr=30,Or=15e3,Nr=3e3,Lr=new Set(["email_code","email_link"]),Dr={"shopping-bag":pt,"book-open":at,user:fe};function Zt(){if(!(typeof window>"u"))try{let e=new URL(window.location.href),t=!1;for(let r of["token","handoff","error","verify"])e.searchParams.has(r)&&(e.searchParams.delete(r),t=!0);t&&window.history.replaceState(window.history.state,"",e.toString())}catch{}}function Ur(e){let[t,r]=(0,u.useState)(()=>Date.now());return(0,u.useEffect)(()=>{if(e===null||e<=Date.now())return;let o=setInterval(()=>r(Date.now()),1e3);return()=>clearInterval(o)},[e]),e===null?0:Math.max(0,Math.ceil((e-t)/1e3))}function ti({variant:e,auth:t,initial:r,returnTo:o,onNavigate:i,onSignedIn:a,onSignedOut:p,className:g}){let{transport:c,messages:l,methods:h,siteId:d,siteName:x,locale:O,siteLocale:A,accountBaseUrl:W}=t,[b,v]=(0,u.useState)(()=>r?.token?.trim()||r?.handoff?.trim()?{kind:"consuming"}:r?.verify&&r.email?.trim()?{kind:"code",email:r.email.trim(),sentAt:Date.now()}:{kind:"identify"}),[oe,Ee]=(0,u.useState)(r?.email??""),[Re,E]=(0,u.useState)(""),[T,y]=(0,u.useState)(null),[He,R]=(0,u.useState)(()=>r?.error?Ne(r.error,l):null),[er,tr]=(0,u.useState)(null),[Fe,rr]=(0,u.useState)(!1),w=(0,u.useRef)(!0),Ge=(0,u.useRef)(null),We=(0,u.useMemo)(()=>h.filter(s=>!Lr.has(s)),[h]),Ye=We.length>0?l.signInSubtitleChoose:l.signInSubtitle,ie=h.includes("passkey"),$=o?Oe(o):null,{getProtectionData:ze,isSubmittable:se,registerFocus:ae,reset:Je,fieldProps:nr,challengeProps:qe,provider:we,prepare:je,renewCaptcha:Xe}=yt({variant:"full",context:`customer-login:${d}`,challengeUrl:c.challengeUrl,altchaChallengeUrl:c.altchaChallengeUrl,entry:"customer_login"}),Qe=we==="hcaptcha"||we==="recaptcha"&&qe.captcha?.recaptchaVersion==="v2",[Ze,le]=(0,u.useState)(!1),[or,ir]=(0,u.useState)(0),j=(0,u.useRef)(null),X=(0,u.useRef)(null),ue=(0,u.useCallback)(()=>{j.current=null,X.current&&(clearTimeout(X.current),X.current=null)},[]),et=(0,u.useCallback)(s=>{if(se){s();return}if(Qe){y(null),R(l.errorBotProtection);return}j.current=s,X.current&&clearTimeout(X.current),X.current=setTimeout(()=>{j.current&&(j.current=null,y(null),le(!0),R(l.errorBotProtection))},Or)},[se,Qe,l.errorBotProtection]);(0,u.useEffect)(()=>{if(!se||!j.current)return;let s=j.current;ue(),s()},[se,ue]);let ce=(0,u.useRef)(null),sr=(0,u.useCallback)(s=>{ce.current&&(clearTimeout(ce.current),ce.current=null),s==="error"?le(!0):s==="verifying"&&(ce.current=setTimeout(()=>le(!0),Nr))},[]),tt=(0,u.useCallback)(()=>{Je(),ae(),Xe(),ir(s=>s+1)},[Je,ae,Xe]);(0,u.useEffect)(()=>(w.current=!0,rr(Ot()),tr(Ve(d)),()=>{w.current=!1,ue(),Z()}),[d,ue]),(0,u.useEffect)(()=>{let s=f=>{f.persisted&&y(null)};return window.addEventListener("pageshow",s),()=>window.removeEventListener("pageshow",s)},[]);let P=(0,u.useCallback)((s,f)=>{w.current&&(!f?.raw&&Lt.has(s.toUpperCase())||R(f?.raw?s:Ne(s,l)))},[l]),de=(0,u.useCallback)(s=>{if(e==="page"){v({kind:"redirecting"});let f=Oe(s.returnTo??$??`${W}${t.landing??_.index}`);window.location.assign(f);return}y(null),v({kind:"identify"})},[e,$,W,t.landing]),ee=(0,u.useCallback)(async(s,f)=>{$e(d,f),a?.(s,f);let S=await c.session().then(Y=>({known:!0,overview:Y}),()=>({known:!1}));if(w.current){if(S.known?t.applySession(S.overview):t.retrySession(),f!=="passkey"&&ie&&!Qt(d)&&await Ht()){let Y=await c.listPasskeys();if(!w.current)return;if(Y.ok&&Y.passkeys.length===0){y(null),R(null),v({kind:"passkey-offer",grant:s});return}}de(s)}},[d,a,c,t,ie,de]),ar=(0,u.useRef)(r);(0,u.useEffect)(()=>{let s=ar.current;if(!s)return;(s.error||s.verify)&&Zt();let f=s.token?.trim()||null,S=s.handoff?.trim()||null;if(f||S){Zt();let Y=f?"link":"handoff",ke=f??S;if(Ge.current===ke)return;Ge.current=ke,c.verifyToken({method:Y,token:ke}).then(ve=>{if(!w.current)return;if(!ve.ok){v({kind:"identify"}),P(ve.code);return}let hr=Y==="link"?"email_link":Ve(d)??"google";return ee(ve,hr)}).catch(()=>{w.current&&(v({kind:"identify"}),P("SERVER_ERROR"))});return}},[]);let rt=(0,u.useCallback)(async(s,f)=>{y(f==="first"?"challenge":"resend"),R(null),await je();let S=await c.requestChallenge({email:s,locale:A,returnTo:$??void 0,protection:ze()});if(w.current){if(y(null),tt(),!S.ok){S.code==="BOT_PROTECTION_FAILED"&&le(!0),P(S.code);return}E(""),v({kind:"code",email:s,sentAt:Date.now()})}},[c,A,$,ze,tt,P,je]),lr=s=>{s.preventDefault();let f=oe.trim();if(!f||!f.includes("@")){R(l.errorInvalidEmail);return}Z(),R(null),y("challenge"),et(()=>{rt(f,"first")})},ur=s=>{y("resend"),et(()=>{rt(s,"resend")})},cr=(0,u.useCallback)(async(s,f)=>{if(!/^\d{6}$/.test(f)){R(l.errorInvalidCode);return}y("verify"),R(null);let S=await c.verifyCode({email:s,code:f});if(w.current){if(!S.ok){y(null),E(""),P(S.code);return}await ee(S,"email_code")}},[c,l.errorInvalidCode,P,ee]),nt=(0,u.useCallback)(async s=>{s||(Z(),y("passkey"),R(null));let f=await Gt(c,{useBrowserAutofill:s,returnTo:$??void 0,locale:A,onAssertion:()=>{w.current&&v({kind:"consuming"})}});if(w.current){if(!f.ok){y(null),v(S=>S.kind==="consuming"?{kind:"identify"}:S),P(f.code);return}await ee(f,"passkey")}},[c,$,A,P,ee]);(0,u.useEffect)(()=>{if(!ie||b.kind!=="identify"||t.user)return;let s=!1;return $t().then(f=>{!s&&f&&nt(!0)}),()=>{s=!0,Z()}},[ie,b.kind,t.user]);let dr=(0,u.useCallback)(async s=>{if(Fe){v({kind:"in-app"});return}Z(),y("oauth"),R(null);let f=await c.startOauth({method:s,returnTo:$??void 0,locale:A});if(w.current){if(!f.ok){y(null),P(f.code);return}$e(d,s),window.location.assign(f.url)}},[Fe,c,$,A,d,P]),pr=async s=>{y("passkey-register"),R(null);let f=await Wt(c);if(w.current){if(y(null),!f.ok){P(f.code);return}Xt(d),de(s)}},fr=s=>{jt(d),de(s)},mr=async()=>{y("verify"),await t.signOut(),w.current&&(y(null),p?.(),i?.())},gr=te(l.signInTitle,{siteName:x}).trim(),ot=He?(0,n.jsx)("div",{role:"alert",className:m(Ie,"mb-4"),children:He}):null,N;b.kind==="consuming"||b.kind==="redirecting"?N=(0,n.jsx)("p",{className:m("py-8 text-center text-sm",D),"aria-live":"polite",children:l.verifying}):b.kind==="passkey-offer"?N=(0,n.jsx)(Yr,{messages:l,busy:T==="passkey-register",onCreate:()=>{pr(b.grant)},onSkip:()=>fr(b.grant)}):b.kind==="in-app"?N=(0,n.jsx)(zr,{messages:l,onBack:()=>v({kind:"identify"})}):b.kind==="code"?N=(0,n.jsx)(Gr,{email:b.email,sentAt:b.sentAt,code:Re,onCodeChange:E,busy:T,messages:l,onVerify:s=>{cr(b.email,s)},onResend:()=>ur(b.email),onChangeEmail:()=>{v({kind:"identify"}),E(""),R(null)}}):t.pending?N=(0,n.jsxs)("p",{className:m("flex items-center gap-2 py-6 text-sm",D),role:"status","aria-live":"polite",children:[(0,n.jsx)("span",{className:"inline-block h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent","aria-hidden":"true"}),l.sessionChecking]}):t.sessionUnavailable?N=(0,n.jsxs)("div",{children:[(0,n.jsx)("div",{role:"alert",className:m(Ie,"mb-4"),children:l.errorServiceUnavailable}),(0,n.jsx)(U,{type:"button",block:!0,onClick:t.retrySession,children:l.contentRetry})]}):t.user?N=e==="panel"?(0,n.jsx)(Wr,{auth:t,busy:T!==null,onNavigate:i,onSignOut:()=>{mr()}}):(0,n.jsx)("p",{className:m("text-sm",D),children:(0,n.jsx)("a",{href:`${W}${t.landing??_.index}`,className:me({block:!0}),children:l.signedInContinue})}):N=(0,n.jsx)(Mr,{email:oe,onEmailChange:s=>{ae(),Ee(s)},onEmailFocus:ae,onSubmit:lr,otherMethods:We,lastMethod:er,busy:T,messages:l,onPasskey:()=>{nt(!1)},onOauth:s=>{dr(s)}});let it=b.kind==="identify"&&(t.pending||t.sessionUnavailable)?null:(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(Ct,{...nr,locale:O,renderAltcha:!1}),(0,n.jsx)(bt,{...qe,locale:O,invisible:!0,revealed:Ze,generation:or,onStateChange:sr,onCaptchaError:()=>R(l.errorBotProtection),className:Ze||we!=="kanorio"?"mt-3":void 0})]});return e==="page"?(0,n.jsx)("div",{className:m("mx-auto w-full max-w-md",g),children:(0,n.jsxs)("div",{className:m(Rt,"p-6 sm:p-8"),children:[(0,n.jsxs)("div",{className:"mb-6",children:[(0,n.jsx)("h1",{className:m("text-xl font-semibold",B),children:gr}),b.kind==="identify"&&!t.user&&!t.pending&&!t.sessionUnavailable?(0,n.jsx)("p",{className:m("mt-1",H),children:Ye}):null]}),ot,N,b.kind==="identify"||b.kind==="code"?it:null]})}):(0,n.jsxs)("div",{className:g,children:[b.kind==="identify"&&!t.user&&!t.pending&&!t.sessionUnavailable?(0,n.jsx)("p",{className:m("mb-4",H),children:Ye}):null,ot,N,b.kind==="identify"||b.kind==="code"?it:null]})}function Mr({email:e,onEmailChange:t,onEmailFocus:r,onSubmit:o,otherMethods:i,lastMethod:a,busy:p,messages:g,onPasskey:c,onOauth:l}){let h=p!==null;return(0,n.jsxs)("div",{className:"space-y-4",children:[i.length>0?(0,n.jsxs)("div",{className:"space-y-2",children:[i.map(d=>(0,n.jsx)(Hr,{method:d,last:a===d,loading:d==="passkey"&&p==="passkey"||d!=="passkey"&&p==="oauth",disabled:h,messages:g,onClick:()=>d==="passkey"?c():l(d)},d)),(0,n.jsxs)("div",{className:"flex items-center gap-3 py-1","aria-hidden":"true",children:[(0,n.jsx)("span",{className:m("h-px flex-1",ge)}),(0,n.jsx)("span",{className:m("text-xs uppercase tracking-wide",D),children:g.orContinueWith}),(0,n.jsx)("span",{className:m("h-px flex-1",ge)})]})]}):null,(0,n.jsxs)("form",{onSubmit:o,className:"space-y-3",noValidate:!0,children:[(0,n.jsx)(Tt,{label:g.emailLabel,htmlFor:"customer-login-email",hint:i.length>0?g.emailCodeHint:void 0,children:(0,n.jsx)(_t,{id:"customer-login-email",type:"email",name:"email",inputMode:"email",required:!0,autoComplete:"username webauthn",value:e,onFocus:r,onChange:d=>t(d.target.value),placeholder:g.emailPlaceholder,disabled:h&&p!=="passkey"})}),(0,n.jsx)(U,{type:"submit",block:!0,loading:p==="challenge",disabled:h,leading:a==="email_code"||a==="email_link"?(0,n.jsx)(Fr,{}):void 0,children:g.continueWithEmail})]})]})}var Br=({className:e})=>(0,n.jsx)(ut,{className:e,"aria-hidden":"true"}),Kr={passkey:({className:e})=>(0,n.jsx)(_e,{className:e,"aria-hidden":"true"}),google:({className:e})=>(0,n.jsx)(It,{className:e})},Vr={apple:"Apple",line:"LINE",kakao:"Kakao",external_oidc:"SSO"};function $r(e,t){return e==="passkey"?t.continueWithPasskey:e==="google"?t.continueWithGoogle:te(t.continueWithProvider,{provider:Vr[e]??e})}function Hr({method:e,last:t,loading:r,disabled:o,messages:i,onClick:a}){let p=Kr[e]??Br;return(0,n.jsxs)(U,{type:"button",variant:"secondary",block:!0,loading:r,disabled:o,onClick:a,leading:(0,n.jsx)(p,{className:"h-4 w-4"}),className:"relative",children:[(0,n.jsx)("span",{children:$r(e,i)}),t?(0,n.jsx)("span",{className:m(wt("neutral"),"absolute right-3"),children:i.lastUsed}):null]})}function Fr(){return(0,n.jsx)(Te,{className:"h-4 w-4","aria-hidden":"true"})}function Gr({email:e,sentAt:t,code:r,onCodeChange:o,busy:i,messages:a,onVerify:p,onResend:g,onChangeEmail:c}){let l=Ur(t+xr*1e3),h=i==="verify";return(0,n.jsxs)("form",{onSubmit:d=>{d.preventDefault(),h||p(r)},className:"space-y-4",noValidate:!0,children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:m("text-base font-semibold",B),children:a.codeStepTitle}),(0,n.jsx)("p",{className:m("mt-1 break-words",H),children:te(a.codeSentHint,{email:e})})]}),(0,n.jsx)(vt,{label:a.codeLabel,value:r,onChange:o,onComplete:d=>!h&&p(d),disabled:h,autoFocus:!0}),(0,n.jsx)(U,{type:"submit",block:!0,loading:h,disabled:i!==null||r.length!==6,children:a.verifyAndSignIn}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[(0,n.jsx)("button",{type:"button",className:Pe,disabled:l>0||i!==null,onClick:g,"aria-live":"polite",children:i==="resend"?a.sendingCode:l>0?te(a.resendIn,{seconds:String(l)}):a.resendCode}),(0,n.jsxs)("button",{type:"button",className:Pe,disabled:i!==null,onClick:c,children:[(0,n.jsx)(st,{className:"h-4 w-4","aria-hidden":"true"}),a.useAnotherEmail]})]})]})}function Wr({auth:e,busy:t,onNavigate:r,onSignOut:o}){let{messages:i,accountBaseUrl:a}=e,p=e.user,g=xt(e.sections),l=(p.name?.trim()||p.email||"").trim().charAt(0).toUpperCase();return(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsx)("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-base font-semibold",style:{backgroundColor:"var(--brand-color, #18181b)",color:"var(--brand-foreground, #ffffff)"},"aria-hidden":"true",children:l||(0,n.jsx)(fe,{className:"h-5 w-5"})}),(0,n.jsxs)("div",{className:"min-w-0",children:[p.name?.trim()?(0,n.jsx)("p",{className:m("truncate text-sm font-semibold",B),children:p.name}):null,p.email?(0,n.jsx)("p",{className:m("truncate text-sm",D),children:p.email}):null]})]}),(0,n.jsx)("nav",{"aria-label":i.shell.menu,children:(0,n.jsxs)("ul",{className:"-mx-2 space-y-0.5",children:[(g.length>0?g:null)?.map(h=>{let d=Dr[h.icon];return(0,n.jsx)("li",{children:(0,n.jsxs)("a",{href:`${a}${h.route}`,onClick:r,className:m("flex min-h-11 items-center gap-3 rounded-[var(--site-radius-button,0.5rem)] px-2 text-sm font-medium transition "+re,B),children:[(0,n.jsx)(d,{className:m("h-4 w-4 shrink-0",D),"aria-hidden":"true"}),i.nav[h.navLabelKey]]})},h.id)}),g.length===0?(0,n.jsx)("li",{children:(0,n.jsxs)("a",{href:`${a}${_.index}`,onClick:r,className:m("flex min-h-11 items-center gap-3 rounded-[var(--site-radius-button,0.5rem)] px-2 text-sm font-medium",B),children:[(0,n.jsx)(fe,{className:m("h-4 w-4 shrink-0",D),"aria-hidden":"true"}),i.title]})}):null]})}),(0,n.jsx)("div",{className:m("pt-3",ge),children:(0,n.jsx)(U,{type:"button",variant:"ghost",block:!0,loading:t,onClick:o,leading:(0,n.jsx)(dt,{className:"h-4 w-4","aria-hidden":"true"}),children:i.signOut})})]})}function Yr({messages:e,busy:t,onCreate:r,onSkip:o}){return(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{className:"flex items-start gap-3",children:[(0,n.jsx)("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-[color-mix(in_srgb,var(--brand-color,#18181b)_12%,transparent)] text-[var(--brand-text,var(--brand-color,#18181b))]","aria-hidden":"true",children:(0,n.jsx)(_e,{className:"h-5 w-5"})}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:m("text-base font-semibold",B),children:e.passkeyOfferTitle}),(0,n.jsx)("p",{className:m("mt-1",H),children:e.passkeyOfferBody})]})]}),(0,n.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,n.jsx)(U,{type:"button",block:!0,loading:t,onClick:r,children:e.passkeyOfferCreate}),(0,n.jsx)(U,{type:"button",variant:"ghost",block:!0,disabled:t,onClick:o,children:e.passkeyOfferSkip})]})]})}function zr({messages:e,onBack:t}){let[r,o]=(0,u.useState)(!1),i=async()=>{try{await navigator.clipboard.writeText(window.location.href),o(!0),setTimeout(()=>o(!1),3e3)}catch{o(!1)}};return(0,n.jsxs)("div",{className:"space-y-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("h2",{className:m("text-base font-semibold",B),children:e.inAppBrowserTitle}),(0,n.jsx)("p",{className:m("mt-1",H),children:e.inAppBrowserBody})]}),(0,n.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,n.jsx)(U,{type:"button",variant:"secondary",block:!0,onClick:()=>{i()},leading:r?(0,n.jsx)(Te,{className:"h-4 w-4","aria-hidden":"true"}):(0,n.jsx)(lt,{className:"h-4 w-4","aria-hidden":"true"}),children:r?e.inAppBrowserCopied:e.inAppBrowserCopyLink}),(0,n.jsx)(U,{type:"button",variant:"ghost",block:!0,onClick:t,children:e.inAppBrowserUseEmail})]})]})}export{me as a,gn as b,hn as c,En as d,Ne as e,xr as f,ti as g};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-KW2CH7SS.js.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{TONE_BG_TINT_STRONG}from"./chunk-RKEHHJDU.js";import{runAltchaLoadedHook}from"./chunk-JH5D6YJX.js";import{cn}from"./chunk-VUTODQFX.js";import{usePartScope}from"./chunk-763LNERD.js";import{useOptionalSiteLabels}from"./chunk-U7H3W23Q.js";import{useResolvedCaptchaTheme}from"./chunk-Q4APVE7S.js";import{createContext,useContext}from"react";import{jsx}from"react/jsx-runtime";var BotProtectionConfigContext=createContext(null);function BotProtectionConfigProvider({value,children}){return jsx(BotProtectionConfigContext.Provider,{value,children})}function useBotProtectionConfig(){return useContext(BotProtectionConfigContext)}function defineProtectionEntry(definition){return definition}var PROTECTION_ENTRIES=[defineProtectionEntry({id:"forms",builtinVariant:"full",providerSelectable:true}),defineProtectionEntry({id:"customer_login",builtinVariant:"full",providerSelectable:true}),defineProtectionEntry({id:"checkout_draft",builtinVariant:"standard",providerSelectable:false})];var SELECTABLE_PROTECTION_ENTRY_IDS=PROTECTION_ENTRIES.filter(entry=>entry.providerSelectable).map(entry=>entry.id);function protectionEntryAction(id){return id}var BOT_PROTECTION_PROVIDERS=["kanorio","turnstile","recaptcha","hcaptcha"];function isBotProtectionProvider(value){return typeof value==="string"&&BOT_PROTECTION_PROVIDERS.includes(value)}function isThirdPartyBotProtectionProvider(value){return isBotProtectionProvider(value)&&value!=="kanorio"}function protectionCData(context){return context.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,255)}var BUILTIN_PUBLIC_BOT_PROTECTION={provider:"kanorio",recaptchaVersion:null,entries:{}};function parsePublicBotProtectionConfig(raw){if(!raw||typeof raw!=="object")return{...BUILTIN_PUBLIC_BOT_PROTECTION,entries:{}};const value=raw;if(!isThirdPartyBotProtectionProvider(value.provider))return{...BUILTIN_PUBLIC_BOT_PROTECTION,entries:{}};const entries={};const rawEntries=value.entries&&typeof value.entries==="object"?value.entries:{};for(const id of SELECTABLE_PROTECTION_ENTRY_IDS){const entry=rawEntries[id];if(entry&&typeof entry.siteKey==="string"&&entry.siteKey){entries[id]={siteKey:entry.siteKey,action:typeof entry.action==="string"?entry.action:protectionEntryAction(id)}}}const recaptchaVersion=value.recaptchaVersion==="v2"||value.recaptchaVersion==="v3"?value.recaptchaVersion:null;if(value.provider==="recaptcha"&&!recaptchaVersion)return{...BUILTIN_PUBLIC_BOT_PROTECTION,entries:{}};return{provider:value.provider,recaptchaVersion:value.provider==="recaptcha"?recaptchaVersion:null,entries}}import{useCallback}from"react";var BOT_PROTECTION_DEFAULTS={MIN_SUBMIT_TIME:5e3,MAX_SUBMIT_TIME:15*60*1e3,TOKEN_EXPIRY:60*60*1e3,INTERACTION_DELAY_MS:2e3};var ALTCHA_CHALLENGE_TTL_MS=10*60*1e3;var ALTCHA_WIDGET_EXPIRE_MS=ALTCHA_CHALLENGE_TTL_MS-60*1e3;var HONEYPOT_FIELD_NAME="_kfp_a";var HONEYPOT_FIELD_WP="_kfp_b";var HONEYPOT_FIELD_CO="_kfp_c";import{useEffect,useRef,createElement,useState}from"react";function resolveAltchaStateChange(detail){if(detail.state==="verified"&&detail.payload){return{kind:"verified",payload:detail.payload}}return{kind:"invalidated",state:detail.state}}var LOADERS={ar:()=>import("./ar-HRZRFWUW.js"),bg:()=>import("./bg-TNDZDXHZ.js"),bn:()=>import("./bn-L44L7SBD.js"),cs:()=>import("./cs-OMRFBZVP.js"),da:()=>import("./da-MEA64IPM.js"),de:()=>import("./de-7GBTXFMH.js"),el:()=>import("./el-BCFO2NS3.js"),en:()=>import("./en-LHV2B2XG.js"),"es-419":()=>import("./es-419-CN2GZEOV.js"),"es-es":()=>import("./es-es-GNKRK4H2.js"),fa:()=>import("./fa-FBR4MORA.js"),fi:()=>import("./fi-BATN376F.js"),"fr-ca":()=>import("./fr-ca-A4GWIOE7.js"),"fr-fr":()=>import("./fr-fr-FEUFFV6I.js"),he:()=>import("./he-RZE7SAH3.js"),hi:()=>import("./hi-G5IRZBZ5.js"),hu:()=>import("./hu-BPCAJCJ3.js"),id:()=>import("./id-E4ZYT3YK.js"),it:()=>import("./it-BGPYU5QL.js"),ja:()=>import("./ja-MA2A5SFZ.js"),ko:()=>import("./ko-G4I5K2UY.js"),mr:()=>import("./mr-HGKBSCPM.js"),nb:()=>import("./nb-ZOWEL6VQ.js"),nl:()=>import("./nl-4KAIKVKC.js"),pl:()=>import("./pl-BRJ5H72A.js"),"pt-br":()=>import("./pt-br-IOF65TN2.js"),"pt-pt":()=>import("./pt-pt-7BYW57KC.js"),ro:()=>import("./ro-GDWJ3F3A.js"),ru:()=>import("./ru-2GEOOKZX.js"),sv:()=>import("./sv-UJ5LCXFA.js"),sw:()=>import("./sw-HPTUVWO6.js"),ta:()=>import("./ta-TOIAFCN5.js"),te:()=>import("./te-PWIXXRJP.js"),th:()=>import("./th-3VH5JHWP.js"),tr:()=>import("./tr-TCPMEXLQ.js"),uk:()=>import("./uk-6S7TMK7C.js"),ur:()=>import("./ur-CV7QI6IC.js"),vi:()=>import("./vi-THIT43PD.js"),"zh-cn":()=>import("./zh-cn-NBHEPFJJ.js"),"zh-tw":()=>import("./zh-tw-HNBFCMMO.js")};var ALIASES={"zh-hant":"zh-tw","zh-hk":"zh-tw","zh-tw":"zh-tw",zh:"zh-cn","zh-cn":"zh-cn","zh-hans":"zh-cn",es:"es-es",fr:"fr-fr",pt:"pt-pt","nl-nl":"nl","nl-be":"nl","en-us":"en","en-gb":"en","en-au":"en","en-ca":"en",no:"nb",nn:"nb",ms:"id"};function resolveAltchaLanguage(locale){const raw=(locale??"").trim().toLowerCase();if(!raw)return"en";if(ALIASES[raw])return ALIASES[raw];if(LOADERS[raw])return raw;const base=raw.split("-")[0];if(ALIASES[base])return ALIASES[base];if(LOADERS[base])return base;return"en"}async function loadAltchaLanguage(locale){const code=resolveAltchaLanguage(locale);await LOADERS[code]();return code}import{jsx as jsx2}from"react/jsx-runtime";function loadAltchaWidget(locale){return Promise.all([import("./altcha-NPBMCOEY.js"),loadAltchaLanguage(locale)]).then(([,language])=>{runAltchaLoadedHook();return language})}function preloadAltchaWidget(locale){loadAltchaWidget(locale).catch(()=>{})}var THEME_CLASS=cn("block w-full","[--altcha-max-width:100%] [--altcha-border-width:1px]","[--altcha-border-radius:0.5rem]","[--altcha-color-base:var(--site-field-bg,rgba(255,255,255,0.9))]","[--altcha-color-border:var(--site-field-border,rgba(0,0,0,0.15))]","[--altcha-color-border-focus:var(--site-field-accent,var(--brand-color,#FF5733))]","[--altcha-color-active:var(--site-field-accent,var(--brand-color,#FF5733))]","[--altcha-color-text:inherit]","text-[15px] text-[var(--site-field-fg,#18181b)]","[&_.altcha-checkbox_input]:accent-[var(--site-field-accent,var(--brand-color,#FF5733))] [&_.altcha-spinner]:text-[var(--site-field-fg-muted,#71717a)]","[&_.altcha-main]:min-h-11 [&_.altcha-main]:px-3.5 [&_.altcha-main]:py-2.5");function AltchaWidget({challengeUrl,onVerified,onInvalidated,expireMs=ALTCHA_WIDGET_EXPIRE_MS,locale,className,invisible=false,revealed=false,generation=0,onStateChange,labels}){const siteLabels=useOptionalSiteLabels();const text=labels??siteLabels?.ui;const containerRef=useRef(null);const scope=usePartScope(containerRef);const[language,setLanguage]=useState(null);useEffect(()=>{let cancelled=false;void loadAltchaWidget(locale).then(code=>{if(!cancelled)setLanguage(code)});return()=>{cancelled=true}},[locale]);useEffect(()=>{if(!onVerified)return;const widget=containerRef.current?.querySelector("altcha-widget");if(!widget)return;const handler=ev=>{const detail=ev.detail;const transition=resolveAltchaStateChange(detail);if(transition.kind==="verified")onVerified(transition.payload);else onInvalidated?.();onStateChange?.(transition.kind==="verified"?"verified":transition.state)};widget.addEventListener("statechange",handler);return()=>widget.removeEventListener("statechange",handler)},[onVerified,onInvalidated,onStateChange,language,generation]);if(!text)throw new Error("AltchaWidget: pass `labels` or render it inside a SiteLabelsProvider");const hidden=invisible&&!revealed;if(!language){if(hidden)return null;return jsx2("div",{ref:scope.ref,className:cn("h-11 w-full animate-pulse rounded-lg "+TONE_BG_TINT_STRONG,scope.className,className),"aria-label":text.botProtectionLoading})}return jsx2("div",{ref:scope.ref,className:cn(THEME_CLASS,scope.className,className,hidden&&"hidden"),"aria-label":text.botProtection,hidden:hidden||void 0,children:createElement("altcha-widget",{key:generation,challengeurl:challengeUrl,expire:expireMs,language,...invisible?{auto:"onload"}:{},hidefooter:true,hidelogo:true})})}import{useEffect as useEffect2,useRef as useRef2}from"react";import{jsx as jsx3}from"react/jsx-runtime";var captchaGlobals=()=>globalThis;var scriptPromises=new Map;function loadScript(src,ready){const existing=scriptPromises.get(src);if(existing)return existing;const promise=new Promise((resolve,reject)=>{if(ready()){resolve();return}const script=document.createElement("script");script.src=src;script.async=true;script.defer=true;script.onerror=()=>{scriptPromises.delete(src);reject(new Error(`Failed to load ${src}`))};script.onload=()=>{const started=Date.now();const poll=()=>{if(ready())resolve();else if(Date.now()-started>1e4)reject(new Error(`Timed out waiting for ${src}`));else setTimeout(poll,50)};poll()};document.head.appendChild(script)});scriptPromises.set(src,promise);return promise}function hlParam(locale){return locale?`&hl=${encodeURIComponent(locale)}`:""}function ThirdPartyCaptcha({provider,siteKey,action,cData,recaptchaVersion,locale,invisible=false,theme,generation=0,onVerified,onInvalidated,onError,registerExecutor,className}){const containerRef=useRef2(null);const scope=usePartScope(containerRef);const widgetRef=useRef2(null);const callbacks=useRef2({onVerified,onInvalidated,onError});callbacks.current={onVerified,onInvalidated,onError};const isV3=provider==="recaptcha"&&recaptchaVersion==="v3";const resolvedTheme=useResolvedCaptchaTheme(theme,containerRef,!isV3);useEffect2(()=>{if(resolvedTheme===void 0)return;let cancelled=false;const el=containerRef.current;const verified=token=>!cancelled&&callbacks.current.onVerified(token);const invalidated=()=>!cancelled&&callbacks.current.onInvalidated();const failed=()=>{if(cancelled)return;callbacks.current.onInvalidated();callbacks.current.onError?.()};const themeOption=resolvedTheme?{theme:resolvedTheme}:{};if(provider==="turnstile"){loadScript("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",()=>Boolean(captchaGlobals().turnstile?.render)).then(()=>{const api=captchaGlobals().turnstile;if(cancelled||!el||!api)return;widgetRef.current=api.render(el,{sitekey:siteKey,action,...cData?{cData}:{},theme:resolvedTheme??"auto",size:"flexible",appearance:invisible?"interaction-only":"always","refresh-expired":"auto",callback:verified,"expired-callback":invalidated,"timeout-callback":invalidated,"error-callback":failed})}).catch(failed)}else if(provider==="hcaptcha"){loadScript(`https://js.hcaptcha.com/1/api.js?render=explicit&recaptchacompat=off${hlParam(locale)}`,()=>Boolean(captchaGlobals().hcaptcha?.render)).then(()=>{const api=captchaGlobals().hcaptcha;if(cancelled||!el||!api)return;widgetRef.current=api.render(el,{sitekey:siteKey,...themeOption,callback:verified,"expired-callback":invalidated,"chalexpired-callback":invalidated,"error-callback":failed})}).catch(failed)}else if(isV3){loadScript(`https://www.google.com/recaptcha/api.js?render=${encodeURIComponent(siteKey)}${hlParam(locale)}`,()=>Boolean(captchaGlobals().grecaptcha?.execute)).then(()=>{if(cancelled)return;registerExecutor?.(()=>new Promise(resolve=>{const api=captchaGlobals().grecaptcha;if(!api)return resolve(null);api.ready(()=>{api.execute(siteKey,{action}).then(resolve,()=>resolve(null))})}))}).catch(failed)}else{loadScript(`https://www.google.com/recaptcha/api.js?render=explicit${hlParam(locale)}`,()=>Boolean(captchaGlobals().grecaptcha?.render)).then(()=>{const api=captchaGlobals().grecaptcha;if(cancelled||!el||!api)return;api.ready(()=>{if(cancelled||widgetRef.current!==null)return;widgetRef.current=api.render(el,{sitekey:siteKey,...themeOption,callback:verified,"expired-callback":invalidated,"error-callback":failed})})}).catch(failed)}return()=>{cancelled=true;registerExecutor?.(null);const id=widgetRef.current;widgetRef.current=null;if(id===null)return;try{if(provider==="turnstile")captchaGlobals().turnstile?.remove(id);else if(provider==="hcaptcha")captchaGlobals().hcaptcha?.remove(id)}catch{}}},[provider,siteKey,action,cData,isV3,invisible,locale,resolvedTheme]);useEffect2(()=>{if(generation===0)return;const id=widgetRef.current;if(id===null)return;try{if(provider==="turnstile")captchaGlobals().turnstile?.reset(id);else if(provider==="hcaptcha")captchaGlobals().hcaptcha?.reset(id);else if(!isV3)captchaGlobals().grecaptcha?.reset(id)}catch{}},[generation,provider,isV3]);if(isV3)return null;return jsx3("div",{ref:scope.ref,className:cn("min-h-[65px] w-full",scope.className,className),"data-captcha-provider":provider})}import{Fragment,jsx as jsx4,jsxs}from"react/jsx-runtime";var HONEYPOT_WRAPPER_STYLE={position:"absolute",width:"1px",height:"1px",padding:0,margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",clipPath:"inset(50%)",whiteSpace:"nowrap",border:0};function appendContext(url,context){if(!context)return url;const sep=url.includes("?")?"&":"?";return`${url}${sep}context=${encodeURIComponent(context)}`}function BotProtectionAltcha({variant,altchaChallengeUrl,context,onAltchaVerified,onAltchaInvalidated,locale,className,invisible,revealed,generation,onStateChange,labels}){if(variant!=="full"||!altchaChallengeUrl||!onAltchaVerified)return null;return jsx4(AltchaWidget,{challengeUrl:appendContext(altchaChallengeUrl,context),onVerified:onAltchaVerified,onInvalidated:onAltchaInvalidated,locale,className,invisible,revealed,generation,onStateChange,labels})}function BotProtectionChallenge({provider,fieldProps,captcha,locale,className,invisible,revealed,generation,onStateChange,onCaptchaError,theme}){if(provider!=="kanorio"&&captcha){return jsx4(ThirdPartyCaptcha,{provider:captcha.provider,siteKey:captcha.siteKey,action:captcha.action,cData:captcha.cData,recaptchaVersion:captcha.recaptchaVersion,locale,invisible,generation:captcha.generation,onVerified:captcha.onVerified,onInvalidated:captcha.onInvalidated,onError:onCaptchaError,registerExecutor:captcha.registerExecutor,theme,className})}return jsx4(BotProtectionAltcha,{...fieldProps,locale,className,invisible,revealed,generation,onStateChange})}function BotProtectionFields({variant,altchaChallengeUrl,context,onAltchaVerified,onAltchaInvalidated,onHoneypotChange,onHoneypotWpChange,onHoneypotCoChange,locale,renderAltcha=true}){const handleHpChange=useCallback(e=>{onHoneypotChange?.(e.target.value)},[onHoneypotChange]);const handleWpChange=useCallback(e=>{onHoneypotWpChange?.(e.target.value)},[onHoneypotWpChange]);const handleCoChange=useCallback(e=>{onHoneypotCoChange?.(e.target.value)},[onHoneypotCoChange]);const honeypots=[{name:HONEYPOT_FIELD_NAME,onChange:handleHpChange},{name:HONEYPOT_FIELD_WP,onChange:handleWpChange},{name:HONEYPOT_FIELD_CO,onChange:handleCoChange}];return jsxs(Fragment,{children:[renderAltcha&&jsx4(BotProtectionAltcha,{variant,altchaChallengeUrl,context,onAltchaVerified,onAltchaInvalidated,locale}),honeypots.map(({name,onChange})=>jsxs("div",{style:HONEYPOT_WRAPPER_STYLE,"aria-hidden":"true",children:[jsx4("label",{htmlFor:name,children:"Leave this field empty"}),jsx4("input",{type:"text",id:name,name,autoComplete:"one-time-code",tabIndex:-1,onChange})]},name))]})}import{useCallback as useCallback2,useEffect as useEffect3,useMemo,useRef as useRef3,useState as useState2}from"react";var SIGNED_TOKEN_REFRESH_MS=10*60*1e3;function useBotProtection(options={}){const{variant="standard",challengeUrl="/api/form-protection/challenge",altchaChallengeUrl="/api/form-protection/altcha",context="",entry,needsUploadToken=false}=options;const contextConfig=useBotProtectionConfig();const config=options.config!==void 0?options.config:contextConfig;const thirdPartyEntry=entry&&config&&config.provider!=="kanorio"?config.entries[entry]:void 0;const provider=thirdPartyEntry&&config?config.provider:"kanorio";const isThirdParty=provider!=="kanorio";const recaptchaVersion=isThirdParty?config?.recaptchaVersion??null:null;const isRecaptchaV3=provider==="recaptcha"&&recaptchaVersion==="v3";const wantsSignedToken=!isThirdParty&&variant==="standard"||isThirdParty&&needsUploadToken;const[isReady,setIsReady]=useState2(variant==="full"||isThirdParty);const[isSubmittable,setIsSubmittable]=useState2(false);const[isAltchaVerified,setIsAltchaVerified]=useState2(false);const[isCaptchaVerified,setIsCaptchaVerified]=useState2(false);const[hasSignedToken,setHasSignedToken]=useState2(false);const[captchaGeneration,setCaptchaGeneration]=useState2(0);const loadTimestampRef=useRef3(0);const tokenRef=useRef3("");const signedTokenRef=useRef3("");const captchaTokenRef=useRef3("");const captchaExecutorRef=useRef3(null);const honeypotRef=useRef3("");const honeypotWpRef=useRef3("");const honeypotCoRef=useRef3("");const firstFocusTimeRef=useRef3(0);const timerRef=useRef3(null);const registerAltchaPayload=useCallback2(payload=>{tokenRef.current=payload;setIsAltchaVerified(true)},[]);const invalidateAltchaPayload=useCallback2(()=>{tokenRef.current="";setIsAltchaVerified(false)},[]);const registerCaptchaToken=useCallback2(token=>{captchaTokenRef.current=token;setIsCaptchaVerified(true)},[]);const invalidateCaptchaToken=useCallback2(()=>{captchaTokenRef.current="";setIsCaptchaVerified(false)},[]);const registerCaptchaExecutor=useCallback2(executor=>{captchaExecutorRef.current=executor},[]);useEffect3(()=>{loadTimestampRef.current=Date.now();honeypotRef.current="";honeypotWpRef.current="";honeypotCoRef.current="";if(!wantsSignedToken){setIsReady(true);return}const url=`${challengeUrl}?context=${encodeURIComponent(context)}`;const fetchToken=()=>fetch(url).then(res=>res.ok?res.json():Promise.reject(new Error("Challenge fetch failed"))).then(data=>{const token=`${data.nonce}|${data.ts}|${data.sig}`;if(isThirdParty)signedTokenRef.current=token;else tokenRef.current=token;setHasSignedToken(true)}).catch(()=>{});void fetchToken().finally(()=>setIsReady(true));const refresh=setInterval(()=>void fetchToken(),SIGNED_TOKEN_REFRESH_MS);return()=>clearInterval(refresh)},[wantsSignedToken,isThirdParty,challengeUrl,context]);useEffect3(()=>()=>{if(timerRef.current)clearTimeout(timerRef.current)},[]);const registerFocus=useCallback2(()=>{if(firstFocusTimeRef.current===0){firstFocusTimeRef.current=Date.now();if(timerRef.current)clearTimeout(timerRef.current);timerRef.current=setTimeout(()=>{setIsSubmittable(true);timerRef.current=null},BOT_PROTECTION_DEFAULTS.INTERACTION_DELAY_MS)}},[]);const effectiveSubmittable=isThirdParty?isSubmittable&&(isRecaptchaV3||isCaptchaVerified):variant==="full"?isSubmittable&&isAltchaVerified:isSubmittable;const baseData=useCallback2(()=>({_hp:honeypotRef.current,_wp:honeypotWpRef.current,_co:honeypotCoRef.current,_ts:loadTimestampRef.current,...context?{_ctx:context}:{}}),[context]);const getProtectionData=useCallback2(()=>{if(isThirdParty)return{...baseData(),_tk:"",captchaToken:captchaTokenRef.current};return{...baseData(),_tk:tokenRef.current}},[baseData,isThirdParty]);const getUploadProtectionData=useCallback2(()=>{if(isThirdParty)return{...baseData(),_tk:signedTokenRef.current};return{...baseData(),_tk:tokenRef.current}},[baseData,isThirdParty]);const prepare=useCallback2(async()=>{if(!isRecaptchaV3)return;const token=await captchaExecutorRef.current?.()??"";captchaTokenRef.current=token;setIsCaptchaVerified(Boolean(token))},[isRecaptchaV3]);const renewCaptcha=useCallback2(()=>{if(!isThirdParty)return;captchaTokenRef.current="";setIsCaptchaVerified(false);setCaptchaGeneration(generation=>generation+1)},[isThirdParty]);const reset=useCallback2(()=>{loadTimestampRef.current=Date.now();honeypotRef.current="";honeypotWpRef.current="";honeypotCoRef.current="";firstFocusTimeRef.current=0;setIsSubmittable(false);setIsAltchaVerified(false);if(timerRef.current){clearTimeout(timerRef.current);timerRef.current=null}if(isThirdParty){captchaTokenRef.current="";setIsCaptchaVerified(false);setCaptchaGeneration(generation=>generation+1);return}if(variant==="standard"){const url=`${challengeUrl}?context=${encodeURIComponent(context)}`;fetch(url).then(res=>res.ok?res.json():Promise.reject(new Error("Challenge fetch failed"))).then(data=>{tokenRef.current=`${data.nonce}|${data.ts}|${data.sig}`}).catch(()=>{tokenRef.current=""})}else{tokenRef.current=""}},[isThirdParty,variant,challengeUrl,context]);const setHoneypotValue=useCallback2(value=>{honeypotRef.current=value},[]);const setHoneypotWpValue=useCallback2(value=>{honeypotWpRef.current=value},[]);const setHoneypotCoValue=useCallback2(value=>{honeypotCoRef.current=value},[]);const fieldProps=useMemo(()=>({variant,context,altchaChallengeUrl,onAltchaVerified:variant==="full"?registerAltchaPayload:void 0,onAltchaInvalidated:variant==="full"?invalidateAltchaPayload:void 0,onHoneypotChange:setHoneypotValue,onHoneypotWpChange:setHoneypotWpValue,onHoneypotCoChange:setHoneypotCoValue}),[variant,context,altchaChallengeUrl,registerAltchaPayload,invalidateAltchaPayload,setHoneypotValue,setHoneypotWpValue,setHoneypotCoValue]);const captcha=useMemo(()=>isThirdParty&&thirdPartyEntry?{provider,siteKey:thirdPartyEntry.siteKey,action:thirdPartyEntry.action,cData:provider==="turnstile"?protectionCData(context):null,recaptchaVersion,generation:captchaGeneration,onVerified:registerCaptchaToken,onInvalidated:invalidateCaptchaToken,registerExecutor:registerCaptchaExecutor}:null,[isThirdParty,thirdPartyEntry,provider,context,recaptchaVersion,captchaGeneration,registerCaptchaToken,invalidateCaptchaToken,registerCaptchaExecutor]);return{getProtectionData,getUploadProtectionData,isReady,isSubmittable:effectiveSubmittable,isUploadReady:isThirdParty?hasSignedToken:effectiveSubmittable,registerFocus,registerAltchaPayload:variant==="full"&&!isThirdParty?registerAltchaPayload:void 0,reset,prepare,renewCaptcha,provider,fieldProps,challengeProps:{provider,fieldProps,captcha},_setHoneypotValue:setHoneypotValue,_setHoneypotWpValue:setHoneypotWpValue,_setHoneypotCoValue:setHoneypotCoValue}}export{BotProtectionConfigProvider,useBotProtectionConfig,parsePublicBotProtectionConfig,preloadAltchaWidget,ThirdPartyCaptcha,BotProtectionAltcha,BotProtectionChallenge,BotProtectionFields,useBotProtection};
|
|
2
|
+
//# sourceMappingURL=chunk-KYXZNMNA.js.map
|