@salla.sa/twilight-theme-engine 1.0.185 → 1.0.186
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/dist/{AddToCartForm-LCSBAN3M.js → AddToCartForm-5A4JIBLL.js} +3 -3
- package/dist/{AddToCartForm-LCSBAN3M.js.map → AddToCartForm-5A4JIBLL.js.map} +1 -1
- package/dist/{BlogAuthorPage-ZYBQYUV7.js → BlogAuthorPage-BMVQU52G.js} +19 -19
- package/dist/{BlogAuthorPage-ZYBQYUV7.js.map → BlogAuthorPage-BMVQU52G.js.map} +1 -1
- package/dist/{BlogCategoryPage-O2ORXWYL.js → BlogCategoryPage-VQB2GPQJ.js} +19 -19
- package/dist/{BlogCategoryPage-O2ORXWYL.js.map → BlogCategoryPage-VQB2GPQJ.js.map} +1 -1
- package/dist/{BlogPage-RXWT2CV3.js → BlogPage-2PVU76RY.js} +17 -17
- package/dist/{BlogPage-RXWT2CV3.js.map → BlogPage-2PVU76RY.js.map} +1 -1
- package/dist/{BlogSinglePage-QY42WRDZ.js → BlogSinglePage-TUP6H6LR.js} +17 -17
- package/dist/{BlogSinglePage-QY42WRDZ.js.map → BlogSinglePage-TUP6H6LR.js.map} +1 -1
- package/dist/{BlogTagPage-P7B3CFAO.js → BlogTagPage-3LVZOCXD.js} +19 -19
- package/dist/{BlogTagPage-P7B3CFAO.js.map → BlogTagPage-3LVZOCXD.js.map} +1 -1
- package/dist/{BrandsPage-FV57PLGZ.js → BrandsPage-IKXVPS6D.js} +18 -18
- package/dist/{BrandsPage-FV57PLGZ.js.map → BrandsPage-IKXVPS6D.js.map} +1 -1
- package/dist/{Breadcrumb-TM4EXKTO.js → Breadcrumb-RDJZ2ZLB.js} +17 -17
- package/dist/{Breadcrumb-TM4EXKTO.js.map → Breadcrumb-RDJZ2ZLB.js.map} +1 -1
- package/dist/{CanvasOverlay-YNXYF27N.js → CanvasOverlay-OFJN4QZX.js} +3 -3
- package/dist/{CanvasOverlay-YNXYF27N.js.map → CanvasOverlay-OFJN4QZX.js.map} +1 -1
- package/dist/{CartItem-DVQET7SW.js → CartItem-I5CXXNRD.js} +17 -17
- package/dist/{CartItem-DVQET7SW.js.map → CartItem-I5CXXNRD.js.map} +1 -1
- package/dist/{CartSummary-XGMWN6PP.js → CartSummary-5TDULSFS.js} +17 -17
- package/dist/{CartSummary-XGMWN6PP.js.map → CartSummary-5TDULSFS.js.map} +1 -1
- package/dist/{Copyright-OTQZENUE.js → Copyright-4IBWI43E.js} +3 -3
- package/dist/{Copyright-OTQZENUE.js.map → Copyright-4IBWI43E.js.map} +1 -1
- package/dist/{CustomerLayout-IMI4SJDO.js → CustomerLayout-32UTZ4U5.js} +17 -17
- package/dist/{CustomerLayout-IMI4SJDO.js.map → CustomerLayout-32UTZ4U5.js.map} +1 -1
- package/dist/{Footer-JUHWLQCI.js → Footer-WG66WSI4.js} +3 -3
- package/dist/{Footer-JUHWLQCI.js.map → Footer-WG66WSI4.js.map} +1 -1
- package/dist/GoogleTag-V7FHUIZW.js +15 -0
- package/dist/{GoogleTag-VBFDNEU6.js.map → GoogleTag-V7FHUIZW.js.map} +1 -1
- package/dist/{Header-P46ZDWIQ.js → Header-C6QOJTFF.js} +8 -8
- package/dist/{Header-P46ZDWIQ.js.map → Header-C6QOJTFF.js.map} +1 -1
- package/dist/{LatestProducts-QWTQZVBJ.js → LatestProducts-63LGH5AD.js} +19 -19
- package/dist/{LatestProducts-QWTQZVBJ.js.map → LatestProducts-63LGH5AD.js.map} +1 -1
- package/dist/{LoyaltyPage-LJOJRJB5.js → LoyaltyPage-BNHK5VHM.js} +17 -17
- package/dist/{LoyaltyPage-LJOJRJB5.js.map → LoyaltyPage-BNHK5VHM.js.map} +1 -1
- package/dist/{LoyaltyPointsPage-4JYLRGKN.js → LoyaltyPointsPage-5V263ISD.js} +6 -6
- package/dist/{LoyaltyPointsPage-4JYLRGKN.js.map → LoyaltyPointsPage-5V263ISD.js.map} +1 -1
- package/dist/{MainMenu-LK22UWZO.js → MainMenu-SJL4B3EZ.js} +5 -5
- package/dist/{MainMenu-LK22UWZO.js.map → MainMenu-SJL4B3EZ.js.map} +1 -1
- package/dist/{MasterLayout-ZA32NBT4.js → MasterLayout-PZ3P54GT.js} +17 -17
- package/dist/{MasterLayout-ZA32NBT4.js.map → MasterLayout-PZ3P54GT.js.map} +1 -1
- package/dist/{MobileMenu-MMDICOBU.js → MobileMenu-YP3VAP5X.js} +18 -18
- package/dist/{MobileMenu-MMDICOBU.js.map → MobileMenu-YP3VAP5X.js.map} +1 -1
- package/dist/{NotificationsPage-V5JAFDFP.js → NotificationsPage-CNZNP5MT.js} +17 -17
- package/dist/{NotificationsPage-V5JAFDFP.js.map → NotificationsPage-CNZNP5MT.js.map} +1 -1
- package/dist/{OrderSinglePage-EKJ5Q4EM.js → OrderSinglePage-SPRSVZAA.js} +18 -18
- package/dist/{OrderSinglePage-EKJ5Q4EM.js.map → OrderSinglePage-SPRSVZAA.js.map} +1 -1
- package/dist/{OrdersPage-JGTRYEST.js → OrdersPage-24NCQYJ5.js} +17 -17
- package/dist/{OrdersPage-JGTRYEST.js.map → OrdersPage-24NCQYJ5.js.map} +1 -1
- package/dist/{PageSingle-J6JBAD45.js → PageSingle-L5EAMR3X.js} +3 -3
- package/dist/{PageSingle-J6JBAD45.js.map → PageSingle-L5EAMR3X.js.map} +1 -1
- package/dist/{ProductDetails-XLM3FGBY.js → ProductDetails-PED2NZEJ.js} +4 -4
- package/dist/{ProductDetails-XLM3FGBY.js.map → ProductDetails-PED2NZEJ.js.map} +1 -1
- package/dist/{ProfilePage-SWFGEY5Y.js → ProfilePage-E44G3WVG.js} +17 -17
- package/dist/{ProfilePage-SWFGEY5Y.js.map → ProfilePage-E44G3WVG.js.map} +1 -1
- package/dist/{ReviewsPage-A733RD4D.js → ReviewsPage-OIUFR3EP.js} +3 -3
- package/dist/{ReviewsPage-A733RD4D.js.map → ReviewsPage-OIUFR3EP.js.map} +1 -1
- package/dist/{SeoCartWidget-DIOS62BL.js → SeoCartWidget-JK52NGON.js} +17 -17
- package/dist/{SeoCartWidget-DIOS62BL.js.map → SeoCartWidget-JK52NGON.js.map} +1 -1
- package/dist/{SettingsPage-FZBUPLLA.js → SettingsPage-6S3MY3PF.js} +17 -17
- package/dist/{SettingsPage-FZBUPLLA.js.map → SettingsPage-6S3MY3PF.js.map} +1 -1
- package/dist/{StoreClosedNotification-ZWRTPUPP.js → StoreClosedNotification-XKNI3VAT.js} +18 -18
- package/dist/{StoreClosedNotification-ZWRTPUPP.js.map → StoreClosedNotification-XKNI3VAT.js.map} +1 -1
- package/dist/{TestimonialsPage-6TSZIUZX.js → TestimonialsPage-PZX5FRHU.js} +3 -3
- package/dist/{TestimonialsPage-6TSZIUZX.js.map → TestimonialsPage-PZX5FRHU.js.map} +1 -1
- package/dist/{ThankYouPage-RPZK6SRW.js → ThankYouPage-SNRSPL5U.js} +17 -17
- package/dist/{ThankYouPage-RPZK6SRW.js.map → ThankYouPage-SNRSPL5U.js.map} +1 -1
- package/dist/{WalletPage-42RFDAUY.js → WalletPage-563XMOW5.js} +18 -18
- package/dist/{WalletPage-42RFDAUY.js.map → WalletPage-563XMOW5.js.map} +1 -1
- package/dist/{WebMcpTools-DLW67GJM.js → WebMcpTools-PYYSHW26.js} +5 -5
- package/dist/{WebMcpTools-DLW67GJM.js.map → WebMcpTools-PYYSHW26.js.map} +1 -1
- package/dist/{WishlistPage-HW3ZQSGB.js → WishlistPage-BAFIG6RB.js} +19 -19
- package/dist/{WishlistPage-HW3ZQSGB.js.map → WishlistPage-BAFIG6RB.js.map} +1 -1
- package/dist/api/advertisement.js +2 -2
- package/dist/api/apps.js +2 -2
- package/dist/api/blog.js +3 -3
- package/dist/api/brands.js +3 -3
- package/dist/api/cart.js +3 -3
- package/dist/api/category.js +3 -3
- package/dist/api/client.js +1 -1
- package/dist/api/custom-url.js +2 -2
- package/dist/api/home.js +2 -2
- package/dist/api/loyalty.js +3 -3
- package/dist/api/menu.js +2 -2
- package/dist/api/notification.js +2 -2
- package/dist/api/order.js +3 -3
- package/dist/api/page.js +3 -3
- package/dist/api/product.js +3 -3
- package/dist/api/profile.js +1 -1
- package/dist/api/store.js +2 -2
- package/dist/api/translations.js +2 -2
- package/dist/api/user.js +2 -2
- package/dist/api/wallet.js +2 -2
- package/dist/api/wishlist.js +4 -4
- package/dist/{chunk-KFF5J6JN.js → chunk-4XWOLTPZ.js} +19 -19
- package/dist/{chunk-KFF5J6JN.js.map → chunk-4XWOLTPZ.js.map} +1 -1
- package/dist/{chunk-QHF66D3P.js → chunk-5MANTOZ5.js} +4 -4
- package/dist/{chunk-QHF66D3P.js.map → chunk-5MANTOZ5.js.map} +1 -1
- package/dist/{chunk-JZOBRBDY.js → chunk-5TVOTTHS.js} +3 -3
- package/dist/{chunk-JZOBRBDY.js.map → chunk-5TVOTTHS.js.map} +1 -1
- package/dist/{chunk-GYHZYJUL.js → chunk-6HEK3NUM.js} +3 -3
- package/dist/{chunk-GYHZYJUL.js.map → chunk-6HEK3NUM.js.map} +1 -1
- package/dist/{chunk-7GUKPZQ6.js → chunk-6MWADUFG.js} +3 -3
- package/dist/{chunk-7GUKPZQ6.js.map → chunk-6MWADUFG.js.map} +1 -1
- package/dist/{chunk-J3RK2CPN.js → chunk-6RJFC2TQ.js} +3 -3
- package/dist/{chunk-J3RK2CPN.js.map → chunk-6RJFC2TQ.js.map} +1 -1
- package/dist/{chunk-53IXAXYU.js → chunk-7B3HAC7N.js} +3 -3
- package/dist/{chunk-53IXAXYU.js.map → chunk-7B3HAC7N.js.map} +1 -1
- package/dist/{chunk-53CWWIKH.js → chunk-7KRZ5LXJ.js} +4 -4
- package/dist/{chunk-53CWWIKH.js.map → chunk-7KRZ5LXJ.js.map} +1 -1
- package/dist/{chunk-CRW77N4M.js → chunk-7RKZXLBL.js} +3 -3
- package/dist/{chunk-CRW77N4M.js.map → chunk-7RKZXLBL.js.map} +1 -1
- package/dist/{chunk-VEUY4U3G.js → chunk-7U3JGTMX.js} +3 -3
- package/dist/{chunk-VEUY4U3G.js.map → chunk-7U3JGTMX.js.map} +1 -1
- package/dist/{chunk-5YLKWMNP.js → chunk-AGKNWEG6.js} +3 -3
- package/dist/{chunk-5YLKWMNP.js.map → chunk-AGKNWEG6.js.map} +1 -1
- package/dist/{chunk-SD4TYJN3.js → chunk-ANTDJTQR.js} +3 -3
- package/dist/{chunk-SD4TYJN3.js.map → chunk-ANTDJTQR.js.map} +1 -1
- package/dist/{chunk-CDMXPX4Z.js → chunk-AXVPFA2U.js} +14 -14
- package/dist/{chunk-CDMXPX4Z.js.map → chunk-AXVPFA2U.js.map} +1 -1
- package/dist/{chunk-3TZIFRGC.js → chunk-BICEPRPK.js} +4 -4
- package/dist/{chunk-3TZIFRGC.js.map → chunk-BICEPRPK.js.map} +1 -1
- package/dist/{chunk-Q2Z4IPAT.js → chunk-BRQOHQB3.js} +7 -7
- package/dist/{chunk-Q2Z4IPAT.js.map → chunk-BRQOHQB3.js.map} +1 -1
- package/dist/{chunk-MHA726OF.js → chunk-C5HAMBR3.js} +4 -4
- package/dist/{chunk-MHA726OF.js.map → chunk-C5HAMBR3.js.map} +1 -1
- package/dist/{chunk-LKITJWSS.js → chunk-FDFL6QKB.js} +3 -3
- package/dist/{chunk-LKITJWSS.js.map → chunk-FDFL6QKB.js.map} +1 -1
- package/dist/{chunk-V5FXJ6RG.js → chunk-FICNVVC2.js} +3 -3
- package/dist/{chunk-V5FXJ6RG.js.map → chunk-FICNVVC2.js.map} +1 -1
- package/dist/{chunk-AYZ6MRDT.js → chunk-GWT6MHWC.js} +4 -4
- package/dist/{chunk-AYZ6MRDT.js.map → chunk-GWT6MHWC.js.map} +1 -1
- package/dist/{chunk-2XFHSSMR.js → chunk-H6FRRUIU.js} +4 -4
- package/dist/{chunk-2XFHSSMR.js.map → chunk-H6FRRUIU.js.map} +1 -1
- package/dist/{chunk-P65YIT3J.js → chunk-IJVAVBIM.js} +3 -3
- package/dist/{chunk-P65YIT3J.js.map → chunk-IJVAVBIM.js.map} +1 -1
- package/dist/{chunk-EV3MX2ZF.js → chunk-INLVNPJ6.js} +3 -3
- package/dist/{chunk-EV3MX2ZF.js.map → chunk-INLVNPJ6.js.map} +1 -1
- package/dist/{chunk-JMJTCJGX.js → chunk-IQOKWDKP.js} +4 -4
- package/dist/{chunk-JMJTCJGX.js.map → chunk-IQOKWDKP.js.map} +1 -1
- package/dist/{chunk-3C55I5FU.js → chunk-JXUASMA7.js} +3 -3
- package/dist/{chunk-3C55I5FU.js.map → chunk-JXUASMA7.js.map} +1 -1
- package/dist/{chunk-3AOC4XPC.js → chunk-KZEXDR6O.js} +3 -3
- package/dist/{chunk-3AOC4XPC.js.map → chunk-KZEXDR6O.js.map} +1 -1
- package/dist/{chunk-L3DCK3MF.js → chunk-N7YB3OG4.js} +3 -3
- package/dist/{chunk-L3DCK3MF.js.map → chunk-N7YB3OG4.js.map} +1 -1
- package/dist/{chunk-CSR5SCSP.js → chunk-OB7HFA7T.js} +4 -4
- package/dist/{chunk-CSR5SCSP.js.map → chunk-OB7HFA7T.js.map} +1 -1
- package/dist/{chunk-EXPUSY6B.js → chunk-ONHZXJAS.js} +3 -3
- package/dist/{chunk-EXPUSY6B.js.map → chunk-ONHZXJAS.js.map} +1 -1
- package/dist/{chunk-R2ZCGB4G.js → chunk-R2VVSCFJ.js} +6 -6
- package/dist/{chunk-R2ZCGB4G.js.map → chunk-R2VVSCFJ.js.map} +1 -1
- package/dist/{chunk-HHZ7HY3D.js → chunk-R5T5XOT6.js} +5 -5
- package/dist/{chunk-HHZ7HY3D.js.map → chunk-R5T5XOT6.js.map} +1 -1
- package/dist/{chunk-5VWFGJS2.js → chunk-SFK7LAHZ.js} +3 -3
- package/dist/{chunk-5VWFGJS2.js.map → chunk-SFK7LAHZ.js.map} +1 -1
- package/dist/{chunk-R2J4BECK.js → chunk-SG5PJAKP.js} +4 -4
- package/dist/{chunk-R2J4BECK.js.map → chunk-SG5PJAKP.js.map} +1 -1
- package/dist/{chunk-5BICYVE3.js → chunk-SUW3BMDE.js} +4 -4
- package/dist/{chunk-5BICYVE3.js.map → chunk-SUW3BMDE.js.map} +1 -1
- package/dist/{chunk-N2346B57.js → chunk-UPKX5CSP.js} +3 -3
- package/dist/{chunk-N2346B57.js.map → chunk-UPKX5CSP.js.map} +1 -1
- package/dist/{chunk-5KEYJA77.js → chunk-VI7RQJS7.js} +4 -4
- package/dist/{chunk-5KEYJA77.js.map → chunk-VI7RQJS7.js.map} +1 -1
- package/dist/{chunk-OOZ7R5J6.js → chunk-VLLKXG5J.js} +5 -5
- package/dist/{chunk-OOZ7R5J6.js.map → chunk-VLLKXG5J.js.map} +1 -1
- package/dist/{chunk-CZHLGKXR.js → chunk-VQZU5VT3.js} +5 -5
- package/dist/{chunk-CZHLGKXR.js.map → chunk-VQZU5VT3.js.map} +1 -1
- package/dist/{chunk-CDO7VXWO.js → chunk-WL5KWZL2.js} +4 -4
- package/dist/{chunk-CDO7VXWO.js.map → chunk-WL5KWZL2.js.map} +1 -1
- package/dist/{chunk-XG2LXO24.js → chunk-X25XUDFI.js} +7 -7
- package/dist/{chunk-XG2LXO24.js.map → chunk-X25XUDFI.js.map} +1 -1
- package/dist/{chunk-TQ4UZJSG.js → chunk-XETJVOYZ.js} +7 -7
- package/dist/{chunk-TQ4UZJSG.js.map → chunk-XETJVOYZ.js.map} +1 -1
- package/dist/{chunk-5TGDSE64.js → chunk-XKAL233L.js} +4 -4
- package/dist/{chunk-5TGDSE64.js.map → chunk-XKAL233L.js.map} +1 -1
- package/dist/{chunk-MHSASWOS.js → chunk-XPT4ZX7U.js} +4 -4
- package/dist/{chunk-MHSASWOS.js.map → chunk-XPT4ZX7U.js.map} +1 -1
- package/dist/{chunk-E6SPIMQ5.js → chunk-XVTXIVFM.js} +5 -5
- package/dist/{chunk-E6SPIMQ5.js.map → chunk-XVTXIVFM.js.map} +1 -1
- package/dist/{chunk-QXAUEOHK.js → chunk-YCQK4JRW.js} +2 -2
- package/dist/{chunk-QXAUEOHK.js.map → chunk-YCQK4JRW.js.map} +1 -1
- package/dist/{chunk-DECKE4BB.js → chunk-YWPVPERZ.js} +3 -3
- package/dist/{chunk-DECKE4BB.js.map → chunk-YWPVPERZ.js.map} +1 -1
- package/dist/{chunk-KMAKPTHT.js → chunk-Z6ZZRFM4.js} +4 -4
- package/dist/{chunk-KMAKPTHT.js.map → chunk-Z6ZZRFM4.js.map} +1 -1
- package/dist/{chunk-QY77WLK3.js → chunk-ZOH4AEIE.js} +3 -3
- package/dist/{chunk-QY77WLK3.js.map → chunk-ZOH4AEIE.js.map} +1 -1
- package/dist/{chunk-XYVU5KGN.js → chunk-ZUUGJHI3.js} +3 -3
- package/dist/{chunk-XYVU5KGN.js.map → chunk-ZUUGJHI3.js.map} +1 -1
- package/dist/components/cart/index.js +1 -1
- package/dist/components/common/index.js +1 -1
- package/dist/components/drawer/index.js +15 -15
- package/dist/components/home/index.js +20 -20
- package/dist/components/layout/index.js +4 -4
- package/dist/components/product/index.js +17 -17
- package/dist/components/store/index.js +16 -16
- package/dist/components/tracking/index.js +6 -6
- package/dist/{custom-urls-DTRBRO4J.js → custom-urls-2CS3REHI.js} +7 -7
- package/dist/{custom-urls-DTRBRO4J.js.map → custom-urls-2CS3REHI.js.map} +1 -1
- package/dist/dev/editor/index.js +1 -1
- package/dist/dev/index.js +1 -1
- package/dist/{document-class-34BKJ6VD.js → document-class-LDIJOBHB.js} +17 -17
- package/dist/{document-class-34BKJ6VD.js.map → document-class-LDIJOBHB.js.map} +1 -1
- package/dist/hooks/index.js +15 -15
- package/dist/hooks/useGtm.js +15 -15
- package/dist/hooks/useMoney.js +15 -15
- package/dist/hooks/useStore.js +15 -15
- package/dist/hooks/useUser.js +3 -3
- package/dist/index.js +15 -15
- package/dist/{navigation-5ACP47I3.js → navigation-RLL752ZZ.js} +4 -4
- package/dist/{navigation-5ACP47I3.js.map → navigation-RLL752ZZ.js.map} +1 -1
- package/dist/{navigation-VVCRXGCD.js → navigation-UOOAMJLY.js} +5 -5
- package/dist/{navigation-VVCRXGCD.js.map → navigation-UOOAMJLY.js.map} +1 -1
- package/dist/{not-found-ABDLLYDO.js → not-found-QYWU3B4R.js} +18 -18
- package/dist/{not-found-ABDLLYDO.js.map → not-found-QYWU3B4R.js.map} +1 -1
- package/dist/providers/index.js +15 -15
- package/dist/routes/account/orders.js +4 -4
- package/dist/routes/account.js +13 -13
- package/dist/routes/blog.js +8 -8
- package/dist/routes/brands/loader.d.ts.map +1 -1
- package/dist/routes/brands.js +13 -5
- package/dist/routes/brands.js.map +1 -1
- package/dist/routes/cart.js +23 -23
- package/dist/routes/home.js +21 -21
- package/dist/routes/index.js +8 -8
- package/dist/routes/loyalty.js +5 -5
- package/dist/routes/page.js +4 -4
- package/dist/routes/product-listing.js +25 -25
- package/dist/routes/product.js +24 -24
- package/dist/routes/seo-redirects.js +8 -8
- package/dist/routes/testimonials.js +2 -2
- package/dist/routes/thank-you.js +4 -4
- package/dist/skeleton.js +21 -21
- package/dist/{store-lookup-RKU4RHPS.js → store-lookup-OO2FPCFW.js} +8 -8
- package/dist/{store-lookup-RKU4RHPS.js.map → store-lookup-OO2FPCFW.js.map} +1 -1
- package/dist/tanstack.js +17 -17
- package/dist/utils/index.js +2 -2
- package/package.json +1 -1
- package/tailwind/routes/brands/loader.ts.txt +19 -1
- package/dist/GoogleTag-VBFDNEU6.js +0 -15
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { parseShortLinkPath } from './chunk-6T7N5FOL.js';
|
|
2
2
|
import { PRODUCT_SLUG_ROUTE_ID, CATEGORY_SLUG_ROUTE_ID } from './chunk-NV4PF3O3.js';
|
|
3
3
|
import { productKeyOfId } from './chunk-SDBR4X3K.js';
|
|
4
|
-
import { redirect, isMissingResource } from './chunk-
|
|
4
|
+
import { redirect, isMissingResource } from './chunk-5TVOTTHS.js';
|
|
5
5
|
import { clearAuthTokenCookie } from './chunk-4OZIBANF.js';
|
|
6
6
|
import { FALLBACK_LOCALE, isLocale } from './chunk-T72DAX7R.js';
|
|
7
7
|
import { useEffect } from 'react';
|
|
@@ -91,7 +91,7 @@ async function twigUrlRedirect(pathname, search, page, options = {}) {
|
|
|
91
91
|
throw redirect(`${locale ? `/${locale}` : ""}${target.path}${search}`, { statusCode: 301 });
|
|
92
92
|
}
|
|
93
93
|
if (!options.queryClient || twigPageUrl(pathname)) return;
|
|
94
|
-
const { customUrlRedirect } = await import('./custom-urls-
|
|
94
|
+
const { customUrlRedirect } = await import('./custom-urls-2CS3REHI.js');
|
|
95
95
|
await customUrlRedirect(pathname, search, {
|
|
96
96
|
queryClient: options.queryClient,
|
|
97
97
|
targetLocale: options.targetLocale
|
|
@@ -106,5 +106,5 @@ function LogoutRedirect() {
|
|
|
106
106
|
}
|
|
107
107
|
|
|
108
108
|
export { LogoutRedirect, accountRedirectLoader, orderRatingRedirectLoader, pendingOrdersRedirectLoader, productsSourceRedirectLoader, ratingRedirectLoader, slugBrandRedirectLoader, twigUrlRedirect };
|
|
109
|
-
//# sourceMappingURL=chunk-
|
|
110
|
-
//# sourceMappingURL=chunk-
|
|
109
|
+
//# sourceMappingURL=chunk-XPT4ZX7U.js.map
|
|
110
|
+
//# sourceMappingURL=chunk-XPT4ZX7U.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/routes/seo-redirects.ts"],"names":["id"],"mappings":";;;;;;;;AAkBA,eAAsB,wBAAwB,GAAA,EAAkD;AAC9F,EAAA,MAAM,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,MAAA,IAAU,eAAA;AACpC,EAAA,MAAM,SAAS,CAAA,CAAA,EAAI,MAAM,WAAW,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,CAAE,CAAA;AACrD;AAOA,eAAsB,4BACpB,GAAA,GAA+C,EAAE,MAAA,EAAQ,IAAG,EAC5C;AAChB,EAAA,MAAM,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,MAAA,IAAU,eAAA;AACpC,EAAA,MAAM,QAAA,CAA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CAAA,GAAI,MAAA,CAAO,MAAA;AACzF,IAAA,MAAM,SAAS,CAAA,EAAG,MAAA,GAAS,CAAA,CAAA,EAAI,MAAM,KAAK,EAAE,CAAA,EAAG,MAAA,CAAO,IAAI,GAAG,MAAM,CAAA,CAAA,EAAI,EAAE,UAAA,EAAY,KAAK,CAAA;AAAA,EAC5F;AACA,EAAA,IAAI,CAAC,OAAA,CAAQ,WAAA,IAAe,WAAA,CAAY,QAAQ,CAAA,EAAG;AACnD,EAAA,MAAM,EAAE,iBAAA,EAAkB,GAAI,MAAM,OAAO,2BAAe,CAAA;AAC1D,EAAA,MAAM,iBAAA,CAAkB,UAAU,MAAA,EAAQ;AAAA,IACxC,aAAa,OAAA,CAAQ,WAAA;AAAA,IACrB,cAAc,OAAA,CAAQ;AAAA,GACvB,CAAA;AACH;AAUO,SAAS,cAAA,GAAuB;AACrC,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,oBAAA,EAAqB;AAErB,IAAA,MAAA,CAAO,QAAA,CAAS,QAAQ,MAAA,CAAO,QAAA,CAAS,KAAK,OAAA,CAAQ,8BAAA,EAAgC,EAAE,CAAC,CAAA;AAAA,EAC1F,CAAA,EAAG,EAAE,CAAA;AACL,EAAA,OAAO,IAAA;AACT","file":"chunk-MHSASWOS.js","sourcesContent":["import { useEffect } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\nimport { isMissingResource, redirect } from '../providers/NavigationProvider';\nimport { FALLBACK_LOCALE, isLocale } from '../providers/locale-constants';\nimport { productKeyOfId } from '../router/product-key-urls';\nimport { CATEGORY_SLUG_ROUTE_ID, PRODUCT_SLUG_ROUTE_ID } from '../router/slug-routes';\nimport { clearAuthTokenCookie } from '../utils/cookies';\nimport { parseShortLinkPath } from './short-link-path';\n\nexport interface SlugBrandParams {\n /** SEO slug segment (ignored — only here to match the route pattern). */\n slug: string;\n /** Brand numeric ID to redirect to. */\n id: string;\n /** Active locale from the `/$locale` parent layout (e.g. `'ar'`, `'en'`). */\n locale?: string;\n}\n\nexport async function slugBrandRedirectLoader(ctx: { params: SlugBrandParams }): Promise<never> {\n const locale = ctx.params.locale || FALLBACK_LOCALE;\n throw redirect(`/${locale}/brands/${ctx.params.id}`);\n}\n\nexport interface PendingOrdersRedirectParams {\n /** Active locale from the `/$locale` parent layout (e.g. `'ar'`, `'en'`). */\n locale?: string;\n}\n\nexport async function pendingOrdersRedirectLoader(\n ctx: { params: PendingOrdersRedirectParams } = { params: {} }\n): Promise<never> {\n const locale = ctx.params.locale || FALLBACK_LOCALE;\n throw redirect(`/${locale}/account/orders?status=pending`);\n}\n\n/** `/account/rating`: the loyalty \"rate your orders\" link. Twig Raed has no rating page and sends it to the orders list. */\nexport async function ratingRedirectLoader(\n ctx: { params: PendingOrdersRedirectParams } = { params: {} }\n): Promise<never> {\n const locale = ctx.params.locale || FALLBACK_LOCALE;\n throw redirect(`/${locale}/account/orders`);\n}\n\n/**\n * `/rating/{id}` and `/account/rating/{id}`: the rate-your-order link in the order email and SMS,\n * sent like Twig to the order with its rating popup. The id goes as it came: the orders API\n * decodes it the way Store's `rateOrder` does (optimus when numeric, else the hash).\n */\nexport async function orderRatingRedirectLoader(ctx: {\n params: PendingOrdersRedirectParams & { id: string };\n /** The incoming query string, `token` included: the SDK signs the visitor in with it. */\n search?: string;\n}): Promise<never> {\n const prefix = ctx.params.locale ? `/${ctx.params.locale}` : '';\n const query = new URLSearchParams(ctx.search);\n query.set('show-rating-popup', 'true');\n throw redirect(`${prefix}/account/orders/${encodeURIComponent(ctx.params.id)}?${query}`);\n}\n\n/** A Twig customer URL (`/profile`, `/orders`, …) kept working as its `/account/…` page. */\nexport async function accountRedirectLoader(ctx: {\n params: PendingOrdersRedirectParams;\n page: string;\n /** The incoming query string (`?status=pending`), kept on the account page. */\n search?: string;\n}): Promise<never> {\n // No locale in the URL stays without one: the locale layout adds it only where the store has several.\n const prefix = ctx.params.locale ? `/${ctx.params.locale}` : '';\n throw redirect(`${prefix}/account/${ctx.page}${ctx.search ?? ''}`, { statusCode: 301 });\n}\n\n/** `/latest-products`, `/most-sales-products` and `/offers` now live at `/products?source=`. */\nexport async function productsSourceRedirectLoader(ctx: {\n params: PendingOrdersRedirectParams;\n source: 'latest' | 'sales' | 'offers';\n search?: string;\n}): Promise<never> {\n const prefix = ctx.params.locale ? `/${ctx.params.locale}` : '';\n const query = new URLSearchParams(ctx.search);\n query.delete('source');\n const rest = query.toString();\n throw redirect(`${prefix}/products?source=${ctx.source}${rest ? `&${rest}` : ''}`, {\n statusCode: 301,\n });\n}\n\nexport { resolveProductKeyPage } from './product/key';\nexport { publicProductKeyPath } from '../router/product-key-urls';\n\n/** Routes a Twig URL lands on by accident: a locale bound as `$slug`, or an id that is no number. */\nconst SLUG_ROUTES = new Set([PRODUCT_SLUG_ROUTE_ID, CATEGORY_SLUG_ROUTE_ID]);\n\n/** `/p{id}` or `/p{id}-{name}`, with or without a leading segment; the id capped as in `./product/id`. */\nconst TWIG_PRODUCT_URL = /^(?:\\/([^/]+))?\\/p(\\d{1,18})(?:-[^/]*)?\\/?$/;\n/** `/category/{hash}`, with or without a leading segment. */\nconst TWIG_CATEGORY_URL = /^(?:\\/([^/]+))?\\/category\\/([A-Za-z0-9]+)\\/?$/;\n\n/** The page the router matched, as the locale layout's `beforeLoad` sees it. */\nexport interface MatchedPage {\n routeId: string;\n params: Record<string, string | undefined>;\n}\n\nfunction rendersNoPage({ routeId, params }: MatchedPage): boolean {\n // A first segment that is no language binds as the locale, of the layout or of the home page.\n if (routeId === '/{-$locale}' || (params.locale && !isLocale(params.locale))) return true;\n if (!SLUG_ROUTES.has(routeId)) return false;\n // A SKU-link address the router's rewrite gave the product route (`router/product-key-urls`).\n if (productKeyOfId(params.id)) return false;\n return (!params.locale && isLocale(params.slug)) || !/^\\d+$/.test(params.id ?? '');\n}\n\nexport interface TwigUrlRedirectOptions {\n /**\n * The language segment the target takes, given the one the address had. The locale layout\n * knows how the store addresses its pages, so the redirect lands there in one hop: `/-/p1`\n * on a store with several languages was sent on again to `/ar/-/p1`, and that second request\n * also fetched the product, because the server starts every loader at once. Without it the\n * address's own segment is kept.\n */\n targetLocale?: (addressLocale: string | undefined) => Promise<string | undefined>;\n /**\n * The request's query client. The category lookup is then shared between a hover preload and\n * the click.\n */\n queryClient?: QueryClient;\n}\n\n/** The category's numeric id for its Twig hash, or `undefined` when the API has no such category. */\nasync function categoryIdOf(hash: string, queryClient?: QueryClient): Promise<string | undefined> {\n const { category } = await import('../api/category');\n try {\n const found = queryClient\n ? await queryClient.ensureQueryData(category.queries.detail(hash))\n : await category.find(hash);\n // Only the id is taken. The category is never filed under its id for the category page:\n // this lookup ran in the address's language (Arabic when it has none, the fallback), and\n // the page may be in another (`/en/-/c…` on an English-only store), while a category's\n // cache key carries no language.\n return String(found.id_ ?? found.id);\n } catch (error) {\n if (isMissingResource(error)) return undefined;\n throw error;\n }\n}\n\n/**\n * The product id behind a short link (`/KjQrpE`). A store without SEO URLs gives every product\n * that address, in its sitemap and in the API's `url`, and the API takes the code in place of\n * the id. Any failure counts as \"no such product\": a bare `/{code}` is also every scanner's\n * `/admin`, so an API error must not turn those into 500s. The not-found page's\n * `useProductShortLink` asks again from the browser, as it did before.\n */\nasync function shortLinkProductId(\n code: string,\n queryClient?: QueryClient\n): Promise<string | undefined> {\n const { product } = await import('../api/product');\n try {\n const found = queryClient\n ? await queryClient.ensureQueryData(product.queries.detail(code))\n : await product.find(code);\n return found?.id ? String(found.id) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Where a Twig URL's page is now, and the language its address carried. */\n/**\n * A Twig product or category URL: `/p{id}…` or `/category/{hash}`, bare or under a language. Under\n * any other first segment it is no Twig route, so the Store's catch-all would have it.\n */\nfunction twigPageUrl(\n pathname: string\n): { kind: 'p' | 'c'; ref: string; locale?: string } | undefined {\n const productUrl = TWIG_PRODUCT_URL.exec(pathname);\n const match = productUrl ?? TWIG_CATEGORY_URL.exec(pathname);\n if (!match || (match[1] && !isLocale(match[1]))) return undefined;\n return { kind: productUrl ? 'p' : 'c', ref: match[2], locale: match[1] };\n}\n\nasync function twigTarget(\n pathname: string,\n queryClient?: QueryClient\n): Promise<{ path: string; locale?: string } | undefined> {\n const pageUrl = twigPageUrl(pathname);\n if (pageUrl) {\n if (pageUrl.kind === 'p') return { path: `/-/p${pageUrl.ref}`, locale: pageUrl.locale };\n const id = await categoryIdOf(pageUrl.ref, queryClient);\n return id ? { path: `/-/c${id}`, locale: pageUrl.locale } : undefined;\n }\n const shortLink = parseShortLinkPath(pathname);\n if (!shortLink) return undefined;\n const id = await shortLinkProductId(shortLink.code, queryClient);\n return id ? { path: `/-/p${id}`, locale: shortLink.locale } : undefined;\n}\n\n/**\n * Twig's product and category URLs, each with or without a locale, sent to the page that has\n * them now: `/p{id}`, `/p{id}-{name}`, `/category/{hash}` and the product short link `/{code}`.\n * Run by the locale layout's `beforeLoad`, only for an address no page answers: the router binds\n * `/ar/p1` to `$slug/p{$id}` (slug `ar`) and `/p1` to the locale.\n *\n * A product URL carries its id, so it is redirected without asking the API: a product that is\n * gone is the product page's not-found, one hop on. A category hash or a short code only the API\n * can turn into the id; one that is gone stays the not-found page at its address.\n *\n * Any other address no page answers, a short code that names no product included, may be one of\n * the merchant's custom URLs, which Twig's catch-all answers last (`./custom-urls`). A gone\n * category's Twig URL is not: Twig's category route answers it.\n */\nexport async function twigUrlRedirect(\n pathname: string,\n search: string,\n page: MatchedPage | undefined,\n options: TwigUrlRedirectOptions = {}\n): Promise<void> {\n if (!page || !rendersNoPage(page)) return;\n const target = await twigTarget(pathname, options.queryClient);\n if (target) {\n const locale = options.targetLocale ? await options.targetLocale(target.locale) : target.locale;\n throw redirect(`${locale ? `/${locale}` : ''}${target.path}${search}`, { statusCode: 301 });\n }\n if (!options.queryClient || twigPageUrl(pathname)) return;\n const { customUrlRedirect } = await import('./custom-urls');\n await customUrlRedirect(pathname, search, {\n queryClient: options.queryClient,\n targetLocale: options.targetLocale,\n });\n}\n\n/**\n * `/logout` — where the SDK sends the browser once `salla.auth.logout()` has run\n * (`salla.url.get('logout?from=…')`). The Twig storefront serves that URL server-side. Here\n * it renders nothing and, in the browser, removes the theme's own `token` cookie (the SDK's\n * `cookie.clearAll()` leaves it) and then does a full navigation home. It has to be a\n * component, not a loader redirect: a loader runs during server rendering, where the cookie\n * can't be cleared, so the redirect would leave the visitor signed in on the next request.\n */\nexport function LogoutRedirect(): null {\n useEffect(() => {\n clearAuthTokenCookie();\n // `/{store base}/{locale}/logout?from=…` → `/{store base}/{locale}`\n window.location.replace(window.location.href.replace(/\\/logout\\/?(\\?[^#]*)?(#.*)?$/, ''));\n }, []);\n return null;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/routes/seo-redirects.ts"],"names":["id"],"mappings":";;;;;;;;AAkBA,eAAsB,wBAAwB,GAAA,EAAkD;AAC9F,EAAA,MAAM,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,MAAA,IAAU,eAAA;AACpC,EAAA,MAAM,SAAS,CAAA,CAAA,EAAI,MAAM,WAAW,GAAA,CAAI,MAAA,CAAO,EAAE,CAAA,CAAE,CAAA;AACrD;AAOA,eAAsB,4BACpB,GAAA,GAA+C,EAAE,MAAA,EAAQ,IAAG,EAC5C;AAChB,EAAA,MAAM,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,MAAA,IAAU,eAAA;AACpC,EAAA,MAAM,QAAA,CAAS,CAAA,CAAA,EAAI,MAAM,CAAA,8BAAA,CAAgC,CAAA;AAC3D;AAGA,eAAsB,qBACpB,GAAA,GAA+C,EAAE,MAAA,EAAQ,IAAG,EAC5C;AAChB,EAAA,MAAM,MAAA,GAAS,GAAA,CAAI,MAAA,CAAO,MAAA,IAAU,eAAA;AACpC,EAAA,MAAM,QAAA,CAAS,CAAA,CAAA,EAAI,MAAM,CAAA,eAAA,CAAiB,CAAA;AAC5C;AAOA,eAAsB,0BAA0B,GAAA,EAI7B;AACjB,EAAA,MAAM,MAAA,GAAS,IAAI,MAAA,CAAO,MAAA,GAAS,IAAI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,iBAAA,CAAkB,UAAU,MAAA,EAAQ;AAAA,IACxC,aAAa,OAAA,CAAQ,WAAA;AAAA,IACrB,cAAc,OAAA,CAAQ;AAAA,GACvB,CAAA;AACH;AAUO,SAAS,cAAA,GAAuB;AACrC,EAAA,SAAA,CAAU,MAAM;AACd,IAAA,oBAAA,EAAqB;AAErB,IAAA,MAAA,CAAO,QAAA,CAAS,QAAQ,MAAA,CAAO,QAAA,CAAS,KAAK,OAAA,CAAQ,8BAAA,EAAgC,EAAE,CAAC,CAAA;AAAA,EAC1F,CAAA,EAAG,EAAE,CAAA;AACL,EAAA,OAAO,IAAA;AACT","file":"chunk-XPT4ZX7U.js","sourcesContent":["import { useEffect } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\nimport { isMissingResource, redirect } from '../providers/NavigationProvider';\nimport { FALLBACK_LOCALE, isLocale } from '../providers/locale-constants';\nimport { productKeyOfId } from '../router/product-key-urls';\nimport { CATEGORY_SLUG_ROUTE_ID, PRODUCT_SLUG_ROUTE_ID } from '../router/slug-routes';\nimport { clearAuthTokenCookie } from '../utils/cookies';\nimport { parseShortLinkPath } from './short-link-path';\n\nexport interface SlugBrandParams {\n /** SEO slug segment (ignored — only here to match the route pattern). */\n slug: string;\n /** Brand numeric ID to redirect to. */\n id: string;\n /** Active locale from the `/$locale` parent layout (e.g. `'ar'`, `'en'`). */\n locale?: string;\n}\n\nexport async function slugBrandRedirectLoader(ctx: { params: SlugBrandParams }): Promise<never> {\n const locale = ctx.params.locale || FALLBACK_LOCALE;\n throw redirect(`/${locale}/brands/${ctx.params.id}`);\n}\n\nexport interface PendingOrdersRedirectParams {\n /** Active locale from the `/$locale` parent layout (e.g. `'ar'`, `'en'`). */\n locale?: string;\n}\n\nexport async function pendingOrdersRedirectLoader(\n ctx: { params: PendingOrdersRedirectParams } = { params: {} }\n): Promise<never> {\n const locale = ctx.params.locale || FALLBACK_LOCALE;\n throw redirect(`/${locale}/account/orders?status=pending`);\n}\n\n/** `/account/rating`: the loyalty \"rate your orders\" link. Twig Raed has no rating page and sends it to the orders list. */\nexport async function ratingRedirectLoader(\n ctx: { params: PendingOrdersRedirectParams } = { params: {} }\n): Promise<never> {\n const locale = ctx.params.locale || FALLBACK_LOCALE;\n throw redirect(`/${locale}/account/orders`);\n}\n\n/**\n * `/rating/{id}` and `/account/rating/{id}`: the rate-your-order link in the order email and SMS,\n * sent like Twig to the order with its rating popup. The id goes as it came: the orders API\n * decodes it the way Store's `rateOrder` does (optimus when numeric, else the hash).\n */\nexport async function orderRatingRedirectLoader(ctx: {\n params: PendingOrdersRedirectParams & { id: string };\n /** The incoming query string, `token` included: the SDK signs the visitor in with it. */\n search?: string;\n}): Promise<never> {\n const prefix = ctx.params.locale ? `/${ctx.params.locale}` : '';\n const query = new URLSearchParams(ctx.search);\n query.set('show-rating-popup', 'true');\n throw redirect(`${prefix}/account/orders/${encodeURIComponent(ctx.params.id)}?${query}`);\n}\n\n/** A Twig customer URL (`/profile`, `/orders`, …) kept working as its `/account/…` page. */\nexport async function accountRedirectLoader(ctx: {\n params: PendingOrdersRedirectParams;\n page: string;\n /** The incoming query string (`?status=pending`), kept on the account page. */\n search?: string;\n}): Promise<never> {\n // No locale in the URL stays without one: the locale layout adds it only where the store has several.\n const prefix = ctx.params.locale ? `/${ctx.params.locale}` : '';\n throw redirect(`${prefix}/account/${ctx.page}${ctx.search ?? ''}`, { statusCode: 301 });\n}\n\n/** `/latest-products`, `/most-sales-products` and `/offers` now live at `/products?source=`. */\nexport async function productsSourceRedirectLoader(ctx: {\n params: PendingOrdersRedirectParams;\n source: 'latest' | 'sales' | 'offers';\n search?: string;\n}): Promise<never> {\n const prefix = ctx.params.locale ? `/${ctx.params.locale}` : '';\n const query = new URLSearchParams(ctx.search);\n query.delete('source');\n const rest = query.toString();\n throw redirect(`${prefix}/products?source=${ctx.source}${rest ? `&${rest}` : ''}`, {\n statusCode: 301,\n });\n}\n\nexport { resolveProductKeyPage } from './product/key';\nexport { publicProductKeyPath } from '../router/product-key-urls';\n\n/** Routes a Twig URL lands on by accident: a locale bound as `$slug`, or an id that is no number. */\nconst SLUG_ROUTES = new Set([PRODUCT_SLUG_ROUTE_ID, CATEGORY_SLUG_ROUTE_ID]);\n\n/** `/p{id}` or `/p{id}-{name}`, with or without a leading segment; the id capped as in `./product/id`. */\nconst TWIG_PRODUCT_URL = /^(?:\\/([^/]+))?\\/p(\\d{1,18})(?:-[^/]*)?\\/?$/;\n/** `/category/{hash}`, with or without a leading segment. */\nconst TWIG_CATEGORY_URL = /^(?:\\/([^/]+))?\\/category\\/([A-Za-z0-9]+)\\/?$/;\n\n/** The page the router matched, as the locale layout's `beforeLoad` sees it. */\nexport interface MatchedPage {\n routeId: string;\n params: Record<string, string | undefined>;\n}\n\nfunction rendersNoPage({ routeId, params }: MatchedPage): boolean {\n // A first segment that is no language binds as the locale, of the layout or of the home page.\n if (routeId === '/{-$locale}' || (params.locale && !isLocale(params.locale))) return true;\n if (!SLUG_ROUTES.has(routeId)) return false;\n // A SKU-link address the router's rewrite gave the product route (`router/product-key-urls`).\n if (productKeyOfId(params.id)) return false;\n return (!params.locale && isLocale(params.slug)) || !/^\\d+$/.test(params.id ?? '');\n}\n\nexport interface TwigUrlRedirectOptions {\n /**\n * The language segment the target takes, given the one the address had. The locale layout\n * knows how the store addresses its pages, so the redirect lands there in one hop: `/-/p1`\n * on a store with several languages was sent on again to `/ar/-/p1`, and that second request\n * also fetched the product, because the server starts every loader at once. Without it the\n * address's own segment is kept.\n */\n targetLocale?: (addressLocale: string | undefined) => Promise<string | undefined>;\n /**\n * The request's query client. The category lookup is then shared between a hover preload and\n * the click.\n */\n queryClient?: QueryClient;\n}\n\n/** The category's numeric id for its Twig hash, or `undefined` when the API has no such category. */\nasync function categoryIdOf(hash: string, queryClient?: QueryClient): Promise<string | undefined> {\n const { category } = await import('../api/category');\n try {\n const found = queryClient\n ? await queryClient.ensureQueryData(category.queries.detail(hash))\n : await category.find(hash);\n // Only the id is taken. The category is never filed under its id for the category page:\n // this lookup ran in the address's language (Arabic when it has none, the fallback), and\n // the page may be in another (`/en/-/c…` on an English-only store), while a category's\n // cache key carries no language.\n return String(found.id_ ?? found.id);\n } catch (error) {\n if (isMissingResource(error)) return undefined;\n throw error;\n }\n}\n\n/**\n * The product id behind a short link (`/KjQrpE`). A store without SEO URLs gives every product\n * that address, in its sitemap and in the API's `url`, and the API takes the code in place of\n * the id. Any failure counts as \"no such product\": a bare `/{code}` is also every scanner's\n * `/admin`, so an API error must not turn those into 500s. The not-found page's\n * `useProductShortLink` asks again from the browser, as it did before.\n */\nasync function shortLinkProductId(\n code: string,\n queryClient?: QueryClient\n): Promise<string | undefined> {\n const { product } = await import('../api/product');\n try {\n const found = queryClient\n ? await queryClient.ensureQueryData(product.queries.detail(code))\n : await product.find(code);\n return found?.id ? String(found.id) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Where a Twig URL's page is now, and the language its address carried. */\n/**\n * A Twig product or category URL: `/p{id}…` or `/category/{hash}`, bare or under a language. Under\n * any other first segment it is no Twig route, so the Store's catch-all would have it.\n */\nfunction twigPageUrl(\n pathname: string\n): { kind: 'p' | 'c'; ref: string; locale?: string } | undefined {\n const productUrl = TWIG_PRODUCT_URL.exec(pathname);\n const match = productUrl ?? TWIG_CATEGORY_URL.exec(pathname);\n if (!match || (match[1] && !isLocale(match[1]))) return undefined;\n return { kind: productUrl ? 'p' : 'c', ref: match[2], locale: match[1] };\n}\n\nasync function twigTarget(\n pathname: string,\n queryClient?: QueryClient\n): Promise<{ path: string; locale?: string } | undefined> {\n const pageUrl = twigPageUrl(pathname);\n if (pageUrl) {\n if (pageUrl.kind === 'p') return { path: `/-/p${pageUrl.ref}`, locale: pageUrl.locale };\n const id = await categoryIdOf(pageUrl.ref, queryClient);\n return id ? { path: `/-/c${id}`, locale: pageUrl.locale } : undefined;\n }\n const shortLink = parseShortLinkPath(pathname);\n if (!shortLink) return undefined;\n const id = await shortLinkProductId(shortLink.code, queryClient);\n return id ? { path: `/-/p${id}`, locale: shortLink.locale } : undefined;\n}\n\n/**\n * Twig's product and category URLs, each with or without a locale, sent to the page that has\n * them now: `/p{id}`, `/p{id}-{name}`, `/category/{hash}` and the product short link `/{code}`.\n * Run by the locale layout's `beforeLoad`, only for an address no page answers: the router binds\n * `/ar/p1` to `$slug/p{$id}` (slug `ar`) and `/p1` to the locale.\n *\n * A product URL carries its id, so it is redirected without asking the API: a product that is\n * gone is the product page's not-found, one hop on. A category hash or a short code only the API\n * can turn into the id; one that is gone stays the not-found page at its address.\n *\n * Any other address no page answers, a short code that names no product included, may be one of\n * the merchant's custom URLs, which Twig's catch-all answers last (`./custom-urls`). A gone\n * category's Twig URL is not: Twig's category route answers it.\n */\nexport async function twigUrlRedirect(\n pathname: string,\n search: string,\n page: MatchedPage | undefined,\n options: TwigUrlRedirectOptions = {}\n): Promise<void> {\n if (!page || !rendersNoPage(page)) return;\n const target = await twigTarget(pathname, options.queryClient);\n if (target) {\n const locale = options.targetLocale ? await options.targetLocale(target.locale) : target.locale;\n throw redirect(`${locale ? `/${locale}` : ''}${target.path}${search}`, { statusCode: 301 });\n }\n if (!options.queryClient || twigPageUrl(pathname)) return;\n const { customUrlRedirect } = await import('./custom-urls');\n await customUrlRedirect(pathname, search, {\n queryClient: options.queryClient,\n targetLocale: options.targetLocale,\n });\n}\n\n/**\n * `/logout` — where the SDK sends the browser once `salla.auth.logout()` has run\n * (`salla.url.get('logout?from=…')`). The Twig storefront serves that URL server-side. Here\n * it renders nothing and, in the browser, removes the theme's own `token` cookie (the SDK's\n * `cookie.clearAll()` leaves it) and then does a full navigation home. It has to be a\n * component, not a loader redirect: a loader runs during server rendering, where the cookie\n * can't be cleared, so the redirect would leave the visitor signed in on the next request.\n */\nexport function LogoutRedirect(): null {\n useEffect(() => {\n clearAuthTokenCookie();\n // `/{store base}/{locale}/logout?from=…` → `/{store base}/{locale}`\n window.location.replace(window.location.href.replace(/\\/logout\\/?(\\?[^#]*)?(#.*)?$/, ''));\n }, []);\n return null;\n}\n"]}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { customUrlRedirect } from './chunk-
|
|
1
|
+
import { customUrlRedirect } from './chunk-VLLKXG5J.js';
|
|
2
2
|
import { PRODUCT_SLUG_ROUTE_ID } from './chunk-NV4PF3O3.js';
|
|
3
|
-
import { product } from './chunk-
|
|
3
|
+
import { product } from './chunk-BICEPRPK.js';
|
|
4
4
|
import { productKeyOfId, publicProductKeyPath } from './chunk-SDBR4X3K.js';
|
|
5
|
-
import { notFound, orThrow, isMissingResource } from './chunk-
|
|
5
|
+
import { notFound, orThrow, isMissingResource } from './chunk-5TVOTTHS.js';
|
|
6
6
|
|
|
7
7
|
// src/routes/product/id.ts
|
|
8
8
|
var PRODUCT_ID = /^\d{1,18}$/;
|
|
@@ -42,5 +42,5 @@ async function resolveProductKeyPage(page, queryClient, address) {
|
|
|
42
42
|
}
|
|
43
43
|
|
|
44
44
|
export { isProductId, productOfKey, resolveProductKeyPage };
|
|
45
|
-
//# sourceMappingURL=chunk-
|
|
46
|
-
//# sourceMappingURL=chunk-
|
|
45
|
+
//# sourceMappingURL=chunk-XVTXIVFM.js.map
|
|
46
|
+
//# sourceMappingURL=chunk-XVTXIVFM.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/routes/product/id.ts","../src/routes/product/key.ts"],"names":[],"mappings":";;;;;;;AAWA,IAAM,UAAA,GAAa,YAAA;AAGZ,SAAS,YAAY,KAAA,EAAoC;AAC9D,EAAA,OAAO,UAAA,CAAW,IAAA,CAAK,KAAA,IAAS,EAAE,CAAA;AACpC;;;ACAA,IAAM,MAAA,GAAS,UAAA;AAMf,eAAsB,YAAA,CACpB,KACA,WAAA,EACkB;AAClB,EAAA,MAAM,EAAA,GAAK,MAAA,CAAO,IAAA,CAAK,GAAG,IAAI,CAAC,CAAA;AAC/B,EAAA,IAAI,OAAO,MAAA,EAAW;AAEpB,IAAA,IAAI,CAAC,WAAA,CAAY,EAAE,CAAA,S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AAA,QAC9D,WAAA;AAAA,QACA,cAAc,OAAA,CAAQ;AAAA,OACvB,CAAA;AAAA,IACH;AACA,IAAA,QAAA,EAAS;AAAA,EACX;AACF","file":"chunk-XVTXIVFM.js","sourcesContent":["/**\n * A product id: 1 to 18 digits.\n *\n * The API keeps product ids in a signed 64-bit integer. Up to 9223372036854775807 it answers\n * a missing product with 410; one past that, it answers 417, which is neither 404 nor 410, so\n * the page went out as a 500 (`/-/p99999999999999999999999`, which scanners ask for). Every\n * 18-digit number fits; real ids have about 10.\n *\n * `TWIG_PRODUCT_URL` in `../seo-redirects.ts` carries the same cap. Both are literals, because static\n * analysis flags a `RegExp` built from a string.\n */\nconst PRODUCT_ID = /^\\d{1,18}$/;\n\n/** Whether `value` can be a product id the API answers 200 or 410 for. */\nexport function isProductId(value: string | undefined): boolean {\n return PRODUCT_ID.test(value ?? '');\n}\n","/**\n * @fileoverview The product at a SKU-link address (`/{key}-{name}`, see `router/product-key-urls`).\n *\n * The rewrite hands the product route an id of `~{key}`. The key is `p{id}` (the product id\n * itself) or a SKU of letters and digits, as Twig's `getProductBySkuOrId` reads it.\n */\nimport type { QueryClient } from '@tanstack/react-query';\nimport type { Product } from '../../types';\nimport { product } from '../../api/product';\nimport { isMissingResource, notFound, orThrow } from '../../providers/NavigationProvider';\nimport { productKeyOfId, publicProductKeyPath } from '../../router/product-key-urls';\nimport { PRODUCT_SLUG_ROUTE_ID } from '../../router/slug-routes';\nimport { customUrlRedirect, type CustomUrlRedirectOptions } from '../custom-urls';\nimport { isProductId } from './id';\n\n/** `p{id}`: Sluggable's key for a product whose SKU is not letters and digits. */\nconst ID_KEY = /^p(\\d+)$/;\n\n/**\n * The product a key names: by id for `p{id}`, else by SKU. A SKU is read through the query cache,\n * which `resolveProductKeyPage` filled in the same navigation, so it costs one call.\n */\nexport async function productOfKey(\n key: string,\n queryClient?: QueryClient | null\n): Promise<Product> {\n const id = ID_KEY.exec(key)?.[1];\n if (id !== undefined) {\n // Past 18 digits the API answers 417, not 404 (see `./id`).\n if (!isProductId(id)) return notFound();\n return product.findOrThrow(id);\n }\n return orThrow(\n queryClient ? queryClient.ensureQueryData(product.queries.bySku(key)) : product.findBySku(key)\n );\n}\n\n/** The address a SKU-link lookup was made for, so a miss can still be one of the merchant's custom URLs. */\nexport interface ProductKeyAddress {\n /** The router's location: the internal path (`/{name}/p~{key}`) and the query string. */\n location: { pathname: string; searchStr: string };\n /** The language segment an item's page takes (the locale layout's rule). */\n targetLocale?: CustomUrlRedirectOptions['targetLocale'];\n}\n\n/**\n * Run by the locale layout's `beforeLoad`: a SKU that names no product is the not-found page, a\n * 404, as Twig's catch-all answers it, unless the address is one of the merchant's custom URLs.\n * Twig tries those after its SKU route: `/values-in-action` is first SKU `values`.\n *\n * It is resolved here, ahead of the product loader, because a theme may turn that loader's\n * not-found into something else: Raed sends it home with a toast. That suits a product that was\n * deleted, but not `/new-arrivals` or a scanner's path, which only look like a SKU link. The\n * answer stays in the query cache for the loader.\n */\nexport async function resolveProductKeyPage(\n page: { routeId: string; params: Record<string, string | undefined> } | undefined,\n queryClient: QueryClient,\n address?: ProductKeyAddress\n): Promise<void> {\n if (page?.routeId !== PRODUCT_SLUG_ROUTE_ID) return;\n const key = productKeyOfId(page.params.id);\n if (!key || ID_KEY.test(key)) return;\n try {\n await queryClient.ensureQueryData(product.queries.bySku(key));\n } catch (error) {\n if (!isMissingResource(error)) throw error;\n const publicPath = address && publicProductKeyPath(address.location.pathname);\n if (publicPath) {\n await customUrlRedirect(publicPath, address.location.searchStr, {\n queryClient,\n targetLocale: address.targetLocale,\n });\n }\n notFound();\n }\n}\n"]}
|
|
@@ -184,5 +184,5 @@ function useCanvasHost() {
|
|
|
184
184
|
}
|
|
185
185
|
|
|
186
186
|
export { matchBlocks, postToCanvas, takeCanvasCommands, useCanvasHost };
|
|
187
|
-
//# sourceMappingURL=chunk-
|
|
188
|
-
//# sourceMappingURL=chunk-
|
|
187
|
+
//# sourceMappingURL=chunk-YCQK4JRW.js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AAE,IAAA,EAAM,MAAM,CAAA;AAC1D,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,CAAO,mBAAA,CAAoB,WAAW,SAAS,CAAA;AAC/C,MAAA,MAAA,CAAO,mBAAA,CAAoB,QAAQ,KAAK,CAAA;AAAA,IAC1C,CAAA;AAAA,EACF,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO,IAAA;AACT","file":"chunk-QXAUEOHK.js","sourcesContent":["/**\n * The storefront's side of the design studio's canvas mode: the studio frames\n * the store and draws its own cards and panels, and the store outlines what the\n * merchant points at and reports what is picked. The same `postMessage`\n * protocol the twig themes' `live-themes-editor.js` speaks in canvas mode.\n */\n\nimport { useEffect, useState } from 'react';\nimport { isEditorFrame } from '../../dev/schema-types';\nimport { getTwilightContext } from '../../twilight/context';\nimport { parentOrigin } from './frame';\nimport { drawLiveBlocks } from './moves';\n\nconst CHILD = 'salla-canvas';\nconst HOST = 'salla-canvas-host';\n\n/** Where the studio runs; it alone turns canvas mode on. */\nexport const CANVAS_ORIGINS = [\n 'https://s.salla.sa',\n 'https://s.salla.dev',\n 'https://s.beta.salla.group',\n 'http://localhost:9000',\n] as const;\n\nexport type CanvasRole = 'component' | 'header' | 'footer';\n\n/** The header's or footer's own logo or menu, picked on its own. */\nexport type CanvasPart = 'logo' | 'menu';\n\n/**\n * A home block as the studio lists it, in page order. The storefront's blocks\n * carry no row id, so the studio's list names them: `eid` is what the studio\n * calls the block, matched to the page by its uuid (`key`) or its `slug`.\n */\nexport interface CanvasBlock {\n eid: string;\n key?: string | null;\n slug?: string | null;\n title?: string | null;\n}\n\nexport type CanvasCommand =\n | { type: 'select'; eid: string; part?: CanvasPart }\n | { type: 'deselect' }\n | { type: 'move'; eid: string; direction: 'up' | 'down' }\n /** Lays the blocks out in this order without saving it. */\n | { type: 'order'; eids: string[] };\n\nexport interface CanvasHost {\n /** The studio's origin once it has spoken, else `null`: the page is not in canvas mode. */\n origin: string | null;\n enabled: boolean;\n blocks: CanvasBlock[] | null;\n}\n\nconst asEid = (value: unknown): string | null =>\n typeof value === 'string' && value ? value : null;\n\nconst asPart = (value: unknown): CanvasPart | undefined =>\n value === 'logo' || value === 'menu' ? value : undefined;\n\nfunction asBlocks(value: unknown): CanvasBlock[] | null {\n if (!Array.isArray(value)) return null;\n return value.flatMap((item) => {\n const block = item as Partial<CanvasBlock> | null;\n const eid = asEid(block?.eid);\n if (!eid) return [];\n return [\n {\n eid,\n key: typeof block?.key === 'string' ? block.key : null,\n slug: typeof block?.slug === 'string' ? block.slug : null,\n title: typeof block?.title === 'string' ? block.title : null,\n },\n ];\n });\n}\n\n/** The command a studio message carries, if it is a well-formed one. */\nexport function readCommand(data: Record<string, unknown>): CanvasCommand | null {\n switch (data.type) {\n case 'select': {\n const eid = asEid(data.eid);\n return eid ? { type: 'select', eid, part: asPart(data.part) } : null;\n }\n case 'deselect':\n return { type: 'deselect' };\n case 'move': {\n const eid = asEid(data.eid);\n const direction =\n data.direction === 'up' || data.direction === 'down' ? data.direction : null;\n return eid && direction ? { type: 'move', eid, direction } : null;\n }\n case 'order':\n return Array.isArray(data.eids)\n ? { type: 'order', eids: data.eids.flatMap((eid) => asEid(eid) ?? []) }\n : null;\n default:\n return null;\n }\n}\n\n/** The engine's name for a studio block: its uuid, or its slug spelled as the storefront's path. */\nconst refOf = (block: CanvasBlock): string => block.key || block.slug?.replace(/_/g, '-') || '';\n\n/**\n * The studio block each page block is, by page order: copies of one component\n * share a uuid, so the n-th on the page is the n-th in the list. `refs` are\n * the page blocks' `data-live-block` values; `null` where none matches, and\n * for every copy of a ref the page and the list count differently, where the\n * n-th could be another row.\n */\nexport function matchBlocks(\n refs: readonly string[],\n blocks: readonly CanvasBlock[]\n): (CanvasBlock | null)[] {\n const names = (block: CanvasBlock, ref: string) => block.eid === ref || refOf(block) === ref;\n const used = new Set<number>();\n return refs.map((ref) => {\n const onPage = refs.filter((each) => each === ref).length;\n if (blocks.filter((block) => names(block, ref)).length !== onPage) return null;\n const at = blocks.findIndex((block, index) => !used.has(index) && names(block, ref));\n if (at === -1) return null;\n used.add(at);\n return blocks[at];\n });\n}\n\n/** Sends `message` to the studio, or, before it has spoken, to whichever allowed origin frames the page. */\nexport function postToCanvas(origin: string | null, message: Record<string, unknown>): void {\n const data = { source: CHILD, v: 1, ...message };\n if (origin) {\n window.parent.postMessage(data, origin);\n return;\n }\n let parent: string | null = null;\n try {\n parent = parentOrigin();\n } catch {\n parent = null;\n }\n const targets: readonly string[] = parent ? [parent] : CANVAS_ORIGINS;\n for (const target of targets) {\n if ((CANVAS_ORIGINS as readonly string[]).includes(target))\n window.parent.postMessage(data, target);\n }\n}\n\n/** What the page redraws in place when the studio saves, as `hello` tells it. */\nexport const CANVAS_CAN = ['refresh'] as const;\n\nlet lastDraw: Promise<unknown> = Promise.resolve();\n\n// Under the studio's own wait, so the page answers before the studio gives up on it.\nconst DRAW_LIMIT = 15_000;\n\n/**\n * Draws the home page again from what the studio just saved, without reloading it: its\n * blocks fetched afresh, spelled as the home loader spells them. Fails off the home page.\n */\nexport function redrawPage(): Promise<void> {\n // One at a time: the query cache would hand this save a fetch started before it.\n const draw = lastDraw.then(drawAfresh);\n lastDraw = draw.catch(() => undefined);\n return draw;\n}\n\nasync function drawAfresh(): Promise<void> {\n const { home } = await import('../../api/home');\n const { queryClient } = getTwilightContext();\n const components = home.queries.components();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const tooLong = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n // Its fetch is called off too, or the next redraw would be handed it.\n void queryClient.cancelQueries({ queryKey: components.queryKey });\n reject(new Error('redraw took too long'));\n }, DRAW_LIMIT);\n });\n const blocks = await Promise.race([\n queryClient.fetchQuery({ ...components, staleTime: 0 }),\n tooLong,\n ]).finally(() => clearTimeout(timer));\n const drawn = drawLiveBlocks(\n blocks.map((block) => ({ ...block, path: block.path?.replace('home.', '') || block.path }))\n );\n if (!drawn) throw new Error('no home page');\n}\n\n// Draws the page again for the section the studio saved; false for a refresh that names none.\nfunction refreshFor(studio: string, data: Record<string, unknown>): boolean {\n const eid = asEid(data.eid);\n if (!eid) {\n postToCanvas(studio, { type: 'refresh-failed', eid: String(data.eid ?? '') });\n return false;\n }\n redrawPage().then(\n () => {\n if (data.select === true) deliver({ type: 'select', eid });\n postToCanvas(studio, { type: 'refreshed', eid });\n },\n () => postToCanvas(studio, { type: 'refresh-failed', eid })\n );\n return true;\n}\n\n/** The overlay on screen takes the studio's commands; ones sent before it mounted wait for it. */\nlet handler: ((command: CanvasCommand) => void) | null = null;\nlet queued: CanvasCommand[] = [];\n\nfunction deliver(command: CanvasCommand): void {\n if (handler) handler(command);\n else queued.push(command);\n}\n\n/** Hands the studio's commands to `fn` while it is set, the waiting ones first. */\nexport function takeCanvasCommands(fn: (command: CanvasCommand) => void): () => void {\n handler = fn;\n const waiting = queued;\n queued = [];\n waiting.forEach(fn);\n return () => {\n if (handler === fn) handler = null;\n };\n}\n\n/**\n * Says hello to the studio once the page has loaded, and follows what it asks\n * for. Off for shoppers, for the theme editor (which never answers) and for the\n * engine's own dev editor, which keep the live editor bar.\n */\nexport function useCanvasHost(): CanvasHost {\n const [host, setHost] = useState<CanvasHost>({ origin: null, enabled: false, blocks: null });\n\n useEffect(() => {\n if (window.self === window.top || (import.meta.env.DEV && isEditorFrame())) return;\n let origin: string | null = null;\n\n const onMessage = (event: MessageEvent) => {\n if (event.source !== window.parent) return;\n const data = (event.data ?? {}) as Record<string, unknown>;\n // The studio saved on the server and wants the page drawn again, as the twig preview does.\n if (data.action === 'preview::reload') {\n if (origin && event.origin === origin) window.location.reload();\n return;\n }\n if (data.source !== HOST) return;\n if (!origin) {\n if (!(CANVAS_ORIGINS as readonly string[]).includes(event.origin)) return;\n origin = event.origin;\n } else if (event.origin !== origin) return;\n const studio = origin;\n\n // A section saved: the page is drawn again in place, and the section picked once the studio names it.\n if (data.type === 'refresh') {\n if (refreshFor(studio, data))\n setHost((prev) => (prev.origin ? prev : { ...prev, origin: studio }));\n } else if (data.type === 'enable') {\n const blocks = asBlocks(data.blocks);\n setHost((prev) => ({ origin: studio, enabled: true, blocks: blocks ?? prev.blocks }));\n } else if (data.type === 'disable') {\n queued = [];\n setHost((prev) => ({ ...prev, origin: studio, enabled: false }));\n } else {\n setHost((prev) => (prev.origin ? prev : { ...prev, origin: studio }));\n const command = readCommand(data);\n if (command) deliver(command);\n }\n };\n\n const hello = () => postToCanvas(origin, { type: 'hello', can: [...CANVAS_CAN] });\n window.addEventListener('message', onMessage);\n if (document.readyState === 'complete') hello();\n else window.addEventListener('load', hello, { once: true });\n return () => {\n window.removeEventListener('message', onMessage);\n window.removeEventListener('load', hello);\n };\n }, []);\n\n return host;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/components/live-editor/canvas.ts"],"names":[],"mappings":";;;;;;AAaA,IAAM,KAAA,GAAQ,cAAA;AACd,IAAM,IAAA,GAAO,mBAAA;AAGN,IAAM,cAAA,GAAiB;AAAA,EAC5B,oBAAA;AAAA,EACA,qBAAA;AAAA,EACA,4BAAA;AAAA,EACA;AACF,CAAA;AAiCA,IAAM,QAAQ,CAAC,KAAA,KACb,OAAO,KAAA,KAAU,QAAA,IAAY,QAAQ,KAAA,GAAQ,IAAA;AAE/C,IAAM,SAAS,CAAC,KAAA,KACd,UAAU,MAAA,IAAU,KAAA,KAAU,SAAS,KAAA,GAAQ,MAAA;AAEjD,SAAS,SAAS,KAAA,EAAsC;AACtD,EAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,GAAG,OAAO,IAAA;AAClC,EAAA,OAAO,KAAA,CAAM,OAAA,CAAQ,CAAC,IAAA,KAAS;AAC7B,IAAA,MAAM,KAAA,GAAQ,IAAA;AACd,IAAA,MAAM,GAAA,GAAM,KAAA,CAAM,KAAA,EAAO,GAAG,CAAA;AAC5B,IAAA,IAAI,CAAC,GAAA,EAAK,OAAO,EAAC;AAClB,IAAA,OAAO;AAAA,MACL;AAAA,QACE,GAAA;AAAA,QACA,KAAK,O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AAiB,OAAO,CAAA;AAAA,MAC9B;AAAA,IACF,CAAA;AAEA,IAAA,MAAM,KAAA,GAAQ,MAAM,YAAA,CAAa,MAAA,EAAQ,EAAE,IAAA,EAAM,OAAA,EAAS,GAAA,EAAK,CAAC,GAAG,UAAU,CAAA,EAAG,CAAA;AAChF,IAAA,MAAA,CAAO,gBAAA,CAAiB,WAAW,SAAS,CAAA;AAC5C,IAAA,IAAI,QAAA,CAAS,UAAA,KAAe,UAAA,EAAY,KAAA,EAAM;AAAA,gBAClC,gBAAA,CAAiB,MAAA,EAAQ,OAAO,EAAE,IAAA,EAAM,MAAM,CAAA;AAC1D,IAAA,OAAO,MAAM;AACX,MAAA,MAAA,CAAO,mBAAA,CAAoB,WAAW,SAAS,CAAA;AAC/C,MAAA,MAAA,CAAO,mBAAA,CAAoB,QAAQ,KAAK,CAAA;AAAA,IAC1C,CAAA;AAAA,EACF,CAAA,EAAG,EAAE,CAAA;AAEL,EAAA,OAAO,IAAA;AACT","file":"chunk-YCQK4JRW.js","sourcesContent":["/**\n * The storefront's side of the design studio's canvas mode: the studio frames\n * the store and draws its own cards and panels, and the store outlines what the\n * merchant points at and reports what is picked. The same `postMessage`\n * protocol the twig themes' `live-themes-editor.js` speaks in canvas mode.\n */\n\nimport { useEffect, useState } from 'react';\nimport { isEditorFrame } from '../../dev/schema-types';\nimport { getTwilightContext } from '../../twilight/context';\nimport { parentOrigin } from './frame';\nimport { drawLiveBlocks } from './moves';\n\nconst CHILD = 'salla-canvas';\nconst HOST = 'salla-canvas-host';\n\n/** Where the studio runs; it alone turns canvas mode on. */\nexport const CANVAS_ORIGINS = [\n 'https://s.salla.sa',\n 'https://s.salla.dev',\n 'https://s.beta.salla.group',\n 'http://localhost:9000',\n] as const;\n\nexport type CanvasRole = 'component' | 'header' | 'footer';\n\n/** The header's or footer's own logo or menu, picked on its own. */\nexport type CanvasPart = 'logo' | 'menu';\n\n/**\n * A home block as the studio lists it, in page order. The storefront's blocks\n * carry no row id, so the studio's list names them: `eid` is what the studio\n * calls the block, matched to the page by its uuid (`key`) or its `slug`.\n */\nexport interface CanvasBlock {\n eid: string;\n key?: string | null;\n slug?: string | null;\n title?: string | null;\n}\n\nexport type CanvasCommand =\n | { type: 'select'; eid: string; part?: CanvasPart }\n | { type: 'deselect' }\n | { type: 'move'; eid: string; direction: 'up' | 'down' }\n /** Lays the blocks out in this order without saving it. */\n | { type: 'order'; eids: string[] };\n\nexport interface CanvasHost {\n /** The studio's origin once it has spoken, else `null`: the page is not in canvas mode. */\n origin: string | null;\n enabled: boolean;\n blocks: CanvasBlock[] | null;\n}\n\nconst asEid = (value: unknown): string | null =>\n typeof value === 'string' && value ? value : null;\n\nconst asPart = (value: unknown): CanvasPart | undefined =>\n value === 'logo' || value === 'menu' ? value : undefined;\n\nfunction asBlocks(value: unknown): CanvasBlock[] | null {\n if (!Array.isArray(value)) return null;\n return value.flatMap((item) => {\n const block = item as Partial<CanvasBlock> | null;\n const eid = asEid(block?.eid);\n if (!eid) return [];\n return [\n {\n eid,\n key: typeof block?.key === 'string' ? block.key : null,\n slug: typeof block?.slug === 'string' ? block.slug : null,\n title: typeof block?.title === 'string' ? block.title : null,\n },\n ];\n });\n}\n\n/** The command a studio message carries, if it is a well-formed one. */\nexport function readCommand(data: Record<string, unknown>): CanvasCommand | null {\n switch (data.type) {\n case 'select': {\n const eid = asEid(data.eid);\n return eid ? { type: 'select', eid, part: asPart(data.part) } : null;\n }\n case 'deselect':\n return { type: 'deselect' };\n case 'move': {\n const eid = asEid(data.eid);\n const direction =\n data.direction === 'up' || data.direction === 'down' ? data.direction : null;\n return eid && direction ? { type: 'move', eid, direction } : null;\n }\n case 'order':\n return Array.isArray(data.eids)\n ? { type: 'order', eids: data.eids.flatMap((eid) => asEid(eid) ?? []) }\n : null;\n default:\n return null;\n }\n}\n\n/** The engine's name for a studio block: its uuid, or its slug spelled as the storefront's path. */\nconst refOf = (block: CanvasBlock): string => block.key || block.slug?.replace(/_/g, '-') || '';\n\n/**\n * The studio block each page block is, by page order: copies of one component\n * share a uuid, so the n-th on the page is the n-th in the list. `refs` are\n * the page blocks' `data-live-block` values; `null` where none matches, and\n * for every copy of a ref the page and the list count differently, where the\n * n-th could be another row.\n */\nexport function matchBlocks(\n refs: readonly string[],\n blocks: readonly CanvasBlock[]\n): (CanvasBlock | null)[] {\n const names = (block: CanvasBlock, ref: string) => block.eid === ref || refOf(block) === ref;\n const used = new Set<number>();\n return refs.map((ref) => {\n const onPage = refs.filter((each) => each === ref).length;\n if (blocks.filter((block) => names(block, ref)).length !== onPage) return null;\n const at = blocks.findIndex((block, index) => !used.has(index) && names(block, ref));\n if (at === -1) return null;\n used.add(at);\n return blocks[at];\n });\n}\n\n/** Sends `message` to the studio, or, before it has spoken, to whichever allowed origin frames the page. */\nexport function postToCanvas(origin: string | null, message: Record<string, unknown>): void {\n const data = { source: CHILD, v: 1, ...message };\n if (origin) {\n window.parent.postMessage(data, origin);\n return;\n }\n let parent: string | null = null;\n try {\n parent = parentOrigin();\n } catch {\n parent = null;\n }\n const targets: readonly string[] = parent ? [parent] : CANVAS_ORIGINS;\n for (const target of targets) {\n if ((CANVAS_ORIGINS as readonly string[]).includes(target))\n window.parent.postMessage(data, target);\n }\n}\n\n/** What the page redraws in place when the studio saves, as `hello` tells it. */\nexport const CANVAS_CAN = ['refresh'] as const;\n\nlet lastDraw: Promise<unknown> = Promise.resolve();\n\n// Under the studio's own wait, so the page answers before the studio gives up on it.\nconst DRAW_LIMIT = 15_000;\n\n/**\n * Draws the home page again from what the studio just saved, without reloading it: its\n * blocks fetched afresh, spelled as the home loader spells them. Fails off the home page.\n */\nexport function redrawPage(): Promise<void> {\n // One at a time: the query cache would hand this save a fetch started before it.\n const draw = lastDraw.then(drawAfresh);\n lastDraw = draw.catch(() => undefined);\n return draw;\n}\n\nasync function drawAfresh(): Promise<void> {\n const { home } = await import('../../api/home');\n const { queryClient } = getTwilightContext();\n const components = home.queries.components();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const tooLong = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n // Its fetch is called off too, or the next redraw would be handed it.\n void queryClient.cancelQueries({ queryKey: components.queryKey });\n reject(new Error('redraw took too long'));\n }, DRAW_LIMIT);\n });\n const blocks = await Promise.race([\n queryClient.fetchQuery({ ...components, staleTime: 0 }),\n tooLong,\n ]).finally(() => clearTimeout(timer));\n const drawn = drawLiveBlocks(\n blocks.map((block) => ({ ...block, path: block.path?.replace('home.', '') || block.path }))\n );\n if (!drawn) throw new Error('no home page');\n}\n\n// Draws the page again for the section the studio saved; false for a refresh that names none.\nfunction refreshFor(studio: string, data: Record<string, unknown>): boolean {\n const eid = asEid(data.eid);\n if (!eid) {\n postToCanvas(studio, { type: 'refresh-failed', eid: String(data.eid ?? '') });\n return false;\n }\n redrawPage().then(\n () => {\n if (data.select === true) deliver({ type: 'select', eid });\n postToCanvas(studio, { type: 'refreshed', eid });\n },\n () => postToCanvas(studio, { type: 'refresh-failed', eid })\n );\n return true;\n}\n\n/** The overlay on screen takes the studio's commands; ones sent before it mounted wait for it. */\nlet handler: ((command: CanvasCommand) => void) | null = null;\nlet queued: CanvasCommand[] = [];\n\nfunction deliver(command: CanvasCommand): void {\n if (handler) handler(command);\n else queued.push(command);\n}\n\n/** Hands the studio's commands to `fn` while it is set, the waiting ones first. */\nexport function takeCanvasCommands(fn: (command: CanvasCommand) => void): () => void {\n handler = fn;\n const waiting = queued;\n queued = [];\n waiting.forEach(fn);\n return () => {\n if (handler === fn) handler = null;\n };\n}\n\n/**\n * Says hello to the studio once the page has loaded, and follows what it asks\n * for. Off for shoppers, for the theme editor (which never answers) and for the\n * engine's own dev editor, which keep the live editor bar.\n */\nexport function useCanvasHost(): CanvasHost {\n const [host, setHost] = useState<CanvasHost>({ origin: null, enabled: false, blocks: null });\n\n useEffect(() => {\n if (window.self === window.top || (import.meta.env.DEV && isEditorFrame())) return;\n let origin: string | null = null;\n\n const onMessage = (event: MessageEvent) => {\n if (event.source !== window.parent) return;\n const data = (event.data ?? {}) as Record<string, unknown>;\n // The studio saved on the server and wants the page drawn again, as the twig preview does.\n if (data.action === 'preview::reload') {\n if (origin && event.origin === origin) window.location.reload();\n return;\n }\n if (data.source !== HOST) return;\n if (!origin) {\n if (!(CANVAS_ORIGINS as readonly string[]).includes(event.origin)) return;\n origin = event.origin;\n } else if (event.origin !== origin) return;\n const studio = origin;\n\n // A section saved: the page is drawn again in place, and the section picked once the studio names it.\n if (data.type === 'refresh') {\n if (refreshFor(studio, data))\n setHost((prev) => (prev.origin ? prev : { ...prev, origin: studio }));\n } else if (data.type === 'enable') {\n const blocks = asBlocks(data.blocks);\n setHost((prev) => ({ origin: studio, enabled: true, blocks: blocks ?? prev.blocks }));\n } else if (data.type === 'disable') {\n queued = [];\n setHost((prev) => ({ ...prev, origin: studio, enabled: false }));\n } else {\n setHost((prev) => (prev.origin ? prev : { ...prev, origin: studio }));\n const command = readCommand(data);\n if (command) deliver(command);\n }\n };\n\n const hello = () => postToCanvas(origin, { type: 'hello', can: [...CANVAS_CAN] });\n window.addEventListener('message', onMessage);\n if (document.readyState === 'complete') hello();\n else window.addEventListener('load', hello, { once: true });\n return () => {\n window.removeEventListener('message', onMessage);\n window.removeEventListener('load', hello);\n };\n }, []);\n\n return host;\n}\n"]}
|
|
@@ -30,7 +30,7 @@ function rebaseApiUrl(url, from, to) {
|
|
|
30
30
|
}
|
|
31
31
|
|
|
32
32
|
// src/utils/engine-version.ts
|
|
33
|
-
var ENGINE_VERSION = "1.0.
|
|
33
|
+
var ENGINE_VERSION = "1.0.186" ;
|
|
34
34
|
var DEV_SETTINGS_TTL_MS = 60 * 6e4;
|
|
35
35
|
var HIT_HEADER = "x-twilight-dev-cache";
|
|
36
36
|
var FETCHED_AT_HEADER = "x-twilight-dev-fetched-at";
|
|
@@ -275,5 +275,5 @@ var filesCdn = ky.extend({
|
|
|
275
275
|
});
|
|
276
276
|
|
|
277
277
|
export { API_BASE_HEADER, ENGINE_VERSION, STORE_IDENTIFIER_HEADER, api, cdn, devSettingsFetchedAt, filesCdn, getActiveCurrency, getActiveScope, getActiveScopeId, getAuthToken, resolveRequestApiBase };
|
|
278
|
-
//# sourceMappingURL=chunk-
|
|
279
|
-
//# sourceMappingURL=chunk-
|
|
278
|
+
//# sourceMappingURL=chunk-YWPVPERZ.js.map
|
|
279
|
+
//# sourceMappingURL=chunk-YWPVPERZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/api-base.ts","../src/utils/engine-version.ts","../src/api/dev-settings-cache.ts","../src/api/client.ts"],"names":["entry","createIsomorphicFn","getCookie"],"mappings":";;;;;;;;;AAWO,IAAM,eAAA,GAAkB;AAG/B,IAAM,aAAA,GAAgB,SAAA;AAQf,SAAS,qBAAA,CACd,QACA,WAAA,EACe;AACf,EAAA,IAAI,CAAC,MAAA,IAAU,CAAC,WAAA,EAAa,OAAO,IAAA;AACpC,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,IAAI,GAAA,CAAI,MAAA,CAAO,IAAA,EAAM,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,GAAA,CAAI,QAAA,KAAa,QAAA,EAAU,OAAO,IAAA;AACtC,EAAA,IAAI,IAAI,IAAA,CAAK,WAAA,OAAkB,WAAA,CAAY,WAAA,IAAe,OAAO,IAAA;AACjE,EAAA,IAAI,GAAA,CAAI,YAAY,GAAA,CAAI,QAAA,IAAY,IAAI,MAAA,IAAU,GAAA,CAAI,MAAM,OAAO,IAAA;AACnE,EAAA,IAAI,IAAI,QAAA,CAAS,OAAA,CAAQ,QAAQ,EAAE,CAAA,KAAM,eAAe,OAAO,IAAA;AAC/D,EAAA,OAAO,CAAA,EAAG,GAAA,CAAI,MAAM,CAAA,EAAG,aAAa,CAAA,CAAA;AACtC;AAOO,SAAS,YAAA,CAAa,GAAA,EAAa,IAAA,EAAc,EAA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The header the storefront dispatcher names the Store API base in, on the\n * storefronts that must not call production: the beta storefront and its per-PR\n * previews (`web.beta.salla.group`, `web-<hash>.beta.salla.group`). There the\n * Store serves the storefront API under its own address, `https://<host>/api/v1`.\n *\n * Trusted for the same reason `x-salla-store-base` is: the dispatcher sets it\n * after dropping everything off its allowlist, so a visitor's copy never arrives.\n * It is still checked against the request's own host, so even a forged one could\n * only point the theme back at the storefront it is already serving.\n */\nexport const API_BASE_HEADER = 'x-salla-api-base';\n\n/** The one path the dispatcher names: the Store's storefront API under its own host. */\nconst API_BASE_PATH = '/api/v1';\n\n/**\n * The API base this request was told to use, or null for the build's default.\n *\n * Accepted only as `https://<the request's own host>/api/v1` (a trailing slash\n * allowed), with no credentials, query or fragment; returned without the slash.\n */\nexport function resolveRequestApiBase(\n header: string | null | undefined,\n requestHost: string | null\n): string | null {\n if (!header || !requestHost) return null;\n let url: URL;\n try {\n url = new URL(header.trim());\n } catch {\n return null;\n }\n if (url.protocol !== 'https:') return null;\n if (url.host.toLowerCase() !== requestHost.toLowerCase()) return null;\n if (url.username || url.password || url.search || url.hash) return null;\n if (url.pathname.replace(/\\/+$/, '') !== API_BASE_PATH) return null;\n return `${url.origin}${API_BASE_PATH}`;\n}\n\n/**\n * `url` moved from one API base to another: `https://api.salla.dev/store/v1/cart/1`\n * under `https://web.beta.salla.group/api/v1` is `https://web.beta.salla.group/api/v1/cart/1`.\n * Null when `url` is not under `from`, which leaves the request as it was.\n */\nexport function rebaseApiUrl(url: string, from: string, to: string): string | null {\n const base = from.replace(/\\/+$/, '');\n if (url !== base && !url.startsWith(`${base}/`) && !url.startsWith(`${base}?`)) return null;\n return to.replace(/\\/+$/, '') + url.slice(base.length);\n}\n","/**\n * The engine's own build version, injected by tsup `define` when dist is\n * built. Falls back to 'dev' when the source runs unbundled (vitest, direct\n * src imports in the monorepo).\n *\n * Exposed at runtime as `salla.versions.engine` by `useTwilightInit` so a\n * storefront can always be asked which engine build rendered it.\n */\nexport const ENGINE_VERSION: string =\n typeof __TWILIGHT_ENGINE_VERSION__ !== 'undefined' ? __TWILIGHT_ENGINE_VERSION__ : 'dev';\n","import type { AfterResponseHook, BeforeRequestHook } from 'ky';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport { DEV_SETTINGS_REFRESH_COOKIE } from '../utils/dev-settings-refresh';\n\n/**\n * A dev server reuses a store's settings for up to an hour.\n *\n * Every server render asks the API for `store/settings`, and a developer clicking\n * around a theme renders dozens of pages a minute. The API answers a burst of\n * settings requests for one store from one address with a challenge, which a\n * server-side fetch cannot pass, so the dev server rendered \"Store Unavailable\"\n * (6.05k challenged `(development; ssr)` calls in the 7 days to 2026-10-25). In\n * development, on the server, the same request within {@link DEV_SETTINGS_TTL_MS}\n * is answered from memory instead. An hour because the API counts settings\n * requests per hour, so one fetch an hour can never reach its limit; the theme\n * editor's \"Fetch fresh store data\" fetches sooner, and says how old the settings\n * are. A production build never runs it: `import.meta.env.DEV` is statically\n * false there.\n */\nexport const DEV_SETTINGS_TTL_MS = 60 * 60_000;\n\n/** Marks an answer from memory, so the store step does not file it again. */\nconst HIT_HEADER = 'x-twilight-dev-cache';\n\n/** When the answer was really fetched from the API (epoch ms), on fresh answers and reused ones alike. */\nconst FETCHED_AT_HEADER = 'x-twilight-dev-fetched-at';\n\n/**\n * When the dev server fetched these settings from the API, read off the answer the\n * cache handed back; `undefined` when the cache did not handle the call (a\n * production build, the browser, a test), so nothing new reaches the settings there.\n */\nexport function devSettingsFetchedAt(headers: Headers | undefined): number | undefined {\n const at = Number(headers?.get(FETCHED_AT_HEADER));\n return Number.isFinite(at) && at > 0 ? at : undefined;\n}\n\n/**\n * Not carried over to an answer from memory: the body is stored decoded, so its\n * original encoding and length no longer describe it.\n */\nconst DROPPED_HEADERS = new Set(['content-encoding', 'content-length']);\n\ninterface Entry {\n body: string;\n status: number;\n statusText: string;\n headers: [string, string][];\n fetchedAt: number;\n /** The refresh cookie's value when this answer was fetched. */\n refresh: string | null;\n}\n\nexport interface DevSettingsCacheOptions {\n /** Whether this call may use the cache at all. */\n enabled: () => boolean;\n /** The current value of {@link DEV_SETTINGS_REFRESH_COOKIE}, or null. */\n refreshToken: () => string | null;\n now?: () => number;\n ttlMs?: number;\n /** Called the first time an answer comes from memory. */\n onFirstHit?: () => void;\n}\n\nfunction isSettingsRequest(request: Request): boolean {\n if (request.method !== 'GET') return false;\n try {\n return new URL(request.url).pathname.endsWith('/store/settings');\n } catch {\n return false;\n }\n}\n\n/**\n * An answer `requestSettings` accepts: JSON carrying `data`. A 200 without it is\n * refused there as \"Store Unavailable\"; kept here, it would be refused for the next\n * hour too, after the API had recovered.\n */\nfunction hasSettings(body: string): boolean {\n try {\n return Boolean((JSON.parse(body) as { data?: unknown } | null)?.data);\n } catch {\n return false;\n }\n}\n\n/**\n * The request as the API receives it: method, URL and every header the client's\n * hooks set. Keyed on the request itself rather than on the inputs that build it,\n * so a header added to the client later cannot be missing from the key.\n */\nfunction keyOf(request: Request): string {\n const headers = [...request.headers].map(([name, value]) => `${name}: ${value}`).join('\\n');\n return `${request.method} ${request.url}\\n${headers}`;\n}\n\n/**\n * The two ky hooks behind the cache: `lookup` runs last among `beforeRequest`, once\n * every header is set, and `store` among `afterResponse`. Only an answer with\n * settings in it is kept, so a timeout, a 429, a challenge or an empty 200 is asked\n * again on the next render.\n */\nexport function createDevSettingsCache(options: DevSettingsCacheOptions) {\n const {\n enabled,\n refreshToken,\n now = Date.now,\n ttlMs = DEV_SETTINGS_TTL_MS,\n onFirstHit,\n } = options;\n const entries = new Map<string, Entry>();\n let announced = false;\n\n const isFresh = (entry: Entry): boolean =>\n now() - entry.fetchedAt < ttlMs && entry.refresh === refreshToken();\n\n const answerOf = (entry: Entry, hit: boolean): Response => {\n const headers = new Headers(entry.headers);\n headers.set(FETCHED_AT_HEADER, String(entry.fetchedAt));\n if (hit) headers.set(HIT_HEADER, 'hit');\n return new Response(entry.body, {\n status: entry.status,\n statusText: entry.statusText,\n headers,\n });\n };\n\n const lookup: BeforeRequestHook = ({ request }) => {\n if (!enabled() || !isSettingsRequest(request)) return;\n const key = keyOf(request);\n const entry = entries.get(key);\n if (!entry) return;\n if (!isFresh(entry)) {\n entries.delete(key);\n return;\n }\n if (!announced) {\n announced = true;\n onFirstHit?.();\n }\n return answerOf(entry, true);\n };\n\n const store: AfterResponseHook = async ({ request, response }) => {\n if (!enabled() || !isSettingsRequest(request) || !response.ok) return;\n if (response.headers.has(HIT_HEADER)) return;\n // ky hands each hook a clone, so reading it leaves the answer it returns intact.\n const body = await response.text();\n if (!hasSettings(body)) return;\n for (const [key, entry] of entries) {\n if (now() - entry.fetchedAt >= ttlMs) entries.delete(key);\n }\n const entry: Entry = {\n body,\n status: response.status,\n statusText: response.statusText,\n headers: [...response.headers].filter(([name]) => !DROPPED_HEADERS.has(name)),\n fetchedAt: now(),\n refresh: refreshToken(),\n };\n entries.set(keyOf(request), entry);\n // Handed on in place of the API's own answer, so it carries its fetch time too.\n return answerOf(entry, false);\n };\n\n return { lookup, store, clear: () => entries.clear() };\n}\n\nconst readRefreshCookie = createIsomorphicFn()\n .server((): string | null => {\n try {\n return getCookie(DEV_SETTINGS_REFRESH_COOKIE) ?? null;\n } catch {\n return null;\n }\n })\n .client((): string | null => null);\n\nexport const devSettingsCache = createDevSettingsCache({\n // A dev server's render only. A production build has `DEV` statically false,\n // the browser keeps the settings it was handed in its query cache, and vitest\n // runs in `test` mode, where every test wants the request it mocked.\n enabled: () =>\n import.meta.env.DEV && import.meta.env.MODE !== 'test' && typeof document === 'undefined',\n refreshToken: readRefreshCookie,\n onFirstHit: () =>\n console.warn(\n `[twilight] Store settings are reused for up to ${DEV_SETTINGS_TTL_MS / 60_000} minutes while you develop, to stay under the Salla API's rate limit. To see a change you made in the dashboard, press \"Fetch fresh store data\" in the theme editor's side panel: it also says when they were last fetched.`\n ),\n});\n","import ky from 'ky';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport { getStoreIdentifier } from '../utils/sdk-helpers';\nimport { requestedDraftThemeName, resolveThemeVersionId } from '../utils/theme-version';\nimport { getInjectedRuntimeEnv, readEnv } from '../utils/runtime-env';\nimport { getRequestStore, getTwilightContext, isAuthTokenRevoked } from '../twilight/context';\nimport { rebaseApiUrl } from '../utils/api-base';\nimport { ENGINE_VERSION } from '../utils/engine-version';\nimport { devSettingsCache } from './dev-settings-cache';\nimport {\n AUTH_TOKEN_COOKIE_NAME,\n CURRENCY_COOKIE_NAME,\n extractCurrencyFromCookies,\n extractScopeFromCookies,\n toCurrencyCode,\n extractTokenFromCookies,\n readSdkScope,\n type ActiveScope,\n} from '../utils/cookies';\n\n// The twilight module store doesn't reliably carry authToken into every scope: on the\n// SERVER workerd has no AsyncLocalStorage, and on BOTH sides this api client can live in a\n// different module instance than the one rootBeforeLoad populates (engine subpath import vs\n// engine-internal relative import). So `getTwilightContext().authToken` is often null even\n// for logged-in users → API calls (orders/customer/…) return `token_not_provided` (400).\n// Read the token directly from the request cookie (server) or document.cookie / salla.storage\n// (client) as a fallback. The server-only import is stripped from the client bundle by\n// createIsomorphicFn.\nconst readFallbackToken = createIsomorphicFn()\n .server((): string | null => {\n try {\n return getCookie(AUTH_TOKEN_COOKIE_NAME) ?? null;\n } catch {\n return null;\n }\n })\n .client((): string | null => {\n const fromCookie =\n typeof document !== 'undefined'\n ? extractTokenFromCookies(document.cookie, AUTH_TOKEN_COOKIE_NAME)\n : null;\n if (fromCookie) return fromCookie;\n const storage = typeof window !== 'undefined' ? window.salla?.storage : undefined;\n const fromStorage =\n typeof storage?.get === 'function' ? storage.get(AUTH_TOKEN_COOKIE_NAME) : null;\n if (typeof fromStorage === 'string' && fromStorage) return fromStorage;\n // `?token=` webview injection lands only on the SDK's axios instance\n const fromSdkApi = typeof window !== 'undefined' ? window.salla?.api?.token : undefined;\n return typeof fromSdkApi === 'string' && fromSdkApi ? fromSdkApi : null;\n });\n\n/**\n * The auth token as the api client sees it: twilight context first, cookie/storage fallback.\n * Use this (not `getTwilightContext().authToken`, which is often null for logged-in users —\n * see the note above) to decide whether an authenticated-only query should run.\n */\nexport const getAuthToken = (): string | null =>\n isAuthTokenRevoked() ? null : (getTwilightContext().authToken ?? readFallbackToken());\n\nconst readRequestCurrency = createIsomorphicFn()\n .server((): string | null => {\n try {\n return toCurrencyCode(getCookie(CURRENCY_COOKIE_NAME));\n } catch {\n return null;\n }\n })\n .client((): string | null => null);\n\n/**\n * The currency the visitor chose, from the `s-curr` cookie the SDK writes: the API\n * answers in the store's own currency unless the request names one.\n */\nexport function getActiveCurrency(): string | null;\nexport function getActiveCurrency(fallback: string): string;\nexport function getActiveCurrency(fallback: string | null = null): string | null {\n const chosen =\n typeof document !== 'undefined'\n ? extractCurrencyFromCookies(document.cookie)\n : readRequestCurrency();\n return chosen ?? fallback;\n}\n\nconst API_HEADERS = {\n ACCEPT: 'accept',\n ACCEPT_LANGUAGE: 'accept-language',\n APP_OS: 's-app-os',\n APP_VERSION: 's-app-version',\n RAY: 's-ray',\n SOURCE: 's-source',\n THEME_TYPE: 's-theme-type',\n REQUESTED_WITH: 'x-requested-with',\n CF_PROXY_WHITELIST: 's-cf-proxy-whitelist-id',\n STORE_IDENTIFIER: 'store-identifier',\n CURRENCY: 'currency',\n AUTHORIZATION: 'Authorization',\n VERSION_ID: 's-version-id',\n THEME_NAME: 's-theme-name',\n SCOPE_ID: 's-scope-id',\n SCOPE_TYPE: 's-scope-type',\n SCOPE_ALLOCATION_TYPE: 's-scope-allocation-type',\n SCOPE_ALLOCATION_ID: 's-scope-allocation-id',\n USER_AGENT: 'user-agent',\n} as const;\n\n/**\n * The header every Salla API call is answered by store.\n *\n * Exported because a caller that already knows which store it is asking about\n * must be able to say so on the request itself — see `store.settings`. Without\n * it the only way to name a store is the ambient resolver, and \"the identifier\n * I checked\" and \"the identifier that was sent\" become two different things.\n */\nexport const STORE_IDENTIFIER_HEADER = API_HEADERS.STORE_IDENTIFIER;\n\n/**\n * Active scope: the market plus its branch allocation, as the SDK stores it. On the\n * client it comes from `salla.storage.get('scope')`; before the SDK hydrates storage\n * it falls back to the `scope` cookie the theme mirrors that selection into (see\n * writeScopeCookie), then to the scope twilightMiddleware seeded from the same\n * cookie on the server. Requests vary by the `s-scope-*` headers, so React Query\n * keys must include this to avoid serving another branch's cached categories/products.\n *\n * The cookie step matters for hydration: the SDK is not guaranteed to have\n * populated `salla.storage` by the time the client rebuilds a dehydrated query\n * key, and without it the client would compute null against a scoped SSR key.\n */\nexport const getActiveScope = (): ActiveScope | null => {\n // `!== undefined`, not `!= null`: a null here is the SDK authoritatively saying \"no branch\n // selected\", which must beat a cookie left over from the previous selection. Only a\n // not-yet-ready storage API (undefined) falls through to the cookie.\n const fromStorage = readSdkScope();\n if (fromStorage !== undefined) return fromStorage;\n\n if (typeof document !== 'undefined') {\n const fromCookie = extractScopeFromCookies(document.cookie);\n if (fromCookie != null) return fromCookie;\n }\n\n try {\n return getTwilightContext().scope;\n } catch {\n return null;\n }\n};\n\n/** {@link getActiveScope} reduced to the market id. */\nexport const getActiveScopeId = (): string | null => getActiveScope()?.id ?? null;\n\n// No `s-store-api-version`: a Cloudflare rule on api.salla.dev adds it to the paths the\n// Swoole pool serves. Sent from here, it put every call there, `cart/{id}` among them.\nconst sharedHeaders = (locale: string) => ({\n [API_HEADERS.ACCEPT]: 'application/json' as const,\n [API_HEADERS.ACCEPT_LANGUAGE]: locale,\n [API_HEADERS.APP_OS]: 'browser',\n [API_HEADERS.APP_VERSION]: '2.14.363',\n [API_HEADERS.RAY]: '50',\n [API_HEADERS.SOURCE]: 'twilight',\n [API_HEADERS.THEME_TYPE]: 'react',\n [API_HEADERS.REQUESTED_WITH]: 'XMLHttpRequest',\n [API_HEADERS.CF_PROXY_WHITELIST]: '019a2f78-a64c-7edb-proxy-whitelist-id-9a3a-17afda90f03a',\n});\n\n/**\n * Who a server-rendered call says it is.\n *\n * Every theme worker reaches api.salla.dev from Cloudflare's one Workers address, so\n * salla.dev's per-IP rate limits counted every React store as a single client and\n * refused the calls each page makes (`store/settings` among them: \"Store Unavailable\").\n * The zone skips rate limiting for a User-Agent shaped `Salla-<Name>/<N.N.N> (<env>; <meta>)`\n * from Cloudflare's or AWS's networks, the convention Salla's other services already send.\n *\n * Built from fixed parts: the zone's pattern takes only digits and dots for the version,\n * so a prerelease suffix is dropped, and an unbundled engine (`dev`) reads as `0.0.0`.\n */\nconst SERVER_USER_AGENT = `Salla-TwilightReact/${\n /^\\d+(?:\\.\\d+)*/.exec(ENGINE_VERSION)?.[0] ?? '0.0.0'\n} (${import.meta.env.DEV ? 'development' : 'production'}; ssr)`;\n\n/**\n * Store API base. `VITE_API_URL` override points a preview at a branch backend; unset → prod\n * `api.salla.dev`. Resolution order matters: the value the SSR worker resolved (published into\n * the head, since worker `vars` are server-only `process.env` and never reach the browser\n * bundle) wins, so the hydrated client keeps talking to the backend that rendered the page.\n */\n\nconst STORE_API_BASE =\n getInjectedRuntimeEnv().apiBase || readEnv('VITE_API_URL') || 'https://api.salla.dev/store/v1';\n\n/**\n * Moves a call onto the API base this request was told to use, when it has one.\n *\n * `STORE_API_BASE` is read once per isolate, and one theme worker serves every\n * storefront the dispatcher sends it: production, and the beta and PR preview\n * storefronts (`web[-<hash>].beta.salla.group`), whose Store API is on their own\n * host (`x-salla-api-base`, see `utils/api-base.ts`). So SSR rebases each call per\n * request. In the browser the request store is empty and `STORE_API_BASE` is\n * already the published per-page value, so this does nothing there.\n *\n * After every hook that sets a header, so the request it copies carries them all.\n * It runs only where the dispatcher named a base (beta), and the dev settings cache\n * after it only in a dev build, which never gets that header.\n */\nfunction toRequestApiBase({ request }: { request: Request }): Request | undefined {\n const { apiBase } = getRequestStore();\n if (!apiBase || apiBase === STORE_API_BASE) return undefined;\n const url = rebaseApiUrl(request.url, STORE_API_BASE, apiBase);\n return url ? new Request(url, request) : undefined;\n}\n\nexport const api = ky.extend({\n prefix: STORE_API_BASE,\n timeout: 8000,\n hooks: {\n beforeRequest: [\n ({ request }) => {\n const { locale } = getTwilightContext();\n const headers = sharedHeaders(locale);\n for (const [key, value] of Object.entries(headers)) {\n request.headers.set(key, value);\n }\n // Only when the caller did not say. `headers.set` here would otherwise\n // overwrite a per-request identifier with the ambient one, which is a\n // silent way to answer a question about one store with another's data.\n if (!request.headers.get(API_HEADERS.STORE_IDENTIFIER)) {\n request.headers.set(API_HEADERS.STORE_IDENTIFIER, getStoreIdentifier());\n }\n\n // Server only. A browser call comes from the shopper's own address and is\n // counted against it, which is what the zone's limits are for.\n if (typeof document === 'undefined') {\n request.headers.set(API_HEADERS.USER_AGENT, SERVER_USER_AGENT);\n }\n\n const scope = getActiveScope();\n\n // The version the request asked for, else the one the settings named for\n // this scope. Absent means \"whatever is live\", which is what an ordinary\n // storefront visit wants — so a null is left off rather than sent empty.\n const versionId = resolveThemeVersionId(scope?.id ?? null);\n if (versionId) {\n request.headers.set(API_HEADERS.VERSION_ID, versionId);\n }\n\n // The draft theme a preview renders, by the name the Store knows drafts\n // by. Without it the Store answers the draft's version as the store's own\n // theme, and checks the draft's components against that one. Absent on\n // every other call, so an ordinary storefront request is unchanged.\n const draftThemeName = requestedDraftThemeName();\n if (draftThemeName) {\n request.headers.set(API_HEADERS.THEME_NAME, draftThemeName);\n }\n\n const currency = getActiveCurrency();\n if (currency) request.headers.set(API_HEADERS.CURRENCY, currency);\n\n const token = getAuthToken();\n if (token) {\n request.headers.set(API_HEADERS.AUTHORIZATION, `Bearer ${token}`);\n }\n\n // The same four the SDK's own client sends. The API resolves stock per\n // allocation: id alone asks about the market, not the branch the shopper chose.\n if (scope) {\n request.headers.set(API_HEADERS.SCOPE_ID, scope.id);\n if (scope.type) request.headers.set(API_HEADERS.SCOPE_TYPE, scope.type);\n if (scope.allocation_type)\n request.headers.set(API_HEADERS.SCOPE_ALLOCATION_TYPE, scope.allocation_type);\n if (scope.allocation_id)\n request.headers.set(API_HEADERS.SCOPE_ALLOCATION_ID, scope.allocation_id);\n }\n },\n toRequestApiBase,\n // Last, so it keys on the request with every header above set.\n devSettingsCache.lookup,\n ],\n afterResponse: [devSettingsCache.store],\n },\n});\n\nexport const cdn = ky.extend({\n prefix: 'https://cdn.salla.network',\n timeout: 5000,\n});\n\n/**\n * The merchant uploader's public bucket, `admin-uploader-prod`.\n *\n * A different host from {@link cdn} and a different thing behind it: this one\n * is an R2 custom domain, so a read never passes through a worker. Storefront\n * translations live here, per language, under `translations/` — see\n * `api/translations.ts`.\n */\nexport const filesCdn = ky.extend({\n prefix: 'https://cdn.files.salla.network',\n timeout: 5000,\n});\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/api-base.ts","../src/utils/engine-version.ts","../src/api/dev-settings-cache.ts","../src/api/client.ts"],"names":["entry","createIsomorphicFn","getCookie"],"mappings":";;;;;;;;;AAWO,IAAM,eAAA,GAAkB;AAG/B,IAAM,aAAA,GAAgB,SAAA;AAQf,SAAS,qBAAA,CACd,QACA,WAAA,EACe;AACf,EAAA,IAAI,CAAC,MAAA,IAAU,CAAC,WAAA,EAAa,OAAO,IAAA;AACpC,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,IAAI,GAAA,CAAI,MAAA,CAAO,IAAA,EAAM,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACA,EAAA,IAAI,GAAA,CAAI,QAAA,KAAa,QAAA,EAAU,OAAO,IAAA;AACtC,EAAA,IAAI,IAAI,IAAA,CAAK,WAAA,OAAkB,WAAA,CAAY,WAAA,IAAe,OAAO,IAAA;AACjE,EAAA,IAAI,GAAA,CAAI,YAAY,GAAA,CAAI,QAAA,IAAY,IAAI,MAAA,IAAU,GAAA,CAAI,MAAM,OAAO,IAAA;AACnE,EAAA,IAAI,IAAI,QAAA,CAAS,OAAA,CAAQ,QAAQ,EAAE,CAAA,KAAM,eAAe,OAAO,IAAA;AAC/D,EAAA,OAAO,CAAA,EAAG,GAAA,CAAI,MAAM,CAA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EAAQ,iCAAA;AAAA,EACR,OAAA,EAAS;AACX,CAAC","file":"chunk-YWPVPERZ.js","sourcesContent":["/**\n * The header the storefront dispatcher names the Store API base in, on the\n * storefronts that must not call production: the beta storefront and its per-PR\n * previews (`web.beta.salla.group`, `web-<hash>.beta.salla.group`). There the\n * Store serves the storefront API under its own address, `https://<host>/api/v1`.\n *\n * Trusted for the same reason `x-salla-store-base` is: the dispatcher sets it\n * after dropping everything off its allowlist, so a visitor's copy never arrives.\n * It is still checked against the request's own host, so even a forged one could\n * only point the theme back at the storefront it is already serving.\n */\nexport const API_BASE_HEADER = 'x-salla-api-base';\n\n/** The one path the dispatcher names: the Store's storefront API under its own host. */\nconst API_BASE_PATH = '/api/v1';\n\n/**\n * The API base this request was told to use, or null for the build's default.\n *\n * Accepted only as `https://<the request's own host>/api/v1` (a trailing slash\n * allowed), with no credentials, query or fragment; returned without the slash.\n */\nexport function resolveRequestApiBase(\n header: string | null | undefined,\n requestHost: string | null\n): string | null {\n if (!header || !requestHost) return null;\n let url: URL;\n try {\n url = new URL(header.trim());\n } catch {\n return null;\n }\n if (url.protocol !== 'https:') return null;\n if (url.host.toLowerCase() !== requestHost.toLowerCase()) return null;\n if (url.username || url.password || url.search || url.hash) return null;\n if (url.pathname.replace(/\\/+$/, '') !== API_BASE_PATH) return null;\n return `${url.origin}${API_BASE_PATH}`;\n}\n\n/**\n * `url` moved from one API base to another: `https://api.salla.dev/store/v1/cart/1`\n * under `https://web.beta.salla.group/api/v1` is `https://web.beta.salla.group/api/v1/cart/1`.\n * Null when `url` is not under `from`, which leaves the request as it was.\n */\nexport function rebaseApiUrl(url: string, from: string, to: string): string | null {\n const base = from.replace(/\\/+$/, '');\n if (url !== base && !url.startsWith(`${base}/`) && !url.startsWith(`${base}?`)) return null;\n return to.replace(/\\/+$/, '') + url.slice(base.length);\n}\n","/**\n * The engine's own build version, injected by tsup `define` when dist is\n * built. Falls back to 'dev' when the source runs unbundled (vitest, direct\n * src imports in the monorepo).\n *\n * Exposed at runtime as `salla.versions.engine` by `useTwilightInit` so a\n * storefront can always be asked which engine build rendered it.\n */\nexport const ENGINE_VERSION: string =\n typeof __TWILIGHT_ENGINE_VERSION__ !== 'undefined' ? __TWILIGHT_ENGINE_VERSION__ : 'dev';\n","import type { AfterResponseHook, BeforeRequestHook } from 'ky';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport { DEV_SETTINGS_REFRESH_COOKIE } from '../utils/dev-settings-refresh';\n\n/**\n * A dev server reuses a store's settings for up to an hour.\n *\n * Every server render asks the API for `store/settings`, and a developer clicking\n * around a theme renders dozens of pages a minute. The API answers a burst of\n * settings requests for one store from one address with a challenge, which a\n * server-side fetch cannot pass, so the dev server rendered \"Store Unavailable\"\n * (6.05k challenged `(development; ssr)` calls in the 7 days to 2026-10-25). In\n * development, on the server, the same request within {@link DEV_SETTINGS_TTL_MS}\n * is answered from memory instead. An hour because the API counts settings\n * requests per hour, so one fetch an hour can never reach its limit; the theme\n * editor's \"Fetch fresh store data\" fetches sooner, and says how old the settings\n * are. A production build never runs it: `import.meta.env.DEV` is statically\n * false there.\n */\nexport const DEV_SETTINGS_TTL_MS = 60 * 60_000;\n\n/** Marks an answer from memory, so the store step does not file it again. */\nconst HIT_HEADER = 'x-twilight-dev-cache';\n\n/** When the answer was really fetched from the API (epoch ms), on fresh answers and reused ones alike. */\nconst FETCHED_AT_HEADER = 'x-twilight-dev-fetched-at';\n\n/**\n * When the dev server fetched these settings from the API, read off the answer the\n * cache handed back; `undefined` when the cache did not handle the call (a\n * production build, the browser, a test), so nothing new reaches the settings there.\n */\nexport function devSettingsFetchedAt(headers: Headers | undefined): number | undefined {\n const at = Number(headers?.get(FETCHED_AT_HEADER));\n return Number.isFinite(at) && at > 0 ? at : undefined;\n}\n\n/**\n * Not carried over to an answer from memory: the body is stored decoded, so its\n * original encoding and length no longer describe it.\n */\nconst DROPPED_HEADERS = new Set(['content-encoding', 'content-length']);\n\ninterface Entry {\n body: string;\n status: number;\n statusText: string;\n headers: [string, string][];\n fetchedAt: number;\n /** The refresh cookie's value when this answer was fetched. */\n refresh: string | null;\n}\n\nexport interface DevSettingsCacheOptions {\n /** Whether this call may use the cache at all. */\n enabled: () => boolean;\n /** The current value of {@link DEV_SETTINGS_REFRESH_COOKIE}, or null. */\n refreshToken: () => string | null;\n now?: () => number;\n ttlMs?: number;\n /** Called the first time an answer comes from memory. */\n onFirstHit?: () => void;\n}\n\nfunction isSettingsRequest(request: Request): boolean {\n if (request.method !== 'GET') return false;\n try {\n return new URL(request.url).pathname.endsWith('/store/settings');\n } catch {\n return false;\n }\n}\n\n/**\n * An answer `requestSettings` accepts: JSON carrying `data`. A 200 without it is\n * refused there as \"Store Unavailable\"; kept here, it would be refused for the next\n * hour too, after the API had recovered.\n */\nfunction hasSettings(body: string): boolean {\n try {\n return Boolean((JSON.parse(body) as { data?: unknown } | null)?.data);\n } catch {\n return false;\n }\n}\n\n/**\n * The request as the API receives it: method, URL and every header the client's\n * hooks set. Keyed on the request itself rather than on the inputs that build it,\n * so a header added to the client later cannot be missing from the key.\n */\nfunction keyOf(request: Request): string {\n const headers = [...request.headers].map(([name, value]) => `${name}: ${value}`).join('\\n');\n return `${request.method} ${request.url}\\n${headers}`;\n}\n\n/**\n * The two ky hooks behind the cache: `lookup` runs last among `beforeRequest`, once\n * every header is set, and `store` among `afterResponse`. Only an answer with\n * settings in it is kept, so a timeout, a 429, a challenge or an empty 200 is asked\n * again on the next render.\n */\nexport function createDevSettingsCache(options: DevSettingsCacheOptions) {\n const {\n enabled,\n refreshToken,\n now = Date.now,\n ttlMs = DEV_SETTINGS_TTL_MS,\n onFirstHit,\n } = options;\n const entries = new Map<string, Entry>();\n let announced = false;\n\n const isFresh = (entry: Entry): boolean =>\n now() - entry.fetchedAt < ttlMs && entry.refresh === refreshToken();\n\n const answerOf = (entry: Entry, hit: boolean): Response => {\n const headers = new Headers(entry.headers);\n headers.set(FETCHED_AT_HEADER, String(entry.fetchedAt));\n if (hit) headers.set(HIT_HEADER, 'hit');\n return new Response(entry.body, {\n status: entry.status,\n statusText: entry.statusText,\n headers,\n });\n };\n\n const lookup: BeforeRequestHook = ({ request }) => {\n if (!enabled() || !isSettingsRequest(request)) return;\n const key = keyOf(request);\n const entry = entries.get(key);\n if (!entry) return;\n if (!isFresh(entry)) {\n entries.delete(key);\n return;\n }\n if (!announced) {\n announced = true;\n onFirstHit?.();\n }\n return answerOf(entry, true);\n };\n\n const store: AfterResponseHook = async ({ request, response }) => {\n if (!enabled() || !isSettingsRequest(request) || !response.ok) return;\n if (response.headers.has(HIT_HEADER)) return;\n // ky hands each hook a clone, so reading it leaves the answer it returns intact.\n const body = await response.text();\n if (!hasSettings(body)) return;\n for (const [key, entry] of entries) {\n if (now() - entry.fetchedAt >= ttlMs) entries.delete(key);\n }\n const entry: Entry = {\n body,\n status: response.status,\n statusText: response.statusText,\n headers: [...response.headers].filter(([name]) => !DROPPED_HEADERS.has(name)),\n fetchedAt: now(),\n refresh: refreshToken(),\n };\n entries.set(keyOf(request), entry);\n // Handed on in place of the API's own answer, so it carries its fetch time too.\n return answerOf(entry, false);\n };\n\n return { lookup, store, clear: () => entries.clear() };\n}\n\nconst readRefreshCookie = createIsomorphicFn()\n .server((): string | null => {\n try {\n return getCookie(DEV_SETTINGS_REFRESH_COOKIE) ?? null;\n } catch {\n return null;\n }\n })\n .client((): string | null => null);\n\nexport const devSettingsCache = createDevSettingsCache({\n // A dev server's render only. A production build has `DEV` statically false,\n // the browser keeps the settings it was handed in its query cache, and vitest\n // runs in `test` mode, where every test wants the request it mocked.\n enabled: () =>\n import.meta.env.DEV && import.meta.env.MODE !== 'test' && typeof document === 'undefined',\n refreshToken: readRefreshCookie,\n onFirstHit: () =>\n console.warn(\n `[twilight] Store settings are reused for up to ${DEV_SETTINGS_TTL_MS / 60_000} minutes while you develop, to stay under the Salla API's rate limit. To see a change you made in the dashboard, press \"Fetch fresh store data\" in the theme editor's side panel: it also says when they were last fetched.`\n ),\n});\n","import ky from 'ky';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport { getStoreIdentifier } from '../utils/sdk-helpers';\nimport { requestedDraftThemeName, resolveThemeVersionId } from '../utils/theme-version';\nimport { getInjectedRuntimeEnv, readEnv } from '../utils/runtime-env';\nimport { getRequestStore, getTwilightContext, isAuthTokenRevoked } from '../twilight/context';\nimport { rebaseApiUrl } from '../utils/api-base';\nimport { ENGINE_VERSION } from '../utils/engine-version';\nimport { devSettingsCache } from './dev-settings-cache';\nimport {\n AUTH_TOKEN_COOKIE_NAME,\n CURRENCY_COOKIE_NAME,\n extractCurrencyFromCookies,\n extractScopeFromCookies,\n toCurrencyCode,\n extractTokenFromCookies,\n readSdkScope,\n type ActiveScope,\n} from '../utils/cookies';\n\n// The twilight module store doesn't reliably carry authToken into every scope: on the\n// SERVER workerd has no AsyncLocalStorage, and on BOTH sides this api client can live in a\n// different module instance than the one rootBeforeLoad populates (engine subpath import vs\n// engine-internal relative import). So `getTwilightContext().authToken` is often null even\n// for logged-in users → API calls (orders/customer/…) return `token_not_provided` (400).\n// Read the token directly from the request cookie (server) or document.cookie / salla.storage\n// (client) as a fallback. The server-only import is stripped from the client bundle by\n// createIsomorphicFn.\nconst readFallbackToken = createIsomorphicFn()\n .server((): string | null => {\n try {\n return getCookie(AUTH_TOKEN_COOKIE_NAME) ?? null;\n } catch {\n return null;\n }\n })\n .client((): string | null => {\n const fromCookie =\n typeof document !== 'undefined'\n ? extractTokenFromCookies(document.cookie, AUTH_TOKEN_COOKIE_NAME)\n : null;\n if (fromCookie) return fromCookie;\n const storage = typeof window !== 'undefined' ? window.salla?.storage : undefined;\n const fromStorage =\n typeof storage?.get === 'function' ? storage.get(AUTH_TOKEN_COOKIE_NAME) : null;\n if (typeof fromStorage === 'string' && fromStorage) return fromStorage;\n // `?token=` webview injection lands only on the SDK's axios instance\n const fromSdkApi = typeof window !== 'undefined' ? window.salla?.api?.token : undefined;\n return typeof fromSdkApi === 'string' && fromSdkApi ? fromSdkApi : null;\n });\n\n/**\n * The auth token as the api client sees it: twilight context first, cookie/storage fallback.\n * Use this (not `getTwilightContext().authToken`, which is often null for logged-in users —\n * see the note above) to decide whether an authenticated-only query should run.\n */\nexport const getAuthToken = (): string | null =>\n isAuthTokenRevoked() ? null : (getTwilightContext().authToken ?? readFallbackToken());\n\nconst readRequestCurrency = createIsomorphicFn()\n .server((): string | null => {\n try {\n return toCurrencyCode(getCookie(CURRENCY_COOKIE_NAME));\n } catch {\n return null;\n }\n })\n .client((): string | null => null);\n\n/**\n * The currency the visitor chose, from the `s-curr` cookie the SDK writes: the API\n * answers in the store's own currency unless the request names one.\n */\nexport function getActiveCurrency(): string | null;\nexport function getActiveCurrency(fallback: string): string;\nexport function getActiveCurrency(fallback: string | null = null): string | null {\n const chosen =\n typeof document !== 'undefined'\n ? extractCurrencyFromCookies(document.cookie)\n : readRequestCurrency();\n return chosen ?? fallback;\n}\n\nconst API_HEADERS = {\n ACCEPT: 'accept',\n ACCEPT_LANGUAGE: 'accept-language',\n APP_OS: 's-app-os',\n APP_VERSION: 's-app-version',\n RAY: 's-ray',\n SOURCE: 's-source',\n THEME_TYPE: 's-theme-type',\n REQUESTED_WITH: 'x-requested-with',\n CF_PROXY_WHITELIST: 's-cf-proxy-whitelist-id',\n STORE_IDENTIFIER: 'store-identifier',\n CURRENCY: 'currency',\n AUTHORIZATION: 'Authorization',\n VERSION_ID: 's-version-id',\n THEME_NAME: 's-theme-name',\n SCOPE_ID: 's-scope-id',\n SCOPE_TYPE: 's-scope-type',\n SCOPE_ALLOCATION_TYPE: 's-scope-allocation-type',\n SCOPE_ALLOCATION_ID: 's-scope-allocation-id',\n USER_AGENT: 'user-agent',\n} as const;\n\n/**\n * The header every Salla API call is answered by store.\n *\n * Exported because a caller that already knows which store it is asking about\n * must be able to say so on the request itself — see `store.settings`. Without\n * it the only way to name a store is the ambient resolver, and \"the identifier\n * I checked\" and \"the identifier that was sent\" become two different things.\n */\nexport const STORE_IDENTIFIER_HEADER = API_HEADERS.STORE_IDENTIFIER;\n\n/**\n * Active scope: the market plus its branch allocation, as the SDK stores it. On the\n * client it comes from `salla.storage.get('scope')`; before the SDK hydrates storage\n * it falls back to the `scope` cookie the theme mirrors that selection into (see\n * writeScopeCookie), then to the scope twilightMiddleware seeded from the same\n * cookie on the server. Requests vary by the `s-scope-*` headers, so React Query\n * keys must include this to avoid serving another branch's cached categories/products.\n *\n * The cookie step matters for hydration: the SDK is not guaranteed to have\n * populated `salla.storage` by the time the client rebuilds a dehydrated query\n * key, and without it the client would compute null against a scoped SSR key.\n */\nexport const getActiveScope = (): ActiveScope | null => {\n // `!== undefined`, not `!= null`: a null here is the SDK authoritatively saying \"no branch\n // selected\", which must beat a cookie left over from the previous selection. Only a\n // not-yet-ready storage API (undefined) falls through to the cookie.\n const fromStorage = readSdkScope();\n if (fromStorage !== undefined) return fromStorage;\n\n if (typeof document !== 'undefined') {\n const fromCookie = extractScopeFromCookies(document.cookie);\n if (fromCookie != null) return fromCookie;\n }\n\n try {\n return getTwilightContext().scope;\n } catch {\n return null;\n }\n};\n\n/** {@link getActiveScope} reduced to the market id. */\nexport const getActiveScopeId = (): string | null => getActiveScope()?.id ?? null;\n\n// No `s-store-api-version`: a Cloudflare rule on api.salla.dev adds it to the paths the\n// Swoole pool serves. Sent from here, it put every call there, `cart/{id}` among them.\nconst sharedHeaders = (locale: string) => ({\n [API_HEADERS.ACCEPT]: 'application/json' as const,\n [API_HEADERS.ACCEPT_LANGUAGE]: locale,\n [API_HEADERS.APP_OS]: 'browser',\n [API_HEADERS.APP_VERSION]: '2.14.363',\n [API_HEADERS.RAY]: '50',\n [API_HEADERS.SOURCE]: 'twilight',\n [API_HEADERS.THEME_TYPE]: 'react',\n [API_HEADERS.REQUESTED_WITH]: 'XMLHttpRequest',\n [API_HEADERS.CF_PROXY_WHITELIST]: '019a2f78-a64c-7edb-proxy-whitelist-id-9a3a-17afda90f03a',\n});\n\n/**\n * Who a server-rendered call says it is.\n *\n * Every theme worker reaches api.salla.dev from Cloudflare's one Workers address, so\n * salla.dev's per-IP rate limits counted every React store as a single client and\n * refused the calls each page makes (`store/settings` among them: \"Store Unavailable\").\n * The zone skips rate limiting for a User-Agent shaped `Salla-<Name>/<N.N.N> (<env>; <meta>)`\n * from Cloudflare's or AWS's networks, the convention Salla's other services already send.\n *\n * Built from fixed parts: the zone's pattern takes only digits and dots for the version,\n * so a prerelease suffix is dropped, and an unbundled engine (`dev`) reads as `0.0.0`.\n */\nconst SERVER_USER_AGENT = `Salla-TwilightReact/${\n /^\\d+(?:\\.\\d+)*/.exec(ENGINE_VERSION)?.[0] ?? '0.0.0'\n} (${import.meta.env.DEV ? 'development' : 'production'}; ssr)`;\n\n/**\n * Store API base. `VITE_API_URL` override points a preview at a branch backend; unset → prod\n * `api.salla.dev`. Resolution order matters: the value the SSR worker resolved (published into\n * the head, since worker `vars` are server-only `process.env` and never reach the browser\n * bundle) wins, so the hydrated client keeps talking to the backend that rendered the page.\n */\n\nconst STORE_API_BASE =\n getInjectedRuntimeEnv().apiBase || readEnv('VITE_API_URL') || 'https://api.salla.dev/store/v1';\n\n/**\n * Moves a call onto the API base this request was told to use, when it has one.\n *\n * `STORE_API_BASE` is read once per isolate, and one theme worker serves every\n * storefront the dispatcher sends it: production, and the beta and PR preview\n * storefronts (`web[-<hash>].beta.salla.group`), whose Store API is on their own\n * host (`x-salla-api-base`, see `utils/api-base.ts`). So SSR rebases each call per\n * request. In the browser the request store is empty and `STORE_API_BASE` is\n * already the published per-page value, so this does nothing there.\n *\n * After every hook that sets a header, so the request it copies carries them all.\n * It runs only where the dispatcher named a base (beta), and the dev settings cache\n * after it only in a dev build, which never gets that header.\n */\nfunction toRequestApiBase({ request }: { request: Request }): Request | undefined {\n const { apiBase } = getRequestStore();\n if (!apiBase || apiBase === STORE_API_BASE) return undefined;\n const url = rebaseApiUrl(request.url, STORE_API_BASE, apiBase);\n return url ? new Request(url, request) : undefined;\n}\n\nexport const api = ky.extend({\n prefix: STORE_API_BASE,\n timeout: 8000,\n hooks: {\n beforeRequest: [\n ({ request }) => {\n const { locale } = getTwilightContext();\n const headers = sharedHeaders(locale);\n for (const [key, value] of Object.entries(headers)) {\n request.headers.set(key, value);\n }\n // Only when the caller did not say. `headers.set` here would otherwise\n // overwrite a per-request identifier with the ambient one, which is a\n // silent way to answer a question about one store with another's data.\n if (!request.headers.get(API_HEADERS.STORE_IDENTIFIER)) {\n request.headers.set(API_HEADERS.STORE_IDENTIFIER, getStoreIdentifier());\n }\n\n // Server only. A browser call comes from the shopper's own address and is\n // counted against it, which is what the zone's limits are for.\n if (typeof document === 'undefined') {\n request.headers.set(API_HEADERS.USER_AGENT, SERVER_USER_AGENT);\n }\n\n const scope = getActiveScope();\n\n // The version the request asked for, else the one the settings named for\n // this scope. Absent means \"whatever is live\", which is what an ordinary\n // storefront visit wants — so a null is left off rather than sent empty.\n const versionId = resolveThemeVersionId(scope?.id ?? null);\n if (versionId) {\n request.headers.set(API_HEADERS.VERSION_ID, versionId);\n }\n\n // The draft theme a preview renders, by the name the Store knows drafts\n // by. Without it the Store answers the draft's version as the store's own\n // theme, and checks the draft's components against that one. Absent on\n // every other call, so an ordinary storefront request is unchanged.\n const draftThemeName = requestedDraftThemeName();\n if (draftThemeName) {\n request.headers.set(API_HEADERS.THEME_NAME, draftThemeName);\n }\n\n const currency = getActiveCurrency();\n if (currency) request.headers.set(API_HEADERS.CURRENCY, currency);\n\n const token = getAuthToken();\n if (token) {\n request.headers.set(API_HEADERS.AUTHORIZATION, `Bearer ${token}`);\n }\n\n // The same four the SDK's own client sends. The API resolves stock per\n // allocation: id alone asks about the market, not the branch the shopper chose.\n if (scope) {\n request.headers.set(API_HEADERS.SCOPE_ID, scope.id);\n if (scope.type) request.headers.set(API_HEADERS.SCOPE_TYPE, scope.type);\n if (scope.allocation_type)\n request.headers.set(API_HEADERS.SCOPE_ALLOCATION_TYPE, scope.allocation_type);\n if (scope.allocation_id)\n request.headers.set(API_HEADERS.SCOPE_ALLOCATION_ID, scope.allocation_id);\n }\n },\n toRequestApiBase,\n // Last, so it keys on the request with every header above set.\n devSettingsCache.lookup,\n ],\n afterResponse: [devSettingsCache.store],\n },\n});\n\nexport const cdn = ky.extend({\n prefix: 'https://cdn.salla.network',\n timeout: 5000,\n});\n\n/**\n * The merchant uploader's public bucket, `admin-uploader-prod`.\n *\n * A different host from {@link cdn} and a different thing behind it: this one\n * is an R2 custom domain, so a read never passes through a worker. Storefront\n * translations live here, per language, under `translations/` — see\n * `api/translations.ts`.\n */\nexport const filesCdn = ky.extend({\n prefix: 'https://cdn.files.salla.network',\n timeout: 5000,\n});\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { orThrow, orUnauthorized } from './chunk-
|
|
2
|
-
import { api } from './chunk-
|
|
1
|
+
import { orThrow, orUnauthorized } from './chunk-5TVOTTHS.js';
|
|
2
|
+
import { api } from './chunk-YWPVPERZ.js';
|
|
3
3
|
import { queryOptions } from '@tanstack/react-query';
|
|
4
4
|
|
|
5
5
|
async function twilightShape(path) {
|
|
@@ -89,5 +89,5 @@ var order = {
|
|
|
89
89
|
};
|
|
90
90
|
|
|
91
91
|
export { order };
|
|
92
|
-
//# sourceMappingURL=chunk-
|
|
93
|
-
//# sourceMappingURL=chunk-
|
|
92
|
+
//# sourceMappingURL=chunk-Z6ZZRFM4.js.map
|
|
93
|
+
//# sourceMappingURL=chunk-Z6ZZRFM4.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/order.ts"],"names":[],"mappings":";;;;AAqDA,eAAe,cAAc,IAAA,EAAsC;AACjE,EAAA,MAAM,QAAA,GAAW,MAAM,GAAA,CACpB,GAAA,CAAI,IAAA,EAAM;AAAA,IACT,KAAA,EAAO;AAAA;AAAA,MAEL,aAAA,EAAe,CAAC,CAAC,EAAE,OAAA,OAAc,OAAA,CAAQ,OAAA,CAAQ,MAAA,CAAO,c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AAO;AAAA,KACvC,CAAA;AAAA,IACH,OAAA,EAAS,CAAC,OAAA,KACR,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,QAAA,EAAU,SAAA,EAAW,OAAO,CAAA;AAAA,MACvC,OAAA,EAAS,MAAM,KAAA,CAAM,OAAA,CAAQ,OAAO;AAAA,KACrC,CAAA;AAAA,IACH,QAAA,EAAU,CAAC,OAAA,KACT,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,QAAA,EAAU,UAAA,EAAY,OAAO,CAAA;AAAA,MACxC,OAAA,EAAS,MAAM,KAAA,CAAM,QAAA,CAAS,OAAO;AAAA,KACtC;AAAA;AAEP","file":"chunk-Z6ZZRFM4.js","sourcesContent":["import { queryOptions } from '@tanstack/react-query';\nimport { api } from './client';\nimport type {\n Order,\n OrderListItem,\n OrderShipmentItem,\n OrderRatingItem,\n} from '../routes/account/types';\nimport type { Pagination } from './types';\nimport { orThrow, orUnauthorized } from '../providers/NavigationProvider';\n\nexport interface OrderDetailResponse {\n order: Order;\n}\n\n/**\n * The order in the shape the Twilight web components read (`salla-order-details`,\n * `salla-order-totals-card`) and the Twig themes render: the API answers `orders/{id}` this\n * way when the request does not say it comes from a React theme (`s-theme-type`).\n */\nexport interface TwilightOrder {\n items: Array<{\n name: string;\n quantity: number;\n product?: { id: number; url?: string; type?: string; image?: { url?: string } };\n options?: unknown[];\n }>;\n [key: string]: unknown;\n}\n\nexport interface CheckoutThankYouData {\n thank_you_title?: string;\n messages?: string[];\n share_message?: string;\n short_share_message?: string;\n}\n\nexport interface OrdersListResponse {\n data: OrderListItem[];\n cursor?: Pagination;\n}\n\nexport interface OrdersListParams {\n page?: number;\n cursor?: string | null;\n status?: string;\n feedback_status?: string;\n /** When set, the list payload includes each order's `items[]` (`with_items=1`). */\n with_items?: boolean | number;\n signal?: AbortSignal;\n}\n\n/** Reads an order path without `s-theme-type`, so the API answers in the Twilight components' shape. */\nasync function twilightShape(path: string): Promise<TwilightOrder> {\n const response = await api\n .get(path, {\n hooks: {\n // Runs after the client's own hook, which marks every request as from a React theme.\n beforeRequest: [({ request }) => request.headers.delete('s-theme-type')],\n },\n })\n .json<{ data: TwilightOrder }>();\n return response.data;\n}\n\nexport const order = {\n list: async (params?: OrdersListParams): Promise<OrdersListResponse> => {\n const {\n page,\n cursor,\n status,\n feedback_status: feedbackStatus,\n with_items: withItems,\n signal,\n } = params ?? {};\n\n const searchParams = new URLSearchParams();\n if (page !== undefined) searchParams.set('page', String(page));\n if (cursor) searchParams.set('cursor', cursor);\n if (status) searchParams.set('status', status);\n if (feedbackStatus) searchParams.set('feedback_status', feedbackStatus);\n if (withItems) searchParams.set('with_items', '1');\n\n const options: Record<string, unknown> = {};\n if (signal) options.signal = signal;\n\n const response = await api\n .get(`orders?${searchParams.toString()}`, options as any)\n .json<{ data: OrderListItem[] | null; cursor?: Pagination }>();\n\n return {\n data: response.data ?? [],\n cursor: response.cursor,\n };\n },\n\n find: async (id: string): Promise<OrderDetailResponse> => {\n const response = await api.get(`orders/${id}`).json<{ data: Order }>();\n\n return { order: response.data };\n },\n\n findForComponents: async (id: string): Promise<TwilightOrder> => twilightShape(`orders/${id}`),\n\n /**\n * The order the thank-you page renders, `orders/{id}/thank-you`: the same payload as `find`, but a guest\n * (no customer token) may read it for the short window after checkout the Twig thank-you page allows.\n */\n findForThankYou: async (id: string): Promise<OrderDetailResponse> => {\n const response = await api.get(`orders/${id}/thank-you`).json<{ data: Order }>();\n\n return { order: response.data };\n },\n\n /** `findForThankYou` in the Twilight components' shape, as `findForComponents` is to `find`. */\n findForThankYouComponents: async (id: string): Promise<TwilightOrder> =>\n twilightShape(`orders/${id}/thank-you`),\n\n shipments: async (orderId: string): Promise<OrderShipmentItem[]> => {\n const response = await api\n .get(`orders/${orderId}/shipments`)\n .json<{ data: OrderShipmentItem[] }>();\n return response.data ?? [];\n },\n\n ratings: async (orderId: string): Promise<OrderRatingItem[]> => {\n const response = await api.get(`orders/${orderId}/ratings`).json<{ data: OrderRatingItem[] }>();\n return response.data ?? [];\n },\n\n findOrThrow: (id: string): Promise<OrderDetailResponse> =>\n orThrow(orUnauthorized(order.find(id))),\n\n thankYou: async (orderId: string): Promise<CheckoutThankYouData> => {\n const { data } = await api\n .get(`checkout/thank-you/${orderId}`)\n .json<{ data: CheckoutThankYouData }>();\n return data;\n },\n\n thankYouOrThrow: (orderId: string): Promise<CheckoutThankYouData> =>\n orThrow(order.thankYou(orderId)),\n\n queries: {\n list: (params?: Omit<OrdersListParams, 'signal'>) =>\n queryOptions({\n queryKey: ['orders', 'list', params],\n queryFn: ({ signal }) => order.list({ ...params, signal }),\n }),\n find: (id: string) =>\n queryOptions({\n queryKey: ['orders', 'detail', id],\n queryFn: () => order.find(id),\n }),\n shipments: (orderId: string) =>\n queryOptions({\n queryKey: ['orders', 'shipments', orderId],\n queryFn: () => order.shipments(orderId),\n }),\n ratings: (orderId: string) =>\n queryOptions({\n queryKey: ['orders', 'ratings', orderId],\n queryFn: () => order.ratings(orderId),\n }),\n thankYou: (orderId: string) =>\n queryOptions({\n queryKey: ['orders', 'thankYou', orderId],\n queryFn: () => order.thankYou(orderId),\n }),\n },\n};\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { registry } from './chunk-Y32RHCOH.js';
|
|
2
|
-
import { useMoney, useNumber } from './chunk-
|
|
2
|
+
import { useMoney, useNumber } from './chunk-4XWOLTPZ.js';
|
|
3
3
|
import { useAsset } from './chunk-Z653O7MX.js';
|
|
4
4
|
import { useWishlist } from './chunk-DVJGKIFQ.js';
|
|
5
5
|
import { useTranslation } from './chunk-TYNZ5B2B.js';
|
|
@@ -229,5 +229,5 @@ var ProductCard = memo(function ProductCard2(props) {
|
|
|
229
229
|
});
|
|
230
230
|
|
|
231
231
|
export { ProductCard };
|
|
232
|
-
//# sourceMappingURL=chunk-
|
|
233
|
-
//# sourceMappingURL=chunk-
|
|
232
|
+
//# sourceMappingURL=chunk-ZOH4AEIE.js.map
|
|
233
|
+
//# sourceMappingURL=chunk-ZOH4AEIE.js.map
|