@salla.sa/twilight-theme-engine 1.0.44 → 1.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (263) hide show
  1. package/dist/{AddToCartForm-H4YMJJV5.js → AddToCartForm-OOHYADAR.js} +3 -3
  2. package/dist/{AddToCartForm-H4YMJJV5.js.map → AddToCartForm-OOHYADAR.js.map} +1 -1
  3. package/dist/{BlogAuthorPage-IFLFUY52.js → BlogAuthorPage-WWW5AI5C.js} +16 -15
  4. package/dist/BlogAuthorPage-WWW5AI5C.js.map +1 -0
  5. package/dist/{BlogCategoryPage-BA2A6HVF.js → BlogCategoryPage-NG3NK253.js} +16 -15
  6. package/dist/BlogCategoryPage-NG3NK253.js.map +1 -0
  7. package/dist/{BlogPage-AI5A6Q3S.js → BlogPage-45Q4NCJD.js} +14 -13
  8. package/dist/BlogPage-45Q4NCJD.js.map +1 -0
  9. package/dist/{BlogSinglePage-UXUDFPOU.js → BlogSinglePage-226G6GNY.js} +14 -13
  10. package/dist/BlogSinglePage-226G6GNY.js.map +1 -0
  11. package/dist/{BlogTagPage-3VFSRR2W.js → BlogTagPage-QXVLCJXK.js} +16 -15
  12. package/dist/BlogTagPage-QXVLCJXK.js.map +1 -0
  13. package/dist/{BrandsPage-ZHK6LR7L.js → BrandsPage-TFPITVGL.js} +14 -13
  14. package/dist/BrandsPage-TFPITVGL.js.map +1 -0
  15. package/dist/{Breadcrumb-QXZGGKXU.js → Breadcrumb-LXSYCVGP.js} +14 -13
  16. package/dist/Breadcrumb-LXSYCVGP.js.map +1 -0
  17. package/dist/{CartItem-3H5OOFNL.js → CartItem-7P2ZPNRC.js} +14 -13
  18. package/dist/CartItem-7P2ZPNRC.js.map +1 -0
  19. package/dist/{CartSummary-SBJ6ALUD.js → CartSummary-W6FWXDLZ.js} +14 -13
  20. package/dist/CartSummary-W6FWXDLZ.js.map +1 -0
  21. package/dist/{Copyright-6FSWBDIX.js → Copyright-WD5FF3T4.js} +3 -3
  22. package/dist/{Copyright-6FSWBDIX.js.map → Copyright-WD5FF3T4.js.map} +1 -1
  23. package/dist/{CustomerLayout-IXGQWXP7.js → CustomerLayout-E7VEI6HY.js} +14 -13
  24. package/dist/CustomerLayout-E7VEI6HY.js.map +1 -0
  25. package/dist/{Footer-S3V2JXKN.js → Footer-DGL76KHV.js} +14 -13
  26. package/dist/{Footer-S3V2JXKN.js.map → Footer-DGL76KHV.js.map} +1 -1
  27. package/dist/{Header-TWQECARS.js → Header-IBSFB44P.js} +7 -6
  28. package/dist/{Header-TWQECARS.js.map → Header-IBSFB44P.js.map} +1 -1
  29. package/dist/{LoyaltyPage-IWISVFJU.js → LoyaltyPage-LVJX2672.js} +15 -14
  30. package/dist/LoyaltyPage-LVJX2672.js.map +1 -0
  31. package/dist/{MainMenu-YPWRYFVK.js → MainMenu-J3BUNME7.js} +8 -7
  32. package/dist/MainMenu-J3BUNME7.js.map +1 -0
  33. package/dist/{MasterLayout-FVZO5MSY.js → MasterLayout-SBIGH2HB.js} +14 -13
  34. package/dist/{MasterLayout-FVZO5MSY.js.map → MasterLayout-SBIGH2HB.js.map} +1 -1
  35. package/dist/{MobileMenu-3EQA32MM.js → MobileMenu-GT5Y5G37.js} +15 -14
  36. package/dist/MobileMenu-GT5Y5G37.js.map +1 -0
  37. package/dist/{NotificationsPage-PI5G6IIK.js → NotificationsPage-4IZU7OEO.js} +14 -13
  38. package/dist/NotificationsPage-4IZU7OEO.js.map +1 -0
  39. package/dist/{OrderSinglePage-SMAGBXYT.js → OrderSinglePage-ZNRBEGQS.js} +18 -16
  40. package/dist/OrderSinglePage-ZNRBEGQS.js.map +1 -0
  41. package/dist/{OrdersPage-7PQGOE4M.js → OrdersPage-TAMZXHKA.js} +15 -14
  42. package/dist/OrdersPage-TAMZXHKA.js.map +1 -0
  43. package/dist/{PageSingle-4QIEAXDX.js → PageSingle-PRPYUPJQ.js} +3 -3
  44. package/dist/{PageSingle-4QIEAXDX.js.map → PageSingle-PRPYUPJQ.js.map} +1 -1
  45. package/dist/{ProductDetails-KVWFJS3P.js → ProductDetails-TLJDAC6Z.js} +3 -3
  46. package/dist/{ProductDetails-KVWFJS3P.js.map → ProductDetails-TLJDAC6Z.js.map} +1 -1
  47. package/dist/{ProfilePage-C5IHJ4YO.js → ProfilePage-CE6AJWBT.js} +14 -13
  48. package/dist/ProfilePage-CE6AJWBT.js.map +1 -0
  49. package/dist/{SeoCartWidget-RBAGC5VY.js → SeoCartWidget-KTU43V5G.js} +14 -13
  50. package/dist/SeoCartWidget-KTU43V5G.js.map +1 -0
  51. package/dist/{SettingsPage-NPLFOZH4.js → SettingsPage-4IHMDH7A.js} +14 -13
  52. package/dist/SettingsPage-4IHMDH7A.js.map +1 -0
  53. package/dist/{StoreClosedNotification-EDAO3OEA.js → StoreClosedNotification-DXI3LH3Z.js} +15 -14
  54. package/dist/{StoreClosedNotification-EDAO3OEA.js.map → StoreClosedNotification-DXI3LH3Z.js.map} +1 -1
  55. package/dist/{TestimonialsPage-TQBBNSXS.js → TestimonialsPage-7XPCC7G5.js} +3 -3
  56. package/dist/{TestimonialsPage-TQBBNSXS.js.map → TestimonialsPage-7XPCC7G5.js.map} +1 -1
  57. package/dist/{ThankYouPage-IF2VZRZO.js → ThankYouPage-P36Q7WCY.js} +14 -13
  58. package/dist/ThankYouPage-P36Q7WCY.js.map +1 -0
  59. package/dist/{WalletPage-4PP3X5DL.js → WalletPage-7BNJRH6H.js} +15 -14
  60. package/dist/WalletPage-7BNJRH6H.js.map +1 -0
  61. package/dist/{WishlistPage-CDDBNNB4.js → WishlistPage-CT3NBFQW.js} +16 -15
  62. package/dist/WishlistPage-CT3NBFQW.js.map +1 -0
  63. package/dist/api/apps.js +5 -4
  64. package/dist/api/brands.js +6 -5
  65. package/dist/api/cart.js +6 -5
  66. package/dist/api/category.js +6 -5
  67. package/dist/api/client.js +4 -3
  68. package/dist/api/home.js +5 -4
  69. package/dist/api/loyalty.js +6 -5
  70. package/dist/api/menu.js +5 -4
  71. package/dist/api/notification.js +5 -4
  72. package/dist/api/order.js +6 -5
  73. package/dist/api/page.js +6 -5
  74. package/dist/api/product.js +6 -5
  75. package/dist/api/profile.js +4 -3
  76. package/dist/api/profile.js.map +1 -1
  77. package/dist/api/store.js +5 -4
  78. package/dist/api/translations.js +5 -4
  79. package/dist/api/user.js +5 -4
  80. package/dist/api/wishlist.js +7 -6
  81. package/dist/{chunk-ULQMJUO2.js → chunk-25NJ5RJO.js} +4 -4
  82. package/dist/{chunk-ULQMJUO2.js.map → chunk-25NJ5RJO.js.map} +1 -1
  83. package/dist/{chunk-KOZYZQH4.js → chunk-2NFVY2KK.js} +4 -4
  84. package/dist/{chunk-KOZYZQH4.js.map → chunk-2NFVY2KK.js.map} +1 -1
  85. package/dist/{chunk-5TRRUV7N.js → chunk-4D44TJ72.js} +3 -3
  86. package/dist/{chunk-5TRRUV7N.js.map → chunk-4D44TJ72.js.map} +1 -1
  87. package/dist/{chunk-2TEGEKIQ.js → chunk-4GYBBD5Q.js} +4 -4
  88. package/dist/{chunk-2TEGEKIQ.js.map → chunk-4GYBBD5Q.js.map} +1 -1
  89. package/dist/{chunk-XYMF5XW7.js → chunk-4I3BH73Z.js} +5 -5
  90. package/dist/{chunk-XYMF5XW7.js.map → chunk-4I3BH73Z.js.map} +1 -1
  91. package/dist/{chunk-KFH3OBFW.js → chunk-4R2QJ7ZL.js} +4 -4
  92. package/dist/{chunk-KFH3OBFW.js.map → chunk-4R2QJ7ZL.js.map} +1 -1
  93. package/dist/{chunk-RBISDOPR.js → chunk-4WRWHIUU.js} +4 -4
  94. package/dist/{chunk-RBISDOPR.js.map → chunk-4WRWHIUU.js.map} +1 -1
  95. package/dist/{chunk-OTIVQ5E3.js → chunk-62KII53A.js} +17 -16
  96. package/dist/chunk-62KII53A.js.map +1 -0
  97. package/dist/{chunk-ZU5IW2SX.js → chunk-6TAGXR2C.js} +7 -7
  98. package/dist/{chunk-ZU5IW2SX.js.map → chunk-6TAGXR2C.js.map} +1 -1
  99. package/dist/{chunk-JLKNBDNE.js → chunk-7ZPCIUMS.js} +4 -4
  100. package/dist/{chunk-JLKNBDNE.js.map → chunk-7ZPCIUMS.js.map} +1 -1
  101. package/dist/{chunk-RIZOT5FN.js → chunk-ASG64WXJ.js} +3 -3
  102. package/dist/{chunk-RIZOT5FN.js.map → chunk-ASG64WXJ.js.map} +1 -1
  103. package/dist/{chunk-BWIESZJK.js → chunk-AVDNMFUA.js} +3 -3
  104. package/dist/{chunk-BWIESZJK.js.map → chunk-AVDNMFUA.js.map} +1 -1
  105. package/dist/{chunk-XOAEDXXI.js → chunk-CNZGOERI.js} +5 -5
  106. package/dist/{chunk-XOAEDXXI.js.map → chunk-CNZGOERI.js.map} +1 -1
  107. package/dist/{chunk-P7RUDHQ6.js → chunk-ENPQPRYV.js} +4 -4
  108. package/dist/{chunk-P7RUDHQ6.js.map → chunk-ENPQPRYV.js.map} +1 -1
  109. package/dist/{chunk-AZ5HAIYQ.js → chunk-FEATBCPL.js} +5 -4
  110. package/dist/chunk-FEATBCPL.js.map +1 -0
  111. package/dist/{chunk-I2REYG5M.js → chunk-GARC3WHA.js} +6 -6
  112. package/dist/{chunk-I2REYG5M.js.map → chunk-GARC3WHA.js.map} +1 -1
  113. package/dist/{chunk-XLJPUFN4.js → chunk-HMCEXUIP.js} +5 -5
  114. package/dist/{chunk-XLJPUFN4.js.map → chunk-HMCEXUIP.js.map} +1 -1
  115. package/dist/{chunk-JBXTU5NM.js → chunk-KY5DLFKQ.js} +62 -78
  116. package/dist/chunk-KY5DLFKQ.js.map +1 -0
  117. package/dist/{chunk-QG2Q6HB5.js → chunk-KZPAFRHC.js} +3 -3
  118. package/dist/{chunk-QG2Q6HB5.js.map → chunk-KZPAFRHC.js.map} +1 -1
  119. package/dist/{chunk-XLGVT7QF.js → chunk-LDNBA7H6.js} +13 -9
  120. package/dist/chunk-LDNBA7H6.js.map +1 -0
  121. package/dist/{chunk-XTOXFAP7.js → chunk-LTOTQ75E.js} +3 -3
  122. package/dist/{chunk-XTOXFAP7.js.map → chunk-LTOTQ75E.js.map} +1 -1
  123. package/dist/{chunk-LF7S7RDH.js → chunk-OJQH7JB7.js} +3 -3
  124. package/dist/{chunk-LF7S7RDH.js.map → chunk-OJQH7JB7.js.map} +1 -1
  125. package/dist/{chunk-YI2UBMWW.js → chunk-OOOQN7HE.js} +35 -14
  126. package/dist/chunk-OOOQN7HE.js.map +1 -0
  127. package/dist/{chunk-CCCKRNO4.js → chunk-OQR6N5L3.js} +3 -3
  128. package/dist/{chunk-CCCKRNO4.js.map → chunk-OQR6N5L3.js.map} +1 -1
  129. package/dist/{chunk-6XWMNQ52.js → chunk-PJWFEMBX.js} +15 -4
  130. package/dist/chunk-PJWFEMBX.js.map +1 -0
  131. package/dist/{chunk-OGGWNPF3.js → chunk-PWQX77OG.js} +3 -3
  132. package/dist/{chunk-OGGWNPF3.js.map → chunk-PWQX77OG.js.map} +1 -1
  133. package/dist/{chunk-ME727LL4.js → chunk-QNYX2XLB.js} +3 -3
  134. package/dist/{chunk-ME727LL4.js.map → chunk-QNYX2XLB.js.map} +1 -1
  135. package/dist/{chunk-X26WB7AG.js → chunk-R6M6RM6U.js} +3 -3
  136. package/dist/{chunk-X26WB7AG.js.map → chunk-R6M6RM6U.js.map} +1 -1
  137. package/dist/{chunk-2KZORZZN.js → chunk-R6XKIKK6.js} +5 -5
  138. package/dist/{chunk-2KZORZZN.js.map → chunk-R6XKIKK6.js.map} +1 -1
  139. package/dist/{chunk-TMR7TZMB.js → chunk-SS6PMXD4.js} +4 -4
  140. package/dist/{chunk-TMR7TZMB.js.map → chunk-SS6PMXD4.js.map} +1 -1
  141. package/dist/{chunk-6KI2QCPL.js → chunk-TU2GYTBL.js} +3 -3
  142. package/dist/{chunk-6KI2QCPL.js.map → chunk-TU2GYTBL.js.map} +1 -1
  143. package/dist/{chunk-YOB23VPF.js → chunk-TUKKZRKX.js} +6 -6
  144. package/dist/{chunk-YOB23VPF.js.map → chunk-TUKKZRKX.js.map} +1 -1
  145. package/dist/{chunk-6MGDRMZM.js → chunk-U7OSJVFN.js} +4 -4
  146. package/dist/{chunk-6MGDRMZM.js.map → chunk-U7OSJVFN.js.map} +1 -1
  147. package/dist/{chunk-ZNWNJZSM.js → chunk-UCSBJ5K2.js} +4 -4
  148. package/dist/{chunk-ZNWNJZSM.js.map → chunk-UCSBJ5K2.js.map} +1 -1
  149. package/dist/{chunk-E5EH32L7.js → chunk-VVOJ5T6U.js} +3 -3
  150. package/dist/{chunk-E5EH32L7.js.map → chunk-VVOJ5T6U.js.map} +1 -1
  151. package/dist/chunk-XKWRHCKI.js +101 -0
  152. package/dist/chunk-XKWRHCKI.js.map +1 -0
  153. package/dist/{chunk-2AGMXJVP.js → chunk-YAYPUOHQ.js} +4 -4
  154. package/dist/{chunk-2AGMXJVP.js.map → chunk-YAYPUOHQ.js.map} +1 -1
  155. package/dist/chunk-YSOWRAZR.js +14 -0
  156. package/dist/{chunk-JLRXUKKL.js.map → chunk-YSOWRAZR.js.map} +1 -1
  157. package/dist/{chunk-NX6BEOXW.js → chunk-ZCTMTICK.js} +4 -4
  158. package/dist/{chunk-NX6BEOXW.js.map → chunk-ZCTMTICK.js.map} +1 -1
  159. package/dist/components/cart/index.js +1 -1
  160. package/dist/components/common/index.js +1 -1
  161. package/dist/components/drawer/index.js +12 -11
  162. package/dist/components/home/index.js +15 -14
  163. package/dist/components/layout/index.js +5 -5
  164. package/dist/components/product/index.js +13 -12
  165. package/dist/components/store/index.js +14 -13
  166. package/dist/components/store/index.js.map +1 -1
  167. package/dist/document-class-DXABEK7X.js +26 -0
  168. package/dist/{document-class-FXDKVI3V.js.map → document-class-DXABEK7X.js.map} +1 -1
  169. package/dist/hooks/index.js +12 -11
  170. package/dist/hooks/useGtm.js +12 -11
  171. package/dist/hooks/useMoney.js +12 -11
  172. package/dist/hooks/useStore.js +12 -11
  173. package/dist/hooks/useUser.js +6 -5
  174. package/dist/index.js +12 -11
  175. package/dist/index.js.map +1 -1
  176. package/dist/{navigation-DQNNT2LY.js → navigation-E5CCL2TU.js} +6 -5
  177. package/dist/{navigation-DQNNT2LY.js.map → navigation-E5CCL2TU.js.map} +1 -1
  178. package/dist/{navigation-D7QS3NK2.js → navigation-JHGLXGSN.js} +5 -4
  179. package/dist/navigation-JHGLXGSN.js.map +1 -0
  180. package/dist/{not-found-QWHWEIIT.js → not-found-CRT4YC5W.js} +14 -13
  181. package/dist/not-found-CRT4YC5W.js.map +1 -0
  182. package/dist/providers/NavigationProvider.d.ts +9 -2
  183. package/dist/providers/NavigationProvider.d.ts.map +1 -1
  184. package/dist/providers/index.js +12 -11
  185. package/dist/routes/account/orders/OrderSinglePage.d.ts.map +1 -1
  186. package/dist/routes/account/orders.js +7 -6
  187. package/dist/routes/account.js +16 -15
  188. package/dist/routes/account.js.map +1 -1
  189. package/dist/routes/blog.js +11 -10
  190. package/dist/routes/blog.js.map +1 -1
  191. package/dist/routes/brands.js +7 -6
  192. package/dist/routes/brands.js.map +1 -1
  193. package/dist/routes/cart.js +20 -19
  194. package/dist/routes/cart.js.map +1 -1
  195. package/dist/routes/home.js +17 -16
  196. package/dist/routes/index.js +4 -3
  197. package/dist/routes/loyalty.js +7 -6
  198. package/dist/routes/loyalty.js.map +1 -1
  199. package/dist/routes/page.js +7 -6
  200. package/dist/routes/page.js.map +1 -1
  201. package/dist/routes/product-listing/ProductListPage.d.ts.map +1 -1
  202. package/dist/routes/product-listing.js +22 -21
  203. package/dist/routes/product-listing.js.map +1 -1
  204. package/dist/routes/product.js +15 -14
  205. package/dist/routes/product.js.map +1 -1
  206. package/dist/routes/root/beforeLoad.d.ts.map +1 -1
  207. package/dist/routes/seo-redirects.js +4 -3
  208. package/dist/routes/testimonials.js +2 -2
  209. package/dist/routes/thank-you.js +7 -6
  210. package/dist/routes/thank-you.js.map +1 -1
  211. package/dist/skeleton.js +17 -16
  212. package/dist/tanstack/middleware/twilight.d.ts.map +1 -1
  213. package/dist/tanstack/router.d.ts.map +1 -1
  214. package/dist/tanstack/store-base.d.ts +20 -0
  215. package/dist/tanstack/store-base.d.ts.map +1 -0
  216. package/dist/tanstack.js +18 -17
  217. package/dist/tanstack.js.map +1 -1
  218. package/dist/twilight/context.d.ts +10 -0
  219. package/dist/twilight/context.d.ts.map +1 -1
  220. package/dist/utils/cookies.d.ts +41 -0
  221. package/dist/utils/cookies.d.ts.map +1 -1
  222. package/dist/utils/index.js +5 -4
  223. package/dist/utils/index.js.map +1 -1
  224. package/dist/utils/runtime-env.d.ts +11 -0
  225. package/dist/utils/runtime-env.d.ts.map +1 -1
  226. package/dist/utils/store-base.d.ts +62 -0
  227. package/dist/utils/store-base.d.ts.map +1 -0
  228. package/dist/utils/store-identity.d.ts +38 -3
  229. package/dist/utils/store-identity.d.ts.map +1 -1
  230. package/dist/vite/index.js +2 -2
  231. package/package.json +1 -1
  232. package/dist/BlogAuthorPage-IFLFUY52.js.map +0 -1
  233. package/dist/BlogCategoryPage-BA2A6HVF.js.map +0 -1
  234. package/dist/BlogPage-AI5A6Q3S.js.map +0 -1
  235. package/dist/BlogSinglePage-UXUDFPOU.js.map +0 -1
  236. package/dist/BlogTagPage-3VFSRR2W.js.map +0 -1
  237. package/dist/BrandsPage-ZHK6LR7L.js.map +0 -1
  238. package/dist/Breadcrumb-QXZGGKXU.js.map +0 -1
  239. package/dist/CartItem-3H5OOFNL.js.map +0 -1
  240. package/dist/CartSummary-SBJ6ALUD.js.map +0 -1
  241. package/dist/CustomerLayout-IXGQWXP7.js.map +0 -1
  242. package/dist/LoyaltyPage-IWISVFJU.js.map +0 -1
  243. package/dist/MainMenu-YPWRYFVK.js.map +0 -1
  244. package/dist/MobileMenu-3EQA32MM.js.map +0 -1
  245. package/dist/NotificationsPage-PI5G6IIK.js.map +0 -1
  246. package/dist/OrderSinglePage-SMAGBXYT.js.map +0 -1
  247. package/dist/OrdersPage-7PQGOE4M.js.map +0 -1
  248. package/dist/ProfilePage-C5IHJ4YO.js.map +0 -1
  249. package/dist/SeoCartWidget-RBAGC5VY.js.map +0 -1
  250. package/dist/SettingsPage-NPLFOZH4.js.map +0 -1
  251. package/dist/ThankYouPage-IF2VZRZO.js.map +0 -1
  252. package/dist/WalletPage-4PP3X5DL.js.map +0 -1
  253. package/dist/WishlistPage-CDDBNNB4.js.map +0 -1
  254. package/dist/chunk-6XWMNQ52.js.map +0 -1
  255. package/dist/chunk-AZ5HAIYQ.js.map +0 -1
  256. package/dist/chunk-JBXTU5NM.js.map +0 -1
  257. package/dist/chunk-JLRXUKKL.js +0 -14
  258. package/dist/chunk-OTIVQ5E3.js.map +0 -1
  259. package/dist/chunk-XLGVT7QF.js.map +0 -1
  260. package/dist/chunk-YI2UBMWW.js.map +0 -1
  261. package/dist/document-class-FXDKVI3V.js +0 -25
  262. package/dist/navigation-D7QS3NK2.js.map +0 -1
  263. package/dist/not-found-QWHWEIIT.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/theme-version.ts","../src/api/client.ts"],"names":[],"mappings":";;;;;;;AAoCO,SAAS,uBAAA,GAAyC;AACvD,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,eAAA,EAAgB;AACtC,EAAA,IAAI,WAAW,OAAO,SAAA;AAEtB,EAAA,OAAO,qBAAA,GAAwB,SAAA,IAAa,IAAA;AAC9C;AAkBO,SAAS,qBAAA,GAAuC;AACrD,EAAA,MAAM,YAAY,uBAAA,EAAwB;AAC1C,EAAA,IAAI,WAAW,OAAO,SAAA;AAEtB,EAAA,IAAI;AACF,IAAA,MAAM,SAAA,GAAY,kBAAA,EAAmB,CAAE,QAAA,EAAU,OAAO,OAAA,EAAS,EAAA;AACjE,IAAA,OAAO,SAAA,IAAa,IAAA,GAAO,MAAA,CAAO,SAAS,CAAA,GAAI,IAAA;AAAA,EACjD,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;;;AC9CA,IAAM,iBAAA,GAAoB,kBAAA,EAAmB,CAC1C,MAAA,CAAO,MA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CAAY,QAAA,EAAU,MAAM,EAAE,CAAA;AAClD,UAAA,IAAI,KAAA,CAAM,MAAM,OAAA,CAAQ,OAAA,CAAQ,IAAI,WAAA,CAAY,UAAA,EAAY,MAAM,IAAI,CAAA;AACtE,UAAA,IAAI,KAAA,CAAM,eAAA;AACR,YAAA,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,WAAA,CAAY,qBAAA,EAAuB,MAAM,eAAe,CAAA;AAC9E,UAAA,IAAI,KAAA,CAAM,aAAA;AACR,YAAA,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,WAAA,CAAY,mBAAA,EAAqB,MAAM,aAAa,CAAA;AAAA,QAC5E;AAAA,MACF;AAAA;AACF;AAEJ,CAAC;AAEM,IAAM,GAAA,GAAM,GAAG,MAAA,CAAO;AAAA,EAC3B,MAAA,EAAQ,2BAAA;AAAA,EACR,OAAA,EAAS;AACX,CAAC","file":"chunk-AZ5HAIYQ.js","sourcesContent":["/**\n * @fileoverview Which version of the theme's settings to render — the one answer,\n * in one place.\n *\n * A merchant's theme settings are versioned. An ordinary storefront visit names\n * no version and gets the live one; the API decides, and reports it back as\n * `theme.profile.id`. Two surfaces need a different one, and both address it in\n * the URL of an iframe:\n *\n * - the merchant's theme editor at `s.salla.sa/themes/editor/…`, which shows a\n * draft version beside the controls that are editing it;\n * - a partner running the theme locally, whose dev server is the iframe.\n *\n * Written as a module of its own rather than inline at the one call site,\n * because `store-identity.ts` exists for exactly this reason: the identifier a\n * request resolved and the identifier it sent were two different values for\n * days, in two files, and every test passed. A second implementation of this is\n * the bug, not a refactor away from one.\n */\nimport { getRequestStore, getTwilightContext } from '../twilight/context';\nimport { getInjectedRuntimeEnv } from './runtime-env';\n\n/**\n * The version this request asked for, or null when it asked for none.\n *\n * Deliberately excludes the version the *settings* name. This is the answer to\n * \"what did the caller address?\", and it has to be available before any settings\n * exist — React Query keys are built from it, and a key that means one thing\n * during SSR and another after hydration is how a page refetches everything it\n * was just handed.\n *\n * 1. what the request named, seeded by `twilightMiddleware` on a host permitted\n * to name one;\n * 2. what SSR resolved and published into the head, which is all the browser has\n * once the dispatcher has stripped `?versionId=` from the URL.\n */\nexport function requestedThemeVersionId(): string | null {\n const { versionId } = getRequestStore();\n if (versionId) return versionId;\n\n return getInjectedRuntimeEnv().versionId || null;\n}\n\n/**\n * The version every Salla API call is answered with — what goes in `s-version-id`.\n *\n * The requested version outranks the settings, because a request that named one\n * is the only reason this is ever anything but the live version: falling back to\n * the settings there would let the first answer overwrite the question.\n *\n * The settings' own `theme.profile.id` stays as the fallback, unchanged. It is\n * what this header has always carried, and on an ordinary storefront it still\n * is — it keeps the rest of a page's calls pinned to the version the settings\n * call resolved, rather than letting a version go live mid-render.\n *\n * Reading the settings is guarded because `getTwilightContext().settings` throws\n * a `SettingsError` when they have not loaded — which is the normal state on the\n * very first call, the settings call itself.\n */\nexport function resolveThemeVersionId(): string | null {\n const requested = requestedThemeVersionId();\n if (requested) return requested;\n\n try {\n const profileId = getTwilightContext().settings?.theme?.profile?.id;\n return profileId != null ? String(profileId) : null;\n } catch {\n return null;\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 { resolveThemeVersionId } from '../utils/theme-version';\n// import { getInjectedRuntimeEnv, readEnv } from '../utils/runtime-env';\nimport { getTwilightContext } from '../twilight/context';\nimport {\n AUTH_TOKEN_COOKIE_NAME,\n extractScopeFromCookies,\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 getTwilightContext().authToken ?? readFallbackToken();\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 STORE_API_VERSION: 's-store-api-version',\n REQUESTED_WITH: 'x-requested-with',\n CF_PROXY_WHITELIST: 's-cf-proxy-whitelist-id',\n STORE_IDENTIFIER: 'store-identifier',\n AUTHORIZATION: 'Authorization',\n VERSION_ID: 's-version-id',\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} 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\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.STORE_API_VERSION]: 'swoole',\n [API_HEADERS.REQUESTED_WITH]: 'XMLHttpRequest',\n [API_HEADERS.CF_PROXY_WHITELIST]: '019a2f78-a64c-7edb-proxy-whitelist-id-9a3a-17afda90f03a',\n});\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\n// const STORE_API_BASE = getInjectedRuntimeEnv().apiBase || readEnv('VITE_API_URL') || 'https://api.salla.dev/store/v1';\n\nexport const api = ky.extend({\n prefix: 'https://api.salla.dev/store/v1', // TODO: check env\n timeout: 8000,\n hooks: {\n beforeRequest: [\n ({ request }) => {\n const { locale, authToken } = 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 // The version the request asked for, else the one the settings named.\n // Absent means \"whatever is live\", which is what an ordinary storefront\n // visit wants — so a null is left off rather than sent empty.\n const versionId = resolveThemeVersionId();\n if (versionId) {\n request.headers.set(API_HEADERS.VERSION_ID, versionId);\n }\n\n const token = authToken ?? readFallbackToken();\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 const scope = getActiveScope();\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 ],\n },\n});\n\nexport const cdn = ky.extend({\n prefix: 'https://cdn.salla.network',\n timeout: 5000,\n});\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/cookies.ts","../src/utils/inline-script.ts","../src/utils/runtime-env.ts","../src/utils/store-identity.ts","../src/utils/sdk-helpers.ts"],"names":[],"mappings":";;;AAAO,IAAM,sBAAA,GAAyB;AAC/B,IAAM,iBAAA,GAAoB,OAAA;AAoB1B,IAAM,oBAAA,GAAuB,WAAA;AAG7B,IAAM,cAAA,GAAiB,SAAA;AAsBvB,IAAM,sBAAA,GAAyB,WAAA;AAG/B,IAAM,gBAAA,GAAmB,WAAA;AAchC,SAAS,eAAe,GAAA,EAA+C;AACrE,EAAA,IAAI,CAAC,KAAK,OAAO,IAAA;AACjB,EAAA,OAAO,oBAAA,CAAqB,IAAA,CAAK,GAAG,CAAA,GAAI,GAAA,GAAM,IAAA;AAChD;AAyCO,IAAM,cAAA,GAAoC,CAAC,sBAAsB,CAAA;AAGxE,SAAS,WAAW,IAAA,EAAsB;AACxC,EAAA,MAAM,OAAA,GAAU,IAAA,CAAK,IAAA,EAAK,CAAE,WAAA,EAAY;AAExC,EAAA,IAAI,OAAA,CAAQ,UAAA,CAAW,GAAG,CAAA,EAAG,OAAO,OAAA,CAAQ,KAAA,CAAM,CAAA,EAAG,OAAA,CAAQ,OAAA,CAAQ,GAAG,CAAA,GAAI,CAAC,CAAA,IAAK,OAAA;AAClF,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,OAAA,CAAQ,GAAG,CAAA;AACjC,EAAA,OAAO,UAAU,EAAA,GAAK,OAAA,GAAU,OAAA,CAAQ,KAAA,CAAM,GAAG,KAAK,CAAA;AACxD;AAEA,SAAS,WAAW,QAAA,EAA2B;AAC7C,EAAA,OACE,QAAA,KAAa,eACb,QAAA,KAAa,WAAA,IACb,aAAa,OAAA,IACb,QAAA,CAAS,SAAS,YAAY,CAAA;AAElC;AAkBO,SAAS,qBAAqB,IAAA,EAA0C;AAC7E,EAAA,IAAI,CAAC,MAAM,OAA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* Which store this request is for, when the hostname does not say.\n *\n * A live storefront is reached at its own domain, so the hostname identifies it\n * and nothing else is needed. A preview is not: every theme under review is\n * served from the one preview hostname, so the store has to be named some other\n * way — the dispatcher takes it from `?storeId=` and puts it here, the same way\n * it remembers which theme to serve.\n *\n * Written by the dispatcher rather than the theme, and set on the *forwarded\n * request* as well as the response, because the response cookie only arrives in\n * time for the second page load and the first one has to render too.\n *\n * The literal is a contract with `STORE_COOKIE` in store-front-dispacher\n * (`src/dispatch/preview.ts`), and **nothing checks the two agree**. Drift does\n * not fail loudly — it renders somebody else's shop. Grep both repos before\n * changing it.\n */\nexport const STORE_ID_COOKIE_NAME = 'salla_sid';\n\n/** Query parameter naming the store, on a host that serves more than one. */\nexport const STORE_ID_PARAM = 'storeId';\n\n/**\n * Which version of the theme's settings to render.\n *\n * A merchant's theme settings are versioned, and the storefront normally shows\n * whichever version is live — the API answers with it, and names it back as\n * `theme.profile.id`. Two places need a different one: the merchant's own theme\n * editor, which previews a draft version before it is published, and a partner\n * running a theme locally against a store whose settings they are editing. Both\n * open the theme inside an iframe, and the version travels in that URL.\n *\n * Named `versionId` rather than the `version_id` the Dashboard uses internally,\n * because it sits beside `?storeId=` and one URL should not spell two ids two\n * ways. The value is the same one either way: the Optimus-encoded version id,\n * which is exactly what `s-version-id` has always carried.\n *\n * The literal is a contract with `VERSION_COOKIE` in store-front-dispacher\n * (`src/dispatch/preview.ts`), on the same terms as {@link STORE_ID_COOKIE_NAME}:\n * nothing checks the two agree, and drift shows a merchant the wrong version of\n * their own settings rather than failing.\n */\nexport const VERSION_ID_COOKIE_NAME = 'salla_vid';\n\n/** Query parameter naming the theme-settings version, where one may be named. */\nexport const VERSION_ID_PARAM = 'versionId';\n\n/**\n * An id named by a request is an integer, and anything else is not one.\n *\n * Validated rather than passed through because these values end up in an upstream\n * API path and header. Leading zeroes, signs, decimals and whitespace are all\n * rejected: the point is a single canonical form, not the widest set of things\n * that could be coerced into a number.\n *\n * One function for both ids on purpose. They arrive the same way, from the same\n * untrusted place, and are spent the same way; two copies of this rule would be\n * two chances for one of them to be relaxed on its own.\n */\nfunction parseRequestId(raw: string | null | undefined): string | null {\n if (!raw) return null;\n return /^[1-9][0-9]{0,18}$/.test(raw) ? raw : null;\n}\n\n/** A store id in its canonical form, or null when it is not one. */\nexport function parseStoreId(raw: string | null | undefined): string | null {\n return parseRequestId(raw);\n}\n\n/** A theme-settings version id in its canonical form, or null when it is not one. */\nexport function parseVersionId(raw: string | null | undefined): string | null {\n return parseRequestId(raw);\n}\n\n/** The store id the dispatcher left in the cookie, or null when absent or malformed. */\nexport function extractStoreIdFromCookies(cookieHeader: string | null): string | null {\n return parseStoreId(extractTokenFromCookies(cookieHeader, STORE_ID_COOKIE_NAME));\n}\n\n/** The version id the dispatcher left in the cookie, or null when absent or malformed. */\nexport function extractVersionIdFromCookies(cookieHeader: string | null): string | null {\n return parseVersionId(extractTokenFromCookies(cookieHeader, VERSION_ID_COOKIE_NAME));\n}\n\n/**\n * The only hosts on which a request may name its own store.\n *\n * **This is a security boundary, not a convenience.** On a merchant's own domain\n * the hostname *is* the store, and it is the only thing that may decide. A theme\n * that also honoured `?storeId=` there would let anyone open\n * `https://reefperfumes.com/?storeId=<someone else>` and be served a different\n * merchant's shop from the domain its owner controls — their branding, their\n * customers' address bar, somebody else's catalogue — and the cookie would keep\n * serving it for the rest of that browser's session. Salla points SaaS domains\n * at this dispatcher, so those hostnames are real and reachable.\n *\n * The override exists for one situation: a host that serves many stores and so\n * cannot identify one from its name. That is the preview host, where every theme\n * under review answers on the same address, and local development.\n *\n * Adding an entry grants that host the ability to render any store on request.\n * Add nothing that a merchant's traffic reaches.\n */\nexport const STORE_ID_HOSTS: readonly string[] = ['preview.salla.design'];\n\n/** The hostname alone — a port never distinguishes one host's authority from another's. */\nfunction hostnameOf(host: string): string {\n const trimmed = host.trim().toLowerCase();\n // IPv6 literals are bracketed, and the colons inside them are not a port.\n if (trimmed.startsWith('[')) return trimmed.slice(0, trimmed.indexOf(']') + 1) || trimmed;\n const colon = trimmed.indexOf(':');\n return colon === -1 ? trimmed : trimmed.slice(0, colon);\n}\n\nfunction isLoopback(hostname: string): boolean {\n return (\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === '[::1]' ||\n hostname.endsWith('.localhost')\n );\n}\n\n/**\n * Whether this host is allowed to let the request choose a store.\n *\n * Deliberately an allowlist of exact hostnames plus loopback. No suffix matching:\n * a rule like \"anything ending in salla.design\" is one wildcard DNS record away\n * from admitting a host nobody meant to admit, and the list of hosts that serve\n * more than one store is short and known.\n *\n * It gates {@link resolveRequestVersionId} as well, and the name has been left\n * alone rather than generalised because one predicate that both call is the\n * property worth keeping — a second, subtly different list is how a host ends up\n * permitted to name one thing and not the other. A version is worth gating for\n * the same reason a store is: on a merchant's own domain, honouring\n * `?versionId=` would publish whatever draft settings they are still working on\n * to anyone who guessed the URL.\n */\nexport function allowsRequestStoreId(host: string | null | undefined): boolean {\n if (!host) return false;\n const hostname = hostnameOf(host);\n return STORE_ID_HOSTS.includes(hostname) || isLoopback(hostname);\n}\n\n/**\n * Whether this host *is* a store, so its name can be used as the identifier.\n *\n * The exact inverse of {@link allowsRequestStoreId}, and deliberately written as\n * one so the two can never disagree: a host that may name its store is a host\n * that serves more than one, and a host that serves more than one cannot be the\n * answer to \"which store is this?\". `preview.salla.design` and `localhost:5188`\n * are not shops; asking the API about them earns a 422 and a page that reads as\n * a broken theme.\n */\nexport function hostIdentifiesStore(host: string | null | undefined): boolean {\n return Boolean(host) && !allowsRequestStoreId(host);\n}\n\n/**\n * The store this request names, on a host permitted to name one.\n *\n * The host check is inside the resolution rather than at a call site, because a\n * call site is a thing someone can add without reading this comment. There is no\n * way to ask \"what store did the request name?\" without also asking \"is this a\n * host that may say?\" — get it wrong and the answer is a security bug that looks\n * like a feature.\n *\n * Between the two permitted sources the URL wins, the same precedence the\n * dispatcher uses for the theme and for the same reason: a link is how someone\n * switches, and a cookie they cannot see should never beat the address they\n * just typed.\n */\nexport function resolveRequestStoreId(\n url: string,\n cookieHeader: string | null,\n host: string | null | undefined\n): string | null {\n return resolveRequestId(url, cookieHeader, host, STORE_ID_PARAM, STORE_ID_COOKIE_NAME);\n}\n\n/**\n * The theme-settings version this request names, on a host permitted to name one.\n *\n * Same shape and the same host gate as {@link resolveRequestStoreId}, deliberately:\n * both answer \"what did this request ask to be shown?\", both are reached only on\n * a host that serves more than one thing, and a version that could be named where\n * a store could not would be a second rule to keep in step with the first.\n *\n * Null is the ordinary answer, and it is not a failure — it means nothing\n * addressed a version, so the store's own live one is what gets rendered.\n */\nexport function resolveRequestVersionId(\n url: string,\n cookieHeader: string | null,\n host: string | null | undefined\n): string | null {\n return resolveRequestId(url, cookieHeader, host, VERSION_ID_PARAM, VERSION_ID_COOKIE_NAME);\n}\n\n/**\n * The id this request names, from the query first and the cookie after.\n *\n * The host check lives here rather than at either call site, for the reason the\n * two wrappers above are wrappers at all: there must be no way to ask what a\n * request named without also asking whether this host may say.\n */\nfunction resolveRequestId(\n url: string,\n cookieHeader: string | null,\n host: string | null | undefined,\n param: string,\n cookieName: string\n): string | null {\n if (!allowsRequestStoreId(host)) return null;\n\n let fromQuery: string | null = null;\n try {\n fromQuery = parseRequestId(new URL(url).searchParams.get(param));\n } catch {\n /* a relative or malformed URL simply names nothing */\n }\n return fromQuery ?? parseRequestId(extractTokenFromCookies(cookieHeader, cookieName));\n}\n\n/**\n * Deletes the auth `token` cookie. This cookie is written client-side by the theme\n * (TwilightProvider), not by the SDK — `salla.cookie.clearAll()` only clears its own\n * allowlist and leaves `token` behind — so logout must clear it here. Client-only.\n */\nexport function clearAuthTokenCookie(): void {\n if (typeof document === 'undefined') return;\n document.cookie = `${AUTH_TOKEN_COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;\n}\n\nexport function extractTokenFromCookies(\n cookieHeader: string | null,\n cookieName: string\n): string | null {\n if (!cookieHeader) return null;\n\n const prefix = `${cookieName}=`;\n let start = 0;\n\n while (start < cookieHeader.length) {\n const idx = cookieHeader.indexOf(prefix, start);\n if (idx === -1) return null;\n\n const prevChar = idx > 0 ? cookieHeader[idx - 1] : '';\n if (prevChar === '' || prevChar === ';' || prevChar === ' ') {\n let end = cookieHeader.indexOf(';', idx);\n if (end === -1) end = cookieHeader.length;\n\n const value = cookieHeader.slice(idx + prefix.length, end).trim();\n try {\n return decodeURIComponent(value) || null;\n } catch {\n return value || null;\n }\n }\n\n start = idx + prefix.length;\n }\n\n return null;\n}\n\n/**\n * The scope the Salla SDK persists as `scope`: the market (`id`/`type`) plus, once\n * bullet delivery confirms an address or branch, the allocation. The SDK sends all\n * four as request headers (`s-scope-id`, `s-scope-type`, `s-scope-allocation-type`,\n * `s-scope-allocation-id`) and the API resolves stock per allocation — a scope sent\n * without its allocation is a different question, answered from a different branch.\n */\nexport interface ActiveScope {\n id: string;\n type?: string;\n allocation_type?: string;\n allocation_id?: string;\n}\n\n/** The SDK stores the scope either as its full object or as a bare id. */\nfunction normalizeScope(raw: unknown): ActiveScope | null {\n if (raw == null) return null;\n if (typeof raw !== 'object') return { id: String(raw) };\n const s = raw as Record<string, unknown>;\n if (s.id == null) return null;\n const scope: ActiveScope = { id: String(s.id) };\n if (s.type != null) scope.type = String(s.type);\n if (s.allocation_type != null) scope.allocation_type = String(s.allocation_type);\n if (s.allocation_id != null) scope.allocation_id = String(s.allocation_id);\n return scope;\n}\n\n/**\n * Reads the active scope from the `scope` cookie, which Salla persists as a JSON\n * object (e.g. `{\"id\":123,\"type\":\"scope\",\"allocation_type\":\"branch\",\"allocation_id\":\"9\"}`).\n * Returns null when the cookie is missing or unparseable. Used server-side, where\n * `salla.storage` is absent.\n */\nexport function extractScopeFromCookies(cookieHeader: string | null): ActiveScope | null {\n const raw = extractTokenFromCookies(cookieHeader, SCOPE_COOKIE_NAME);\n if (!raw) return null;\n try {\n return normalizeScope(JSON.parse(raw));\n } catch {\n return null;\n }\n}\n\n/** {@link extractScopeFromCookies} reduced to the id. */\nexport function extractScopeIdFromCookies(cookieHeader: string | null): string | null {\n return extractScopeFromCookies(cookieHeader)?.id ?? null;\n}\n\n/**\n * The scope the Salla SDK persisted in its storage (`salla.storage.get('scope')`).\n *\n * Returns `undefined` when the SDK storage API isn't ready yet — deliberately\n * distinct from `null` (\"no branch selected\"), so callers can't mistake a\n * not-yet-hydrated SDK for a cleared selection. Client-only.\n */\nexport function readSdkScope(): ActiveScope | null | undefined {\n const storage = typeof window !== 'undefined' ? window.salla?.storage : undefined;\n if (typeof storage?.get !== 'function') return undefined;\n return normalizeScope(storage.get(SCOPE_COOKIE_NAME));\n}\n\n/** {@link readSdkScope} reduced to the id; keeps the not-ready/none distinction. */\nexport function readSdkScopeId(): string | null | undefined {\n const scope = readSdkScope();\n return scope === undefined ? undefined : (scope?.id ?? null);\n}\n\n/** One year — the SDK keeps the selected branch in localStorage indefinitely. */\nconst SCOPE_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;\n\nconst sameScope = (a: ActiveScope | null, b: ActiveScope | null): boolean =>\n JSON.stringify(a) === JSON.stringify(b);\n\n/**\n * Mirrors the scope the Salla SDK selected into the `scope` cookie so the SERVER\n * can see it. The SDK persists the selection in localStorage ONLY and writes no\n * cookie, so without this the server computes scope=null for every visitor who\n * picked a branch while the client computes the branch id — the dehydrated settings\n * query key never matches and the client refetches store settings on every page\n * load (SAL-122).\n *\n * Written in the SDK's own JSON shape so {@link extractScopeFromCookies} parses it,\n * allocation included: the bullet-delivery component writes the same cookie with the\n * full object, and rewriting it with the id alone would drop the branch the server\n * needs. Returns true when the cookie was (re)written. Client-only; no-op on the server.\n */\nexport function writeScopeCookie(scope: ActiveScope | null): boolean {\n if (typeof document === 'undefined') return false;\n if (sameScope(extractScopeFromCookies(document.cookie), scope)) return false;\n\n if (scope == null) {\n document.cookie = `${SCOPE_COOKIE_NAME}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/`;\n return true;\n }\n\n const value = encodeURIComponent(JSON.stringify(scope));\n document.cookie = `${SCOPE_COOKIE_NAME}=${value}; path=/; max-age=${SCOPE_COOKIE_MAX_AGE}; samesite=lax`;\n return true;\n}\n\n/**\n * Keeps the `scope` cookie in step with the SDK's selected branch. Call on every\n * client navigation; it no-ops while the SDK storage API is still hydrating so a\n * late-loading SDK can't wipe a valid cookie.\n */\nexport function syncScopeCookie(): boolean {\n const scope = readSdkScope();\n return scope === undefined ? false : writeScopeCookie(scope);\n}\n","/**\n * Escape a JSON-stringified value for safe embedding inside an inline `<script>` body.\n *\n * The head injects script bodies raw, so a `</script>` inside partner-set data would break out\n * of the tag; U+2028/U+2029 are line terminators in JS but not in JSON, so they must go too.\n */\nexport function escapeForInlineScript(value: string): string {\n return value\n .replace(/</g, '\\\\u003c')\n .replace(/>/g, '\\\\u003e')\n .replace(/&/g, '\\\\u0026')\n .replace(/\\u2028/g, '\\\\u2028')\n .replace(/\\u2029/g, '\\\\u2029');\n}\n","import { escapeForInlineScript } from './inline-script';\nimport { getRequestStore } from '../twilight/context';\nimport { hostIdentifiesStore } from './cookies';\n\n/** Where `rootHead` publishes the SSR-resolved env for the browser bundle to read. */\nconst RUNTIME_ENV_KEY = '__SALLA_RUNTIME_ENV__';\n\n/** The env values that must agree between the SSR render and the hydrated client. */\nexport interface RuntimeEnv {\n /** Store API base — `VITE_API_URL`. */\n apiBase?: string;\n /** Store identifier — `VITE_STORE_DOMAIN`. */\n storeIdentifier?: string;\n /**\n * The theme-settings version the request named, if any.\n *\n * Published for the same reason `storeIdentifier` is: the dispatcher strips\n * `?versionId=` on the way in, so by the time the browser has the page its own\n * URL no longer says which version it is showing. Without this the hydrated\n * client would ask the API about the store's live version and quietly replace\n * the draft it was handed.\n *\n * Absent — not empty — when nothing named one, so it drops out of the inline\n * script entirely rather than publishing a value that means \"live\".\n */\n versionId?: string;\n}\n\n/**\n * A build-time `import.meta.env` var, falling back to the worker's runtime `process.env`\n * (wrangler `vars`, exposed via the `nodejs_compat_populate_process_env` flag).\n */\nexport function readEnv(key: string): string | undefined {\n try {\n const vite = (import.meta as unknown as { env?: Record<string, string | undefined> }).env?.[\n key\n ];\n if (vite) return vite;\n } catch {\n /* import.meta.env not available in all environments */\n }\n return typeof process !== 'undefined' ? process.env?.[key] : undefined;\n}\n\n/**\n * What this runtime resolves from its own env — server-side that includes the worker vars.\n * Prefers what the server already published, so re-rendering the head during hydration yields\n * the same script instead of dropping it.\n */\nexport function resolveRuntimeEnv(): RuntimeEnv {\n const injected = getInjectedRuntimeEnv();\n const { storeId, versionId, requestHost } = getRequestStore();\n return {\n apiBase: injected.apiBase || readEnv('VITE_API_URL'),\n // The request outranks the build-time var here for the same reason it does\n // in `resolveStoreIdentifier`, and this is the copy that reaches the\n // browser: publish the store SSR actually rendered, or hydration resolves\n // again from a URL whose `?storeId=` the dispatcher has already stripped and\n // queries a different store than the markup it is hydrating.\n storeIdentifier:\n injected.storeIdentifier ||\n storeId ||\n (hostIdentifiesStore(requestHost) ? requestHost : null) ||\n readEnv('VITE_STORE_DOMAIN'),\n // No env fallback on purpose. A store identifier has one because a build can\n // legitimately be pinned to a store; a version is something a request asks\n // for, and a build-time default would make every visitor of every store see\n // whichever draft was current when the theme was compiled.\n versionId: injected.versionId || versionId || undefined,\n };\n}\n\n/**\n * The env the SSR worker resolved, as handed to the browser by `rootHead`. Empty on the server\n * and on a client whose head carried nothing.\n *\n * Worker `vars` are *runtime* env: they live in `process.env` on the server only, while\n * `import.meta.env` is substituted at build time. A bundle built without those vars therefore\n * sees `undefined` in the browser and silently falls back to the production defaults — SSR\n * would render off the configured backend while every post-hydration fetch hits another one.\n */\nexport function getInjectedRuntimeEnv(): RuntimeEnv {\n const holder = globalThis as typeof globalThis & { [RUNTIME_ENV_KEY]?: RuntimeEnv };\n return holder[RUNTIME_ENV_KEY] ?? {};\n}\n\n/**\n * Inline head `<script>` body publishing the server-resolved env, or null when there is nothing\n * to publish (no overrides configured — the defaults already agree on both sides).\n */\nexport function renderRuntimeEnvScript(env: RuntimeEnv = resolveRuntimeEnv()): string | null {\n const set = Object.entries(env).filter(([, value]) => Boolean(value));\n if (!set.length) return null;\n const json = escapeForInlineScript(JSON.stringify(Object.fromEntries(set)));\n return `window.${RUNTIME_ENV_KEY}=${json};`;\n}\n","/**\n * @fileoverview Which store to ask about — the one answer, in one place.\n *\n * This lived in two places once. `api/store.ts` learned to read the store a\n * request names, and `utils/sdk-helpers.ts` — the copy `api/client.ts` actually\n * sets the `store-identifier` header from — did not. So the resolver that had\n * been taught the answer was consulted for a null check and thrown away, every\n * outgoing request carried an empty identifier, the API answered\n * `422 Store Identifier not found`, and every published theme rendered\n * \"Store Unavailable\" while its tests passed: the client's suite mocked the\n * resolver, and the resolver's suite never went near a request.\n *\n * Hence one module, imported by both. If a third place ever needs a store\n * identifier, it imports this — a second implementation is the bug, not a\n * refactor away from it.\n *\n * See `docs/store-identity.md` for the full picture, including the security\n * boundary on who may name a store.\n */\nimport { getRequestStore } from '../twilight/context';\nimport { hostIdentifiesStore } from './cookies';\nimport { getInjectedRuntimeEnv, readEnv } from './runtime-env';\n\n/**\n * Which store to ask about, in the order the answers can be trusted.\n *\n * A deployed theme worker is published with **no vars and no bindings** — the\n * script metadata carries `main_module`, compatibility settings, assets and tags\n * and nothing else — so `VITE_STORE_DOMAIN` exists only where a build baked it\n * in, which is local development. In production this function used to reach the\n * end of that chain and return the empty string, `store.settings` refused to\n * call with no identifier, and the root loader threw \"Store Unavailable\" — a\n * theme that renders its own failure page for every visitor of every store.\n *\n * The order:\n *\n * 1. what the caller passed, which is always deliberate;\n * 2. the store this request names — the `?storeId=` a preview was opened with,\n * then the cookie remembering it — seeded by `twilightMiddleware`, and only\n * on a host permitted to name one;\n * 3. what SSR already resolved and published, so the hydrated client asks about\n * the same store the server rendered instead of resolving again from a URL\n * that no longer names it;\n * 4. the request's own host, which *is* the identity of a live storefront —\n * but only when that host is a storefront. `preview.salla.design` and\n * `localhost` serve many stores, so their names identify none;\n * 5. `VITE_STORE_DOMAIN`, last, because a build-time constant is a development\n * convenience and must never outrank what the request actually said.\n */\nexport function resolveStoreIdentifier(explicit?: string): string {\n if (explicit) return explicit;\n\n const { storeId, requestHost } = getRequestStore();\n if (storeId) return storeId;\n\n const injected = getInjectedRuntimeEnv().storeIdentifier;\n if (injected) return injected;\n\n if (hostIdentifiesStore(requestHost)) return requestHost as string;\n\n // The browser's own address, for a client render that reached neither of the\n // above — a live storefront, where the host is the store.\n const browserHost = typeof window !== 'undefined' ? window.location.host : null;\n if (hostIdentifiesStore(browserHost)) return browserHost as string;\n\n return readEnv('VITE_STORE_DOMAIN') || readEnv('STORE_DOMAIN') || '';\n}\n","export type { StoreContext } from '../api/store';\nimport { resolveStoreIdentifier } from './store-identity';\n\nconst isBrowser = typeof window !== 'undefined';\n\n/**\n * Which store to ask the API about — see {@link resolveStoreIdentifier}.\n *\n * A delegation, not a second implementation. This name is the one on the wire\n * (`api/client.ts` sets the `store-identifier` header from it) and the one\n * themes import from `@salla.sa/twilight-theme-engine/utils`, so it stays; what\n * it must never do again is answer differently from the resolver everything\n * else asks. It had its own copy of the order once, missing the store the\n * request names and preferring the build-time `VITE_STORE_DOMAIN` that a\n * deployed worker does not have — so every published theme sent an empty\n * identifier and rendered \"Store Unavailable\".\n */\nexport function getStoreIdentifier(explicit?: string): string {\n return resolveStoreIdentifier(explicit);\n}\n\n/**\n * Get Salla SDK instance if available\n */\nexport function getSallaSDK(): typeof window.salla | undefined {\n if (!isBrowser) return undefined;\n return window.salla;\n}\n\n/**\n * Push the active route locale onto the Salla SDK.\n *\n * Why this is needed (and why it must run on every navigation):\n * - The SDK seeds its locale from `navigator.language` — the theme sets no `s-lang`\n * cookie or `window.locale` — so an English browser starts the SDK in `en` even on\n * an `/ar` store.\n * - The SDK fixes its axios `accept-language` header ONCE, at init. `salla.lang.setLocale`\n * only swaps UI translations (it never touches the header), and `salla.init()` is a\n * no-op after `Salla.status === 'ready'`, so the header never refreshes on its own.\n * - `profile::info.fetched` (login / profile refresh on navigation) overrides the header\n * to the *account's* language.\n *\n * Net result without this: `salla.api.*` calls (cart/product details) return data in the\n * wrong locale — e.g. English cart item names on `/ar/cart` — intermittently, depending on\n * load order and whether a profile fetch ran. Re-asserting the URL locale here keeps the\n * header correct. No-op on the server and until the SDK exposes the methods.\n */\nexport function syncSdkLocale(locale: string): void {\n const sdk = getSallaSDK();\n if (!sdk || !locale) return;\n try {\n sdk.lang?.setLocale?.(locale);\n sdk.api?.setHeader?.('accept-language', locale);\n // The localization modal swaps `/${user.language_code}/` in the URL on submit;\n // the SDK never sets this locally, so without it the switch reloads the same page.\n sdk.config?.set?.('user.language_code', locale);\n } catch {\n // SDK partially loaded — the header is re-asserted on the next navigation.\n }\n}\n"]}
@@ -1,14 +0,0 @@
1
- import { lazy } from 'react';
2
-
3
- // src/components/cart/lazy.ts
4
- var LazyCartItem = lazy(() => import('./CartItem-3H5OOFNL.js').then((m) => ({ default: m.CartItem })));
5
- var LazyCartSummary = lazy(
6
- () => import('./CartSummary-SBJ6ALUD.js').then((m) => ({ default: m.CartSummary }))
7
- );
8
- var LazySeoCartWidget = lazy(
9
- () => import('./SeoCartWidget-RBAGC5VY.js').then((m) => ({ default: m.SeoCartWidget }))
10
- );
11
-
12
- export { LazyCartItem, LazyCartSummary, LazySeoCartWidget };
13
- //# sourceMappingURL=chunk-JLRXUKKL.js.map
14
- //# sourceMappingURL=chunk-JLRXUKKL.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/apply-theme.ts","../src/providers/twilight-theme.ts","../src/utils/engine-version.ts","../src/providers/twilight-init.ts","../src/providers/navigation-setups.ts","../src/providers/DocumentSyncRegistry.ts","../src/hooks/useDate.ts","../src/hooks/useNumber.ts","../src/hooks/useMoney.tsx","../src/hooks/useGtm.ts","../src/hooks/useOpeningHours.ts","../src/hooks/usePageConfig.ts","../src/utils/breadcrumb.ts","../src/hooks/useBreadcrumbs.ts","../src/hooks/registerDefaultHooks.tsx","../src/components/layout/Footer.tsx","../src/components/layout/MasterLayout.tsx","../src/components/snippets/AppsSnippets.tsx","../src/providers/TwilightProvider.tsx","../src/hooks/useStore.ts"],"names":["color","useEffect","lazy","useMemo","useState","jsx","jsxs","Fragment","Suspense","getSalla","React","useCallback"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,SAAS,WAAW,KAAA,EAAoB;AAC7C,EAAA,IAAI,OAAO,aAAa,WAAA,EAAa;AAErC,EAAA,MAAM,OAA2B,EAAC;AAElC,EAAA,IAAI,KAAA,CAAM,MAAM,IAAA,EAAM;AACpB,IAAA,IAAA,CAAK,IAAA;AAAA,MACH,CAAC,aAAA,EAAe,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA;AAAA,MAC/B,CAAC,cAAA,EAAgB,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA;AAAA,MAChC,CAAC,gBAAA,EAAkB,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA;AAAA,MAClC,CAAC,eAAA,EAAiB,CAAA,EAAG,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,OAAA,CAAS,CAAA;AAAA,MAC7C,CAAC,aAAA,EAAe,CAAA,EAAG,KAAA,CAAM,IAAA,CAAK,IAAI,CAAA,KAAA,CAAO;AAAA,KAC3C;AAAA,EACF;AAEA,EAAA,MAAM,EAAE,KAAA,EAAAA,MAAAA,EAAM,GAAI,KAAA;AAClB,EAAA,IAAIA,MAAAA,EAAO;AACT,IAAA,IAAA,CAAK,IAAA,CAAK,CAAC,cAAA,EAAgB,SAAS,CAAC,CAAA;AAErC,IAAA,IAAIA,OAAM,OAAA,EAAS;AACjB,MAAA,MAAM,CAAA,GAAI,KAAA,CAAUA,MAAAA,CAAM,OAAO,CAAA;AACjC,MAAA,IAAA,CAAK,IAAA;AAAA,QACH,CAAC,iBAAA,EAAmBA,MAAAA,CAAM,OAAO,CAAA;AAAA,QACjC,CAAC,sBAAA,EAAwB,CAAA,CAAE,MAAA,CAAO,IAAI,CAAC,CAAA;AAAA,QACvC,CAAC,uBAAA,EAAyB,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,QAAA,EAAU;AACjD,QAAA,SAAA,CAAU,CAAC,UAAU,EAAE,GAAG,MAAM,GAAI,IAAA,CAAK,OAAyB,CAAE,CAAA;AAAA,MACtE;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF,CAAA,EAAG,CAAC,KAAA,EAAO,SAAS,CAAC,CAAA;AAErB,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,OAAA,EAAQ;AAC7B","file":"chunk-OTIVQ5E3.js","sourcesContent":["import type { Theme } from '../types';\nimport { color as makeColor } from './color';\n\nexport function applyTheme(theme: Theme): void {\n if (typeof document === 'undefined') return;\n\n const vars: [string, string][] = [];\n\n if (theme.font?.name) {\n vars.push(\n ['--font-main', theme.font.name],\n ['--font-light', theme.font.name],\n ['--font-regular', theme.font.name],\n ['--font-medium', `${theme.font.name}-Medium`],\n ['--font-bold', `${theme.font.name}-Bold`]\n );\n }\n\n const { color } = theme;\n if (color) {\n vars.push(['--color-text', '#222222']);\n\n if (color.primary) {\n const c = makeColor(color.primary);\n vars.push(\n ['--color-primary', color.primary],\n ['--color-primary-dark', c.darken(0.15)],\n ['--color-primary-light', c.lighten(0.15)],\n ['--color-title', color.primary],\n ['--color-secondary', color.primary]\n );\n }\n\n if (color.reverse_text) {\n vars.push(\n ['--color-primary-reverse', color.reverse_text],\n ['--color-text-reverse', color.reverse_text],\n ['--color-reverse-text', color.reverse_text]\n );\n }\n\n if (color.reverse_primary) {\n vars.push(['--color-reverse-primary', color.reverse_primary]);\n }\n }\n\n vars.push(['--page-height', '100%']);\n\n const root = document.documentElement;\n for (const [prop, val] of vars) {\n root.style.setProperty(prop, val);\n }\n}\n","import { useEffect } from 'react';\nimport { applyTheme } from '../utils/apply-theme';\nimport { useDocumentClass } from '../hooks/useDocumentClass';\nimport type { Theme } from '../types';\n\nexport function fontToClass(name: string | undefined): string | null {\n if (!name) return null;\n const slug = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n return slug ? `font-${slug}` : null;\n}\n\nexport function ThemeDocumentSync({\n theme,\n locale,\n direction,\n isMobileWebview,\n}: {\n theme: Theme;\n locale: string;\n direction: 'rtl' | 'ltr';\n isMobileWebview: boolean;\n}): null {\n const bodyClasses = [\n theme.name ? `salla-${theme.name}` : null,\n `color-mode-${theme.color?.is_dark ? 'dark' : 'light'}`,\n direction,\n theme.mode === 'preview' ? 'preview-mode' : null,\n fontToClass(theme.font?.name),\n isMobileWebview ? 'mobile-webview' : null,\n theme.settings?.footer_is_dark ? 'footer-is-dark' : 'footer-is-light',\n theme.settings?.topnav_is_dark ? 'topnav-is-dark' : null,\n theme.settings?.sticky_add_to_cart ? 'is-sticky-product-bar' : null,\n ].filter(Boolean) as string[];\n\n useDocumentClass({\n html: { lang: locale, dir: direction },\n body: { class: bodyClasses },\n });\n\n useEffect(() => {\n applyTheme(theme);\n }, [theme]);\n\n return null;\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 Dispatch, type SetStateAction, useEffect, useMemo, useState } from 'react';\nimport type { SallaCurrency, SallaSDK } from '../types/salla-sdk';\nimport { useDevSettingsOverrides } from '../dev/dev-settings-store';\nimport { getTwilightContext } from '../twilight/context';\nimport type { Store, Theme } from '../types';\nimport { syncScopeCookie } from '../utils/cookies';\nimport { ENGINE_VERSION } from '../utils/engine-version';\nimport { type StoreContext, syncSdkLocale } from '../utils/sdk-helpers';\nimport { getLanguageInfo } from './locale-constants';\n\n// ─── Helpers ──────────────────────────────────────────────────────────────────\n\nfunction getSalla(): SallaSDK | undefined {\n if (typeof window === 'undefined') return undefined;\n return window.salla;\n}\n\n// ─── Hook ─────────────────────────────────────────────────────────────────────\n\nexport interface UseTwilightInitOptions {\n debug: boolean;\n initialData?: StoreContext | Record<string, unknown>;\n onReady?: (data: { store: Store; theme: Theme }) => void;\n onError?: (error: Error) => void;\n initialLocale: string;\n}\n\nexport interface UseTwilightInitReturn {\n isReady: boolean;\n storeData: Store;\n setStoreData: Dispatch<SetStateAction<Store>>;\n themeData: Theme;\n currency: SallaCurrency | null;\n isMobileWebview: boolean;\n}\n\nexport function useTwilightInit({\n debug: _debug,\n initialData,\n onReady,\n onError: _onError,\n initialLocale,\n}: UseTwilightInitOptions): UseTwilightInitReturn {\n const isBrowser = typeof window !== 'undefined';\n const initialLanguage = getLanguageInfo(initialLocale);\n const settingsData = initialData as StoreContext | undefined;\n\n const [isReady, setReady] = useState<boolean>(() => !!settingsData);\n const [storeData, setStoreData] = useState<Store>(\n () => (settingsData?.store as Store) ?? ({} as Store)\n );\n const [baseTheme] = useState<Theme>(() => {\n const theme = settingsData?.theme as Partial<Theme> | undefined;\n if (theme) {\n return {\n ...theme,\n is_rtl: theme.is_rtl ?? initialLanguage.dir === 'rtl',\n } as Theme;\n }\n return { is_rtl: initialLanguage.dir === 'rtl' } as Theme;\n });\n\n // Dev-mode only: overlay the settings the DevSettingsWidget has enabled onto\n // the real theme so the storefront renders with them live. `import.meta.env.DEV`\n // is statically false in production builds, so this whole branch (and the\n // overrides hook's effect) is dead-code-eliminated from the shipped bundle.\n const devOverrides = useDevSettingsOverrides();\n const themeData = useMemo<Theme>(() => {\n if (import.meta.env.DEV && devOverrides.enabled) {\n const overrides = devOverrides.settings;\n if (overrides && Object.keys(overrides).length > 0) {\n return {\n ...baseTheme,\n settings: { ...(baseTheme.settings ?? {}), ...overrides } as Theme['settings'],\n };\n }\n }\n return baseTheme;\n }, [baseTheme, devOverrides]);\n const [currency] = useState<SallaCurrency | null>(null);\n const [isMobileWebview] = useState<boolean>(false); // todo :: add a flage in the store data for mobile\n\n useEffect(() => {\n if (!isBrowser || !themeData) return;\n const sdk = getSalla();\n sdk?.config?.set?.('theme.is_rtl', themeData.is_rtl ?? false);\n window.enable_more_menu = String(themeData.settings?.enable_more_menu ?? true);\n }, [themeData, isBrowser]);\n\n useEffect(() => {\n const sdk = getSalla();\n if (!sdk) return;\n\n // Expose which engine build rendered this storefront (salla.versions.engine)\n // for debugging and support tooling. Merged, not assigned, so other Salla\n // packages can register their own versions on the same object.\n const sdkWithVersions = sdk as SallaSDK & { versions?: Record<string, string> };\n sdkWithVersions.versions = { ...sdkWithVersions.versions, engine: ENGINE_VERSION };\n\n if (initialLocale) {\n // Sync UI translations + the SDK's axios accept-language header to the route locale.\n // The header set may be a no-op now if the SDK isn't fully ready; it's re-asserted\n // after onReady below, and on every navigation in rootBeforeLoad.\n syncSdkLocale(initialLocale);\n }\n\n if (typeof sdk.init !== 'function') return;\n\n const ctx = getTwilightContext();\n const pageCtx = ctx.page;\n const initData = pageCtx\n ? {\n ...settingsData,\n page: {\n ...pageCtx,\n url: pageCtx.url ?? ctx.location.pathname + ctx.location.searchStr,\n },\n }\n : settingsData;\n\n sdk.init(initData);\n\n const initSdk = async () => {\n try {\n await sdk.onReady();\n } catch {\n // sdk.onReady() may fail during partial initialization\n }\n\n // The SDK loads async; the sync above may have run against a not-yet-ready SDK.\n // Now that it's ready, re-assert so the very first SDK API calls use the route locale.\n syncSdkLocale(initialLocale);\n\n // Mirror the selected branch into the `scope` cookie so the NEXT SSR request keys\n // its settings query on the same scope the client does. rootBeforeLoad also calls\n // this, but only from a client-side navigation: on the initial load TanStack\n // restores the root match's __beforeLoadContext instead of re-running beforeLoad,\n // so a visitor who never navigates would otherwise never write the cookie. Here is\n // the earliest point salla.storage is guaranteed populated.\n syncScopeCookie();\n\n setReady(true);\n document.dispatchEvent(new CustomEvent('theme::ready'));\n\n onReady?.({\n store: storeData,\n theme: themeData,\n });\n };\n\n initSdk();\n // eslint-disable-next-line react-hooks/exhaustive-deps -- Intentional: SDK init runs once per locale change only\n }, [initialLocale]);\n\n return {\n isReady,\n storeData,\n setStoreData,\n themeData,\n currency,\n isMobileWebview,\n };\n}\n","import { lazy, type LazyExoticComponent, type FC, type ReactNode } from 'react';\n\nexport const navigationSetups: Record<string, LazyExoticComponent<FC<{ children: ReactNode }>>> = {\n tanstack: lazy(() =>\n import('../tanstack/navigation').then((m) => ({ default: m.NavigationSetup }))\n ),\n nextjs: lazy(() => import('../nextjs/navigation').then((m) => ({ default: m.NavigationSetup }))),\n};\n","import { lazy, type FC, type LazyExoticComponent } from 'react';\n\n/**\n * Registry for framework-specific document sync components.\n * Each framework (tanstack, nextjs, etc.) can register its own sync component.\n * Used by TwilightProvider to automatically apply route-based body classes.\n *\n * @example Adding a new framework\n * ```ts\n * import { registerDocumentSync } from '@salla.sa/twilight-theme-engine';\n *\n * registerDocumentSync('my-framework', lazy(() => import('./my-document-sync')));\n * ```\n */\nexport const routeDocumentSyncs: Record<string, LazyExoticComponent<FC>> = {\n tanstack: lazy(() =>\n import('../tanstack/document-class').then((m) => ({\n default: m.TanStackDocumentSync,\n }))\n ),\n // Add other frameworks here:\n // nextjs: lazy(() => import('../nextjs/document-sync').then(m => ({ default: m.NextjsDocumentSync }))),\n};\n\n/**\n * Register a framework-specific document sync component.\n * Convenience function for adding new frameworks to the registry.\n */\nexport function registerDocumentSync(framework: string, component: LazyExoticComponent<FC>): void {\n routeDocumentSyncs[framework] = component;\n}\n","import { useTranslation } from '../providers/I18nProvider';\n\ntype DateFormat = 'full' | 'long' | 'medium' | 'short' | 'time';\n\nexport type DateInput =\n | string\n | number\n | Date\n | { date: string; timezone_type: number; timezone: string }\n | undefined;\n\nfunction normalizeDate(input: DateInput): Date {\n if (!input) return new Date();\n if (input instanceof Date) return input;\n if (typeof input === 'number') return new Date(input);\n if (typeof input === 'object' && 'date' in input) return new Date(input.date);\n return new Date(input);\n}\n\nexport interface UseDateResult {\n format: (date: DateInput, formatType?: DateFormat) => string;\n ago: (date: DateInput) => string;\n now: Date;\n}\n\n/**\n * useDate - Hook for formatting dates\n *\n * @example\n * const { format, ago, now } = useDate();\n * format('2024-03-15') // 'March 15, 2024'\n * format('2024-03-15', 'full') // 'Friday, March 15, 2024'\n * ago(Date.now() - 3600000) // '1 hour ago'\n * now // current Date object\n */\nexport function useDate(): UseDateResult {\n const { locale } = useTranslation();\n\n const format = (date: DateInput, formatType: DateFormat = 'medium'): string => {\n const dateObj = normalizeDate(date);\n\n const formatOptionsMap: Record<DateFormat, Intl.DateTimeFormatOptions> = {\n full: { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' },\n long: { year: 'numeric', month: 'long', day: 'numeric' },\n medium: { year: 'numeric', month: 'long', day: 'numeric' },\n short: { year: 'numeric', month: 'short', day: 'numeric' },\n time: { hour: '2-digit', minute: '2-digit' },\n };\n\n try {\n return new Intl.DateTimeFormat(locale, formatOptionsMap[formatType]).format(dateObj);\n } catch {\n return dateObj.toLocaleDateString(locale);\n }\n };\n\n const ago = (date: DateInput): string => {\n const dateObj = normalizeDate(date);\n const diffInSeconds = Math.floor((Date.now() - dateObj.getTime()) / 1000);\n\n const units: Array<{ unit: Intl.RelativeTimeFormatUnit; threshold: number; divisor: number }> =\n [\n { unit: 'year', threshold: 31536000, divisor: 31536000 },\n { unit: 'month', threshold: 2592000, divisor: 2592000 },\n { unit: 'week', threshold: 604800, divisor: 604800 },\n { unit: 'day', threshold: 86400, divisor: 86400 },\n { unit: 'hour', threshold: 3600, divisor: 3600 },\n { unit: 'minute', threshold: 60, divisor: 60 },\n { unit: 'second', threshold: 1, divisor: 1 },\n ];\n\n for (const { unit, threshold, divisor } of units) {\n if (diffInSeconds >= threshold) {\n const value = Math.floor(diffInSeconds / divisor);\n try {\n return new Intl.RelativeTimeFormat(locale, { numeric: 'auto', style: 'long' }).format(\n -value,\n unit\n );\n } catch {\n return new Intl.RelativeTimeFormat('en', { numeric: 'auto' }).format(-value, unit);\n }\n }\n }\n\n return locale.startsWith('ar') ? 'الآن' : 'just now';\n };\n\n return { format, ago, now: new Date() };\n}\n","import { useTwilight } from '../providers/TwilightProvider';\n\nconst ARABIC_NUMERALS = ['٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩'];\n\nconst toArabic = (input: number | string): string => {\n const str = String(input);\n return str.replace(/[0-9]/g, (d) => ARABIC_NUMERALS[parseInt(d)]);\n};\n\n/**\n * UseNumberResult - Return type for useNumber hook\n */\nexport interface UseNumberResult {\n /** Format number with store settings */\n format: (number: number | string) => string;\n /** Convert to Arabic numerals */\n toArabic: (input: number | string) => string;\n /** Whether Arabic numerals are enabled */\n useArabicNumerals: boolean;\n}\n\n/**\n * useNumber - Hook for number formatting\n *\n * @returns Object with number formatting utilities\n *\n * @example\n * const { format, toArabic, useArabicNumerals } = useNumber();\n * format(1234) // '١٢٣٤' if arabic numbers enabled, else '1234'\n * toArabic(1234) // '١٢٣٤'\n * useArabicNumerals // boolean from store settings\n */\nexport function useNumber(): UseNumberResult {\n const { store } = useTwilight();\n const useArabicNumerals = store?.settings?.arabic_numbers_enabled ?? false;\n\n const format = (number: number | string): string => {\n return useArabicNumerals ? toArabic(number) : String(number);\n };\n\n return {\n /** Format number with store settings */\n format,\n /** Convert to Arabic numerals */\n toArabic,\n /** Whether Arabic numerals are enabled */\n useArabicNumerals,\n };\n}\n","import { useTwilight } from '../providers/TwilightProvider';\nimport { useTranslation } from '../providers/I18nProvider';\nimport React from 'react';\n\nconst AR_LOCALE = 'ar';\nconst SAR_CURRENCY = 'SAR';\n\nconst intlCache = new Map<string, Intl.NumberFormat>();\nfunction getCachedIntl(loc: string, opts: Intl.NumberFormatOptions): Intl.NumberFormat {\n const key = `${loc}|${JSON.stringify(opts)}`;\n let fmt = intlCache.get(key);\n if (!fmt) {\n fmt = new Intl.NumberFormat(loc, opts);\n intlCache.set(key, fmt);\n }\n return fmt;\n}\n\n/**\n * Parse a money string to a number.\n *\n * Locale-agnostic by design: normalises both Western (`,.`) and\n * Arabic-Indic (`٬`, `٫`) separators using fixed rules. Do NOT add\n * locale-dependent separator logic here — if per-locale rules are\n * ever needed, refactor back into the hook body where `locale`\n * is available.\n */\nconst parse = (moneyString: string): number => {\n const cleaned = moneyString.replace(/[^\\d.,٬٫]/g, '');\n const normalized = cleaned.replace(/٬/g, '').replace(/٫/g, '.');\n const parts = normalized.split(/[.,]/);\n if (parts.length > 2) {\n return parseFloat(`${parts.slice(0, -1).join('')}.${parts[parts.length - 1]}`);\n }\n return parseFloat(normalized.replace(/,/g, ''));\n};\n\n/**\n * Check if a value is a valid monetary amount.\n *\n * Locale-agnostic: accepts numbers and numeric strings only.\n */\nconst isValid = (value: unknown): boolean => {\n if (typeof value === 'number' && !isNaN(value) && isFinite(value)) return true;\n if (typeof value === 'string') {\n const parsed = parseFloat(value);\n return !isNaN(parsed) && isFinite(parsed);\n }\n return false;\n};\n\n/**\n * UseMoneyResult - Return type for useMoney hook\n */\nexport interface UseMoneyResult {\n /** Format amount with currency */\n format: (\n amount: number | string | undefined,\n options?: { currency?: string; locale?: string; type?: 'product' | 'general' }\n ) => React.ReactNode;\n /** Parse money string to number */\n parse: (moneyString: string) => number;\n /** Check if value is valid monetary amount */\n isValid: (value: unknown) => boolean;\n}\n\n/**\n * useMoney - Hook for formatting monetary values\n *\n * @example\n * const { format, parse, isValid } = useMoney();\n * // Render price (SAR shows with icon):\n * <span>{format(100)}</span> // '100.00' with <i className=\"sicon-sar\" />\n */\nexport function useMoney(): UseMoneyResult {\n const { store } = useTwilight();\n const { locale } = useTranslation();\n const useArabicNumerals = store?.settings?.arabic_numbers_enabled ?? false;\n\n const format = (\n amount: number | string | undefined,\n options?: { currency?: string; locale?: string; type?: 'product' | 'general' }\n ): React.ReactNode => {\n const currency = options?.currency ?? 'SAR';\n const loc = options?.locale ?? locale;\n const type = options?.type ?? 'product'; // Default to 'product'\n\n // Handle undefined or null case\n if (amount == null || amount === '') {\n const showDash = type === 'product' ? store?.settings?.product?.show_price_as_dash : false; // General type defaults to not showing dash\n\n return showDash ? '-' : '';\n }\n\n const numericAmount = typeof amount === 'string' ? parseFloat(amount) : amount;\n\n if (typeof amount === 'string' && amount === '-') return amount;\n if (isNaN(numericAmount)) return String(amount);\n\n // Handle zero amounts with dash based on settings\n if (!numericAmount && numericAmount !== 0) {\n // This covers cases where amount evaluates to falsy but isn't explicitly 0\n const showDash = type === 'product' ? store?.settings?.product?.show_price_as_dash : false; // General type defaults to not showing dash\n\n return showDash ? '-' : '';\n }\n\n let formatted = getCachedIntl(loc, {\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }).format(numericAmount);\n\n // Apply Arabic numerals if enabled\n if (useArabicNumerals && loc.startsWith(AR_LOCALE)) {\n formatted = formatted.replace(/[0-9]/g, (d) => '٠١٢٣٤٥٦٧٨٩'[parseInt(d)]);\n }\n\n // For SAR, return with icon element\n if (currency === SAR_CURRENCY) {\n return (\n <>\n {formatted} <i className=\"sicon-sar\" />\n </>\n );\n }\n\n // For non-SAR currencies, try standard currency formatting\n try {\n return getCachedIntl(loc, {\n style: 'currency',\n currency,\n minimumFractionDigits: 2,\n maximumFractionDigits: 2,\n }).format(numericAmount);\n } catch {\n return `${formatted} ${currency}`;\n }\n };\n\n return { format, parse, isValid };\n}\n","import { useCallback } from 'react';\nimport type { Product, Cart, CartItem } from '../types';\nimport { useTwilight } from '../providers/TwilightProvider';\nimport { useUser } from './useUser';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface UseGtmResult {\n /** Check if GTM is enabled */\n enabled: boolean;\n /** Raw push to dataLayer */\n push: (data: Record<string, unknown>) => void;\n /** Track page view */\n viewPage: (pageType: string) => void;\n /** Track product detail view */\n detail: (product: Product) => void;\n /** Track product impressions (listing) */\n impressions: (products: Product[], list?: string) => void;\n /** Track product click */\n click: (product: Product, list?: string, position?: number) => void;\n /** Track add to cart */\n add: (product: Product, quantity?: number) => void;\n /** Track remove from cart */\n remove: (item: CartItem) => void;\n /** Track checkout */\n checkout: (cart: Cart, step?: number) => void;\n /** Track purchase */\n purchase: (orderId: string | number, cart: Cart) => void;\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\n/** Generate unique event ID */\nfunction eventId(prefix: string): string {\n return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;\n}\n\n/** Convert Product to GTM format */\nfunction toProduct(product: Product, overrides?: Record<string, unknown>): Record<string, unknown> {\n return {\n id: product.id,\n name: product.name,\n price: product.sale_price,\n brand: product.brand?.name,\n category: product.category?.name,\n quantity: 1,\n ...overrides,\n };\n}\n\n/** Get currency from product or fallback */\nfunction getCurrency(product?: Product, fallback = 'SAR'): string {\n return product?.currency ?? fallback;\n}\n\n// ============================================================================\n// Hook Implementation\n// ============================================================================\n\n/**\n * useGtm - Google Tag Manager hook for tracking events\n *\n * @example\n * ```tsx\n * function ProductPage({ product }) {\n * const gtm = useGtm();\n *\n * useEffect(() => { gtm.detail(product); }, [product.id]);\n * return <button onClick={() => gtm.add(product)}>Add to Cart</button>;\n * }\n * ```\n */\nexport function useGtm(): UseGtmResult {\n const { store } = useTwilight();\n const { data: user } = useUser();\n\n const gtmIds = store.settings?.keys?.gtm;\n const enabled = !!(gtmIds && gtmIds.length > 0);\n const currency = user?.preferences?.currency_code ?? 'SAR';\n\n const push = useCallback(\n (data: Record<string, unknown>) => {\n if (!enabled) return;\n window.dataLayer = window.dataLayer || [];\n window.dataLayer.push(data);\n },\n [enabled]\n );\n\n const viewPage = useCallback((pageType: string) => push({ event: 'viewPage', pageType }), [push]);\n\n const detail = useCallback(\n (product: Product) =>\n push({\n event: 'detail',\n ecommerce: {\n currencyCode: getCurrency(product, currency),\n event_id: eventId('detail'),\n detail: { products: [toProduct(product)] },\n },\n }),\n [push, currency]\n );\n\n const impressions = useCallback(\n (products: Product[], list?: string) => {\n if (products.length === 0) return;\n push({\n event: 'impressions',\n ecommerce: {\n currencyCode: getCurrency(products[0], currency),\n event_id: eventId('impressions'),\n impressions: {\n products: products.map((p, i) => toProduct(p, { position: i + 1, list })),\n },\n },\n });\n },\n [push, currency]\n );\n\n const click = useCallback(\n (product: Product, list?: string, position?: number) =>\n push({\n event: 'click',\n ecommerce: {\n currencyCode: getCurrency(product, currency),\n event_id: eventId('click'),\n click: {\n actionField: { list },\n products: [toProduct(product, { position, list })],\n },\n },\n }),\n [push, currency]\n );\n\n const add = useCallback(\n (product: Product, quantity = 1) =>\n push({\n event: 'addToCart',\n ecommerce: {\n currencyCode: getCurrency(product, currency),\n event_id: eventId('addToCart'),\n add: { products: [toProduct(product, { quantity })] },\n },\n }),\n [push, currency]\n );\n\n const remove = useCallback(\n (item: CartItem) =>\n push({\n event: 'removeFromCart',\n ecommerce: {\n currencyCode: currency,\n event_id: eventId('removeFromCart'),\n remove: {\n products: [\n {\n id: item.product_id,\n name: item.product_name,\n price: typeof item.price === 'number' ? item.price : item.price.amount,\n quantity: item.quantity,\n },\n ],\n },\n },\n }),\n [push, currency]\n );\n\n const checkout = useCallback(\n (cart: Cart, step = 1) =>\n push({\n event: 'checkout',\n ecommerce: {\n currencyCode: currency,\n event_id: eventId('checkout'),\n checkout: {\n actionField: { step, id: cart.id },\n products: cart.items.map((item) => ({\n id: item.product_id,\n name: item.product_name,\n price: typeof item.price === 'number' ? item.price : item.price.amount,\n quantity: item.quantity,\n })),\n },\n },\n }),\n [push, currency]\n );\n\n const purchase = useCallback(\n (orderId: string | number, cart: Cart) =>\n push({\n event: 'purchase',\n ecommerce: {\n currencyCode: currency,\n event_id: eventId('purchase'),\n purchase: {\n actionField: {\n id: orderId,\n revenue: cart.total,\n tax: cart.tax_amount,\n coupon: cart.coupon,\n },\n products: cart.items.map((item) => ({\n id: item.product_id,\n name: item.product_name,\n price: typeof item.price === 'number' ? item.price : item.price.amount,\n quantity: item.quantity,\n })),\n },\n },\n }),\n [push, currency]\n );\n\n return { enabled, push, viewPage, detail, impressions, click, add, remove, checkout, purchase };\n}\n","import { useMemo } from 'react';\nimport { useTranslation } from '../providers/I18nProvider';\nimport type { OpeningHoursSettings } from '../types';\n\ntype DayOfWeek = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday';\n\nconst DAYS: DayOfWeek[] = [\n 'monday',\n 'tuesday',\n 'wednesday',\n 'thursday',\n 'friday',\n 'saturday',\n 'sunday',\n];\n\nconst DAY_NAMES: Record<string, string> = {\n monday: 'common.days.monday',\n tuesday: 'common.days.tuesday',\n wednesday: 'common.days.wednesday',\n thursday: 'common.days.thursday',\n friday: 'common.days.friday',\n saturday: 'common.days.saturday',\n sunday: 'common.days.sunday',\n};\n\nconst TIME_NAMES: Record<string, string> = {\n AM: 'common.time.am',\n PM: 'common.time.pm',\n};\n\ninterface ParsedTimeRange {\n start: number; // minutes from midnight\n end: number; // minutes from midnight\n}\n\ninterface DaySchedule {\n ranges: ParsedTimeRange[];\n}\n\nexport interface UseOpeningHoursResult {\n /** Whether the store is currently open */\n isOpen: boolean;\n /** Whether opening hours feature is enabled and configured */\n isEnabled: boolean;\n /** Next opening time as Date object, null if currently open or not configured */\n nextOpen: Date | null;\n /** Formatted next opening time string, empty if currently open or not configured */\n nextOpenFormatted: string;\n}\n\n/**\n * Parse a time string like \"09:00\" or \"9:00 AM\" to minutes from midnight.\n */\nfunction parseTime(timeStr: string): number {\n const cleaned = timeStr.trim().toLowerCase();\n const match = cleaned.match(/^(\\d{1,2}):(\\d{2})(?:\\s*(am|pm))?$/);\n\n if (!match) {\n return 0;\n }\n\n let hours = parseInt(match[1], 10);\n const minutes = parseInt(match[2], 10);\n const meridiem = match[3];\n\n if (meridiem === 'pm' && hours < 12) {\n hours += 12;\n } else if (meridiem === 'am' && hours === 12) {\n hours = 0;\n }\n\n return hours * 60 + minutes;\n}\n\n/**\n * Parse opening hours ranges for a day.\n * Input format: [\"09:00-12:00\", \"13:00-18:00\"] or [\"09:00 AM - 12:00 PM\"]\n */\nfunction parseRanges(ranges: string[]): ParsedTimeRange[] {\n return ranges\n .map((range) => {\n const parts = range.split('-').map((s) => s.trim());\n if (parts.length !== 2) return null;\n\n const start = parseTime(parts[0]);\n const end = parseTime(parts[1]);\n\n return { start, end };\n })\n .filter((r): r is ParsedTimeRange => r !== null && r.start < r.end);\n}\n\n/**\n * Convert day index (0 = Monday) to day name.\n */\nfunction indexToDay(index: number): DayOfWeek {\n return DAYS[index % 7];\n}\n\n/**\n * Get the day index for a date (0 = Monday, 6 = Sunday).\n */\nfunction getDayIndex(date: Date): number {\n const jsDay = date.getDay(); // 0 = Sunday, 1 = Monday, etc.\n return jsDay === 0 ? 6 : jsDay - 1; // Convert to 0 = Monday\n}\n\n/**\n * Get current time in minutes from midnight.\n */\nfunction getTimeInMinutes(date: Date): number {\n return date.getHours() * 60 + date.getMinutes();\n}\n\n/**\n * Check if the given time falls within any of the ranges.\n */\nfunction isInRanges(time: number, ranges: ParsedTimeRange[]): boolean {\n return ranges.some((range) => time >= range.start && time < range.end);\n}\n\n/**\n * Find the next time range that starts after the given time.\n */\nfunction findNextRange(time: number, ranges: ParsedTimeRange[]): ParsedTimeRange | null {\n const sorted = [...ranges].sort((a, b) => a.start - b.start);\n return sorted.find((range) => range.start > time) ?? null;\n}\n\n/**\n * useOpeningHours - Hook for checking store opening status and next open time.\n *\n * @param settings - Opening hours settings from the store\n * @returns Opening status information\n *\n * @example\n * ```tsx\n * const { isOpen, nextOpenFormatted } = useOpeningHours(store.settings.opening_hours);\n *\n * if (!isOpen) {\n * return <div>Store closed. Opens at {nextOpenFormatted}</div>;\n * }\n * ```\n */\nexport function useOpeningHours(settings?: OpeningHoursSettings): UseOpeningHoursResult {\n const { t } = useTranslation();\n\n return useMemo(() => {\n if (!settings?.enabled || !settings?.hours) {\n return {\n isOpen: true, // Assume open if not configured\n isEnabled: false,\n nextOpen: null,\n nextOpenFormatted: '',\n };\n }\n\n const hours = settings.hours;\n const now = new Date();\n const currentDayIndex = getDayIndex(now);\n const currentTime = getTimeInMinutes(now);\n\n // Build schedule for all days\n const schedule: Record<DayOfWeek, DaySchedule> = {} as Record<DayOfWeek, DaySchedule>;\n for (const day of DAYS) {\n const dayRanges = hours[day];\n schedule[day] = {\n ranges: dayRanges ? parseRanges(dayRanges) : [],\n };\n }\n\n // Check if currently open\n const todaySchedule = schedule[indexToDay(currentDayIndex)];\n if (isInRanges(currentTime, todaySchedule.ranges)) {\n return {\n isOpen: true,\n isEnabled: true,\n nextOpen: null,\n nextOpenFormatted: '',\n };\n }\n\n // Find next open time\n // Check remaining ranges today\n const nextRangeToday = findNextRange(currentTime, todaySchedule.ranges);\n if (nextRangeToday) {\n const nextOpen = new Date(now);\n nextOpen.setHours(Math.floor(nextRangeToday.start / 60), nextRangeToday.start % 60, 0, 0);\n\n return {\n isOpen: false,\n isEnabled: true,\n nextOpen,\n nextOpenFormatted: formatNextOpen(nextOpen, t),\n };\n }\n\n // Check subsequent days (up to 7 days ahead)\n for (let i = 1; i <= 7; i++) {\n const nextDayIndex = (currentDayIndex + i) % 7;\n const nextDayName = indexToDay(nextDayIndex);\n const nextDaySchedule = schedule[nextDayName];\n\n if (nextDaySchedule.ranges.length > 0) {\n // Get the first range of that day\n const firstRange = [...nextDaySchedule.ranges].sort((a, b) => a.start - b.start)[0];\n\n const nextOpen = new Date(now);\n nextOpen.setDate(nextOpen.getDate() + i);\n nextOpen.setHours(Math.floor(firstRange.start / 60), firstRange.start % 60, 0, 0);\n\n return {\n isOpen: false,\n isEnabled: true,\n nextOpen,\n nextOpenFormatted: formatNextOpen(nextOpen, t),\n };\n }\n }\n\n // No opening hours found in the next week - assume open\n return {\n isOpen: true,\n isEnabled: true,\n nextOpen: null,\n nextOpenFormatted: '',\n };\n }, [settings, t]);\n}\n\n/**\n * Format the next open time similar to the PHP widget.\n * Output: \"Sunday 09:00 AM\" (translated)\n */\nfunction formatNextOpen(date: Date, t: (key: string) => string): string {\n const dayName = t(DAY_NAMES[indexToDay(getDayIndex(date))]);\n const hours = date.getHours();\n const minutes = date.getMinutes().toString().padStart(2, '0');\n const isPM = hours >= 12;\n const displayHours = hours > 12 ? hours - 12 : hours === 0 ? 12 : hours;\n const meridiem = t(TIME_NAMES[isPM ? 'PM' : 'AM']);\n\n return `${dayName} ${displayHours}:${minutes} ${meridiem}`;\n}\n","import { useEffect, useRef } from 'react';\n\n/**\n * Page config data structure for salla.config.set('page', ...)\n */\nexport interface PageConfigData {\n slug: string;\n id?: string | number;\n title: string;\n /** Optional - defaults to current location pathname + search */\n url?: string;\n parent?: { id: string | number; name: string; url: string } | null;\n}\n\n/**\n * usePageConfig - Centralized hook for setting salla.config.page\n *\n * Replaces scattered salla?.config?.set('page', ...) calls across multiple pages.\n * Handles optional salla object safely.\n * Automatically uses current URL from router context if url not provided.\n *\n * @param pageData - Page configuration data to set\n *\n * @example\n * ```tsx\n * // URL is auto-detected from router context\n * usePageConfig({\n * slug: 'product.index',\n * id: categoryId,\n * title: category.name,\n * });\n *\n * // With explicit URL override\n * usePageConfig({\n * slug: 'product.index',\n * id: categoryId,\n * title: category.name,\n * url: '/custom-url',\n * });\n * ```\n */\nexport function usePageConfig(pageData: PageConfigData): void {\n const pageDataRef = useRef(pageData);\n pageDataRef.current = pageData;\n\n useEffect(() => {\n const salla = window.salla;\n if (!salla?.config?.set) {\n if (process.env.NODE_ENV === 'development') {\n console.warn('[usePageConfig] salla.config.set not available. Page config not set.');\n }\n return;\n }\n\n const current = pageDataRef.current;\n const url = current.url ?? window.location.pathname + window.location.search;\n\n salla.config.set('page', {\n ...current,\n url,\n });\n }, []);\n}\n","import type { Breadcrumb } from '../types';\n\nconst BREADCRUMB_REFERRER_KEY = 'breadcrumb-referrer';\n\nexport function getBreadcrumbReferrer(): Breadcrumb | null {\n try {\n const raw = sessionStorage.getItem(BREADCRUMB_REFERRER_KEY);\n if (!raw) return null;\n const { name, url } = JSON.parse(raw);\n return typeof name === 'string' && typeof url === 'string' ? { name, url } : null;\n } catch {\n return null;\n }\n}\n\nexport function setBreadcrumbReferrer(breadcrumb: Breadcrumb): void {\n try {\n sessionStorage.setItem(BREADCRUMB_REFERRER_KEY, JSON.stringify(breadcrumb));\n } catch {\n // sessionStorage unavailable (private browsing quota, etc.)\n }\n}\n","import { useMemo, useEffect, useState } from 'react';\nimport { useLocation, useIsHome } from '../providers/NavigationProvider';\nimport { useTranslation } from '../providers/I18nProvider';\nimport { getBreadcrumbReferrer, setBreadcrumbReferrer } from '../utils/breadcrumb';\nimport type { Breadcrumb, Page } from '../types';\n\nexport function useBreadcrumbs(page?: Page | null): Breadcrumb[] {\n const location = useLocation();\n const isHome = useIsHome();\n const { t } = useTranslation();\n\n const [referrerCrumb, setReferrerCrumb] = useState<Breadcrumb | null>(null);\n\n useEffect(() => {\n if (page?.slug === 'product.single') {\n const ref = getBreadcrumbReferrer();\n if (ref) setReferrerCrumb(ref);\n return;\n }\n\n setReferrerCrumb(null);\n\n if (!isHome && page) {\n setBreadcrumbReferrer({ name: page.title, url: location.pathname + location.searchStr });\n }\n }, [page, isHome, location.pathname, location.searchStr]);\n\n return useMemo(() => {\n if (!page) return [];\n\n if (page.breadcrumbs?.length) {\n if (page.slug === 'product.single' && referrerCrumb) {\n const last = page.breadcrumbs.at(-1);\n return last ? [page.breadcrumbs[0], referrerCrumb, last] : page.breadcrumbs;\n }\n return page.breadcrumbs;\n }\n\n if (isHome) return [];\n\n const home: Breadcrumb = { name: t('common.titles.home'), url: '/' };\n return [home, { name: page.title, url: location.pathname }];\n }, [isHome, location.pathname, page, t, referrerCrumb]);\n}\n","/**\n * Auto-registered default hooks for tracking/notification components.\n *\n * This module is imported automatically by hooks/index.ts to register\n * default handlers for body:start and body:end hooks.\n *\n * All handlers check conditions at render time via twilight context,\n * so they work without any setup from theme-custom.\n */\n\nimport React, { lazy, Suspense } from 'react';\nimport { hookRegistry } from './HookRegistry';\nimport { HookName } from '../types/hooks';\nimport type { HookContext } from './HookSlot';\nimport { useUser } from './useUser';\nimport { FAST_CHECKOUT_SCRIPT_ID, FAST_CHECKOUT_SCRIPT_URL } from '../utils/fast-checkout';\n\n// Lazy load tracking/notification components from theme-engine\nconst GoogleTagBody = lazy(() =>\n import('../components/tracking/GoogleTag').then((m) => ({ default: m.GoogleTagBody }))\n);\n\nconst TwilightBundles = lazy(() =>\n import('../components/tracking/TwilightBundles').then((m) => ({ default: m.TwilightBundles }))\n);\n\nconst LazySiftSnippet = lazy(() =>\n import('../components/tracking/SiftSnippet').then((m) => ({ default: m.SiftSnippet }))\n);\n\nconst LazyStoreClosedNotification = lazy(() =>\n import('../components/store/StoreClosedNotification').then((m) => ({\n default: m.StoreClosedNotification,\n }))\n);\n\n// Lazy load cart widget components\nconst LazyPriceQuoteButton = lazy(() =>\n import('../components/cart/PriceQuoteButton').then((m) => ({ default: m.PriceQuoteButton }))\n);\n\nconst LazyPreOrderNotification = lazy(() =>\n import('../components/cart/PreOrderNotification').then((m) => ({\n default: m.PreOrderNotification,\n }))\n);\n\n/**\n * GTM handler - renders GoogleTagBody if store has GTM keys configured.\n */\nfunction gtmHandler({ twilight }: HookContext): React.ReactNode {\n if (!twilight?.store?.settings?.keys?.gtm?.length) {\n return null;\n }\n\n return (\n <Suspense fallback={null}>\n <GoogleTagBody gtmIds={twilight.store.settings.keys.gtm} />\n </Suspense>\n );\n}\n\n/**\n * Sift handler - renders SiftSnippet if store has sift key configured.\n */\nfunction useSiftHandler({ twilight }: HookContext): React.ReactNode {\n const { data: user } = useUser();\n\n if (!twilight?.store?.settings?.keys?.sift) {\n return null;\n }\n\n const customerId = user?.type === 'user' && user.id ? String(user.id) : '';\n\n return (\n <Suspense fallback={null}>\n <LazySiftSnippet beaconKey={twilight.store.settings.keys.sift} customerId={customerId} />\n </Suspense>\n );\n}\n\n/**\n * Store closed notification handler - renders if opening hours feature is enabled.\n */\nfunction storeClosedHandler({ twilight }: HookContext): React.ReactNode {\n if (!twilight?.store?.settings?.opening_hours?.enabled) {\n return null;\n }\n\n return (\n <Suspense fallback={null}>\n <LazyStoreClosedNotification />\n </Suspense>\n );\n}\n\n/**\n * Fast checkout handler - keeps the `#fast-checkout-js` tag in the DOM when quick purchase\n * (`store.settings.buy_now`) is on. The head copy loads it early, but TanStack drops head\n * scripts after hydration, and `salla-add-product-button` checks for the tag by id at render.\n */\nfunction fastCheckoutHandler({ twilight }: HookContext): React.ReactNode {\n if (!twilight?.store?.settings?.buy_now) {\n return null;\n }\n\n return <script id={FAST_CHECKOUT_SCRIPT_ID} type=\"module\" src={FAST_CHECKOUT_SCRIPT_URL} />;\n}\n\n/**\n * Twilight bundles handler - always renders (core tracking).\n */\nfunction bundlesHandler(): React.ReactNode {\n return (\n <Suspense fallback={null}>\n <TwilightBundles />\n </Suspense>\n );\n}\n\n/**\n * Price quote handler - renders if price-quote feature is enabled.\n * Twig: PriceQuoteWidget - checks feature('price-quote')->isAccessibleForCustomers()\n */\nfunction priceQuoteHandler({ twilight }: HookContext): React.ReactNode {\n // TODO: support price_quote in store settings API response\n if (!twilight?.store?.settings?.features?.price_quote) {\n return null;\n }\n\n return (\n <Suspense fallback={null}>\n <LazyPriceQuoteButton />\n </Suspense>\n );\n}\n\n/**\n * Pre-order notification handler - renders if cart has items with active pre-order campaigns.\n * Twig: PreOrderNotificationWidget - checks cart items for getHasActivePreorderCampaign()\n */\nfunction preOrderNotificationHandler({ twilight, cartItems }: HookContext): React.ReactNode {\n if (!twilight?.store?.settings?.features?.['pre-order-campaigns']) {\n return null;\n }\n\n const items = cartItems as\n Array<{ has_pre_order_campaign?: boolean; parent_id?: unknown }> | undefined;\n const hasPreOrder = items?.some((item) => !item.parent_id && item.has_pre_order_campaign);\n\n if (!hasPreOrder) {\n return null;\n }\n\n return (\n <Suspense fallback={null}>\n <LazyPreOrderNotification />\n </Suspense>\n );\n}\n\n/**\n * Register all default hooks from theme-engine.\n * Called automatically on module import.\n *\n * Note: theme-custom can register additional handlers like AddProductToast.\n */\nfunction registerDefaultHooks(): void {\n // Body start hooks (tracking, notifications)\n hookRegistry.register(HookName.BODY_START, gtmHandler, 100);\n hookRegistry.register(HookName.BODY_START, useSiftHandler, 90);\n hookRegistry.register(HookName.BODY_START, storeClosedHandler, 80);\n\n // Body end hooks (bundles)\n hookRegistry.register(HookName.BODY_END, bundlesHandler, 100);\n hookRegistry.register(HookName.BODY_END, fastCheckoutHandler, 90);\n\n // Cart hooks\n hookRegistry.register('cart:submit.start', priceQuoteHandler, 100);\n hookRegistry.register('cart:items.start', preOrderNotificationHandler, 100);\n}\n\n// Auto-register on module load\nregisterDefaultHooks();\n\nexport { registerDefaultHooks };\n","import { useState } from 'react';\nimport { SallaAppsIcons } from '@salla.sa/twilight-components-react/apps-icons';\nimport { SallaContacts } from '@salla.sa/twilight-components-react/contacts';\nimport { SallaMenu } from '@salla.sa/twilight-components-react/menu';\nimport { SallaPayments } from '@salla.sa/twilight-components-react/payments';\nimport { SallaSocial } from '@salla.sa/twilight-components-react/social';\nimport { SallaTrustBadges } from '@salla.sa/twilight-components-react/trust-badges';\nimport { useTranslation } from '../../providers/I18nProvider';\nimport { HookSlot } from '../../hooks/HookSlot';\nimport { Copyright } from './Copyright';\nimport { useTwilight } from '../../providers/twilight-context';\nimport { Link, Image } from '../common';\nimport { ImageModal } from '../../components/modal';\nimport { useAsset } from '../../hooks';\n\nexport function Footer() {\n const { store, theme } = useTwilight();\n const { cdn } = useAsset();\n const { t } = useTranslation();\n const [isTaxModalOpen, setIsTaxModalOpen] = useState(false);\n const [taxImageSrc, setTaxImageSrc] = useState('');\n\n const handleTaxImageClick = (event: React.MouseEvent<HTMLAnchorElement>) => {\n event.preventDefault();\n const modalId = event.currentTarget.dataset.modalId;\n const modal = document.getElementById(modalId || '');\n const img = modal?.querySelector('img');\n const imgSrc = img?.dataset.src;\n\n if (imgSrc) {\n setTaxImageSrc(imgSrc);\n setIsTaxModalOpen(true);\n }\n };\n\n return (\n <footer className=\"store-footer\" suppressHydrationWarning>\n <HookSlot name=\"footer:start\" />\n <div aria-label=\"footer\" className=\"store-footer__inner\">\n <div className=\"container grid grid-cols-1 lg:grid-cols-6 gap-8 lg:gap-6\">\n {/* Store Info */}\n <div className=\"lg:col-span-2 rtl:lg:pl-20 ltr:lg:pr-20\">\n <Link to=\"/\" className=\"flex items-center m-0\">\n <h3>{store.name}</h3>\n </Link>\n {store.description && (\n <div\n className=\"max-w-sm leading-6 mb-6\"\n dangerouslySetInnerHTML={{ __html: store.description }}\n />\n )}\n\n <div className=\"hidden lg:block\">\n <SallaSocial className=\"block mb-6\" />\n </div>\n\n <div className=\"flex gap-4\">\n <SallaTrustBadges {...(theme.settings?.footer_is_dark ? { dark: true } : {})} />\n\n {store.settings?.tax?.number && (\n <div className=\"flex rtl:space-x-reverse space-x-2 items-end\">\n {store.settings?.tax?.certificate && (\n <a\n data-modal-id=\"modal-value-tax\"\n href=\"#/\"\n aria-label={store.settings?.tax?.number}\n onClick={handleTaxImageClick}\n >\n <img\n width={40}\n height={40}\n src={cdn('/images/placeholder.png')}\n className=\"w-10 rounded-sm hover:opacity-80 transition-opacity\"\n alt=\"value added tax\"\n loading=\"lazy\"\n decoding=\"async\"\n />\n </a>\n )}\n <div>\n <p className=\"text-sm text-text-grey mb-1\">\n {t('common.elements.tax_number', 'Tax Number')}\n </p>\n <b className=\"text-sm\">{store.settings?.tax?.number}</b>\n </div>\n </div>\n )}\n </div>\n </div>\n\n {/* Footer Links */}\n <div>\n <h3>{t('blocks.footer.pages_links', 'Important Links')}</h3>\n <SallaMenu source=\"footer\" />\n </div>\n\n {/* Contact Info */}\n <div>\n <SallaContacts\n contacts={store.contacts}\n contactsTitle={t('blocks.footer.social', 'Stay in touch')}\n />\n\n <div className=\"lg:hidden contact-social\">\n <SallaSocial />\n </div>\n </div>\n\n {/* App Icons */}\n <SallaAppsIcons\n apps={store.apps}\n appsTitle={t('blocks.footer.download_apps', 'Get our apps')}\n className=\"lg:col-span-2 rtl:lg:pr-20 ltr:lg:pl-20\"\n />\n </div>\n </div>\n\n {/* Copyright */}\n <div className=\"md:flex items-center justify-between py-4 container text-center\">\n <span className=\"text-sm copyright-text\">\n <HookSlot\n name=\"copyright\"\n context={{ storeName: store.name }}\n fallback={<Copyright storeName={store.name} />}\n />\n </span>\n <SallaPayments />\n </div>\n\n {/* Hidden modal content for data extraction */}\n <div id=\"modal-value-tax\" className=\"hidden\">\n <Image src={store.settings?.tax?.certificate || undefined} alt=\"Tax Certificate\" />\n </div>\n\n {/* Image Modal */}\n <ImageModal\n isOpen={isTaxModalOpen}\n onClose={() => setIsTaxModalOpen(false)}\n src={taxImageSrc}\n alt=\"Tax Certificate\"\n title={t('common.elements.tax_certificate', 'Tax Certificate')}\n />\n <HookSlot name=\"footer:end\" />\n </footer>\n );\n}\n","import { lazy, Suspense } from 'react';\nimport { Header } from './Header';\nimport { Footer } from './Footer';\nimport type { LayoutProps } from '../../types';\nimport { useTwilight } from '../../providers/twilight-context';\nimport { useUser } from '../../hooks';\n\nconst SallaLoginModal = lazy(() =>\n import('@salla.sa/twilight-components-react/login-modal').then((m) => ({\n default: m.SallaLoginModal,\n }))\n);\nconst SallaScopes = lazy(() =>\n import('@salla.sa/twilight-components-react/scopes').then((m) => ({\n default: m.SallaScopes,\n }))\n);\nconst SallaOfferModal = lazy(() =>\n import('@salla.sa/twilight-components-react/offer-modal').then((m) => ({\n default: m.SallaOfferModal,\n }))\n);\n\nexport function MasterLayout({ children }: LayoutProps) {\n const { store } = useTwilight();\n const { isLoggedIn } = useUser();\n\n return (\n <>\n <div className=\"app-inner flex flex-col min-h-full\">\n <Header />\n <main id=\"main-content\" role=\"main\" className=\"flex-1\">\n {children}\n </main>\n <Footer />\n </div>\n\n <Suspense>\n <SallaOfferModal />\n </Suspense>\n\n {!isLoggedIn && (\n <Suspense>\n <SallaLoginModal\n isEmailAllowed={store?.settings?.auth?.email_allowed}\n isMobileAllowed={store?.settings?.auth?.mobile_allowed}\n isEmailRequired={store?.settings?.auth?.is_email_required}\n suppressHydrationWarning\n />\n </Suspense>\n )}\n\n {store?.scope && (\n <Suspense>\n <SallaScopes\n selection={store?.scope?.display_as === 'popup' ? 'mandatory' : 'optional'}\n suppressHydrationWarning\n />\n </Suspense>\n )}\n </>\n );\n}\n","import { useEffect, useMemo } from 'react';\nimport { useQuery } from '@tanstack/react-query';\nimport { apps, type AppSnippetRow } from '../../api/apps';\nimport { installAppScope } from '../../utils/app-scope';\nimport { applyThemeHookSlots } from '../../utils/theme-hook-slots';\nimport { getTwilightContext } from '../../twilight/context';\n\n/** How long to wait on the SDK / settings before injecting anyway. */\nconst READY_TIMEOUT_MS = 2500;\n\n// Module-level so StrictMode double-effects and remounts can't inject twice per page load.\nlet injected = false;\n\n/** A snippet plus its app's scope id — the key that resolves its config bucket. */\ntype OwnedSnippet = AppSnippetRow & { appScopeId: string };\n\n/**\n * Appends raw snippet HTML to `target`, recreating each `<script>` — innerHTML-parsed\n * scripts are flagged \"already started\" and never run.\n */\nexport function injectHtml(html: string, target: HTMLElement) {\n const tpl = document.createElement('template');\n tpl.innerHTML = html;\n tpl.content.querySelectorAll('script').forEach((inert) => {\n // importmap scripts can't be added post-init; the engine already injects its own.\n if (inert.type === 'importmap') {\n inert.remove();\n return;\n }\n const script = document.createElement('script');\n for (const attr of Array.from(inert.attributes)) {\n script.setAttribute(attr.name, attr.value);\n }\n script.text = inert.text;\n inert.replaceWith(script);\n });\n target.appendChild(tpl.content);\n}\n\n/**\n * Replaces `{{customer.x}}` placeholders with SDK config `user.*` values. Non-`customer.`\n * params are left untouched, matching the classic themes.\n */\nexport function resolveCustomerParams(content: string, params?: string[]): string {\n if (!params?.length) return content;\n for (const param of params) {\n if (!param.startsWith('customer.')) continue;\n const value = String(window.salla?.config.get(param.replace(/^customer\\./, 'user.')) ?? '');\n // Tolerate inner whitespace (`{{ customer.email }}`); function replacement keeps `value`\n // literal so a `$&` in customer data isn't expanded.\n const escaped = param.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const placeholder = new RegExp(`\\\\{\\\\{\\\\s*${escaped}\\\\s*\\\\}\\\\}`, 'g');\n content = content.replace(placeholder, () => value);\n }\n return content;\n}\n\n/** Resolves after `ms`, so a promise that may never settle can't block injection. */\nconst timeout = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * `onReady` hangs forever if the SDK never initializes; race a timeout so a broken SDK\n * degrades to unsubstituted placeholders instead of dropping every snippet.\n */\nconst waitForSdk = (): Promise<unknown> => {\n const ready = window.salla?.onReady();\n return ready ? Promise.race([ready, timeout(READY_TIMEOUT_MS)]) : Promise.resolve();\n};\n\n/**\n * Whitelists hook slots, installs the config sandbox, then injects the inline snippets.\n * Runs once per page load, after the SDK is ready.\n */\nfunction mountSnippets(\n owned: OwnedSnippet[],\n clientSnippets: OwnedSnippet[],\n buckets: Record<string, Record<string, unknown>>\n): void {\n // Backstop for the inline head copy (see renderThemeHookSlotsScript) — that one runs at\n // parse time, ahead of the snippet scripts; this only covers a head that didn't render.\n applyThemeHookSlots();\n\n // Install before any snippet resolves config. The inline SSR-head install normally got there\n // first (with these buckets, or with none when its prefetch failed), so this either installs\n // the factory or seeds the buckets into it. Pass the complete map once.\n installAppScope({ apps: buckets });\n\n // Flag every CDN scope with a missing bucket (SSR-rendered ones included).\n const unresolved = new Set<string>();\n for (const s of owned) {\n if (s.url && !(s.appScopeId in buckets)) unresolved.add(s.appScopeId);\n }\n\n for (const snippet of clientSnippets) {\n // Honour `place`: a head-placed snippet is often a <meta>/<link>/<style> (site\n // verification, canonical, preload) that crawlers only read inside <head>.\n const target = snippet.place?.includes('head') ? document.head : document.body;\n try {\n injectHtml(resolveCustomerParams(snippet.content, snippet.customer_parameters), target);\n } catch (error) {\n console.error(`[salla] failed to inject snippet for app ${snippet.appScopeId}`, error);\n }\n }\n\n if (unresolved.size) {\n // One line per page, not per snippet; expected during settings-endpoint rollout.\n console.warn(\n `[salla] app settings missing for ${unresolved.size} app(s); their snippets ran without app.* config`,\n [...unresolved]\n );\n }\n}\n\n/** A CDN snippet reduced to what its SSR `<script>` tag needs. */\ninterface SsrCdnScript {\n key: string;\n url: string;\n snippetId?: number;\n appScopeId: string;\n}\n\n/**\n * Mounts installed apps' snippets once per page load:\n * - **CDN** — rendered as SSR `<script>` tags in <body> (see return), so they exist on first\n * paint. `place` doesn't apply: they're deferred scripts, which run in order either way.\n * - **inline** — injected client-side in the effect, into `place`'s target (head or body).\n */\nexport function AppsSnippets() {\n // From twilight context, not useQuery: React Query isn't dehydrated here, so useQuery has no\n // SSR data — but the CDN <script> tags must render server-side.\n const ssrSnippets = getTwilightContext().appsSnippets;\n\n // Client fallback for when the SSR prefetch failed or timed out (it fails open, non-fatal).\n // Without it a single blip on `apps/snippets` would drop every installed app's snippets for\n // the whole page load — no CDN tags, no inline scripts, no hook slots. Retries here because\n // the query's own `retry: 0` exists only to bound the SSR wait.\n const { data: fallbackSnippets } = useQuery({\n ...apps.queries.snippets(),\n enabled: !ssrSnippets,\n retry: 2,\n });\n const data = ssrSnippets ?? fallbackSnippets;\n\n const { data: settings, isSuccess, isError } = useQuery({ ...apps.queries.settings(), retry: 2 });\n\n // Fail open: inject once settings settle either way, so snippets that never read `app.*`\n // aren't dropped when the bucket is empty.\n const settingsSettled = isSuccess || isError;\n\n // Each enabled app's snippets, tagged with its scope id (the encoded `id`). Older payloads\n // lacking `id` get a deterministic per-app fallback sharing one empty bucket.\n const owned = useMemo<OwnedSnippet[]>(\n () =>\n (data ?? [])\n .filter((app) => app.status === 'enabled')\n .flatMap((app) =>\n app.snippets.map((s) => ({ ...s, appScopeId: app.id ?? `unresolved-${app.app_id}` }))\n ),\n [data]\n );\n\n // Every CDN snippet → a real `<script>` tag in the SSR body (rendered below).\n const ssrCdnScripts = useMemo<SsrCdnScript[]>(\n () =>\n owned\n .filter((s) => s.url)\n .map((s, i) => ({\n key: `${s.appScopeId}:${s.id ?? i}`,\n url: s.url as string,\n snippetId: s.id,\n appScopeId: s.appScopeId,\n })),\n [owned]\n );\n\n useEffect(() => {\n if (injected || !data || !settingsSettled) return;\n injected = true;\n\n // Client-injected: inline snippets only. Every CDN snippet is SSR-rendered (below).\n const clientSnippets = owned.filter((s) => !s.url);\n\n // Always wait for the SDK: a snippet body calls the global `salla`/`Salla` (config, hooks,\n // event bus) whether or not it declares customer parameters, and those are only populated\n // after init. The wait is timeout-raced, so a broken SDK still can't strand injection.\n void waitForSdk().then(() => mountSnippets(owned, clientSnippets, settings?.apps ?? {}));\n }, [data, owned, settings, settingsSettled]);\n\n // CDN snippets as classic `defer` scripts: non-blocking, in-order, kept in <body> (React hoists\n // only `async` to <head>), and still exposing `document.currentScript` for the wrapper.\n return (\n <>\n {ssrCdnScripts.map((s) => (\n <script\n key={s.key}\n src={s.url}\n defer\n data-scope-id={s.appScopeId}\n data-snippet-id={s.snippetId != null ? String(s.snippetId) : ''}\n />\n ))}\n </>\n );\n}\n","import React, { useMemo, Suspense, useState, useEffect } from 'react';\nimport { WidgetHead } from '../components/layout/WidgetHead';\nimport { HookSlot } from '../hooks/HookSlot';\nimport { HookName } from '../types/hooks';\nimport { DocumentClassProvider } from './DocumentClassProvider';\nimport { TwilightContext } from './twilight-context';\nimport { ThemeDocumentSync } from './twilight-theme';\nimport { useTwilightInit } from './twilight-init';\nimport { I18nProvider, FALLBACK_LOCALE } from './I18nProvider';\nimport { NavigationInterceptor } from './NavigationProvider';\nimport { navigationSetups } from './navigation-setups';\nimport { routeDocumentSyncs } from './DocumentSyncRegistry';\nimport { MasterLayout } from '../components/layout/MasterLayout';\nimport { Toaster } from '../components/toast/Toaster';\nimport { AppsSnippets } from '../components/snippets/AppsSnippets';\nimport { getTwilightContext, updateTwilightContext } from '../twilight/context';\nimport { AUTH_TOKEN_COOKIE_NAME, clearAuthTokenCookie } from '../utils/cookies';\nimport type {\n TwilightContextValue,\n TwilightConfig,\n TwilightProviderProps,\n TwilightLog,\n} from '../types/twilight';\nimport type { StoreContext } from '../api/store';\n\nconst getSalla = () => (typeof window !== 'undefined' ? window.salla : undefined);\n\nconst TWILIGHT_LOG_STYLES = {\n header:\n 'background: linear-gradient(90deg, #7c3aed, #6366f1); color: white; padding: 4px 8px; border-radius: 4px; font-weight: bold;',\n error:\n 'background: #dc2626; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;',\n warn: 'background: #f59e0b; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;',\n info: 'background: #3b82f6; color: white; padding: 2px 6px; border-radius: 3px; font-weight: bold;',\n label: 'color: #7c3aed; font-weight: bold;',\n value: 'color: inherit;',\n};\n\nexport { useTwilight } from './twilight-context';\nexport type { TwilightProviderProps };\n\nexport function TwilightProvider({\n children,\n debug = false,\n skeleton,\n translations: themeTranslations,\n onReady,\n onError,\n client = { framework: 'tanstack', interceptLinks: true },\n toast = true,\n toastMobilePosition = 'bottom-center',\n addToCartToast = true,\n routeClass = true,\n layout: LayoutComponent = MasterLayout,\n}: TwilightProviderProps): React.ReactElement {\n const ctx = getTwilightContext();\n const initialLocale = ctx.locale || FALLBACK_LOCALE;\n let initialData: StoreContext | undefined;\n try {\n initialData = ctx.settings;\n } catch {\n // Settings not initialized yet — loading state\n }\n\n // Auth token state for React re-renders on login/logout\n const [authToken, setAuthToken] = useState<string | null>(() => {\n if (typeof window !== 'undefined') {\n return ctx.authToken ?? window.localStorage.getItem(AUTH_TOKEN_COOKIE_NAME);\n }\n return null;\n });\n\n // SDK auth event listeners\n useEffect(() => {\n if (typeof window === 'undefined') return;\n\n const sdk = getSalla();\n if (!sdk?.auth?.event) return;\n\n // Symmetric counterpart to handleTokenInvalid's clear below. path=/ + Lax so the\n // cookie is sent on the native webview's top-level navigation to /account/orders,\n // letting twilightMiddleware authenticate the SSR render — the SDK only stores the\n // token in localStorage, which the server can't read.\n const writeAuthCookie = (token: string) => {\n document.cookie = `${AUTH_TOKEN_COOKIE_NAME}=${token}; path=/; max-age=${60 * 60 * 24 * 30}; SameSite=Lax; Secure`;\n };\n\n const clearAuthCookie = clearAuthTokenCookie;\n\n // The SDK only refreshes `user.type` on a full page load, but our auth flows update\n // the UI without one — SDK components read it directly (e.g. salla-login-modal's\n // render bails for 'user' and never creates its inner modal), so keep it in sync.\n const setSdkUserType = (type: 'user' | 'guest') => {\n sdk.config?.set?.('user.type', type);\n };\n\n const handleLogin = () => {\n const newToken = sdk.storage.get(AUTH_TOKEN_COOKIE_NAME) as string | null;\n // logged.in can fire before the token is stored (iframe mirror) — don't clobber\n if (!newToken) return;\n setAuthToken(newToken);\n updateTwilightContext({ authToken: newToken });\n setSdkUserType('user');\n };\n\n // Fires on a fresh token fetch (login / web-session refresh — the native app flow).\n // Mirror the token into a cookie so SSR loads of authenticated pages are authenticated.\n const handleTokenFetched = (token: unknown) => {\n if (typeof token !== 'string' || !token) return;\n setAuthToken(token);\n updateTwilightContext({ authToken: token });\n writeAuthCookie(token);\n setSdkUserType('user');\n };\n\n const handleLogout = () => {\n const wasLoggedIn = Boolean(getTwilightContext().authToken);\n setAuthToken(null);\n updateTwilightContext({ authToken: null });\n setSdkUserType('guest');\n // Clear the SSR cookie too, otherwise a logged-out user's next full-page load\n // would still send a stale token to the server.\n try {\n clearAuthCookie();\n } catch {\n // Cookie removal may fail in restricted environments\n }\n // SDK logout redirects via location.href only after an accounts-iframe roundtrip\n // that can hang forever (iOS webview). If its redirect hasn't unloaded the page\n // by then, reload so SSR re-renders as guest. Guarded to logged-in users so the\n // SDK's force_logout guest flow can't reload-loop.\n if (wasLoggedIn) {\n window.setTimeout(() => window.location.reload(), 3500);\n }\n };\n\n const handleTokenInvalid = () => {\n setAuthToken(null);\n updateTwilightContext({ authToken: null });\n setSdkUserType('guest');\n try {\n window.localStorage.removeItem(AUTH_TOKEN_COOKIE_NAME);\n sdk.storage.remove?.(AUTH_TOKEN_COOKIE_NAME);\n clearAuthCookie();\n } catch {\n // Storage/cookie removal may fail in restricted environments\n }\n };\n\n sdk.auth.event.onLoggedIn(handleLogin);\n sdk.auth.event.onLoggedOut(handleLogout);\n sdk.event.on('auth::token.invalid', handleTokenInvalid);\n sdk.event.on('auth::token.fetched', handleTokenFetched);\n // fires on every token path, and BEFORE logged.in in the login-iframe flow\n sdk.event.on('api::token.injected', handleTokenFetched);\n\n return () => {\n // Sub-emitters use root salla.event.off for cleanup\n sdk.event.off('auth::loggedIn', handleLogin);\n sdk.event.off('auth::loggedOut', handleLogout);\n sdk.event.off('auth::token.invalid', handleTokenInvalid);\n sdk.event.off('auth::token.fetched', handleTokenFetched);\n sdk.event.off('api::token.injected', handleTokenFetched);\n };\n }, []);\n\n const { isReady, storeData, setStoreData, themeData, currency, isMobileWebview } =\n useTwilightInit({\n debug,\n initialData,\n onReady,\n onError,\n initialLocale,\n });\n\n const config = useMemo<TwilightConfig>(() => ({ debug }), [debug]);\n\n const log = useMemo<TwilightLog>(\n () => ({\n groupCollapsed: (title) =>\n console.groupCollapsed(`%c ⚡ Twilight: ${title} `, TWILIGHT_LOG_STYLES.header),\n group: (title) => console.group(`%c${title}`, TWILIGHT_LOG_STYLES.label),\n groupEnd: () => console.groupEnd(),\n error: (label, value) =>\n console.log(`%c[${label}]%c`, TWILIGHT_LOG_STYLES.error, TWILIGHT_LOG_STYLES.value, value),\n warn: (label, value) =>\n console.log(`%c[${label}]%c`, TWILIGHT_LOG_STYLES.warn, TWILIGHT_LOG_STYLES.value, value),\n info: (label, value) =>\n console.log(`%c[${label}]%c`, TWILIGHT_LOG_STYLES.info, TWILIGHT_LOG_STYLES.value, value),\n label: (label, value) =>\n console.log(`%c[${label}]%c`, TWILIGHT_LOG_STYLES.label, TWILIGHT_LOG_STYLES.value, value),\n dir: (label, value) => {\n console.log(`%c${label}`, TWILIGHT_LOG_STYLES.label);\n console.dir(value);\n },\n trace: (label, trace) => {\n console.log(`%c${label}`, TWILIGHT_LOG_STYLES.label);\n console.error(trace);\n },\n }),\n []\n );\n\n const contextValue = useMemo<TwilightContextValue>(\n () => ({\n isReady,\n store: storeData,\n _setStore: setStoreData,\n theme: themeData,\n currency,\n config,\n log,\n get salla() {\n return getSalla();\n },\n get settings() {\n return getTwilightContext().settings;\n },\n get locale() {\n return getTwilightContext().locale;\n },\n get routeId() {\n return getTwilightContext().routeId;\n },\n get location() {\n return getTwilightContext().location;\n },\n get authToken() {\n return authToken;\n },\n get i18n() {\n return getTwilightContext().i18n;\n },\n get dir() {\n return getTwilightContext().dir;\n },\n get extras() {\n return getTwilightContext().extras;\n },\n }),\n [isReady, storeData, setStoreData, themeData, currency, config, log, authToken]\n );\n\n const framework = client !== false ? (client?.framework ?? 'tanstack') : null;\n const LazyNavSetup = framework ? navigationSetups[framework] : null;\n const LazyDocumentSync = routeClass && framework ? routeDocumentSyncs[framework] : null;\n const interceptLinks = client !== false && (client?.interceptLinks ?? true);\n\n const documentSyncElement = useMemo(\n () => (LazyDocumentSync ? React.createElement(LazyDocumentSync) : null),\n [LazyDocumentSync]\n );\n\n const readyShell = useMemo(() => {\n if (!isReady) return null;\n return {\n LayoutComponent,\n LazyNavSetup,\n toast,\n toastMobilePosition,\n addToCartToast,\n interceptLinks,\n };\n }, [\n isReady,\n LazyNavSetup,\n LayoutComponent,\n toast,\n toastMobilePosition,\n addToCartToast,\n interceptLinks,\n ]);\n\n const readyContent = useMemo(() => {\n if (!readyShell) return null;\n\n const inner = readyShell.LayoutComponent ? (\n <readyShell.LayoutComponent>{children}</readyShell.LayoutComponent>\n ) : (\n children\n );\n\n const wrapped = (\n <>\n <WidgetHead />\n {/* Installed apps' snippets — client-only, injected once per page load. Lives\n here so every theme gets marketplace apps without re-implementing injection. */}\n <AppsSnippets />\n <HookSlot name={HookName.BODY_START} />\n <Suspense fallback={null}>\n {readyShell.toast && (\n <Toaster\n mobilePosition={readyShell.toastMobilePosition}\n addToCartToast={readyShell.addToCartToast}\n />\n )}\n {readyShell.interceptLinks && <NavigationInterceptor />}\n </Suspense>\n {inner}\n <HookSlot name={HookName.BODY_END} />\n </>\n );\n\n if (readyShell.LazyNavSetup) {\n return React.createElement(readyShell.LazyNavSetup, null, wrapped);\n }\n return wrapped;\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [readyShell]);\n\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const i18nInstance = useMemo(() => getTwilightContext().i18n, [initialLocale]);\n\n return (\n <DocumentClassProvider>\n <TwilightContext.Provider value={contextValue}>\n <I18nProvider i18nInstance={i18nInstance} themeTranslations={themeTranslations}>\n <ThemeDocumentSync\n theme={themeData}\n locale={initialLocale}\n direction={getTwilightContext().dir}\n isMobileWebview={isMobileWebview}\n />\n {documentSyncElement}\n {!isReady && (\n <div className=\"loading-overlay\">{skeleton || <div className=\"loading-spinner\" />}</div>\n )}\n {readyContent}\n </I18nProvider>\n </TwilightContext.Provider>\n </DocumentClassProvider>\n );\n}\n\nexport default TwilightProvider;\n","import { useCallback } from 'react';\nimport { useTwilight } from '../providers/TwilightProvider';\nimport type { Store } from '../types';\n\n/**\n * UseStoreResult - Return type for useStore hook\n *\n * Extends the Store interface with a refresh method to re-fetch\n * the latest store configuration from the Salla SDK.\n */\nexport interface UseStoreResult extends Store {\n refresh: () => Promise<void>;\n}\n\n/**\n * useStore - Hook for accessing and managing store state\n *\n * Provides access to the store configuration and metadata from the\n * Twilight provider. Includes a refresh method to update the store\n * state with the latest data from the Salla SDK.\n *\n * @returns Store object with refresh() method to reload store data\n *\n * @example\n * ```tsx\n * function StoreInfo() {\n * const { name, currency, refresh } = useStore();\n *\n * return (\n * <div>\n * <h1>{name}</h1>\n * <button onClick={refresh}>Refresh store data</button>\n * <p>Current currency: {currency}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useStore(): UseStoreResult {\n const { store, _setStore, salla } = useTwilight();\n\n const refresh = useCallback(async () => {\n if (!salla) return;\n try {\n const data = salla.config.all();\n if (data?.store && typeof data.store === 'object') {\n _setStore((prev) => ({ ...prev, ...(data.store as Partial<Store>) }));\n }\n } catch {\n // Silently ignore errors - store remains unchanged\n }\n }, [salla, _setStore]);\n\n return { ...store, refresh };\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/providers/NavigationProvider.ts"],"names":[],"mappings":";;;;;AAyBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACS,IAAA,EACA,OAAA,GAAU,KAAA,EACjB;AACA,IAAA,KAAA,CAAM,CAAA,YAAA,EA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AAA;AAAA,EACF,CAAA,EAAG,CAAC,WAAW,CAAC,CAAA;AAClB","file":"chunk-XLGVT7QF.js","sourcesContent":["import {\n createElement,\n createContext,\n useContext,\n useCallback,\n useRef,\n useEffect,\n useSyncExternalStore,\n type ReactNode,\n} from 'react';\nimport { useTwilight } from './twilight-context';\nimport { getTwilightContext, subscribeTwilight, type TwilightLocation } from '../twilight/context';\nimport { RouteId } from '../router/route-ids';\n\n// Re-export RouteId from centralized location\nexport { RouteId } from '../router/route-ids';\nexport type { RouteIdType } from '../router/route-ids';\n\n// Re-export TwilightLocation as Location for convenience\nexport type { TwilightLocation as Location } from '../twilight/context';\n\nexport type NavigateOptions = { replace?: boolean };\nexport type NavigateFn = (to: string, opts?: NavigateOptions) => void;\n\n/** Redirect error - thrown to trigger a redirect */\nexport class RedirectError extends Error {\n constructor(\n public path: string,\n public replace = false\n ) {\n super(`Redirect to ${path}`);\n this.name = 'RedirectError';\n }\n}\n\n/** NotFound error - thrown to trigger 404 */\nexport class NotFoundError extends Error {\n constructor(message?: string) {\n super(message ?? 'Not Found');\n this.name = 'NotFoundError';\n }\n}\n\n/** Unauthorized error - thrown to trigger 401 */\nexport class UnauthorizedError extends Error {\n constructor(message?: string) {\n super(message ?? 'Unauthorized');\n this.name = 'UnauthorizedError';\n }\n}\n\nexport { SettingsError } from '../utils/errors';\n\nexport const defaultNavigate: NavigateFn = (to, opts) => {\n if (opts?.replace) window.location.replace(to);\n else window.location.href = to;\n};\n\n/** Default redirect - throws RedirectError with browser navigation as fallback */\nexport const defaultRedirect = (path: string, opts?: { replace?: boolean }): never => {\n const replace = opts?.replace ?? false;\n\n // In browser, perform actual navigation before throwing\n if (typeof window !== 'undefined') {\n if (replace) window.location.replace(path);\n else window.location.href = path;\n }\n\n throw new RedirectError(path, replace);\n};\n\n/** Default notFound - throws generic error */\nexport const defaultNotFound = (message?: string): never => {\n throw new NotFoundError(message);\n};\n\n/** Default unauthorized - throws generic error */\nexport const defaultUnauthorized = (message?: string): never => {\n throw new UnauthorizedError(message);\n};\n\n// ─── Framework-agnostic functions for loaders (outside React context) ──────\n\n/**\n * Throw a notFound error. Use in route loaders.\n * Framework adapters will override this to throw framework-specific errors.\n *\n * @example\n * ```ts\n * // In loader\n * import { notFound } from '@salla.sa/twilight-theme-engine/providers';\n *\n * if (!data) throw notFound();\n * ```\n */\nexport let notFound = defaultNotFound;\n\n/**\n * Throw an unauthorized error. Use in route loaders to protect authenticated routes.\n * Framework adapters will override this to throw framework-specific errors.\n *\n * @example\n * ```ts\n * import { unauthorized } from '@salla.sa/twilight-theme-engine/providers';\n *\n * if (!user) throw unauthorized();\n * ```\n */\nexport let unauthorized = defaultUnauthorized;\n\n/**\n * Throw a redirect. Use in route loaders.\n * Framework adapters will override this to throw framework-specific redirects.\n *\n * @param path - Path to redirect to\n * @param opts - Redirect options\n *\n * @example\n * ```ts\n * // In loader\n * import { redirect } from '@salla.sa/twilight-theme-engine/providers';\n *\n * throw redirect('/ar/cart');\n * ```\n */\nexport let redirect = defaultRedirect;\n\n/**\n * Configure navigation functions for a specific framework.\n * Called by framework adapters during setup.\n */\nexport function configureNavigation(config: {\n notFound?: (message?: string) => never;\n redirect?: (path: string, opts?: { replace?: boolean }) => never;\n unauthorized?: (_message?: string) => never;\n}): void {\n if (config.notFound) notFound = config.notFound;\n if (config.redirect) redirect = config.redirect;\n if (config.unauthorized) unauthorized = config.unauthorized;\n}\n\n// ─── Loader Error Handling Helpers ─────────────────────────────────────────────\n\n/**\n * Wraps an API promise with error handling for route loaders.\n * On any error, logs debug info and throws notFound() for clean UX.\n *\n * @example\n * ```ts\n * findOrThrow: (id, locale) => orThrow(product.find(id, locale)),\n * const data = await product.findOrThrow(id, locale);\n * ```\n */\nexport async function orThrow<T>(promise: Promise<T>): Promise<T> {\n try {\n return await promise;\n } catch (error) {\n console.debug('[loader error]', error);\n throw new NotFoundError();\n }\n}\n\n/**\n * Wraps an API promise with error handling for authenticated route loaders.\n * On a 401/403 response throws unauthorized(); other errors propagate.\n *\n * @example\n * ```ts\n * const data = await orUnauthorized(order.find(id, locale));\n * ```\n */\nexport async function orUnauthorized<T>(promise: Promise<T>): Promise<T> {\n try {\n return await promise;\n } catch (error) {\n const status = (error as unknown as { response?: { status?: number } })?.response?.status;\n if (status === 401 || status === 403) {\n throw unauthorized();\n }\n throw error;\n }\n}\n\n// ─── Navigation Context ──────────────────────────────────────────────────────\n\ninterface NavigationContextValue {\n navigate: NavigateFn;\n}\n\nconst NavigationContext = createContext<NavigationContextValue>({\n navigate: defaultNavigate,\n});\n\nexport function NavigationProvider({\n navigate,\n children,\n}: {\n navigate: NavigateFn;\n children: ReactNode;\n}) {\n return createElement(NavigationContext.Provider, { value: { navigate } }, children);\n}\n\n// ─── Primary Hooks (High Compatibility) ───────────────────────────────────────\n\n/**\n * Get the navigate function.\n * Matches React Router, TanStack Router, and Remix naming convention.\n *\n * @returns Navigate function\n *\n * @example\n * ```tsx\n * const navigate = useNavigate();\n * navigate('/cart');\n * navigate('/cart', { replace: true });\n * ```\n */\nexport function useNavigate(): NavigateFn {\n return useContext(NavigationContext).navigate;\n}\n\n/**\n * Get the current route ID.\n * Used for route detection (isHome, isProduct, etc.)\n *\n * @returns Current route ID string\n *\n * @example\n * ```tsx\n * const routeId = useRouteId();\n * if (routeId === RouteId.INDEX) { ... }\n * ```\n */\nexport function useRouteId(): string {\n return useSyncExternalStore(\n subscribeTwilight,\n () => getTwilightContext().routeId,\n () => getTwilightContext().routeId\n );\n}\n\n/**\n * Get the current location (TanStack Router compatible).\n * Reads from the router context for SSR compatibility.\n *\n * @returns Location object matching TanStack's ParsedLocation\n *\n * @example\n * ```tsx\n * const location = useLocation();\n * console.log(location.pathname); // '/ar/products'\n * console.log(location.searchStr); // '?q=shoes&page=2'\n * console.log(location.search); // { q: 'shoes', page: '2' }\n * console.log(location.href); // 'https://store.com/ar/products?q=shoes'\n * console.log(location.hash); // '#section-1'\n * console.log(location.state); // { scrollY: 100 }\n * ```\n */\nexport function useLocation<TSearch = Record<string, unknown>>(): TwilightLocation<TSearch> {\n useTwilight();\n return getTwilightContext().location as TwilightLocation<TSearch>;\n}\n\n// ─── Selector Hooks ───────────────────────────────────────────────────────────\n\n/**\n * Check if current page is homepage */\nexport function useIsHome(): boolean {\n return useRouteId() === RouteId.INDEX;\n}\n\n/** Check if current page is product detail */\nexport function useIsProduct(): boolean {\n return useRouteId() === RouteId.PRODUCT_SINGLE;\n}\n\n/** Check if current page is cart */\nexport function useIsCart(): boolean {\n return useRouteId() === RouteId.CART;\n}\n\n/** Check if current page is in customer area */\nexport function useIsCustomer(): boolean {\n return useRouteId().startsWith('customer');\n}\n\n/** Check if current page is blog related */\nexport function useIsBlog(): boolean {\n const routeId = useRouteId();\n return routeId === RouteId.BLOG_INDEX || routeId === RouteId.BLOG_SINGLE;\n}\n\n/** Check if current page is brands related */\nexport function useIsBrands(): boolean {\n const routeId = useRouteId();\n return routeId === RouteId.BRANDS_INDEX || routeId === RouteId.BRANDS_SINGLE;\n}\n\n/** Check if current page is search */\nexport function useIsSearch(): boolean {\n return useRouteId() === RouteId.SEARCH;\n}\n\n// ─── Navigation Interceptor ──────────────────────────────────────────────────\n\n/**\n * NavigationInterceptor - Framework-agnostic SPA navigation interceptor.\n *\n * Uses navigate function from NavigationProvider context and store URL\n * from TwilightProvider to intercept same-origin navigations.\n */\nexport function NavigationInterceptor(): null {\n const navigate = useNavigate();\n const { store } = useTwilight();\n useNavigationInterceptor(navigate, store?.url);\n return null;\n}\n\n/**\n * resolveRelativePath - Resolve href to store-relative path\n *\n * Returns `null` when the URL is not on the same origin as the store,\n * keeping this helper safe against open-redirect misuse.\n *\n * @param href - The URL to resolve\n * @param storeUrl - The store's base URL\n * @returns The relative path string, or null if the URL is external\n */\nexport function resolveRelativePath(href: string, storeUrl: string): string | null {\n try {\n const target = new URL(href, window.location.href);\n const base = new URL(storeUrl);\n\n if (target.origin !== base.origin) return null;\n\n const path = target.pathname + target.search + target.hash;\n return path || '/';\n } catch {\n return null;\n }\n}\n\n/**\n * EXTERNAL_TARGETS - Target attribute values that indicate external navigation\n */\nconst EXTERNAL_TARGETS = new Set(['_blank', '_parent', '_top']);\n\n/**\n * shouldIntercept - Determine if an anchor click should be intercepted by SPA router\n *\n * Follows browser conventions: modifier keys, external targets, downloads,\n * and non-HTTP(S) protocols are left to the browser's default behavior.\n *\n * @param anchor - The anchor element that was clicked\n * @param event - The click event\n * @returns true if the click should be intercepted by the router\n */\nexport function shouldIntercept(anchor: HTMLAnchorElement, event: MouseEvent): boolean {\n if (event.defaultPrevented) return false;\n\n if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return false;\n\n const targetAttr = anchor.getAttribute('target');\n if (targetAttr && EXTERNAL_TARGETS.has(targetAttr)) return false;\n\n if (anchor.hasAttribute('download')) return false;\n\n const rel = (anchor.getAttribute('rel') ?? '').split(/\\s+/);\n if (rel.includes('external')) return false;\n\n const href = anchor.getAttribute('href') ?? '';\n if (!href) return false;\n\n try {\n const url = new URL(href, window.location.href);\n if (url.protocol.startsWith('javascript:')) return false;\n } catch {\n return false;\n }\n\n return true;\n}\n\n// ─── Navigation Interceptor Hook (framework-agnostic) ─────────────────────────\n\n/**\n * Hook for navigation interception using framework-agnostic navigate function.\n * Framework adapters call this with their navigate implementation.\n */\nexport function useNavigationInterceptor(navigate: NavigateFn, storeUrl: string | undefined): void {\n const storeUrlRef = useRef<string | undefined>(storeUrl);\n\n useEffect(() => {\n storeUrlRef.current = storeUrl;\n }, [storeUrl]);\n\n const tryNavigate = useCallback(\n (href: string, replace = false): boolean => {\n const currentStoreUrl = storeUrlRef.current;\n if (!currentStoreUrl) return false;\n\n const relativePath = resolveRelativePath(href, currentStoreUrl);\n if (!relativePath) return false;\n\n navigate(relativePath, { replace });\n return true;\n },\n [navigate]\n );\n\n useEffect(() => {\n // ── Pointer movement tracking ────────────────────────────────────────────\n // Detect drag/scroll gestures to avoid intercepting clicks from swipes.\n let pointerStartX = 0;\n let pointerStartY = 0;\n let pointerSwiped = false;\n const MOVE_THRESHOLD = 10;\n\n function handlePointerDown(event: PointerEvent): void {\n pointerStartX = event.clientX;\n pointerStartY = event.clientY;\n pointerSwiped = false;\n }\n\n function handlePointerUp(event: PointerEvent): void {\n const dx = Math.abs(event.clientX - pointerStartX);\n const dy = Math.abs(event.clientY - pointerStartY);\n pointerSwiped = dx > MOVE_THRESHOLD || dy > MOVE_THRESHOLD;\n }\n\n // ── Anchor click interception ────────────────────────────────────────────\n function handleClick(event: MouseEvent): void {\n // Ignore clicks that resulted from swipe/drag gestures.\n if (pointerSwiped) {\n pointerSwiped = false;\n return;\n }\n\n const path = event.composedPath();\n const anchor = path.find((el): el is HTMLAnchorElement => el instanceof HTMLAnchorElement);\n\n if (!anchor || !shouldIntercept(anchor, event)) return;\n\n if (tryNavigate(anchor.href, false)) {\n event.preventDefault();\n }\n }\n\n // ── window.location.assign patch ─────────────────────────────────────────\n const origAssign = window.location.assign;\n function patchedAssign(url: string): void {\n if (!tryNavigate(url, false)) origAssign.call(window.location, url);\n }\n\n // ── window.location.replace patch ────────────────────────────────────────\n const origReplace = window.location.replace;\n function patchedReplace(url: string): void {\n if (!tryNavigate(url, true)) origReplace.call(window.location, url);\n }\n\n let assignPatched = false;\n let replacePatched = false;\n try {\n window.location.assign = patchedAssign;\n assignPatched = true;\n } catch {\n /* non-writable in this environment */\n }\n try {\n window.location.replace = patchedReplace;\n replacePatched = true;\n } catch {\n /* non-writable in this environment */\n }\n\n document.addEventListener('click', handleClick, { capture: true });\n document.addEventListener('pointerdown', handlePointerDown, { passive: true });\n document.addEventListener('pointerup', handlePointerUp, { passive: true });\n\n return () => {\n document.removeEventListener('click', handleClick, { capture: true });\n document.removeEventListener('pointerdown', handlePointerDown);\n document.removeEventListener('pointerup', handlePointerUp);\n if (assignPatched) {\n try {\n window.location.assign = origAssign;\n } catch {\n /* ignore */\n }\n }\n if (replacePatched) {\n try {\n window.location.replace = origReplace;\n } catch {\n /* ignore */\n }\n }\n };\n }, [tryNavigate]);\n}\n\n// ─── Client navigation config ─────────────────────────────────────────────────\n\nexport interface ClientNav {\n /** Framework adapter to use for client-side navigation. @default 'tanstack' */\n framework?: 'tanstack' | 'nextjs';\n /**\n * Intercept same-origin `<a>` clicks and `window.location` calls from web\n * components and route them through the framework router.\n * @default true\n */\n interceptLinks?: boolean;\n}\n\n// Framework adapter setups are registered in navigation-setups.ts to avoid circular imports.\n"]}