@salla.sa/twilight-theme-engine 1.0.158 → 1.0.160

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 (231) hide show
  1. package/dist/{AddToCartForm-GZETOEEG.js → AddToCartForm-WO3Q37IB.js} +3 -3
  2. package/dist/{AddToCartForm-GZETOEEG.js.map → AddToCartForm-WO3Q37IB.js.map} +1 -1
  3. package/dist/{BlogAuthorPage-RJIQXJVF.js → BlogAuthorPage-G42EU6FR.js} +17 -17
  4. package/dist/{BlogAuthorPage-RJIQXJVF.js.map → BlogAuthorPage-G42EU6FR.js.map} +1 -1
  5. package/dist/{BlogCategoryPage-5TTKBNC2.js → BlogCategoryPage-4W5YUDPY.js} +17 -17
  6. package/dist/{BlogCategoryPage-5TTKBNC2.js.map → BlogCategoryPage-4W5YUDPY.js.map} +1 -1
  7. package/dist/{BlogPage-QGHFED55.js → BlogPage-CNOYALV7.js} +15 -15
  8. package/dist/{BlogPage-QGHFED55.js.map → BlogPage-CNOYALV7.js.map} +1 -1
  9. package/dist/{BlogSinglePage-NZ4CC4Y7.js → BlogSinglePage-2ON6VYQW.js} +15 -15
  10. package/dist/{BlogSinglePage-NZ4CC4Y7.js.map → BlogSinglePage-2ON6VYQW.js.map} +1 -1
  11. package/dist/{BlogTagPage-XIXMIK3G.js → BlogTagPage-NJ4OUCUQ.js} +17 -17
  12. package/dist/{BlogTagPage-XIXMIK3G.js.map → BlogTagPage-NJ4OUCUQ.js.map} +1 -1
  13. package/dist/{BrandsPage-QOZZKEYH.js → BrandsPage-GRGSUB7N.js} +16 -16
  14. package/dist/{BrandsPage-QOZZKEYH.js.map → BrandsPage-GRGSUB7N.js.map} +1 -1
  15. package/dist/{Breadcrumb-XLAZO772.js → Breadcrumb-5ADSKVA5.js} +15 -15
  16. package/dist/{Breadcrumb-XLAZO772.js.map → Breadcrumb-5ADSKVA5.js.map} +1 -1
  17. package/dist/{CartItem-WW5RBG3O.js → CartItem-X5KG7GIG.js} +15 -15
  18. package/dist/{CartItem-WW5RBG3O.js.map → CartItem-X5KG7GIG.js.map} +1 -1
  19. package/dist/{CartSummary-V6YYOCZS.js → CartSummary-B5BYFOGX.js} +15 -15
  20. package/dist/{CartSummary-V6YYOCZS.js.map → CartSummary-B5BYFOGX.js.map} +1 -1
  21. package/dist/{Copyright-Y7MTRSHH.js → Copyright-5GKK7P5J.js} +3 -3
  22. package/dist/{Copyright-Y7MTRSHH.js.map → Copyright-5GKK7P5J.js.map} +1 -1
  23. package/dist/{CustomerLayout-SFEAGDMD.js → CustomerLayout-5JG5KFK5.js} +15 -15
  24. package/dist/{CustomerLayout-SFEAGDMD.js.map → CustomerLayout-5JG5KFK5.js.map} +1 -1
  25. package/dist/{Footer-R3MAJOND.js → Footer-YVE4RF3P.js} +4 -4
  26. package/dist/{Footer-R3MAJOND.js.map → Footer-YVE4RF3P.js.map} +1 -1
  27. package/dist/{Header-JOOHPZX2.js → Header-C65BO5LS.js} +8 -8
  28. package/dist/{Header-JOOHPZX2.js.map → Header-C65BO5LS.js.map} +1 -1
  29. package/dist/{LatestProducts-DJAZJWMV.js → LatestProducts-ET72HRAB.js} +17 -17
  30. package/dist/{LatestProducts-DJAZJWMV.js.map → LatestProducts-ET72HRAB.js.map} +1 -1
  31. package/dist/{LoyaltyPage-GKDHYRP5.js → LoyaltyPage-EJP3TZ75.js} +15 -15
  32. package/dist/{LoyaltyPage-GKDHYRP5.js.map → LoyaltyPage-EJP3TZ75.js.map} +1 -1
  33. package/dist/{LoyaltyPointsPage-WROFM6RF.js → LoyaltyPointsPage-AJYZA3JM.js} +6 -6
  34. package/dist/{LoyaltyPointsPage-WROFM6RF.js.map → LoyaltyPointsPage-AJYZA3JM.js.map} +1 -1
  35. package/dist/{MainMenu-ECQUTKST.js → MainMenu-USTSBBNS.js} +5 -5
  36. package/dist/{MainMenu-ECQUTKST.js.map → MainMenu-USTSBBNS.js.map} +1 -1
  37. package/dist/{MasterLayout-7RCUFU6Q.js → MasterLayout-QO4PZDEH.js} +15 -15
  38. package/dist/{MasterLayout-7RCUFU6Q.js.map → MasterLayout-QO4PZDEH.js.map} +1 -1
  39. package/dist/{MobileMenu-MFMM5O5M.js → MobileMenu-MQ5ZDXPX.js} +16 -16
  40. package/dist/{MobileMenu-MFMM5O5M.js.map → MobileMenu-MQ5ZDXPX.js.map} +1 -1
  41. package/dist/{NotificationsPage-GXDS4UD4.js → NotificationsPage-ZGNL7D3A.js} +15 -15
  42. package/dist/{NotificationsPage-GXDS4UD4.js.map → NotificationsPage-ZGNL7D3A.js.map} +1 -1
  43. package/dist/{OrderSinglePage-DO5WEUYF.js → OrderSinglePage-4C7Y73GQ.js} +16 -16
  44. package/dist/{OrderSinglePage-DO5WEUYF.js.map → OrderSinglePage-4C7Y73GQ.js.map} +1 -1
  45. package/dist/{OrdersPage-QCDXT3XJ.js → OrdersPage-RMHXFJ7X.js} +15 -15
  46. package/dist/{OrdersPage-QCDXT3XJ.js.map → OrdersPage-RMHXFJ7X.js.map} +1 -1
  47. package/dist/{PageSingle-LAB6LK3K.js → PageSingle-LPCTWSZY.js} +3 -3
  48. package/dist/{PageSingle-LAB6LK3K.js.map → PageSingle-LPCTWSZY.js.map} +1 -1
  49. package/dist/{ProductDetails-SER5G6JA.js → ProductDetails-C5UCFEHI.js} +4 -4
  50. package/dist/{ProductDetails-SER5G6JA.js.map → ProductDetails-C5UCFEHI.js.map} +1 -1
  51. package/dist/{ProfilePage-E27JE4I7.js → ProfilePage-NU4YYRCU.js} +15 -15
  52. package/dist/{ProfilePage-E27JE4I7.js.map → ProfilePage-NU4YYRCU.js.map} +1 -1
  53. package/dist/{ReviewsPage-NVVDXY3I.js → ReviewsPage-7L6JV5FD.js} +3 -3
  54. package/dist/{ReviewsPage-NVVDXY3I.js.map → ReviewsPage-7L6JV5FD.js.map} +1 -1
  55. package/dist/{SeoCartWidget-F6RFGVSX.js → SeoCartWidget-5XELGB2J.js} +15 -15
  56. package/dist/{SeoCartWidget-F6RFGVSX.js.map → SeoCartWidget-5XELGB2J.js.map} +1 -1
  57. package/dist/{SettingsPage-AY2B35MW.js → SettingsPage-EJS75UO7.js} +15 -15
  58. package/dist/{SettingsPage-AY2B35MW.js.map → SettingsPage-EJS75UO7.js.map} +1 -1
  59. package/dist/{StoreClosedNotification-YCEZARXE.js → StoreClosedNotification-ZIZNAIF4.js} +16 -16
  60. package/dist/{StoreClosedNotification-YCEZARXE.js.map → StoreClosedNotification-ZIZNAIF4.js.map} +1 -1
  61. package/dist/{TestimonialsPage-6TR6YE23.js → TestimonialsPage-QSTGFAVA.js} +3 -3
  62. package/dist/{TestimonialsPage-6TR6YE23.js.map → TestimonialsPage-QSTGFAVA.js.map} +1 -1
  63. package/dist/{ThankYouPage-LYX2W6XD.js → ThankYouPage-SWCRKH4V.js} +15 -15
  64. package/dist/{ThankYouPage-LYX2W6XD.js.map → ThankYouPage-SWCRKH4V.js.map} +1 -1
  65. package/dist/{WalletPage-4BE4TE5V.js → WalletPage-RZ4GXBUD.js} +16 -16
  66. package/dist/{WalletPage-4BE4TE5V.js.map → WalletPage-RZ4GXBUD.js.map} +1 -1
  67. package/dist/{WebMcpTools-RDHFYQ3D.js → WebMcpTools-2Y354KN2.js} +5 -5
  68. package/dist/{WebMcpTools-RDHFYQ3D.js.map → WebMcpTools-2Y354KN2.js.map} +1 -1
  69. package/dist/{WishlistPage-AZXLGPYB.js → WishlistPage-RRK2STY5.js} +17 -17
  70. package/dist/{WishlistPage-AZXLGPYB.js.map → WishlistPage-RRK2STY5.js.map} +1 -1
  71. package/dist/api/advertisement.js +2 -2
  72. package/dist/api/apps.js +2 -2
  73. package/dist/api/blog.js +3 -3
  74. package/dist/api/brands.js +3 -3
  75. package/dist/api/cart.js +3 -3
  76. package/dist/api/category.js +3 -3
  77. package/dist/api/client.js +1 -1
  78. package/dist/api/home.js +2 -2
  79. package/dist/api/loyalty.js +3 -3
  80. package/dist/api/menu.js +2 -2
  81. package/dist/api/notification.js +2 -2
  82. package/dist/api/order.d.ts +7 -0
  83. package/dist/api/order.d.ts.map +1 -1
  84. package/dist/api/order.js +3 -3
  85. package/dist/api/page.js +3 -3
  86. package/dist/api/product.js +3 -3
  87. package/dist/api/profile.js +1 -1
  88. package/dist/api/store.js +3 -3
  89. package/dist/api/translations.js +2 -2
  90. package/dist/api/user.js +2 -2
  91. package/dist/api/wallet.js +2 -2
  92. package/dist/api/wishlist.js +4 -4
  93. package/dist/{chunk-DYY4JCHZ.js → chunk-27JKRCEG.js} +3 -3
  94. package/dist/{chunk-DYY4JCHZ.js.map → chunk-27JKRCEG.js.map} +1 -1
  95. package/dist/{chunk-CR4VZMWB.js → chunk-2YZ2LEGT.js} +4 -4
  96. package/dist/{chunk-CR4VZMWB.js.map → chunk-2YZ2LEGT.js.map} +1 -1
  97. package/dist/{chunk-JD6NO476.js → chunk-37VWVWTB.js} +4 -4
  98. package/dist/{chunk-JD6NO476.js.map → chunk-37VWVWTB.js.map} +1 -1
  99. package/dist/{chunk-4QM6O6I5.js → chunk-4QMSIMNH.js} +23 -12
  100. package/dist/chunk-4QMSIMNH.js.map +1 -0
  101. package/dist/{chunk-BWLX7ZNI.js → chunk-5AGNOWT6.js} +3 -3
  102. package/dist/{chunk-BWLX7ZNI.js.map → chunk-5AGNOWT6.js.map} +1 -1
  103. package/dist/{chunk-HFV2PMKP.js → chunk-6A2UQ3SB.js} +7 -7
  104. package/dist/{chunk-HFV2PMKP.js.map → chunk-6A2UQ3SB.js.map} +1 -1
  105. package/dist/{chunk-B44627O6.js → chunk-6Q3VO6T7.js} +4 -4
  106. package/dist/{chunk-B44627O6.js.map → chunk-6Q3VO6T7.js.map} +1 -1
  107. package/dist/{chunk-USTSY5YA.js → chunk-7A3FB2OP.js} +3 -3
  108. package/dist/{chunk-USTSY5YA.js.map → chunk-7A3FB2OP.js.map} +1 -1
  109. package/dist/{chunk-NNJITZU6.js → chunk-AJQMYYXA.js} +4 -4
  110. package/dist/{chunk-NNJITZU6.js.map → chunk-AJQMYYXA.js.map} +1 -1
  111. package/dist/{chunk-ZQO52IZR.js → chunk-ATBBE4YC.js} +4 -4
  112. package/dist/{chunk-ZQO52IZR.js.map → chunk-ATBBE4YC.js.map} +1 -1
  113. package/dist/{chunk-WDRXUTSR.js → chunk-BC56MCLT.js} +5 -5
  114. package/dist/{chunk-WDRXUTSR.js.map → chunk-BC56MCLT.js.map} +1 -1
  115. package/dist/{chunk-7BCMTALC.js → chunk-CJA3EKON.js} +4 -4
  116. package/dist/{chunk-7BCMTALC.js.map → chunk-CJA3EKON.js.map} +1 -1
  117. package/dist/{chunk-LN2PHLJS.js → chunk-EFNQMFYG.js} +3 -3
  118. package/dist/{chunk-LN2PHLJS.js.map → chunk-EFNQMFYG.js.map} +1 -1
  119. package/dist/{chunk-XMRPNMMA.js → chunk-FLOSHIZV.js} +3 -3
  120. package/dist/{chunk-XMRPNMMA.js.map → chunk-FLOSHIZV.js.map} +1 -1
  121. package/dist/{chunk-LFKES3G4.js → chunk-FX3KPJZR.js} +4 -4
  122. package/dist/{chunk-LFKES3G4.js.map → chunk-FX3KPJZR.js.map} +1 -1
  123. package/dist/{chunk-PDWL4JOZ.js → chunk-GWHS6PHA.js} +7 -7
  124. package/dist/{chunk-PDWL4JOZ.js.map → chunk-GWHS6PHA.js.map} +1 -1
  125. package/dist/{chunk-5E6MSUW5.js → chunk-H3DZZUTA.js} +16 -16
  126. package/dist/{chunk-5E6MSUW5.js.map → chunk-H3DZZUTA.js.map} +1 -1
  127. package/dist/{chunk-F4Q5AW3J.js → chunk-IRUBUZ67.js} +3 -3
  128. package/dist/{chunk-F4Q5AW3J.js.map → chunk-IRUBUZ67.js.map} +1 -1
  129. package/dist/{chunk-AMJYM4FH.js → chunk-K4YSZ73N.js} +7 -7
  130. package/dist/{chunk-AMJYM4FH.js.map → chunk-K4YSZ73N.js.map} +1 -1
  131. package/dist/{chunk-BXAKPZJH.js → chunk-L6NITMGC.js} +4 -4
  132. package/dist/{chunk-BXAKPZJH.js.map → chunk-L6NITMGC.js.map} +1 -1
  133. package/dist/{chunk-TVSQH6T7.js → chunk-LK643DPN.js} +2 -2
  134. package/dist/{chunk-TVSQH6T7.js.map → chunk-LK643DPN.js.map} +1 -1
  135. package/dist/{chunk-OSJ57JYL.js → chunk-ORGZ3LIU.js} +4 -4
  136. package/dist/{chunk-OSJ57JYL.js.map → chunk-ORGZ3LIU.js.map} +1 -1
  137. package/dist/{chunk-GYUAVCKK.js → chunk-P34BFRH5.js} +4 -4
  138. package/dist/{chunk-GYUAVCKK.js.map → chunk-P34BFRH5.js.map} +1 -1
  139. package/dist/{chunk-7WSDVOIQ.js → chunk-PTMZXDBK.js} +4 -4
  140. package/dist/{chunk-7WSDVOIQ.js.map → chunk-PTMZXDBK.js.map} +1 -1
  141. package/dist/{chunk-U2XY667M.js → chunk-PUXHO3JL.js} +3 -3
  142. package/dist/{chunk-U2XY667M.js.map → chunk-PUXHO3JL.js.map} +1 -1
  143. package/dist/{chunk-YLQP7XSW.js → chunk-QFUGYRVB.js} +3 -3
  144. package/dist/{chunk-YLQP7XSW.js.map → chunk-QFUGYRVB.js.map} +1 -1
  145. package/dist/{chunk-HG33DQ2C.js → chunk-SB3Q35IT.js} +5 -5
  146. package/dist/{chunk-HG33DQ2C.js.map → chunk-SB3Q35IT.js.map} +1 -1
  147. package/dist/{chunk-N3VFFUZL.js → chunk-SXMRICQQ.js} +3 -3
  148. package/dist/{chunk-N3VFFUZL.js.map → chunk-SXMRICQQ.js.map} +1 -1
  149. package/dist/{chunk-3VMHSGKM.js → chunk-T4UA26NJ.js} +5 -5
  150. package/dist/{chunk-3VMHSGKM.js.map → chunk-T4UA26NJ.js.map} +1 -1
  151. package/dist/{chunk-EL2CCE4E.js → chunk-TIP53Q7K.js} +3 -3
  152. package/dist/{chunk-EL2CCE4E.js.map → chunk-TIP53Q7K.js.map} +1 -1
  153. package/dist/{chunk-ZS6ZAE4Q.js → chunk-TUBNYNJ2.js} +3 -3
  154. package/dist/{chunk-ZS6ZAE4Q.js.map → chunk-TUBNYNJ2.js.map} +1 -1
  155. package/dist/{chunk-53ZWOFFE.js → chunk-UF6XPCEO.js} +3 -3
  156. package/dist/{chunk-53ZWOFFE.js.map → chunk-UF6XPCEO.js.map} +1 -1
  157. package/dist/{chunk-KEGJQH7N.js → chunk-VPKQVAM3.js} +4 -4
  158. package/dist/{chunk-KEGJQH7N.js.map → chunk-VPKQVAM3.js.map} +1 -1
  159. package/dist/{chunk-XFTY3TUT.js → chunk-VXFRQB3H.js} +3 -3
  160. package/dist/{chunk-XFTY3TUT.js.map → chunk-VXFRQB3H.js.map} +1 -1
  161. package/dist/{chunk-AVGOJEOA.js → chunk-WGUKKSPD.js} +3 -3
  162. package/dist/{chunk-AVGOJEOA.js.map → chunk-WGUKKSPD.js.map} +1 -1
  163. package/dist/{chunk-T2OUBYWG.js → chunk-WZJCJCU3.js} +3 -3
  164. package/dist/{chunk-T2OUBYWG.js.map → chunk-WZJCJCU3.js.map} +1 -1
  165. package/dist/{chunk-XHLLT2LF.js → chunk-XBUV6MFL.js} +12 -12
  166. package/dist/chunk-XBUV6MFL.js.map +1 -0
  167. package/dist/{chunk-KWMGZIKF.js → chunk-XP4JJJ2T.js} +3 -3
  168. package/dist/{chunk-KWMGZIKF.js.map → chunk-XP4JJJ2T.js.map} +1 -1
  169. package/dist/{chunk-ZVPYNP3B.js → chunk-Y4UI4IZP.js} +3 -3
  170. package/dist/{chunk-ZVPYNP3B.js.map → chunk-Y4UI4IZP.js.map} +1 -1
  171. package/dist/{chunk-GD4CI5ZM.js → chunk-Y7I253RD.js} +7 -7
  172. package/dist/{chunk-GD4CI5ZM.js.map → chunk-Y7I253RD.js.map} +1 -1
  173. package/dist/{chunk-R5SGEYTJ.js → chunk-YNQFX4UM.js} +4 -4
  174. package/dist/{chunk-R5SGEYTJ.js.map → chunk-YNQFX4UM.js.map} +1 -1
  175. package/dist/{chunk-AIGCTNRU.js → chunk-Z7SWZZGP.js} +3 -3
  176. package/dist/{chunk-AIGCTNRU.js.map → chunk-Z7SWZZGP.js.map} +1 -1
  177. package/dist/components/cart/index.js +1 -1
  178. package/dist/components/common/index.js +1 -1
  179. package/dist/components/drawer/index.js +13 -13
  180. package/dist/components/home/index.js +18 -18
  181. package/dist/components/layout/index.js +4 -4
  182. package/dist/components/product/index.js +15 -15
  183. package/dist/components/store/index.js +14 -14
  184. package/dist/dev/editor/index.js +1 -1
  185. package/dist/dev/index.js +1 -1
  186. package/dist/{document-class-2VKLTAW6.js → document-class-VMIEM3DX.js} +13 -13
  187. package/dist/{document-class-2VKLTAW6.js.map → document-class-VMIEM3DX.js.map} +1 -1
  188. package/dist/hooks/index.js +13 -13
  189. package/dist/hooks/useGtm.js +13 -13
  190. package/dist/hooks/useMoney.js +13 -13
  191. package/dist/hooks/useStore.js +13 -13
  192. package/dist/hooks/useUser.js +3 -3
  193. package/dist/index.js +13 -13
  194. package/dist/{navigation-ME6YZX4I.js → navigation-5MSQCFWP.js} +4 -4
  195. package/dist/{navigation-ME6YZX4I.js.map → navigation-5MSQCFWP.js.map} +1 -1
  196. package/dist/{navigation-PK372JGM.js → navigation-KHKJWPOU.js} +5 -5
  197. package/dist/{navigation-PK372JGM.js.map → navigation-KHKJWPOU.js.map} +1 -1
  198. package/dist/{not-found-7RW544XQ.js → not-found-4ZBVHGIY.js} +16 -16
  199. package/dist/{not-found-7RW544XQ.js.map → not-found-4ZBVHGIY.js.map} +1 -1
  200. package/dist/providers/index.js +13 -13
  201. package/dist/routes/account/orders.js +4 -4
  202. package/dist/routes/account.js +13 -13
  203. package/dist/routes/blog.js +8 -8
  204. package/dist/routes/brands.js +4 -4
  205. package/dist/routes/cart.js +22 -22
  206. package/dist/routes/home.js +19 -19
  207. package/dist/routes/index.js +3 -3
  208. package/dist/routes/loyalty.js +5 -5
  209. package/dist/routes/page.js +4 -4
  210. package/dist/routes/product-listing.js +23 -23
  211. package/dist/routes/product.js +18 -18
  212. package/dist/routes/root/beforeLoad.d.ts +2 -2
  213. package/dist/routes/seo-redirects.js +3 -3
  214. package/dist/routes/testimonials.js +2 -2
  215. package/dist/routes/thank-you/loader.d.ts.map +1 -1
  216. package/dist/routes/thank-you.js +13 -6
  217. package/dist/routes/thank-you.js.map +1 -1
  218. package/dist/skeleton.js +19 -19
  219. package/dist/{store-lookup-RGH3DTCO.js → store-lookup-UXXFSOT5.js} +8 -8
  220. package/dist/{store-lookup-RGH3DTCO.js.map → store-lookup-UXXFSOT5.js.map} +1 -1
  221. package/dist/tanstack/middleware/twilight.d.ts +21 -9
  222. package/dist/tanstack/middleware/twilight.d.ts.map +1 -1
  223. package/dist/tanstack.js +22 -20
  224. package/dist/tanstack.js.map +1 -1
  225. package/dist/utils/index.js +2 -2
  226. package/dist/utils/maintenance.d.ts +3 -3
  227. package/package.json +1 -1
  228. package/tailwind/routes/root/beforeLoad.ts.txt +2 -2
  229. package/tailwind/routes/thank-you/loader.ts.txt +14 -3
  230. package/dist/chunk-4QM6O6I5.js.map +0 -1
  231. package/dist/chunk-XHLLT2LF.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/home.ts"],"names":[],"mappings":";;;AAQA,eAAe,KAAK,MAAA,EAA+D;AACjF,EAAA,MAAM,KAAA,GAAQ,SAAS,CAAA,CAAA,EAAI,IAAI,gBAAgB,MAAM,CAAA,CAAE,QAAA,EAAU,CAAA,CAAA,GAAK,EAAA;AACtE,EAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,GAAA,CAAI,IAAI,CAAA,cAAA,EAAiB,KAAK,CAAA,CAAE,CAAA,CAAE,IAAA,EAAoC;AAC7F,EAAA,OAAO,QAAQ,EAAC;AAClB;AAGA,SAAS,OAAA,CAAQ,QAA6B,QAAA,EAAoD;AAChG,EAAA,IAAI,CAAC,QAAA,CAAS,MAAA,EAAQ,OAAO,MAAA;AAC7B,EAAA,MAAM,KAAA,GAAQ,IAAI,GAAA,CAAI,QAAA,CAAS,IAAI,CAAC,KAAA,KAAU,KAAA,CAAM,IAAI,CA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,KAAA,CAAM,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAS,EAAE,GAAE,CAAE,CAAA;AAAA,EACpF,CAAA;AAAA,EAEA,OAAA,EAAS;AAAA,IACP,UAAA,EAAY,MACV,YAAA,CAAa;AAAA;AAAA,MAEX,QAAA,EAAU,CAAC,MAAA,EAAQ,YAAA,EAAc,EAAE,KAAA,EAAO,cAAA,IAAkB,CAAA;AAAA,MAC5D,OAAA,EAAS,MAAM,IAAA,CAAK,UAAA;AAAW,KAChC,CAAA;AAAA,IAEH,MAAA,EAAQ,CAAC,IAAA,EAAc,KAAA,KACrB,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,MAAA,EAAQ,QAAA,EAAU,MAAM,KAAK,CAAA;AAAA,MACxC,OAAA,EAAS,MAAM,IAAA,CAAK,MAAA,CAAO,MAAM,KAAK;AAAA,KACvC;AAAA;AAEP","file":"chunk-ZS6ZAE4Q.js","sourcesContent":["import { queryOptions } from '@tanstack/react-query';\nimport { api, getActiveScope } from './client';\nimport type { HomeComponentData } from '../types';\n\n/** The page a hook's blocks render on; blocks can target specific products, categories or pages. */\nexport type BlockScope =\n { product_id: number | string } | { category_id: number | string } | { page_id: number | string };\n\nasync function list(params?: Record<string, string>): Promise<HomeComponentData[]> {\n const query = params ? `?${new URLSearchParams(params).toString()}` : '';\n const { data } = await api.get(`component/list${query}`).json<{ data: HomeComponentData[] }>();\n return data ?? [];\n}\n\n/** `blocks` minus each of `excluded`, matched by content: the API sends no id or order to match on. */\nfunction without(blocks: HomeComponentData[], excluded: HomeComponentData[]): HomeComponentData[] {\n if (!excluded.length) return blocks;\n const paths = new Set(excluded.map((block) => block.path));\n const left = excluded.map((block) => JSON.stringify(block));\n return blocks.filter((block) => {\n if (!paths.has(block.path)) return true;\n const index = left.indexOf(JSON.stringify(block));\n if (index === -1) return true;\n left.splice(index, 1);\n return false;\n });\n}\n\nexport const home = {\n components: async (): Promise<HomeComponentData[]> => {\n // The unfiltered list also has the product, category and page blocks, which the home leaves out.\n const [blocks, pageBlocks] = await Promise.all([list(), list({ show_in: 'pages' })]);\n return without(blocks, pageBlocks);\n },\n\n /** The blocks the merchant placed at `hook` on a product, category or page. */\n blocks: async (hook: string, scope: BlockScope): Promise<HomeComponentData[]> => {\n const scopeParams = Object.fromEntries(\n Object.entries(scope).map(([key, id]) => [key, String(id)])\n );\n const blocks = await list({ hooks: hook, ...scopeParams });\n return blocks.map((block) => ({ ...block, path: block.path.replace('home.', '') }));\n },\n\n queries: {\n components: () =>\n queryOptions({\n // Each market (scope) has its own theme version, and its own home page with it.\n queryKey: ['home', 'components', { scope: getActiveScope() }],\n queryFn: () => home.components(),\n }),\n\n blocks: (hook: string, scope: BlockScope) =>\n queryOptions({\n queryKey: ['home', 'blocks', hook, scope],\n queryFn: () => home.blocks(hook, scope),\n }),\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/api/home.ts"],"names":[],"mappings":";;;AAQA,eAAe,KAAK,MAAA,EAA+D;AACjF,EAAA,MAAM,KAAA,GAAQ,SAAS,CAAA,CAAA,EAAI,IAAI,gBAAgB,MAAM,CAAA,CAAE,QAAA,EAAU,CAAA,CAAA,GAAK,EAAA;AACtE,EAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,GAAA,CAAI,IAAI,CAAA,cAAA,EAAiB,KAAK,CAAA,CAAE,CAAA,CAAE,IAAA,EAAoC;AAC7F,EAAA,OAAO,QAAQ,EAAC;AAClB;AAGA,SAAS,OAAA,CAAQ,QAA6B,QAAA,EAAoD;AAChG,EAAA,IAAI,CAAC,QAAA,CAAS,MAAA,EAAQ,OAAO,MAAA;AAC7B,EAAA,MAAM,KAAA,GAAQ,IAAI,GAAA,CAAI,QAAA,CAAS,IAAI,CAAC,KAAA,KAAU,KAAA,CAAM,IAAI,CAAC,CAAA;AACzD,EAAA,MAAM,IAAA,GAAO,SAAS,GAAA,CAAI,CAAC,UAAU,IAAA,CAAK,SAAA,CAAU,KAAK,CAAC,CAAA;AAC1D,E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A,IACP,UAAA,EAAY,MACV,YAAA,CAAa;AAAA;AAAA,MAEX,QAAA,EAAU,CAAC,MAAA,EAAQ,YAAA,EAAc,EAAE,KAAA,EAAO,cAAA,IAAkB,CAAA;AAAA,MAC5D,OAAA,EAAS,MAAM,IAAA,CAAK,UAAA;AAAW,KAChC,CAAA;AAAA,IAEH,MAAA,EAAQ,CAAC,IAAA,EAAc,KAAA,KACrB,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,MAAA,EAAQ,QAAA,EAAU,MAAM,KAAK,CAAA;AAAA,MACxC,OAAA,EAAS,MAAM,IAAA,CAAK,MAAA,CAAO,MAAM,KAAK;AAAA,KACvC;AAAA;AAEP","file":"chunk-TUBNYNJ2.js","sourcesContent":["import { queryOptions } from '@tanstack/react-query';\nimport { api, getActiveScope } from './client';\nimport type { HomeComponentData } from '../types';\n\n/** The page a hook's blocks render on; blocks can target specific products, categories or pages. */\nexport type BlockScope =\n { product_id: number | string } | { category_id: number | string } | { page_id: number | string };\n\nasync function list(params?: Record<string, string>): Promise<HomeComponentData[]> {\n const query = params ? `?${new URLSearchParams(params).toString()}` : '';\n const { data } = await api.get(`component/list${query}`).json<{ data: HomeComponentData[] }>();\n return data ?? [];\n}\n\n/** `blocks` minus each of `excluded`, matched by content: the API sends no id or order to match on. */\nfunction without(blocks: HomeComponentData[], excluded: HomeComponentData[]): HomeComponentData[] {\n if (!excluded.length) return blocks;\n const paths = new Set(excluded.map((block) => block.path));\n const left = excluded.map((block) => JSON.stringify(block));\n return blocks.filter((block) => {\n if (!paths.has(block.path)) return true;\n const index = left.indexOf(JSON.stringify(block));\n if (index === -1) return true;\n left.splice(index, 1);\n return false;\n });\n}\n\nexport const home = {\n components: async (): Promise<HomeComponentData[]> => {\n // The unfiltered list also has the product, category and page blocks, which the home leaves out.\n const [blocks, pageBlocks] = await Promise.all([list(), list({ show_in: 'pages' })]);\n return without(blocks, pageBlocks);\n },\n\n /** The blocks the merchant placed at `hook` on a product, category or page. */\n blocks: async (hook: string, scope: BlockScope): Promise<HomeComponentData[]> => {\n const scopeParams = Object.fromEntries(\n Object.entries(scope).map(([key, id]) => [key, String(id)])\n );\n const blocks = await list({ hooks: hook, ...scopeParams });\n return blocks.map((block) => ({ ...block, path: block.path.replace('home.', '') }));\n },\n\n queries: {\n components: () =>\n queryOptions({\n // Each market (scope) has its own theme version, and its own home page with it.\n queryKey: ['home', 'components', { scope: getActiveScope() }],\n queryFn: () => home.components(),\n }),\n\n blocks: (hook: string, scope: BlockScope) =>\n queryOptions({\n queryKey: ['home', 'blocks', hook, scope],\n queryFn: () => home.blocks(hook, scope),\n }),\n },\n};\n"]}
@@ -7,7 +7,7 @@ import { createIsomorphicFn } from '@tanstack/react-start';
7
7
  import { getCookie } from '@tanstack/react-start/server';
8
8
 
9
9
  // src/utils/engine-version.ts
10
- var ENGINE_VERSION = "1.0.158" ;
10
+ var ENGINE_VERSION = "1.0.160" ;
11
11
  var DEV_SETTINGS_TTL_MS = 60 * 6e4;
12
12
  var HIT_HEADER = "x-twilight-dev-cache";
13
13
  var FETCHED_AT_HEADER = "x-twilight-dev-fetched-at";
@@ -242,5 +242,5 @@ var filesCdn = ky.extend({
242
242
  });
243
243
 
244
244
  export { ENGINE_VERSION, STORE_IDENTIFIER_HEADER, api, cdn, devSettingsFetchedAt, filesCdn, getActiveCurrency, getActiveScope, getActiveScopeId, getAuthToken };
245
- //# sourceMappingURL=chunk-53ZWOFFE.js.map
246
- //# sourceMappingURL=chunk-53ZWOFFE.js.map
245
+ //# sourceMappingURL=chunk-UF6XPCEO.js.map
246
+ //# sourceMappingURL=chunk-UF6XPCEO.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/engine-version.ts","../src/api/dev-settings-cache.ts","../src/api/client.ts"],"names":["entry","createIsomorphicFn","getCookie"],"mappings":";;;;;;;;;AAQO,IAAM,cAAA,GAC0C,SAAA;ACWhD,IAAM,sBAAsB,EAAA,GAAK,GAAA;AAGxC,IAAM,UAAA,G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,GAAA,GAAM,GAAG,MAAA,CAAO;AAAA,EAC3B,MAAA,EAAQ,2BAAA;AAAA,EACR,OAAA,EAAS;AACX,CAAC;AAUM,IAAM,QAAA,GAAW,GAAG,MAAA,CAAO;AAAA,EAChC,MAAA,EAAQ,iCAAA;AAAA,EACR,OAAA,EAAS;AACX,CAAC","file":"chunk-53ZWOFFE.js","sourcesContent":["/**\n * The engine's own build version, injected by tsup `define` when dist is\n * built. Falls back to 'dev' when the source runs unbundled (vitest, direct\n * src imports in the monorepo).\n *\n * Exposed at runtime as `salla.versions.engine` by `useTwilightInit` so a\n * storefront can always be asked which engine build rendered it.\n */\nexport const ENGINE_VERSION: string =\n typeof __TWILIGHT_ENGINE_VERSION__ !== 'undefined' ? __TWILIGHT_ENGINE_VERSION__ : 'dev';\n","import type { AfterResponseHook, BeforeRequestHook } from 'ky';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport { DEV_SETTINGS_REFRESH_COOKIE } from '../utils/dev-settings-refresh';\n\n/**\n * A dev server reuses a store's settings for up to an hour.\n *\n * Every server render asks the API for `store/settings`, and a developer clicking\n * around a theme renders dozens of pages a minute. The API answers a burst of\n * settings requests for one store from one address with a challenge, which a\n * server-side fetch cannot pass, so the dev server rendered \"Store Unavailable\"\n * (6.05k challenged `(development; ssr)` calls in the 7 days to 2026-10-25). In\n * development, on the server, the same request within {@link DEV_SETTINGS_TTL_MS}\n * is answered from memory instead. An hour because the API counts settings\n * requests per hour, so one fetch an hour can never reach its limit; the theme\n * editor's \"Fetch fresh store data\" fetches sooner, and says how old the settings\n * are. A production build never runs it: `import.meta.env.DEV` is statically\n * false there.\n */\nexport const DEV_SETTINGS_TTL_MS = 60 * 60_000;\n\n/** Marks an answer from memory, so the store step does not file it again. */\nconst HIT_HEADER = 'x-twilight-dev-cache';\n\n/** When the answer was really fetched from the API (epoch ms), on fresh answers and reused ones alike. */\nconst FETCHED_AT_HEADER = 'x-twilight-dev-fetched-at';\n\n/**\n * When the dev server fetched these settings from the API, read off the answer the\n * cache handed back; `undefined` when the cache did not handle the call (a\n * production build, the browser, a test), so nothing new reaches the settings there.\n */\nexport function devSettingsFetchedAt(headers: Headers | undefined): number | undefined {\n const at = Number(headers?.get(FETCHED_AT_HEADER));\n return Number.isFinite(at) && at > 0 ? at : undefined;\n}\n\n/**\n * Not carried over to an answer from memory: the body is stored decoded, so its\n * original encoding and length no longer describe it.\n */\nconst DROPPED_HEADERS = new Set(['content-encoding', 'content-length']);\n\ninterface Entry {\n body: string;\n status: number;\n statusText: string;\n headers: [string, string][];\n fetchedAt: number;\n /** The refresh cookie's value when this answer was fetched. */\n refresh: string | null;\n}\n\nexport interface DevSettingsCacheOptions {\n /** Whether this call may use the cache at all. */\n enabled: () => boolean;\n /** The current value of {@link DEV_SETTINGS_REFRESH_COOKIE}, or null. */\n refreshToken: () => string | null;\n now?: () => number;\n ttlMs?: number;\n /** Called the first time an answer comes from memory. */\n onFirstHit?: () => void;\n}\n\nfunction isSettingsRequest(request: Request): boolean {\n if (request.method !== 'GET') return false;\n try {\n return new URL(request.url).pathname.endsWith('/store/settings');\n } catch {\n return false;\n }\n}\n\n/**\n * An answer `requestSettings` accepts: JSON carrying `data`. A 200 without it is\n * refused there as \"Store Unavailable\"; kept here, it would be refused for the next\n * hour too, after the API had recovered.\n */\nfunction hasSettings(body: string): boolean {\n try {\n return Boolean((JSON.parse(body) as { data?: unknown } | null)?.data);\n } catch {\n return false;\n }\n}\n\n/**\n * The request as the API receives it: method, URL and every header the client's\n * hooks set. Keyed on the request itself rather than on the inputs that build it,\n * so a header added to the client later cannot be missing from the key.\n */\nfunction keyOf(request: Request): string {\n const headers = [...request.headers].map(([name, value]) => `${name}: ${value}`).join('\\n');\n return `${request.method} ${request.url}\\n${headers}`;\n}\n\n/**\n * The two ky hooks behind the cache: `lookup` runs last among `beforeRequest`, once\n * every header is set, and `store` among `afterResponse`. Only an answer with\n * settings in it is kept, so a timeout, a 429, a challenge or an empty 200 is asked\n * again on the next render.\n */\nexport function createDevSettingsCache(options: DevSettingsCacheOptions) {\n const {\n enabled,\n refreshToken,\n now = Date.now,\n ttlMs = DEV_SETTINGS_TTL_MS,\n onFirstHit,\n } = options;\n const entries = new Map<string, Entry>();\n let announced = false;\n\n const isFresh = (entry: Entry): boolean =>\n now() - entry.fetchedAt < ttlMs && entry.refresh === refreshToken();\n\n const answerOf = (entry: Entry, hit: boolean): Response => {\n const headers = new Headers(entry.headers);\n headers.set(FETCHED_AT_HEADER, String(entry.fetchedAt));\n if (hit) headers.set(HIT_HEADER, 'hit');\n return new Response(entry.body, {\n status: entry.status,\n statusText: entry.statusText,\n headers,\n });\n };\n\n const lookup: BeforeRequestHook = ({ request }) => {\n if (!enabled() || !isSettingsRequest(request)) return;\n const key = keyOf(request);\n const entry = entries.get(key);\n if (!entry) return;\n if (!isFresh(entry)) {\n entries.delete(key);\n return;\n }\n if (!announced) {\n announced = true;\n onFirstHit?.();\n }\n return answerOf(entry, true);\n };\n\n const store: AfterResponseHook = async ({ request, response }) => {\n if (!enabled() || !isSettingsRequest(request) || !response.ok) return;\n if (response.headers.has(HIT_HEADER)) return;\n // ky hands each hook a clone, so reading it leaves the answer it returns intact.\n const body = await response.text();\n if (!hasSettings(body)) return;\n for (const [key, entry] of entries) {\n if (now() - entry.fetchedAt >= ttlMs) entries.delete(key);\n }\n const entry: Entry = {\n body,\n status: response.status,\n statusText: response.statusText,\n headers: [...response.headers].filter(([name]) => !DROPPED_HEADERS.has(name)),\n fetchedAt: now(),\n refresh: refreshToken(),\n };\n entries.set(keyOf(request), entry);\n // Handed on in place of the API's own answer, so it carries its fetch time too.\n return answerOf(entry, false);\n };\n\n return { lookup, store, clear: () => entries.clear() };\n}\n\nconst readRefreshCookie = createIsomorphicFn()\n .server((): string | null => {\n try {\n return getCookie(DEV_SETTINGS_REFRESH_COOKIE) ?? null;\n } catch {\n return null;\n }\n })\n .client((): string | null => null);\n\nexport const devSettingsCache = createDevSettingsCache({\n // A dev server's render only. A production build has `DEV` statically false,\n // the browser keeps the settings it was handed in its query cache, and vitest\n // runs in `test` mode, where every test wants the request it mocked.\n enabled: () =>\n import.meta.env.DEV && import.meta.env.MODE !== 'test' && typeof document === 'undefined',\n refreshToken: readRefreshCookie,\n onFirstHit: () =>\n console.warn(\n `[twilight] Store settings are reused for up to ${DEV_SETTINGS_TTL_MS / 60_000} minutes while you develop, to stay under the Salla API's rate limit. To see a change you made in the dashboard, press \"Fetch fresh store data\" in the theme editor's side panel: it also says when they were last fetched.`\n ),\n});\n","import ky from 'ky';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport { getStoreIdentifier } from '../utils/sdk-helpers';\nimport { resolveThemeVersionId } from '../utils/theme-version';\nimport { getInjectedRuntimeEnv, readEnv } from '../utils/runtime-env';\nimport { getTwilightContext } from '../twilight/context';\nimport { ENGINE_VERSION } from '../utils/engine-version';\nimport { devSettingsCache } from './dev-settings-cache';\nimport {\n AUTH_TOKEN_COOKIE_NAME,\n CURRENCY_COOKIE_NAME,\n extractCurrencyFromCookies,\n extractScopeFromCookies,\n toCurrencyCode,\n extractTokenFromCookies,\n readSdkScope,\n type ActiveScope,\n} from '../utils/cookies';\n\n// The twilight module store doesn't reliably carry authToken into every scope: on the\n// SERVER workerd has no AsyncLocalStorage, and on BOTH sides this api client can live in a\n// different module instance than the one rootBeforeLoad populates (engine subpath import vs\n// engine-internal relative import). So `getTwilightContext().authToken` is often null even\n// for logged-in users → API calls (orders/customer/…) return `token_not_provided` (400).\n// Read the token directly from the request cookie (server) or document.cookie / salla.storage\n// (client) as a fallback. The server-only import is stripped from the client bundle by\n// createIsomorphicFn.\nconst readFallbackToken = createIsomorphicFn()\n .server((): string | null => {\n try {\n return getCookie(AUTH_TOKEN_COOKIE_NAME) ?? null;\n } catch {\n return null;\n }\n })\n .client((): string | null => {\n const fromCookie =\n typeof document !== 'undefined'\n ? extractTokenFromCookies(document.cookie, AUTH_TOKEN_COOKIE_NAME)\n : null;\n if (fromCookie) return fromCookie;\n const storage = typeof window !== 'undefined' ? window.salla?.storage : undefined;\n const fromStorage =\n typeof storage?.get === 'function' ? storage.get(AUTH_TOKEN_COOKIE_NAME) : null;\n if (typeof fromStorage === 'string' && fromStorage) return fromStorage;\n // `?token=` webview injection lands only on the SDK's axios instance\n const fromSdkApi = typeof window !== 'undefined' ? window.salla?.api?.token : undefined;\n return typeof fromSdkApi === 'string' && fromSdkApi ? fromSdkApi : null;\n });\n\n/**\n * The auth token as the api client sees it: twilight context first, cookie/storage fallback.\n * Use this (not `getTwilightContext().authToken`, which is often null for logged-in users —\n * see the note above) to decide whether an authenticated-only query should run.\n */\nexport const getAuthToken = (): string | null =>\n getTwilightContext().authToken ?? readFallbackToken();\n\nconst readRequestCurrency = createIsomorphicFn()\n .server((): string | null => {\n try {\n return toCurrencyCode(getCookie(CURRENCY_COOKIE_NAME));\n } catch {\n return null;\n }\n })\n .client((): string | null => null);\n\n/**\n * The currency the visitor chose, from the `s-curr` cookie the SDK writes: the API\n * answers in the store's own currency unless the request names one.\n */\nexport function getActiveCurrency(): string | null;\nexport function getActiveCurrency(fallback: string): string;\nexport function getActiveCurrency(fallback: string | null = null): string | null {\n const chosen =\n typeof document !== 'undefined'\n ? extractCurrencyFromCookies(document.cookie)\n : readRequestCurrency();\n return chosen ?? fallback;\n}\n\nconst API_HEADERS = {\n ACCEPT: 'accept',\n ACCEPT_LANGUAGE: 'accept-language',\n APP_OS: 's-app-os',\n APP_VERSION: 's-app-version',\n RAY: 's-ray',\n SOURCE: 's-source',\n THEME_TYPE: 's-theme-type',\n 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 CURRENCY: 'currency',\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 USER_AGENT: 'user-agent',\n} as const;\n\n/**\n * The header every Salla API call is answered by store.\n *\n * Exported because a caller that already knows which store it is asking about\n * must be able to say so on the request itself — see `store.settings`. Without\n * it the only way to name a store is the ambient resolver, and \"the identifier\n * I checked\" and \"the identifier that was sent\" become two different things.\n */\nexport const STORE_IDENTIFIER_HEADER = API_HEADERS.STORE_IDENTIFIER;\n\n/**\n * Active scope: the market plus its branch allocation, as the SDK stores it. On the\n * client it comes from `salla.storage.get('scope')`; before the SDK hydrates storage\n * it falls back to the `scope` cookie the theme mirrors that selection into (see\n * writeScopeCookie), then to the scope twilightMiddleware seeded from the same\n * cookie on the server. Requests vary by the `s-scope-*` headers, so React Query\n * keys must include this to avoid serving another branch's cached categories/products.\n *\n * The cookie step matters for hydration: the SDK is not guaranteed to have\n * populated `salla.storage` by the time the client rebuilds a dehydrated query\n * key, and without it the client would compute null against a scoped SSR key.\n */\nexport const getActiveScope = (): ActiveScope | null => {\n // `!== undefined`, not `!= null`: a null here is the SDK authoritatively saying \"no branch\n // selected\", which must beat a cookie left over from the previous selection. Only a\n // not-yet-ready storage API (undefined) falls through to the cookie.\n const fromStorage = readSdkScope();\n if (fromStorage !== undefined) return fromStorage;\n\n if (typeof document !== 'undefined') {\n const fromCookie = extractScopeFromCookies(document.cookie);\n if (fromCookie != null) return fromCookie;\n }\n\n try {\n return getTwilightContext().scope;\n } catch {\n return null;\n }\n};\n\n/** {@link getActiveScope} reduced to the market id. */\nexport const getActiveScopeId = (): string | null => getActiveScope()?.id ?? null;\n\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 * Who a server-rendered call says it is.\n *\n * Every theme worker reaches api.salla.dev from Cloudflare's one Workers address, so\n * salla.dev's per-IP rate limits counted every React store as a single client and\n * refused the calls each page makes (`store/settings` among them: \"Store Unavailable\").\n * The zone skips rate limiting for a User-Agent shaped `Salla-<Name>/<N.N.N> (<env>; <meta>)`\n * from Cloudflare's or AWS's networks, the convention Salla's other services already send.\n *\n * Built from fixed parts: the zone's pattern takes only digits and dots for the version,\n * so a prerelease suffix is dropped, and an unbundled engine (`dev`) reads as `0.0.0`.\n */\nconst SERVER_USER_AGENT = `Salla-TwilightReact/${\n /^\\d+(?:\\.\\d+)*/.exec(ENGINE_VERSION)?.[0] ?? '0.0.0'\n} (${import.meta.env.DEV ? 'development' : 'production'}; ssr)`;\n\n/**\n * Store API base. `VITE_API_URL` override points a preview at a branch backend; unset → prod\n * `api.salla.dev`. Resolution order matters: the value the SSR worker resolved (published into\n * the head, since worker `vars` are server-only `process.env` and never reach the browser\n * bundle) wins, so the hydrated client keeps talking to the backend that rendered the page.\n */\n\nconst STORE_API_BASE =\n getInjectedRuntimeEnv().apiBase || readEnv('VITE_API_URL') || 'https://api.salla.dev/store/v1';\n\nexport const api = ky.extend({\n prefix: STORE_API_BASE,\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 // Server only. A browser call comes from the shopper's own address and is\n // counted against it, which is what the zone's limits are for.\n if (typeof document === 'undefined') {\n request.headers.set(API_HEADERS.USER_AGENT, SERVER_USER_AGENT);\n }\n\n const scope = getActiveScope();\n\n // The version the request asked for, else the one the settings named for\n // this scope. Absent means \"whatever is live\", which is what an ordinary\n // storefront visit wants — so a null is left off rather than sent empty.\n const versionId = resolveThemeVersionId(scope?.id ?? null);\n if (versionId) {\n request.headers.set(API_HEADERS.VERSION_ID, versionId);\n }\n\n const currency = getActiveCurrency();\n if (currency) request.headers.set(API_HEADERS.CURRENCY, currency);\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 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 // Last, so it keys on the request with every header above set.\n devSettingsCache.lookup,\n ],\n afterResponse: [devSettingsCache.store],\n },\n});\n\nexport const cdn = ky.extend({\n prefix: 'https://cdn.salla.network',\n timeout: 5000,\n});\n\n/**\n * The merchant uploader's public bucket, `admin-uploader-prod`.\n *\n * A different host from {@link cdn} and a different thing behind it: this one\n * is an R2 custom domain, so a read never passes through a worker. Storefront\n * translations live here, per language, under `translations/` — see\n * `api/translations.ts`.\n */\nexport const filesCdn = ky.extend({\n prefix: 'https://cdn.files.salla.network',\n timeout: 5000,\n});\n"]}
1
+ {"version":3,"sources":["../src/utils/engine-version.ts","../src/api/dev-settings-cache.ts","../src/api/client.ts"],"names":["entry","createIsomor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AA;AAAA,MAEA,gBAAA,CAAiB;AAAA,KACnB;AAAA,IACA,aAAA,EAAe,CAAC,gBAAA,CAAiB,KAAK;AAAA;AAE1C,CAAC;AAEM,IAAM,GAAA,GAAM,GAAG,MAAA,CAAO;AAAA,EAC3B,MAAA,EAAQ,2BAAA;AAAA,EACR,OAAA,EAAS;AACX,CAAC;AAUM,IAAM,QAAA,GAAW,GAAG,MAAA,CAAO;AAAA,EAChC,MAAA,EAAQ,iCAAA;AAAA,EACR,OAAA,EAAS;AACX,CAAC","file":"chunk-UF6XPCEO.js","sourcesContent":["/**\n * The engine's own build version, injected by tsup `define` when dist is\n * built. Falls back to 'dev' when the source runs unbundled (vitest, direct\n * src imports in the monorepo).\n *\n * Exposed at runtime as `salla.versions.engine` by `useTwilightInit` so a\n * storefront can always be asked which engine build rendered it.\n */\nexport const ENGINE_VERSION: string =\n typeof __TWILIGHT_ENGINE_VERSION__ !== 'undefined' ? __TWILIGHT_ENGINE_VERSION__ : 'dev';\n","import type { AfterResponseHook, BeforeRequestHook } from 'ky';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport { DEV_SETTINGS_REFRESH_COOKIE } from '../utils/dev-settings-refresh';\n\n/**\n * A dev server reuses a store's settings for up to an hour.\n *\n * Every server render asks the API for `store/settings`, and a developer clicking\n * around a theme renders dozens of pages a minute. The API answers a burst of\n * settings requests for one store from one address with a challenge, which a\n * server-side fetch cannot pass, so the dev server rendered \"Store Unavailable\"\n * (6.05k challenged `(development; ssr)` calls in the 7 days to 2026-10-25). In\n * development, on the server, the same request within {@link DEV_SETTINGS_TTL_MS}\n * is answered from memory instead. An hour because the API counts settings\n * requests per hour, so one fetch an hour can never reach its limit; the theme\n * editor's \"Fetch fresh store data\" fetches sooner, and says how old the settings\n * are. A production build never runs it: `import.meta.env.DEV` is statically\n * false there.\n */\nexport const DEV_SETTINGS_TTL_MS = 60 * 60_000;\n\n/** Marks an answer from memory, so the store step does not file it again. */\nconst HIT_HEADER = 'x-twilight-dev-cache';\n\n/** When the answer was really fetched from the API (epoch ms), on fresh answers and reused ones alike. */\nconst FETCHED_AT_HEADER = 'x-twilight-dev-fetched-at';\n\n/**\n * When the dev server fetched these settings from the API, read off the answer the\n * cache handed back; `undefined` when the cache did not handle the call (a\n * production build, the browser, a test), so nothing new reaches the settings there.\n */\nexport function devSettingsFetchedAt(headers: Headers | undefined): number | undefined {\n const at = Number(headers?.get(FETCHED_AT_HEADER));\n return Number.isFinite(at) && at > 0 ? at : undefined;\n}\n\n/**\n * Not carried over to an answer from memory: the body is stored decoded, so its\n * original encoding and length no longer describe it.\n */\nconst DROPPED_HEADERS = new Set(['content-encoding', 'content-length']);\n\ninterface Entry {\n body: string;\n status: number;\n statusText: string;\n headers: [string, string][];\n fetchedAt: number;\n /** The refresh cookie's value when this answer was fetched. */\n refresh: string | null;\n}\n\nexport interface DevSettingsCacheOptions {\n /** Whether this call may use the cache at all. */\n enabled: () => boolean;\n /** The current value of {@link DEV_SETTINGS_REFRESH_COOKIE}, or null. */\n refreshToken: () => string | null;\n now?: () => number;\n ttlMs?: number;\n /** Called the first time an answer comes from memory. */\n onFirstHit?: () => void;\n}\n\nfunction isSettingsRequest(request: Request): boolean {\n if (request.method !== 'GET') return false;\n try {\n return new URL(request.url).pathname.endsWith('/store/settings');\n } catch {\n return false;\n }\n}\n\n/**\n * An answer `requestSettings` accepts: JSON carrying `data`. A 200 without it is\n * refused there as \"Store Unavailable\"; kept here, it would be refused for the next\n * hour too, after the API had recovered.\n */\nfunction hasSettings(body: string): boolean {\n try {\n return Boolean((JSON.parse(body) as { data?: unknown } | null)?.data);\n } catch {\n return false;\n }\n}\n\n/**\n * The request as the API receives it: method, URL and every header the client's\n * hooks set. Keyed on the request itself rather than on the inputs that build it,\n * so a header added to the client later cannot be missing from the key.\n */\nfunction keyOf(request: Request): string {\n const headers = [...request.headers].map(([name, value]) => `${name}: ${value}`).join('\\n');\n return `${request.method} ${request.url}\\n${headers}`;\n}\n\n/**\n * The two ky hooks behind the cache: `lookup` runs last among `beforeRequest`, once\n * every header is set, and `store` among `afterResponse`. Only an answer with\n * settings in it is kept, so a timeout, a 429, a challenge or an empty 200 is asked\n * again on the next render.\n */\nexport function createDevSettingsCache(options: DevSettingsCacheOptions) {\n const {\n enabled,\n refreshToken,\n now = Date.now,\n ttlMs = DEV_SETTINGS_TTL_MS,\n onFirstHit,\n } = options;\n const entries = new Map<string, Entry>();\n let announced = false;\n\n const isFresh = (entry: Entry): boolean =>\n now() - entry.fetchedAt < ttlMs && entry.refresh === refreshToken();\n\n const answerOf = (entry: Entry, hit: boolean): Response => {\n const headers = new Headers(entry.headers);\n headers.set(FETCHED_AT_HEADER, String(entry.fetchedAt));\n if (hit) headers.set(HIT_HEADER, 'hit');\n return new Response(entry.body, {\n status: entry.status,\n statusText: entry.statusText,\n headers,\n });\n };\n\n const lookup: BeforeRequestHook = ({ request }) => {\n if (!enabled() || !isSettingsRequest(request)) return;\n const key = keyOf(request);\n const entry = entries.get(key);\n if (!entry) return;\n if (!isFresh(entry)) {\n entries.delete(key);\n return;\n }\n if (!announced) {\n announced = true;\n onFirstHit?.();\n }\n return answerOf(entry, true);\n };\n\n const store: AfterResponseHook = async ({ request, response }) => {\n if (!enabled() || !isSettingsRequest(request) || !response.ok) return;\n if (response.headers.has(HIT_HEADER)) return;\n // ky hands each hook a clone, so reading it leaves the answer it returns intact.\n const body = await response.text();\n if (!hasSettings(body)) return;\n for (const [key, entry] of entries) {\n if (now() - entry.fetchedAt >= ttlMs) entries.delete(key);\n }\n const entry: Entry = {\n body,\n status: response.status,\n statusText: response.statusText,\n headers: [...response.headers].filter(([name]) => !DROPPED_HEADERS.has(name)),\n fetchedAt: now(),\n refresh: refreshToken(),\n };\n entries.set(keyOf(request), entry);\n // Handed on in place of the API's own answer, so it carries its fetch time too.\n return answerOf(entry, false);\n };\n\n return { lookup, store, clear: () => entries.clear() };\n}\n\nconst readRefreshCookie = createIsomorphicFn()\n .server((): string | null => {\n try {\n return getCookie(DEV_SETTINGS_REFRESH_COOKIE) ?? null;\n } catch {\n return null;\n }\n })\n .client((): string | null => null);\n\nexport const devSettingsCache = createDevSettingsCache({\n // A dev server's render only. A production build has `DEV` statically false,\n // the browser keeps the settings it was handed in its query cache, and vitest\n // runs in `test` mode, where every test wants the request it mocked.\n enabled: () =>\n import.meta.env.DEV && import.meta.env.MODE !== 'test' && typeof document === 'undefined',\n refreshToken: readRefreshCookie,\n onFirstHit: () =>\n console.warn(\n `[twilight] Store settings are reused for up to ${DEV_SETTINGS_TTL_MS / 60_000} minutes while you develop, to stay under the Salla API's rate limit. To see a change you made in the dashboard, press \"Fetch fresh store data\" in the theme editor's side panel: it also says when they were last fetched.`\n ),\n});\n","import ky from 'ky';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport { getStoreIdentifier } from '../utils/sdk-helpers';\nimport { resolveThemeVersionId } from '../utils/theme-version';\nimport { getInjectedRuntimeEnv, readEnv } from '../utils/runtime-env';\nimport { getTwilightContext } from '../twilight/context';\nimport { ENGINE_VERSION } from '../utils/engine-version';\nimport { devSettingsCache } from './dev-settings-cache';\nimport {\n AUTH_TOKEN_COOKIE_NAME,\n CURRENCY_COOKIE_NAME,\n extractCurrencyFromCookies,\n extractScopeFromCookies,\n toCurrencyCode,\n extractTokenFromCookies,\n readSdkScope,\n type ActiveScope,\n} from '../utils/cookies';\n\n// The twilight module store doesn't reliably carry authToken into every scope: on the\n// SERVER workerd has no AsyncLocalStorage, and on BOTH sides this api client can live in a\n// different module instance than the one rootBeforeLoad populates (engine subpath import vs\n// engine-internal relative import). So `getTwilightContext().authToken` is often null even\n// for logged-in users → API calls (orders/customer/…) return `token_not_provided` (400).\n// Read the token directly from the request cookie (server) or document.cookie / salla.storage\n// (client) as a fallback. The server-only import is stripped from the client bundle by\n// createIsomorphicFn.\nconst readFallbackToken = createIsomorphicFn()\n .server((): string | null => {\n try {\n return getCookie(AUTH_TOKEN_COOKIE_NAME) ?? null;\n } catch {\n return null;\n }\n })\n .client((): string | null => {\n const fromCookie =\n typeof document !== 'undefined'\n ? extractTokenFromCookies(document.cookie, AUTH_TOKEN_COOKIE_NAME)\n : null;\n if (fromCookie) return fromCookie;\n const storage = typeof window !== 'undefined' ? window.salla?.storage : undefined;\n const fromStorage =\n typeof storage?.get === 'function' ? storage.get(AUTH_TOKEN_COOKIE_NAME) : null;\n if (typeof fromStorage === 'string' && fromStorage) return fromStorage;\n // `?token=` webview injection lands only on the SDK's axios instance\n const fromSdkApi = typeof window !== 'undefined' ? window.salla?.api?.token : undefined;\n return typeof fromSdkApi === 'string' && fromSdkApi ? fromSdkApi : null;\n });\n\n/**\n * The auth token as the api client sees it: twilight context first, cookie/storage fallback.\n * Use this (not `getTwilightContext().authToken`, which is often null for logged-in users —\n * see the note above) to decide whether an authenticated-only query should run.\n */\nexport const getAuthToken = (): string | null =>\n getTwilightContext().authToken ?? readFallbackToken();\n\nconst readRequestCurrency = createIsomorphicFn()\n .server((): string | null => {\n try {\n return toCurrencyCode(getCookie(CURRENCY_COOKIE_NAME));\n } catch {\n return null;\n }\n })\n .client((): string | null => null);\n\n/**\n * The currency the visitor chose, from the `s-curr` cookie the SDK writes: the API\n * answers in the store's own currency unless the request names one.\n */\nexport function getActiveCurrency(): string | null;\nexport function getActiveCurrency(fallback: string): string;\nexport function getActiveCurrency(fallback: string | null = null): string | null {\n const chosen =\n typeof document !== 'undefined'\n ? extractCurrencyFromCookies(document.cookie)\n : readRequestCurrency();\n return chosen ?? fallback;\n}\n\nconst API_HEADERS = {\n ACCEPT: 'accept',\n ACCEPT_LANGUAGE: 'accept-language',\n APP_OS: 's-app-os',\n APP_VERSION: 's-app-version',\n RAY: 's-ray',\n SOURCE: 's-source',\n THEME_TYPE: 's-theme-type',\n 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 CURRENCY: 'currency',\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 USER_AGENT: 'user-agent',\n} as const;\n\n/**\n * The header every Salla API call is answered by store.\n *\n * Exported because a caller that already knows which store it is asking about\n * must be able to say so on the request itself — see `store.settings`. Without\n * it the only way to name a store is the ambient resolver, and \"the identifier\n * I checked\" and \"the identifier that was sent\" become two different things.\n */\nexport const STORE_IDENTIFIER_HEADER = API_HEADERS.STORE_IDENTIFIER;\n\n/**\n * Active scope: the market plus its branch allocation, as the SDK stores it. On the\n * client it comes from `salla.storage.get('scope')`; before the SDK hydrates storage\n * it falls back to the `scope` cookie the theme mirrors that selection into (see\n * writeScopeCookie), then to the scope twilightMiddleware seeded from the same\n * cookie on the server. Requests vary by the `s-scope-*` headers, so React Query\n * keys must include this to avoid serving another branch's cached categories/products.\n *\n * The cookie step matters for hydration: the SDK is not guaranteed to have\n * populated `salla.storage` by the time the client rebuilds a dehydrated query\n * key, and without it the client would compute null against a scoped SSR key.\n */\nexport const getActiveScope = (): ActiveScope | null => {\n // `!== undefined`, not `!= null`: a null here is the SDK authoritatively saying \"no branch\n // selected\", which must beat a cookie left over from the previous selection. Only a\n // not-yet-ready storage API (undefined) falls through to the cookie.\n const fromStorage = readSdkScope();\n if (fromStorage !== undefined) return fromStorage;\n\n if (typeof document !== 'undefined') {\n const fromCookie = extractScopeFromCookies(document.cookie);\n if (fromCookie != null) return fromCookie;\n }\n\n try {\n return getTwilightContext().scope;\n } catch {\n return null;\n }\n};\n\n/** {@link getActiveScope} reduced to the market id. */\nexport const getActiveScopeId = (): string | null => getActiveScope()?.id ?? null;\n\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 * Who a server-rendered call says it is.\n *\n * Every theme worker reaches api.salla.dev from Cloudflare's one Workers address, so\n * salla.dev's per-IP rate limits counted every React store as a single client and\n * refused the calls each page makes (`store/settings` among them: \"Store Unavailable\").\n * The zone skips rate limiting for a User-Agent shaped `Salla-<Name>/<N.N.N> (<env>; <meta>)`\n * from Cloudflare's or AWS's networks, the convention Salla's other services already send.\n *\n * Built from fixed parts: the zone's pattern takes only digits and dots for the version,\n * so a prerelease suffix is dropped, and an unbundled engine (`dev`) reads as `0.0.0`.\n */\nconst SERVER_USER_AGENT = `Salla-TwilightReact/${\n /^\\d+(?:\\.\\d+)*/.exec(ENGINE_VERSION)?.[0] ?? '0.0.0'\n} (${import.meta.env.DEV ? 'development' : 'production'}; ssr)`;\n\n/**\n * Store API base. `VITE_API_URL` override points a preview at a branch backend; unset → prod\n * `api.salla.dev`. Resolution order matters: the value the SSR worker resolved (published into\n * the head, since worker `vars` are server-only `process.env` and never reach the browser\n * bundle) wins, so the hydrated client keeps talking to the backend that rendered the page.\n */\n\nconst STORE_API_BASE =\n getInjectedRuntimeEnv().apiBase || readEnv('VITE_API_URL') || 'https://api.salla.dev/store/v1';\n\nexport const api = ky.extend({\n prefix: STORE_API_BASE,\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 // Server only. A browser call comes from the shopper's own address and is\n // counted against it, which is what the zone's limits are for.\n if (typeof document === 'undefined') {\n request.headers.set(API_HEADERS.USER_AGENT, SERVER_USER_AGENT);\n }\n\n const scope = getActiveScope();\n\n // The version the request asked for, else the one the settings named for\n // this scope. Absent means \"whatever is live\", which is what an ordinary\n // storefront visit wants — so a null is left off rather than sent empty.\n const versionId = resolveThemeVersionId(scope?.id ?? null);\n if (versionId) {\n request.headers.set(API_HEADERS.VERSION_ID, versionId);\n }\n\n const currency = getActiveCurrency();\n if (currency) request.headers.set(API_HEADERS.CURRENCY, currency);\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 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 // Last, so it keys on the request with every header above set.\n devSettingsCache.lookup,\n ],\n afterResponse: [devSettingsCache.store],\n },\n});\n\nexport const cdn = ky.extend({\n prefix: 'https://cdn.salla.network',\n timeout: 5000,\n});\n\n/**\n * The merchant uploader's public bucket, `admin-uploader-prod`.\n *\n * A different host from {@link cdn} and a different thing behind it: this one\n * is an R2 custom domain, so a read never passes through a worker. Storefront\n * translations live here, per language, under `translations/` — see\n * `api/translations.ts`.\n */\nexport const filesCdn = ky.extend({\n prefix: 'https://cdn.files.salla.network',\n timeout: 5000,\n});\n"]}
@@ -1,5 +1,5 @@
1
- import { orThrow } from './chunk-U2XY667M.js';
2
- import { getAuthToken, api } from './chunk-53ZWOFFE.js';
1
+ import { orThrow } from './chunk-PUXHO3JL.js';
2
+ import { getAuthToken, api } from './chunk-UF6XPCEO.js';
3
3
  import { queryOptions } from '@tanstack/react-query';
4
4
 
5
5
  var loyalty = {
@@ -29,5 +29,5 @@ var loyalty = {
29
29
  };
30
30
 
31
31
  export { loyalty };
32
- //# sourceMappingURL=chunk-KEGJQH7N.js.map
33
- //# sourceMappingURL=chunk-KEGJQH7N.js.map
32
+ //# sourceMappingURL=chunk-VPKQVAM3.js.map
33
+ //# sourceMappingURL=chunk-VPKQVAM3.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/loyalty.ts"],"names":[],"mappings":";;;;AAKO,IAAM,OAAA,GAAU;AAAA,EACrB,KAAK,YAA8B;AACjC,IAAA,MAAM,EAAE,MAAK,GAAI,MAAM,IAAI,GAAA,CAAI,SAAS,EAAE,IAAA,EAAwB;AAClE,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AAAA,EAEA,UAAA,EAAY,MAAwB,OAAA,CAAQ,OAAA,CAAQ,KAAK,CAAA;AAAA,EAEzD,kBAAkB,YAA6B;AAC7C,IAAA,MAAM,WAAW,MAAM,GAAA,CAAI,GAAA,CAAI,gBAAgB,EAAE,IAAA,EAA2B;AAC5E,IAAA,OAAO,QAAA,CAAS,OAAA;AAAA,EAClB,CAAA;AAAA,EAEA,OAAA,EAAS;AAAA,IACP,MAAA,EAAQ,MACN,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,SAAS,CAAA;AAAA,MACpB,OAAA,EAAS,MAAM,OAAA,CAAQ,GAAA;AAAI,KAC5B,CAAA;AAAA,IACH,MAAA,EAAQ,MACN,YAAA,CAA4B;AAAA,MAC1B,QAAA,EAAU,CAAC,SAAA,EAAW,QAAQ,CAAA;AAAA,MAC9B,OAAA,EAAS,MAAM,OAAA,CAAQ,gBAAA,EAAiB;AAAA;AAAA;AAAA,MAGxC,OAAA,EAAS,CAAC,CAAC,YAAA,EAAa;AAAA,MACxB,SAAA,EAAW;AAAA,KACZ;AAAA;AAEP","file":"chunk-KEGJQH7N.js","sourcesContent":["import { queryOptions } from '@tanstack/react-query';\nimport { api, getAuthToken } from './client';\nimport type { Loyalty, PointBalanceResponse } from '../routes/loyalty/types';\nimport { orThrow } from '../providers/NavigationProvider';\n\nexport const loyalty = {\n get: async (): Promise<Loyalty> => {\n const { data } = await api.get('loyalty').json<{ data: Loyalty }>();\n return data;\n },\n\n getOrThrow: (): Promise<Loyalty> => orThrow(loyalty.get()),\n\n getPointsBalance: async (): Promise<number> => {\n const response = await api.get('balance/points').json<PointBalanceResponse>();\n return response.balance;\n },\n\n queries: {\n detail: () =>\n queryOptions({\n queryKey: ['loyalty'],\n queryFn: () => loyalty.get(),\n }),\n points: () =>\n queryOptions<number | null>({\n queryKey: ['loyalty', 'points'],\n queryFn: () => loyalty.getPointsBalance(),\n // Points are customer-scoped; skip for guests (no token) — the request would\n // otherwise 400 with `token_not_provided`.\n enabled: !!getAuthToken(),\n staleTime: 30_000,\n }),\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/api/loyalty.ts"],"names":[],"mappings":";;;;AAKO,IAAM,OAAA,GAAU;AAAA,EACrB,KAAK,YAA8B;AACjC,IAAA,MAAM,EAAE,MAAK,GAAI,MAAM,IAAI,GAAA,CAAI,SAAS,EAAE,IAAA,EAAwB;AAClE,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AAAA,EAEA,UAAA,EAAY,MAAwB,OAAA,CAAQ,OAAA,CAAQ,KAAK,CAAA;AAAA,EAEzD,kBAAkB,YAA6B;AAC7C,IAAA,MAAM,WAAW,MAAM,GAAA,CAAI,GAAA,CAAI,gBAAgB,EAAE,IAAA,EAA2B;AAC5E,IAAA,OAAO,QAAA,CAAS,OAAA;AAAA,EAClB,CAAA;AAAA,EAEA,OAAA,EAAS;AAAA,IACP,MAAA,EAAQ,MACN,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,SAAS,CAAA;AAAA,MACpB,OAAA,EAAS,MAAM,OAAA,CAAQ,GAAA;AAAI,KAC5B,CAAA;AAAA,IACH,MAAA,EAAQ,MACN,YAAA,CAA4B;AAAA,MAC1B,QAAA,EAAU,CAAC,SAAA,EAAW,QAAQ,CAAA;AAAA,MAC9B,OAAA,EAAS,MAAM,OAAA,CAAQ,gBAAA,EAAiB;AAAA;AAAA;AAAA,MAGxC,OAAA,EAAS,CAAC,CAAC,YAAA,EAAa;AAAA,MACxB,SAAA,EAAW;AAAA,KACZ;AAAA;AAEP","file":"chunk-VPKQVAM3.js","sourcesContent":["import { queryOptions } from '@tanstack/react-query';\nimport { api, getAuthToken } from './client';\nimport type { Loyalty, PointBalanceResponse } from '../routes/loyalty/types';\nimport { orThrow } from '../providers/NavigationProvider';\n\nexport const loyalty = {\n get: async (): Promise<Loyalty> => {\n const { data } = await api.get('loyalty').json<{ data: Loyalty }>();\n return data;\n },\n\n getOrThrow: (): Promise<Loyalty> => orThrow(loyalty.get()),\n\n getPointsBalance: async (): Promise<number> => {\n const response = await api.get('balance/points').json<PointBalanceResponse>();\n return response.balance;\n },\n\n queries: {\n detail: () =>\n queryOptions({\n queryKey: ['loyalty'],\n queryFn: () => loyalty.get(),\n }),\n points: () =>\n queryOptions<number | null>({\n queryKey: ['loyalty', 'points'],\n queryFn: () => loyalty.getPointsBalance(),\n // Points are customer-scoped; skip for guests (no token) — the request would\n // otherwise 400 with `token_not_provided`.\n enabled: !!getAuthToken(),\n staleTime: 30_000,\n }),\n },\n};\n"]}
@@ -147,7 +147,7 @@ function takeFrameReport(message) {
147
147
  async function answerLookup(message) {
148
148
  const { requestId, source, query } = message;
149
149
  try {
150
- const { lookupInStore } = await import('./store-lookup-RGH3DTCO.js');
150
+ const { lookupInStore } = await import('./store-lookup-UXXFSOT5.js');
151
151
  sendToEditor({ kind: "lookup-result", requestId, items: await lookupInStore(source, query) });
152
152
  } catch (error) {
153
153
  sendToEditor({
@@ -500,5 +500,5 @@ function useDevLayoutBlocks(components) {
500
500
  var useDevHomeBlocks = import.meta.env.DEV ? useDevLayoutBlocks : (components) => components;
501
501
 
502
502
  export { blockPath, devSettingsStore, useDevEditorMeta, useDevHomeBlocks, useDevReportSettingsFetchedAt, useDevSettingsOverrides, useDevSettingsState };
503
- //# sourceMappingURL=chunk-XFTY3TUT.js.map
504
- //# sourceMappingURL=chunk-XFTY3TUT.js.map
503
+ //# sourceMappingURL=chunk-VXFRQB3H.js.map
504
+ //# sourceMappingURL=chunk-VXFRQB3H.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dev/dev-settings-store.ts"],"names":["block"],"mappings":";;;;AA4CA,IAAM,kBAAA,GAAqB,uBAAA;AAE3B,IAAM,aAAA,GAAgB,GAAA;AAEtB,IAAM,YAAA,GAAe,kBAAA;AAErB,IAAM,aAAA,GAAgB,iBAAA;AAEtB,IAAM,aAAA,GAAgB,GAAA;AACtB,IAAM,cAAA,GAAiB,IAAA;AAiBvB,IAAM,cAAA,uBAAqB,GAAA,EAA2B;AAqBtD,SAAS,QAAA,CAAS,QAAQ,CAAA,EAAW;AACnC,EAAA,MAAM,SAAS,UAAA,CAAW,MAAA,CAAO,gBAAgB,IAAI,UAAA,CAAW,KAAK,CAAC,CAAA;AACtE,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,MAAA,EAAQ,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC3E;AAEA,IAAI,KAAA;AAQJ,SAAS,OAAA,GAAkB;AACzB,EAAA,KAAA,KAAU,QAAA,EAAS;AACnB,EAAA,OAAO,KAAA;AACT;AAEA,IAAI,UAAA;AACJ,IAAI,SAAA,GAA6B,mBAAA;AAGjC,SAAS,QAAA,GAA4B;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,KAAA,CAAM,MAAA,EAAQ,MAAA,EAAQ,CAAA;AAE3D,MAAA,MAAM,KAAA,GAAQ,SAAS,CAAA,EAAG,KAAA,CAAM,EAAE,CAAA,CAAA,EAAI,MAAM,KAAK,KAAA,CAAM,EAAA;AACvD,MAAA,OAAO,EAAE,GAAG,KAAA,CAAM,MAAA,EAAQ,MAAM,KAAA,CAAM,IAAA,EAAM,UAAU,KAAA,EAAM;AAAA,IAC9D,CAAC,CAAA;AAAA,EACH,CAAA,EAAG,CAAC,UAAA,EAAY,SAAS,CAAC,CAAA;AAC5B;AAEO,IAAM,mBACX,MAAA,CAAA,IAAA,CAAY,GAAA,CAAI,GAAA,GAAM,kBAAA,GAAqB,CAAC,UAAA,KAAe","file":"chunk-XFTY3TUT.js","sourcesContent":["/**\n * Client-side store for the dev editor: theme-setting overrides and a dev-owned\n * home layout. Saved to `twilight.preview.json` through the dev server (see\n * `twilight-schema.plugin.ts`), not to localStorage, for three reasons: the\n * server render can read a file, so the page hydrates with the edited layout\n * instead of flashing the store's; the state survives a port or browser\n * change; and the developer can open, diff or delete it.\n *\n * The saved state reaches this module through `virtual:twilight/schema`, which\n * the root route imports on both sides before anything renders and which puts\n * it on `globalThis[DEV_PREVIEW_GLOBAL]`. Server snapshots read that value\n * (the server's modules are re-run after each save); the browser copies it once\n * and then owns the state.\n *\n * The theme editor (`/__twilight/editor`) frames the storefront, so two copies\n * of this store run side by side. Edits reach every copy on the origin at once\n * over a `BroadcastChannel` (the file save is debounced), and only the copy\n * that made an edit saves it. Everything else between an editor and its frame\n * (the home page's blocks, the store base, scroll-to-block) goes by\n * `postMessage` to that one window, so another storefront tab never answers.\n */\n\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport {\n DEV_LOOKUP_TIMEOUT_MS,\n DEV_PREVIEW_ENDPOINT,\n DEV_PREVIEW_EVENT,\n DEV_PREVIEW_GLOBAL,\n EMPTY_PREVIEW_STATE,\n isEditorFrame,\n normalizePreviewState,\n type DevLookupItem,\n type DevLookupSource,\n type DevPreviewBlock,\n type DevPreviewState,\n type DevSchema,\n} from './schema-types';\nimport { resolveStoreBase } from '../utils/store-identity';\n\nexport type DevSettingsState = DevPreviewState;\nexport type DevSaveStatus = 'idle' | 'saving' | 'saved' | 'error';\ntype LiveBlocks = { path?: string }[];\n\n/** Where the old localStorage-backed widget kept its state; migrated once. */\nconst LEGACY_STORAGE_KEY = 'twilight:dev-settings';\n/** Batch keystrokes into one write. */\nconst SAVE_DELAY_MS = 250;\n/** Same-browser channel every copy of the store listens on, for edits. */\nconst CHANNEL_NAME = 'twilight:preview';\n/** Envelope type of the editor ↔ frame `postMessage`s. */\nconst FRAME_MESSAGE = 'twilight:editor';\n/** How long the frame keeps looking for a block that is still rendering (just added, say). */\nconst FOCUS_WAIT_MS = 2000;\nconst FOCUS_FLASH_MS = 1200;\n\n/** Editor ↔ the storefront it frames. */\ntype FrameMessage =\n | { kind: 'live-blocks'; blocks: LiveBlocks | null }\n | { kind: 'frame-info'; base: string | null }\n | { kind: 'settings-fetched'; at: number }\n | { kind: 'request-live-blocks' }\n | { kind: 'focus-block'; index: number }\n | { kind: 'lookup'; requestId: string; source: DevLookupSource; query: string }\n | { kind: 'lookup-result'; requestId: string; items?: DevLookupItem[]; error?: string };\n\ninterface PendingLookup {\n resolve: (items: DevLookupItem[]) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\nconst pendingLookups = new Map<string, PendingLookup>();\n\n/** What the editor shows besides the saved state. */\nexport interface DevEditorMeta {\n /** The blocks the framed home page shows; `null` when it is not on the home page. */\n liveBlocks: LiveBlocks | null;\n saveStatus: DevSaveStatus;\n /** The frame's store segment; `undefined` until the frame has said. */\n frameBase: string | null | undefined;\n /**\n * When the dev server last asked the API for the frame's store settings (epoch\n * ms), which it reuses for a while (see `api/dev-settings-cache.ts`); `null`\n * until the frame says.\n */\n settingsFetchedAt: number | null;\n}\n\n/**\n * A short random hex id. `getRandomValues`, not `randomUUID`: the latter only\n * exists in secure contexts, and the dev server may be opened on a LAN address.\n */\nfunction randomId(bytes = 6): string {\n const values = globalThis.crypto.getRandomValues(new Uint8Array(bytes));\n return Array.from(values, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nlet tabId: string | undefined;\n\n/**\n * Sent with every save so this tab can ignore its own broadcast. Made on first\n * use, never at module load: Cloudflare Workers refuse random values in global\n * scope, and this module is in the worker bundle (its use is dev-only, its\n * top level is not).\n */\nfunction myTabId(): string {\n tabId ??= randomId();\n return tabId;\n}\n\nlet seedSource: unknown;\nlet seedState: DevPreviewState = EMPTY_PREVIEW_STATE;\n\n/** The saved file as this page loaded it, normalized once per value so snapshots keep their identity. */\nfunction readSeed(): DevPreviewState {\n const raw = (globalThis as Record<string, unknown>)[DEV_PREVIEW_GLOBAL];\n if (raw !== seedSource) {\n seedSource = raw;\n seedState = normalizePreviewState(raw) ?? EMPTY_PREVIEW_STATE;\n }\n return seedState;\n}\n\n// The widget (bundled into the `/dev` entry) and the theme merge (bundled into\n// the engine index via `useTwilightInit`) import this module from two different\n// chunks, so each would otherwise get its OWN copy of the state — the widget\n// would enable a store the merge never reads. Back the state with a single\n// globalThis-keyed instance so every copy shares one source of truth. Dev-only,\n// so a global is acceptable (and lazy, so the module stays side-effect free and\n// tree-shakes out of production).\ninterface DevStoreSingleton {\n state: DevPreviewState;\n listeners: Set<() => void>;\n /** This page's own home blocks, when it is a storefront on its home page. Never saved. */\n ownBlocks: LiveBlocks | null;\n meta: DevEditorMeta;\n metaListeners: Set<() => void>;\n saveTimer: ReturnType<typeof setTimeout> | undefined;\n /** An edit that has not been sent yet. */\n dirty: boolean;\n /** A save request on its way; the next one waits for it, so saves land in order. */\n inFlight: boolean;\n /** The old localStorage copy is removed only once the file has the migrated values. */\n legacyPending: boolean;\n channel: BroadcastChannel | null;\n /** In the editor: the storefront frame's window. */\n getFrame: (() => Window | null) | null;\n /** In the frame: when the server fetched the settings this page rendered with. */\n settingsFetchedAt: number | null;\n /** Detach this copy's listeners and channel. A page keeps one copy for good; tests swap them. */\n dispose: () => void;\n}\n\nconst SINGLETON_KEY = '__twilightDevSettingsStore__';\n\nfunction singleton(): DevStoreSingleton {\n const g = globalThis as unknown as Record<string, DevStoreSingleton | undefined>;\n let s = g[SINGLETON_KEY];\n if (!s) {\n const seeded = (globalThis as Record<string, unknown>)[DEV_PREVIEW_GLOBAL] != null;\n s = {\n state: readSeed(),\n listeners: new Set(),\n ownBlocks: null,\n meta: { liveBlocks: null, saveStatus: 'idle', frameBase: undefined, settingsFetchedAt: null },\n metaListeners: new Set(),\n saveTimer: undefined,\n dirty: false,\n inFlight: false,\n legacyPending: false,\n channel: null,\n getFrame: null,\n settingsFetchedAt: null,\n dispose: () => {},\n };\n g[SINGLETON_KEY] = s;\n if (typeof window !== 'undefined') setUpBrowser(s, seeded);\n }\n return s;\n}\n\nfunction setUpBrowser(s: DevStoreSingleton, seeded: boolean): void {\n const listeners = new AbortController();\n const { signal } = listeners;\n if (!seeded) migrateLegacy(s);\n listenForOtherTabs();\n s.channel = openChannel();\n listenForFrameMessages(s, signal);\n window.addEventListener('pagehide', () => flushOnExit(s), { signal });\n s.dispose = () => {\n listeners.abort();\n s.channel?.close();\n clearTimeout(s.saveTimer);\n };\n if (isEditorFrame()) sendToEditor({ kind: 'frame-info', base: resolveStoreBase() });\n}\n\n/** Carry the old widget's settings over; its per-block patches don't map to a layout. */\nfunction migrateLegacy(s: DevStoreSingleton): void {\n try {\n const raw = window.localStorage.getItem(LEGACY_STORAGE_KEY);\n if (!raw) return;\n const legacy = normalizePreviewState(JSON.parse(raw));\n if (!legacy) return;\n s.state = { enabled: legacy.enabled, settings: legacy.settings, layout: null };\n s.legacyPending = true;\n scheduleSave(s);\n } catch {\n // Storage blocked or the old value is corrupt: nothing worth keeping.\n }\n}\n\n/** Vite's HMR client, typed locally: the engine's `ImportMeta` must not clash with `vite/client`. */\ninterface HotContext {\n on(event: string, cb: (payload: { state?: unknown; from?: unknown }) => void): void;\n}\n\n/**\n * Take a state another copy committed. Not while this copy has an edit of its\n * own waiting to be saved: that edit is newer, and saving it will tell the rest.\n */\nfunction receive(raw: unknown): void {\n const s = singleton();\n if (s.dirty || s.inFlight || s.saveTimer) return;\n const next = normalizePreviewState(raw);\n if (next && JSON.stringify(next) !== JSON.stringify(s.state)) emit(next);\n}\n\n/** Tabs in another browser hear about a save from the dev server. */\nfunction listenForOtherTabs(): void {\n const hot = (import.meta as ImportMeta & { hot?: HotContext }).hot;\n if (!hot) return;\n hot.on(DEV_PREVIEW_EVENT, (payload) => {\n if (payload?.from !== myTabId()) receive(payload?.state);\n });\n}\n\nfunction openChannel(): BroadcastChannel | null {\n if (typeof BroadcastChannel === 'undefined') return null;\n const channel = new BroadcastChannel(CHANNEL_NAME);\n channel.onmessage = ({ data }: MessageEvent<{ state?: unknown; from?: string }>) => {\n if (data && data.from !== myTabId()) receive(data.state);\n };\n return channel;\n}\n\nfunction sendToEditor(message: FrameMessage): void {\n if (isEditorFrame())\n window.parent.postMessage({ type: FRAME_MESSAGE, message }, window.location.origin);\n}\n\nfunction sendToFrame(message: FrameMessage): void {\n singleton().getFrame?.()?.postMessage({ type: FRAME_MESSAGE, message }, window.location.origin);\n}\n\nfunction reportToEditor(s: DevStoreSingleton): void {\n sendToEditor({ kind: 'frame-info', base: resolveStoreBase() });\n sendToEditor({ kind: 'live-blocks', blocks: s.ownBlocks });\n if (s.settingsFetchedAt != null)\n sendToEditor({ kind: 'settings-fetched', at: s.settingsFetchedAt });\n}\n\n/**\n * The editor ↔ frame conversation. A frame only takes requests from its own\n * parent; an editor only takes reports from the frame it shows.\n */\nfunction listenForFrameMessages(s: DevStoreSingleton, signal: AbortSignal): void {\n window.addEventListener(\n 'message',\n (event: MessageEvent) => {\n if (event.origin !== window.location.origin || event.data?.type !== FRAME_MESSAGE) return;\n const message = event.data.message as FrameMessage;\n if (window.parent !== window && event.source === window.parent) {\n answerEditor(s, message);\n return;\n }\n const frame = s.getFrame?.();\n if (frame && event.source === frame) takeFrameReport(message);\n },\n { signal }\n );\n}\n\n/** In the frame: what its editor asks for. */\nfunction answerEditor(s: DevStoreSingleton, message: FrameMessage): void {\n if (message.kind === 'request-live-blocks') reportToEditor(s);\n else if (message.kind === 'focus-block') scrollToBlock(message.index);\n else if (message.kind === 'lookup') void answerLookup(message);\n}\n\n/** In the editor: what its frame reports. */\nfunction takeFrameReport(message: FrameMessage): void {\n if (message.kind === 'lookup-result') settleLookup(message);\n else if (message.kind === 'live-blocks') setMeta({ liveBlocks: message.blocks });\n else if (message.kind === 'frame-info') setMeta({ frameBase: message.base });\n else if (message.kind === 'settings-fetched' && Number.isFinite(message.at))\n setMeta({ settingsFetchedAt: message.at });\n}\n\n/** In the frame: look the request up in the store and send back what was found, or why not. */\nasync function answerLookup(message: Extract<FrameMessage, { kind: 'lookup' }>): Promise<void> {\n const { requestId, source, query } = message;\n try {\n const { lookupInStore } = await import('./store-lookup');\n sendToEditor({ kind: 'lookup-result', requestId, items: await lookupInStore(source, query) });\n } catch (error) {\n sendToEditor({\n kind: 'lookup-result',\n requestId,\n error: error instanceof Error ? error.message : 'lookup failed',\n });\n }\n}\n\nfunction settleLookup(message: Extract<FrameMessage, { kind: 'lookup-result' }>): void {\n const pending = pendingLookups.get(message.requestId);\n if (!pending) return;\n pendingLookups.delete(message.requestId);\n clearTimeout(pending.timer);\n if (message.items) pending.resolve(message.items);\n else pending.reject(new Error(message.error ?? 'lookup failed'));\n}\n\n/**\n * In the editor's frame: bring a home block into view and flash an outline on\n * it. Dev-only editor chrome, so it styles the element directly rather than\n * through the theme's React tree. A block added a moment ago may not be in the\n * DOM yet, so look for it for a little while.\n */\nfunction scrollToBlock(index: number): void {\n const started = Date.now();\n const find = () => {\n const el = document.querySelector<HTMLElement>(`[data-home-block=\"${index}\"]`);\n if (!el) {\n if (Date.now() - started < FOCUS_WAIT_MS) requestAnimationFrame(find);\n return;\n }\n const { outline, outlineOffset, scrollMarginTop } = el.style;\n // Clear a sticky header, which would otherwise cover the block's top.\n el.style.scrollMarginTop = '80px';\n el.scrollIntoView({ behavior: 'smooth', block: 'start' });\n el.style.outline = '2px solid #0d9488';\n el.style.outlineOffset = '-2px';\n setTimeout(() => {\n el.style.outline = outline;\n el.style.outlineOffset = outlineOffset;\n el.style.scrollMarginTop = scrollMarginTop;\n }, FOCUS_FLASH_MS);\n };\n find();\n}\n\nfunction emit(next: DevPreviewState): void {\n const s = singleton();\n s.state = next;\n s.listeners.forEach((l) => l());\n}\n\nfunction setMeta(patch: Partial<DevEditorMeta>): void {\n const s = singleton();\n s.meta = { ...s.meta, ...patch };\n s.metaListeners.forEach((l) => l());\n}\n\nfunction saveRequest(s: DevStoreSingleton, keepalive = false): Promise<Response> {\n return fetch(DEV_PREVIEW_ENDPOINT, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ state: s.state, from: myTabId() }),\n keepalive,\n });\n}\n\n/** Send the current state, one request at a time; edits made meanwhile go in the next one. */\nasync function flush(s: DevStoreSingleton): Promise<void> {\n if (s.inFlight || !s.dirty) return;\n s.inFlight = true;\n s.dirty = false;\n let failed = false;\n try {\n const res = await saveRequest(s);\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n if (s.legacyPending) {\n s.legacyPending = false;\n try {\n window.localStorage.removeItem(LEGACY_STORAGE_KEY);\n } catch {\n // Storage went away; the file has the values now either way.\n }\n }\n if (!s.dirty && !s.saveTimer) setMeta({ saveStatus: 'saved' });\n } catch (error) {\n // Still unsaved: another tab's state must not replace it, and leaving the\n // page still sends it. Edits made while this request was out are sent once\n // more; the failed one alone waits for the next edit, so nothing loops.\n failed = !s.dirty;\n s.dirty = true;\n setMeta({ saveStatus: 'error' });\n console.error('[twilight-react:preview] could not save twilight.preview.json', error);\n } finally {\n s.inFlight = false;\n if (!failed && s.dirty && !s.saveTimer) void flush(s);\n }\n}\n\nfunction scheduleSave(s: DevStoreSingleton): void {\n if (typeof window === 'undefined' || typeof fetch === 'undefined') return;\n s.dirty = true;\n clearTimeout(s.saveTimer);\n setMeta({ saveStatus: 'saving' });\n s.saveTimer = setTimeout(() => {\n s.saveTimer = undefined;\n void flush(s);\n }, SAVE_DELAY_MS);\n}\n\n/** Closing or reloading the editor must not drop the last edit: send it on the way out. */\nfunction flushOnExit(s: DevStoreSingleton): void {\n if (!s.dirty) return;\n clearTimeout(s.saveTimer);\n s.saveTimer = undefined;\n s.dirty = false;\n void saveRequest(s, true).catch(() => {});\n}\n\nfunction commit(next: DevPreviewState): void {\n const s = singleton();\n emit(next);\n try {\n s.channel?.postMessage({ state: next, from: myTabId() });\n } catch {\n // A value that can't be cloned: the other copies pick it up from the save instead.\n }\n scheduleSave(s);\n}\n\nfunction newBlockId(): string {\n return `b-${randomId()}`;\n}\n\n/** Home loader spelling of a twilight.json path. */\nexport function blockPath(path: string): string {\n return path.replace(/^home\\./, '');\n}\n\nfunction updateLayout(update: (layout: DevPreviewBlock[]) => DevPreviewBlock[]): void {\n const { state } = singleton();\n commit({ ...state, layout: update(state.layout ?? []) });\n}\n\n/** A new block for a twilight.json component, filled with its defaults. */\nfunction blockFor(schema: DevSchema, path: string): DevPreviewBlock {\n const component = schema.components.find((c) => c.path === path);\n const defaults = schema.blockDefaults?.[path] ?? schema.componentDefaults[path] ?? {};\n return {\n id: newBlockId(),\n path: blockPath(path),\n fields: { ...(component?.key ? { key: component.key } : {}), ...defaults },\n };\n}\n\nexport const devSettingsStore = {\n get: (): DevPreviewState => singleton().state,\n /** What the server rendered: the saved file as of this page load. */\n getServer: (): DevPreviewState => readSeed(),\n subscribe(listener: () => void): () => void {\n const s = singleton();\n s.listeners.add(listener);\n return () => {\n s.listeners.delete(listener);\n };\n },\n /** Turn overrides on, seeding any unset setting with its twilight.json default. */\n enable(schema: DevSchema): void {\n const { state } = singleton();\n commit({\n ...state,\n enabled: true,\n settings: { ...schema.settingsDefaults, ...state.settings },\n });\n },\n disable(): void {\n commit({ ...singleton().state, enabled: false });\n },\n setSetting(id: string, value: unknown): void {\n const { state } = singleton();\n commit({ ...state, settings: { ...state.settings, [id]: value } });\n },\n /** Restore every setting to its twilight.json default (keeps enabled and the layout). */\n resetSettings(schema: DevSchema): void {\n commit({ ...singleton().state, settings: { ...schema.settingsDefaults } });\n },\n\n // ── Editor ↔ frame ───────────────────────────────────────────────────────\n\n /** The editor tells the store which window is its storefront frame. */\n connectFrame(getFrame: () => Window | null): () => void {\n const s = singleton();\n s.getFrame = getFrame;\n return () => {\n if (s.getFrame === getFrame) s.getFrame = null;\n };\n },\n /** A storefront's home page reports its blocks (`null` when it leaves); in the editor's frame they go to the editor. Not saved. */\n setLiveBlocks(blocks: LiveBlocks | null): void {\n const s = singleton();\n s.ownBlocks = blocks;\n sendToEditor({ kind: 'live-blocks', blocks });\n },\n /** Ask the frame for its home page's blocks and its store base. */\n requestLiveBlocks(): void {\n sendToFrame({ kind: 'request-live-blocks' });\n },\n /**\n * In the editor: a page loaded in the frame. The fetch time the last page\n * reported says nothing about this one, and a page whose settings failed reports\n * none, so it is dropped before this page is asked for its report.\n */\n frameLoaded(): void {\n setMeta({ settingsFetchedAt: null });\n sendToFrame({ kind: 'request-live-blocks' });\n },\n /**\n * Search the dev store through the editor's frame. Rejects when there is no\n * frame, it doesn't answer in time, or the store refuses; pickers then fall\n * back to samples.\n */\n lookup(source: DevLookupSource, query: string): Promise<DevLookupItem[]> {\n const frame = singleton().getFrame?.();\n if (!frame) return Promise.reject(new Error('no storefront frame'));\n const requestId = randomId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n pendingLookups.delete(requestId);\n reject(new Error('the storefront did not answer'));\n }, DEV_LOOKUP_TIMEOUT_MS);\n pendingLookups.set(requestId, { resolve, reject, timer });\n sendToFrame({ kind: 'lookup', requestId, source, query });\n });\n },\n /** Scroll the editor's frame to the home block at `index`. */\n focusBlock(index: number): void {\n sendToFrame({ kind: 'focus-block', index });\n },\n /** In the frame: tell the editor when the server fetched the settings this page rendered with. */\n reportSettingsFetchedAt(at: number): void {\n const s = singleton();\n if (s.settingsFetchedAt === at) return;\n s.settingsFetchedAt = at;\n sendToEditor({ kind: 'settings-fetched', at });\n },\n getMeta: (): DevEditorMeta => singleton().meta,\n subscribeMeta(listener: () => void): () => void {\n const s = singleton();\n s.metaListeners.add(listener);\n return () => {\n s.metaListeners.delete(listener);\n };\n },\n\n // ── Home layout ──────────────────────────────────────────────────────────\n\n /**\n * Take over the home layout. Starts from the blocks the home page showed (the\n * frame's in the editor; an empty page stays empty), otherwise from every\n * twilight.json component. Returns, for each block the page showed, the id of\n * the layout block it became (`null` for one without a path, which is dropped).\n */\n customizeLayout(schema: DevSchema): (string | null)[] {\n const s = singleton();\n const live = s.meta.liveBlocks ?? s.ownBlocks;\n const taken = (live ?? []).map(({ path, ...fields }) =>\n typeof path === 'string' && path !== ''\n ? { id: newBlockId(), path: blockPath(path), fields }\n : null\n );\n const layout: DevPreviewBlock[] =\n live !== null\n ? taken.filter((block): block is DevPreviewBlock => block !== null)\n : schema.components.map((component) => blockFor(schema, component.path));\n commit({ ...s.state, enabled: true, layout });\n return taken.map((block) => block?.id ?? null);\n },\n startEmptyLayout(): void {\n commit({ ...singleton().state, enabled: true, layout: [] });\n },\n /** Back to the store's own blocks. */\n clearLayout(): void {\n commit({ ...singleton().state, layout: null });\n },\n /** Insert a twilight.json component at `at` (default: the end); returns the new block's id. */\n addBlock(schema: DevSchema, path: string, at?: number): string {\n const block = blockFor(schema, path);\n updateLayout((layout) => {\n const next = [...layout];\n next.splice(at ?? next.length, 0, block);\n return next;\n });\n return block.id;\n },\n removeBlock(id: string): void {\n updateLayout((layout) => layout.filter((block) => block.id !== id));\n },\n duplicateBlock(id: string): void {\n updateLayout((layout) => {\n const index = layout.findIndex((block) => block.id === id);\n if (index === -1) return layout;\n const copy = { ...layout[index], id: newBlockId(), fields: { ...layout[index].fields } };\n return [...layout.slice(0, index + 1), copy, ...layout.slice(index + 1)];\n });\n },\n /** Move a block to index `to` (its position after the move). */\n moveBlock(id: string, to: number): void {\n updateLayout((layout) => {\n const from = layout.findIndex((block) => block.id === id);\n if (from === -1) return layout;\n const target = Math.max(0, Math.min(to, layout.length - 1));\n if (target === from) return layout;\n const next = [...layout];\n const [block] = next.splice(from, 1);\n next.splice(target, 0, block);\n return next;\n });\n },\n setBlockField(id: string, fieldId: string, value: unknown): void {\n updateLayout((layout) =>\n layout.map((block) =>\n block.id === id ? { ...block, fields: { ...block.fields, [fieldId]: value } } : block\n )\n );\n },\n};\n\nconst SERVER_META: DevEditorMeta = {\n liveBlocks: null,\n saveStatus: 'idle',\n frameBase: undefined,\n settingsFetchedAt: null,\n};\n\n/** The frame's blocks and store base, and the save status, for the editor. */\nexport function useDevEditorMeta(): DevEditorMeta {\n return useSyncExternalStore(\n devSettingsStore.subscribeMeta,\n devSettingsStore.getMeta,\n () => SERVER_META\n );\n}\n\n/** Raw store subscription. */\nexport function useDevSettingsState(): DevPreviewState {\n return useSyncExternalStore(\n devSettingsStore.subscribe,\n devSettingsStore.get,\n devSettingsStore.getServer\n );\n}\n\n/**\n * Overrides for SSR-rendered consumers (the theme). The server and the first\n * browser render both read the saved file, so they agree and nothing flashes.\n *\n * Which hook this is gets decided once, when the module loads: in production\n * `import.meta.env.DEV` is a static `false`, so only the empty one survives\n * bundling and the store subscription (and the whole store module, which has\n * no other prod consumer) is dead-code-eliminated. No hook is ever called\n * conditionally.\n */\nexport const useDevSettingsOverrides: () => DevPreviewState = import.meta.env.DEV\n ? useDevSettingsState\n : () => EMPTY_PREVIEW_STATE;\n\nfunction useReportSettingsFetchedAt(at: number | undefined): void {\n useEffect(() => {\n if (at != null) devSettingsStore.reportSettingsFetchedAt(at);\n }, [at]);\n}\n\n/**\n * In the editor's frame: report when the dev server fetched this page's store\n * settings, so the editor can say how old they are. A no-op in production, decided\n * once at load like {@link useDevSettingsOverrides}.\n */\nexport const useDevReportSettingsFetchedAt: (at: number | undefined) => void = import.meta.env.DEV\n ? useReportSettingsFetchedAt\n : () => {};\n\n/** A rendered home block; `__dev_id` keys a dev-layout block across reorders. */\nexport type DevHomeBlock<T> = T & { __dev_id?: string };\n\n/**\n * Whether a list in a block's fields gained, lost or reordered items. Blocks\n * often hand their items to a web component that takes them once when it\n * starts (a slider moves its slides into its own track), so such a change\n * never reaches the page until the block mounts again. Editing an item's\n * values is not one: the nodes stay put and update in place.\n */\nexport function listsReshaped(\n before: Record<string, unknown>,\n after: Record<string, unknown>\n): boolean {\n for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {\n const a = before[key];\n const b = after[key];\n if (!Array.isArray(a) && !Array.isArray(b)) continue;\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return true;\n const aItems = a.map((item) => JSON.stringify(item));\n const bItems = b.map((item) => JSON.stringify(item));\n const moved = aItems.some((item, i) => item !== bItems[i]);\n if (moved && [...aItems].sort().join('\\n') === [...bItems].sort().join('\\n')) return true;\n }\n return false;\n}\n\n/**\n * The home page's blocks: the dev layout when one is saved and enabled, else\n * the store's own blocks untouched. Also reports the store's blocks to the\n * editor so \"Customize\" can start from what the page showed, and withdraws\n * them when the page goes.\n *\n * Same production story as {@link useDevSettingsOverrides}: chosen once at\n * module load, so production keeps only the passthrough.\n */\nfunction useDevLayoutBlocks<T extends { path?: string }>(components: T[]): DevHomeBlock<T>[] {\n const overrides = useDevSettingsState();\n // Per block: the fields last rendered, and how often its lists were reshaped.\n const seen = useRef(new Map<string, { fields: Record<string, unknown>; mounts: number }>());\n useEffect(() => {\n devSettingsStore.setLiveBlocks(components);\n return () => devSettingsStore.setLiveBlocks(null);\n }, [components]);\n return useMemo(() => {\n if (!overrides.enabled || !overrides.layout) return components;\n return overrides.layout.map((block) => {\n const last = seen.current.get(block.id);\n const mounts =\n (last?.mounts ?? 0) + (last && listsReshaped(last.fields, block.fields) ? 1 : 0);\n seen.current.set(block.id, { fields: block.fields, mounts });\n // A new key mounts the block again, so a reshaped list reaches the page.\n const devId = mounts ? `${block.id}~${mounts}` : block.id;\n return { ...block.fields, path: block.path, __dev_id: devId } as DevHomeBlock<T>;\n });\n }, [components, overrides]);\n}\n\nexport const useDevHomeBlocks: <T extends { path?: string }>(components: T[]) => DevHomeBlock<T>[] =\n import.meta.env.DEV ? useDevLayoutBlocks : (components) => components;\n"]}
1
+ {"version":3,"sources":["../src/dev/dev-settings-store.ts"],"names":["block"],"mappings":";;;;AA4CA,IAAM,kBAAA,GAAqB,uBAAA;AAE3B,IAAM,aAAA,GAAgB,GAAA;AAEtB,IAAM,YAAA,GAAe,kBAAA;AAErB,IAAM,aAAA,GAAgB,iBAAA;AAEtB,IAAM,aAAA,GAAgB,GAAA;AACtB,IAAM,cAAA,GAAiB,IAAA;AAiBvB,IAAM,cAAA,uBAAqB,GAAA,EAA2B;AAqBtD,SAAS,QAAA,CAAS,QAAQ,CAAA,EAAW;AACnC,EAAA,MAAM,SAAS,UAAA,CAAW,MAAA,CAAO,gBAAgB,IAAI,UAAA,CAAW,KAAK,CAAC,CAAA;AACtE,EAAA,OAAO,KAAA,CAAM,IAAA,CAAK,MAAA,EAAQ,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAC3E;AAEA,IAAI,KAAA;AAQJ,SAAS,OAAA,GAAkB;AACzB,EAAA,KAAA,KAAU,QAAA,EAAS;AACnB,EAAA,OAAO,KAAA;AACT;AAEA,IAAI,UAAA;AACJ,IAAI,SAAA,GAA6B,mBAAA;AAGjC,SAAS,QAAA,GAA4B;AACnC,EAAA,MAAM,GAAA,GAAO,WAAuC,kBAAkB,CAAA;AACtE,EAAA,IAAI,QAAQ,UAAA,EAAY;AACtB,IAAA,UAAA,GAAa,GAAA;AACb,IAAA,SAAA,GAAY,qBAAA,CAAsB,GAAG,CAAA,IAAK,mBAAA;AAAA,EAC5C;AACA,EAAA,OAAO,SAAA;AACT;AAgCA,IAAM,aAAA,GAAgB,8BAAA;AAEtB,SAAS,SAAA,GAA+B;AACtC,EAAA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AA,EACH,CAAA,EAAG,CAAC,UAAA,EAAY,SAAS,CAAC,CAAA;AAC5B;AAEO,IAAM,mBACX,MAAA,CAAA,IAAA,CAAY,GAAA,CAAI,GAAA,GAAM,kBAAA,GAAqB,CAAC,UAAA,KAAe","file":"chunk-VXFRQB3H.js","sourcesContent":["/**\n * Client-side store for the dev editor: theme-setting overrides and a dev-owned\n * home layout. Saved to `twilight.preview.json` through the dev server (see\n * `twilight-schema.plugin.ts`), not to localStorage, for three reasons: the\n * server render can read a file, so the page hydrates with the edited layout\n * instead of flashing the store's; the state survives a port or browser\n * change; and the developer can open, diff or delete it.\n *\n * The saved state reaches this module through `virtual:twilight/schema`, which\n * the root route imports on both sides before anything renders and which puts\n * it on `globalThis[DEV_PREVIEW_GLOBAL]`. Server snapshots read that value\n * (the server's modules are re-run after each save); the browser copies it once\n * and then owns the state.\n *\n * The theme editor (`/__twilight/editor`) frames the storefront, so two copies\n * of this store run side by side. Edits reach every copy on the origin at once\n * over a `BroadcastChannel` (the file save is debounced), and only the copy\n * that made an edit saves it. Everything else between an editor and its frame\n * (the home page's blocks, the store base, scroll-to-block) goes by\n * `postMessage` to that one window, so another storefront tab never answers.\n */\n\nimport { useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\nimport {\n DEV_LOOKUP_TIMEOUT_MS,\n DEV_PREVIEW_ENDPOINT,\n DEV_PREVIEW_EVENT,\n DEV_PREVIEW_GLOBAL,\n EMPTY_PREVIEW_STATE,\n isEditorFrame,\n normalizePreviewState,\n type DevLookupItem,\n type DevLookupSource,\n type DevPreviewBlock,\n type DevPreviewState,\n type DevSchema,\n} from './schema-types';\nimport { resolveStoreBase } from '../utils/store-identity';\n\nexport type DevSettingsState = DevPreviewState;\nexport type DevSaveStatus = 'idle' | 'saving' | 'saved' | 'error';\ntype LiveBlocks = { path?: string }[];\n\n/** Where the old localStorage-backed widget kept its state; migrated once. */\nconst LEGACY_STORAGE_KEY = 'twilight:dev-settings';\n/** Batch keystrokes into one write. */\nconst SAVE_DELAY_MS = 250;\n/** Same-browser channel every copy of the store listens on, for edits. */\nconst CHANNEL_NAME = 'twilight:preview';\n/** Envelope type of the editor ↔ frame `postMessage`s. */\nconst FRAME_MESSAGE = 'twilight:editor';\n/** How long the frame keeps looking for a block that is still rendering (just added, say). */\nconst FOCUS_WAIT_MS = 2000;\nconst FOCUS_FLASH_MS = 1200;\n\n/** Editor ↔ the storefront it frames. */\ntype FrameMessage =\n | { kind: 'live-blocks'; blocks: LiveBlocks | null }\n | { kind: 'frame-info'; base: string | null }\n | { kind: 'settings-fetched'; at: number }\n | { kind: 'request-live-blocks' }\n | { kind: 'focus-block'; index: number }\n | { kind: 'lookup'; requestId: string; source: DevLookupSource; query: string }\n | { kind: 'lookup-result'; requestId: string; items?: DevLookupItem[]; error?: string };\n\ninterface PendingLookup {\n resolve: (items: DevLookupItem[]) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n}\nconst pendingLookups = new Map<string, PendingLookup>();\n\n/** What the editor shows besides the saved state. */\nexport interface DevEditorMeta {\n /** The blocks the framed home page shows; `null` when it is not on the home page. */\n liveBlocks: LiveBlocks | null;\n saveStatus: DevSaveStatus;\n /** The frame's store segment; `undefined` until the frame has said. */\n frameBase: string | null | undefined;\n /**\n * When the dev server last asked the API for the frame's store settings (epoch\n * ms), which it reuses for a while (see `api/dev-settings-cache.ts`); `null`\n * until the frame says.\n */\n settingsFetchedAt: number | null;\n}\n\n/**\n * A short random hex id. `getRandomValues`, not `randomUUID`: the latter only\n * exists in secure contexts, and the dev server may be opened on a LAN address.\n */\nfunction randomId(bytes = 6): string {\n const values = globalThis.crypto.getRandomValues(new Uint8Array(bytes));\n return Array.from(values, (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\nlet tabId: string | undefined;\n\n/**\n * Sent with every save so this tab can ignore its own broadcast. Made on first\n * use, never at module load: Cloudflare Workers refuse random values in global\n * scope, and this module is in the worker bundle (its use is dev-only, its\n * top level is not).\n */\nfunction myTabId(): string {\n tabId ??= randomId();\n return tabId;\n}\n\nlet seedSource: unknown;\nlet seedState: DevPreviewState = EMPTY_PREVIEW_STATE;\n\n/** The saved file as this page loaded it, normalized once per value so snapshots keep their identity. */\nfunction readSeed(): DevPreviewState {\n const raw = (globalThis as Record<string, unknown>)[DEV_PREVIEW_GLOBAL];\n if (raw !== seedSource) {\n seedSource = raw;\n seedState = normalizePreviewState(raw) ?? EMPTY_PREVIEW_STATE;\n }\n return seedState;\n}\n\n// The widget (bundled into the `/dev` entry) and the theme merge (bundled into\n// the engine index via `useTwilightInit`) import this module from two different\n// chunks, so each would otherwise get its OWN copy of the state — the widget\n// would enable a store the merge never reads. Back the state with a single\n// globalThis-keyed instance so every copy shares one source of truth. Dev-only,\n// so a global is acceptable (and lazy, so the module stays side-effect free and\n// tree-shakes out of production).\ninterface DevStoreSingleton {\n state: DevPreviewState;\n listeners: Set<() => void>;\n /** This page's own home blocks, when it is a storefront on its home page. Never saved. */\n ownBlocks: LiveBlocks | null;\n meta: DevEditorMeta;\n metaListeners: Set<() => void>;\n saveTimer: ReturnType<typeof setTimeout> | undefined;\n /** An edit that has not been sent yet. */\n dirty: boolean;\n /** A save request on its way; the next one waits for it, so saves land in order. */\n inFlight: boolean;\n /** The old localStorage copy is removed only once the file has the migrated values. */\n legacyPending: boolean;\n channel: BroadcastChannel | null;\n /** In the editor: the storefront frame's window. */\n getFrame: (() => Window | null) | null;\n /** In the frame: when the server fetched the settings this page rendered with. */\n settingsFetchedAt: number | null;\n /** Detach this copy's listeners and channel. A page keeps one copy for good; tests swap them. */\n dispose: () => void;\n}\n\nconst SINGLETON_KEY = '__twilightDevSettingsStore__';\n\nfunction singleton(): DevStoreSingleton {\n const g = globalThis as unknown as Record<string, DevStoreSingleton | undefined>;\n let s = g[SINGLETON_KEY];\n if (!s) {\n const seeded = (globalThis as Record<string, unknown>)[DEV_PREVIEW_GLOBAL] != null;\n s = {\n state: readSeed(),\n listeners: new Set(),\n ownBlocks: null,\n meta: { liveBlocks: null, saveStatus: 'idle', frameBase: undefined, settingsFetchedAt: null },\n metaListeners: new Set(),\n saveTimer: undefined,\n dirty: false,\n inFlight: false,\n legacyPending: false,\n channel: null,\n getFrame: null,\n settingsFetchedAt: null,\n dispose: () => {},\n };\n g[SINGLETON_KEY] = s;\n if (typeof window !== 'undefined') setUpBrowser(s, seeded);\n }\n return s;\n}\n\nfunction setUpBrowser(s: DevStoreSingleton, seeded: boolean): void {\n const listeners = new AbortController();\n const { signal } = listeners;\n if (!seeded) migrateLegacy(s);\n listenForOtherTabs();\n s.channel = openChannel();\n listenForFrameMessages(s, signal);\n window.addEventListener('pagehide', () => flushOnExit(s), { signal });\n s.dispose = () => {\n listeners.abort();\n s.channel?.close();\n clearTimeout(s.saveTimer);\n };\n if (isEditorFrame()) sendToEditor({ kind: 'frame-info', base: resolveStoreBase() });\n}\n\n/** Carry the old widget's settings over; its per-block patches don't map to a layout. */\nfunction migrateLegacy(s: DevStoreSingleton): void {\n try {\n const raw = window.localStorage.getItem(LEGACY_STORAGE_KEY);\n if (!raw) return;\n const legacy = normalizePreviewState(JSON.parse(raw));\n if (!legacy) return;\n s.state = { enabled: legacy.enabled, settings: legacy.settings, layout: null };\n s.legacyPending = true;\n scheduleSave(s);\n } catch {\n // Storage blocked or the old value is corrupt: nothing worth keeping.\n }\n}\n\n/** Vite's HMR client, typed locally: the engine's `ImportMeta` must not clash with `vite/client`. */\ninterface HotContext {\n on(event: string, cb: (payload: { state?: unknown; from?: unknown }) => void): void;\n}\n\n/**\n * Take a state another copy committed. Not while this copy has an edit of its\n * own waiting to be saved: that edit is newer, and saving it will tell the rest.\n */\nfunction receive(raw: unknown): void {\n const s = singleton();\n if (s.dirty || s.inFlight || s.saveTimer) return;\n const next = normalizePreviewState(raw);\n if (next && JSON.stringify(next) !== JSON.stringify(s.state)) emit(next);\n}\n\n/** Tabs in another browser hear about a save from the dev server. */\nfunction listenForOtherTabs(): void {\n const hot = (import.meta as ImportMeta & { hot?: HotContext }).hot;\n if (!hot) return;\n hot.on(DEV_PREVIEW_EVENT, (payload) => {\n if (payload?.from !== myTabId()) receive(payload?.state);\n });\n}\n\nfunction openChannel(): BroadcastChannel | null {\n if (typeof BroadcastChannel === 'undefined') return null;\n const channel = new BroadcastChannel(CHANNEL_NAME);\n channel.onmessage = ({ data }: MessageEvent<{ state?: unknown; from?: string }>) => {\n if (data && data.from !== myTabId()) receive(data.state);\n };\n return channel;\n}\n\nfunction sendToEditor(message: FrameMessage): void {\n if (isEditorFrame())\n window.parent.postMessage({ type: FRAME_MESSAGE, message }, window.location.origin);\n}\n\nfunction sendToFrame(message: FrameMessage): void {\n singleton().getFrame?.()?.postMessage({ type: FRAME_MESSAGE, message }, window.location.origin);\n}\n\nfunction reportToEditor(s: DevStoreSingleton): void {\n sendToEditor({ kind: 'frame-info', base: resolveStoreBase() });\n sendToEditor({ kind: 'live-blocks', blocks: s.ownBlocks });\n if (s.settingsFetchedAt != null)\n sendToEditor({ kind: 'settings-fetched', at: s.settingsFetchedAt });\n}\n\n/**\n * The editor ↔ frame conversation. A frame only takes requests from its own\n * parent; an editor only takes reports from the frame it shows.\n */\nfunction listenForFrameMessages(s: DevStoreSingleton, signal: AbortSignal): void {\n window.addEventListener(\n 'message',\n (event: MessageEvent) => {\n if (event.origin !== window.location.origin || event.data?.type !== FRAME_MESSAGE) return;\n const message = event.data.message as FrameMessage;\n if (window.parent !== window && event.source === window.parent) {\n answerEditor(s, message);\n return;\n }\n const frame = s.getFrame?.();\n if (frame && event.source === frame) takeFrameReport(message);\n },\n { signal }\n );\n}\n\n/** In the frame: what its editor asks for. */\nfunction answerEditor(s: DevStoreSingleton, message: FrameMessage): void {\n if (message.kind === 'request-live-blocks') reportToEditor(s);\n else if (message.kind === 'focus-block') scrollToBlock(message.index);\n else if (message.kind === 'lookup') void answerLookup(message);\n}\n\n/** In the editor: what its frame reports. */\nfunction takeFrameReport(message: FrameMessage): void {\n if (message.kind === 'lookup-result') settleLookup(message);\n else if (message.kind === 'live-blocks') setMeta({ liveBlocks: message.blocks });\n else if (message.kind === 'frame-info') setMeta({ frameBase: message.base });\n else if (message.kind === 'settings-fetched' && Number.isFinite(message.at))\n setMeta({ settingsFetchedAt: message.at });\n}\n\n/** In the frame: look the request up in the store and send back what was found, or why not. */\nasync function answerLookup(message: Extract<FrameMessage, { kind: 'lookup' }>): Promise<void> {\n const { requestId, source, query } = message;\n try {\n const { lookupInStore } = await import('./store-lookup');\n sendToEditor({ kind: 'lookup-result', requestId, items: await lookupInStore(source, query) });\n } catch (error) {\n sendToEditor({\n kind: 'lookup-result',\n requestId,\n error: error instanceof Error ? error.message : 'lookup failed',\n });\n }\n}\n\nfunction settleLookup(message: Extract<FrameMessage, { kind: 'lookup-result' }>): void {\n const pending = pendingLookups.get(message.requestId);\n if (!pending) return;\n pendingLookups.delete(message.requestId);\n clearTimeout(pending.timer);\n if (message.items) pending.resolve(message.items);\n else pending.reject(new Error(message.error ?? 'lookup failed'));\n}\n\n/**\n * In the editor's frame: bring a home block into view and flash an outline on\n * it. Dev-only editor chrome, so it styles the element directly rather than\n * through the theme's React tree. A block added a moment ago may not be in the\n * DOM yet, so look for it for a little while.\n */\nfunction scrollToBlock(index: number): void {\n const started = Date.now();\n const find = () => {\n const el = document.querySelector<HTMLElement>(`[data-home-block=\"${index}\"]`);\n if (!el) {\n if (Date.now() - started < FOCUS_WAIT_MS) requestAnimationFrame(find);\n return;\n }\n const { outline, outlineOffset, scrollMarginTop } = el.style;\n // Clear a sticky header, which would otherwise cover the block's top.\n el.style.scrollMarginTop = '80px';\n el.scrollIntoView({ behavior: 'smooth', block: 'start' });\n el.style.outline = '2px solid #0d9488';\n el.style.outlineOffset = '-2px';\n setTimeout(() => {\n el.style.outline = outline;\n el.style.outlineOffset = outlineOffset;\n el.style.scrollMarginTop = scrollMarginTop;\n }, FOCUS_FLASH_MS);\n };\n find();\n}\n\nfunction emit(next: DevPreviewState): void {\n const s = singleton();\n s.state = next;\n s.listeners.forEach((l) => l());\n}\n\nfunction setMeta(patch: Partial<DevEditorMeta>): void {\n const s = singleton();\n s.meta = { ...s.meta, ...patch };\n s.metaListeners.forEach((l) => l());\n}\n\nfunction saveRequest(s: DevStoreSingleton, keepalive = false): Promise<Response> {\n return fetch(DEV_PREVIEW_ENDPOINT, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ state: s.state, from: myTabId() }),\n keepalive,\n });\n}\n\n/** Send the current state, one request at a time; edits made meanwhile go in the next one. */\nasync function flush(s: DevStoreSingleton): Promise<void> {\n if (s.inFlight || !s.dirty) return;\n s.inFlight = true;\n s.dirty = false;\n let failed = false;\n try {\n const res = await saveRequest(s);\n if (!res.ok) throw new Error(`HTTP ${res.status}`);\n if (s.legacyPending) {\n s.legacyPending = false;\n try {\n window.localStorage.removeItem(LEGACY_STORAGE_KEY);\n } catch {\n // Storage went away; the file has the values now either way.\n }\n }\n if (!s.dirty && !s.saveTimer) setMeta({ saveStatus: 'saved' });\n } catch (error) {\n // Still unsaved: another tab's state must not replace it, and leaving the\n // page still sends it. Edits made while this request was out are sent once\n // more; the failed one alone waits for the next edit, so nothing loops.\n failed = !s.dirty;\n s.dirty = true;\n setMeta({ saveStatus: 'error' });\n console.error('[twilight-react:preview] could not save twilight.preview.json', error);\n } finally {\n s.inFlight = false;\n if (!failed && s.dirty && !s.saveTimer) void flush(s);\n }\n}\n\nfunction scheduleSave(s: DevStoreSingleton): void {\n if (typeof window === 'undefined' || typeof fetch === 'undefined') return;\n s.dirty = true;\n clearTimeout(s.saveTimer);\n setMeta({ saveStatus: 'saving' });\n s.saveTimer = setTimeout(() => {\n s.saveTimer = undefined;\n void flush(s);\n }, SAVE_DELAY_MS);\n}\n\n/** Closing or reloading the editor must not drop the last edit: send it on the way out. */\nfunction flushOnExit(s: DevStoreSingleton): void {\n if (!s.dirty) return;\n clearTimeout(s.saveTimer);\n s.saveTimer = undefined;\n s.dirty = false;\n void saveRequest(s, true).catch(() => {});\n}\n\nfunction commit(next: DevPreviewState): void {\n const s = singleton();\n emit(next);\n try {\n s.channel?.postMessage({ state: next, from: myTabId() });\n } catch {\n // A value that can't be cloned: the other copies pick it up from the save instead.\n }\n scheduleSave(s);\n}\n\nfunction newBlockId(): string {\n return `b-${randomId()}`;\n}\n\n/** Home loader spelling of a twilight.json path. */\nexport function blockPath(path: string): string {\n return path.replace(/^home\\./, '');\n}\n\nfunction updateLayout(update: (layout: DevPreviewBlock[]) => DevPreviewBlock[]): void {\n const { state } = singleton();\n commit({ ...state, layout: update(state.layout ?? []) });\n}\n\n/** A new block for a twilight.json component, filled with its defaults. */\nfunction blockFor(schema: DevSchema, path: string): DevPreviewBlock {\n const component = schema.components.find((c) => c.path === path);\n const defaults = schema.blockDefaults?.[path] ?? schema.componentDefaults[path] ?? {};\n return {\n id: newBlockId(),\n path: blockPath(path),\n fields: { ...(component?.key ? { key: component.key } : {}), ...defaults },\n };\n}\n\nexport const devSettingsStore = {\n get: (): DevPreviewState => singleton().state,\n /** What the server rendered: the saved file as of this page load. */\n getServer: (): DevPreviewState => readSeed(),\n subscribe(listener: () => void): () => void {\n const s = singleton();\n s.listeners.add(listener);\n return () => {\n s.listeners.delete(listener);\n };\n },\n /** Turn overrides on, seeding any unset setting with its twilight.json default. */\n enable(schema: DevSchema): void {\n const { state } = singleton();\n commit({\n ...state,\n enabled: true,\n settings: { ...schema.settingsDefaults, ...state.settings },\n });\n },\n disable(): void {\n commit({ ...singleton().state, enabled: false });\n },\n setSetting(id: string, value: unknown): void {\n const { state } = singleton();\n commit({ ...state, settings: { ...state.settings, [id]: value } });\n },\n /** Restore every setting to its twilight.json default (keeps enabled and the layout). */\n resetSettings(schema: DevSchema): void {\n commit({ ...singleton().state, settings: { ...schema.settingsDefaults } });\n },\n\n // ── Editor ↔ frame ───────────────────────────────────────────────────────\n\n /** The editor tells the store which window is its storefront frame. */\n connectFrame(getFrame: () => Window | null): () => void {\n const s = singleton();\n s.getFrame = getFrame;\n return () => {\n if (s.getFrame === getFrame) s.getFrame = null;\n };\n },\n /** A storefront's home page reports its blocks (`null` when it leaves); in the editor's frame they go to the editor. Not saved. */\n setLiveBlocks(blocks: LiveBlocks | null): void {\n const s = singleton();\n s.ownBlocks = blocks;\n sendToEditor({ kind: 'live-blocks', blocks });\n },\n /** Ask the frame for its home page's blocks and its store base. */\n requestLiveBlocks(): void {\n sendToFrame({ kind: 'request-live-blocks' });\n },\n /**\n * In the editor: a page loaded in the frame. The fetch time the last page\n * reported says nothing about this one, and a page whose settings failed reports\n * none, so it is dropped before this page is asked for its report.\n */\n frameLoaded(): void {\n setMeta({ settingsFetchedAt: null });\n sendToFrame({ kind: 'request-live-blocks' });\n },\n /**\n * Search the dev store through the editor's frame. Rejects when there is no\n * frame, it doesn't answer in time, or the store refuses; pickers then fall\n * back to samples.\n */\n lookup(source: DevLookupSource, query: string): Promise<DevLookupItem[]> {\n const frame = singleton().getFrame?.();\n if (!frame) return Promise.reject(new Error('no storefront frame'));\n const requestId = randomId();\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n pendingLookups.delete(requestId);\n reject(new Error('the storefront did not answer'));\n }, DEV_LOOKUP_TIMEOUT_MS);\n pendingLookups.set(requestId, { resolve, reject, timer });\n sendToFrame({ kind: 'lookup', requestId, source, query });\n });\n },\n /** Scroll the editor's frame to the home block at `index`. */\n focusBlock(index: number): void {\n sendToFrame({ kind: 'focus-block', index });\n },\n /** In the frame: tell the editor when the server fetched the settings this page rendered with. */\n reportSettingsFetchedAt(at: number): void {\n const s = singleton();\n if (s.settingsFetchedAt === at) return;\n s.settingsFetchedAt = at;\n sendToEditor({ kind: 'settings-fetched', at });\n },\n getMeta: (): DevEditorMeta => singleton().meta,\n subscribeMeta(listener: () => void): () => void {\n const s = singleton();\n s.metaListeners.add(listener);\n return () => {\n s.metaListeners.delete(listener);\n };\n },\n\n // ── Home layout ──────────────────────────────────────────────────────────\n\n /**\n * Take over the home layout. Starts from the blocks the home page showed (the\n * frame's in the editor; an empty page stays empty), otherwise from every\n * twilight.json component. Returns, for each block the page showed, the id of\n * the layout block it became (`null` for one without a path, which is dropped).\n */\n customizeLayout(schema: DevSchema): (string | null)[] {\n const s = singleton();\n const live = s.meta.liveBlocks ?? s.ownBlocks;\n const taken = (live ?? []).map(({ path, ...fields }) =>\n typeof path === 'string' && path !== ''\n ? { id: newBlockId(), path: blockPath(path), fields }\n : null\n );\n const layout: DevPreviewBlock[] =\n live !== null\n ? taken.filter((block): block is DevPreviewBlock => block !== null)\n : schema.components.map((component) => blockFor(schema, component.path));\n commit({ ...s.state, enabled: true, layout });\n return taken.map((block) => block?.id ?? null);\n },\n startEmptyLayout(): void {\n commit({ ...singleton().state, enabled: true, layout: [] });\n },\n /** Back to the store's own blocks. */\n clearLayout(): void {\n commit({ ...singleton().state, layout: null });\n },\n /** Insert a twilight.json component at `at` (default: the end); returns the new block's id. */\n addBlock(schema: DevSchema, path: string, at?: number): string {\n const block = blockFor(schema, path);\n updateLayout((layout) => {\n const next = [...layout];\n next.splice(at ?? next.length, 0, block);\n return next;\n });\n return block.id;\n },\n removeBlock(id: string): void {\n updateLayout((layout) => layout.filter((block) => block.id !== id));\n },\n duplicateBlock(id: string): void {\n updateLayout((layout) => {\n const index = layout.findIndex((block) => block.id === id);\n if (index === -1) return layout;\n const copy = { ...layout[index], id: newBlockId(), fields: { ...layout[index].fields } };\n return [...layout.slice(0, index + 1), copy, ...layout.slice(index + 1)];\n });\n },\n /** Move a block to index `to` (its position after the move). */\n moveBlock(id: string, to: number): void {\n updateLayout((layout) => {\n const from = layout.findIndex((block) => block.id === id);\n if (from === -1) return layout;\n const target = Math.max(0, Math.min(to, layout.length - 1));\n if (target === from) return layout;\n const next = [...layout];\n const [block] = next.splice(from, 1);\n next.splice(target, 0, block);\n return next;\n });\n },\n setBlockField(id: string, fieldId: string, value: unknown): void {\n updateLayout((layout) =>\n layout.map((block) =>\n block.id === id ? { ...block, fields: { ...block.fields, [fieldId]: value } } : block\n )\n );\n },\n};\n\nconst SERVER_META: DevEditorMeta = {\n liveBlocks: null,\n saveStatus: 'idle',\n frameBase: undefined,\n settingsFetchedAt: null,\n};\n\n/** The frame's blocks and store base, and the save status, for the editor. */\nexport function useDevEditorMeta(): DevEditorMeta {\n return useSyncExternalStore(\n devSettingsStore.subscribeMeta,\n devSettingsStore.getMeta,\n () => SERVER_META\n );\n}\n\n/** Raw store subscription. */\nexport function useDevSettingsState(): DevPreviewState {\n return useSyncExternalStore(\n devSettingsStore.subscribe,\n devSettingsStore.get,\n devSettingsStore.getServer\n );\n}\n\n/**\n * Overrides for SSR-rendered consumers (the theme). The server and the first\n * browser render both read the saved file, so they agree and nothing flashes.\n *\n * Which hook this is gets decided once, when the module loads: in production\n * `import.meta.env.DEV` is a static `false`, so only the empty one survives\n * bundling and the store subscription (and the whole store module, which has\n * no other prod consumer) is dead-code-eliminated. No hook is ever called\n * conditionally.\n */\nexport const useDevSettingsOverrides: () => DevPreviewState = import.meta.env.DEV\n ? useDevSettingsState\n : () => EMPTY_PREVIEW_STATE;\n\nfunction useReportSettingsFetchedAt(at: number | undefined): void {\n useEffect(() => {\n if (at != null) devSettingsStore.reportSettingsFetchedAt(at);\n }, [at]);\n}\n\n/**\n * In the editor's frame: report when the dev server fetched this page's store\n * settings, so the editor can say how old they are. A no-op in production, decided\n * once at load like {@link useDevSettingsOverrides}.\n */\nexport const useDevReportSettingsFetchedAt: (at: number | undefined) => void = import.meta.env.DEV\n ? useReportSettingsFetchedAt\n : () => {};\n\n/** A rendered home block; `__dev_id` keys a dev-layout block across reorders. */\nexport type DevHomeBlock<T> = T & { __dev_id?: string };\n\n/**\n * Whether a list in a block's fields gained, lost or reordered items. Blocks\n * often hand their items to a web component that takes them once when it\n * starts (a slider moves its slides into its own track), so such a change\n * never reaches the page until the block mounts again. Editing an item's\n * values is not one: the nodes stay put and update in place.\n */\nexport function listsReshaped(\n before: Record<string, unknown>,\n after: Record<string, unknown>\n): boolean {\n for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {\n const a = before[key];\n const b = after[key];\n if (!Array.isArray(a) && !Array.isArray(b)) continue;\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return true;\n const aItems = a.map((item) => JSON.stringify(item));\n const bItems = b.map((item) => JSON.stringify(item));\n const moved = aItems.some((item, i) => item !== bItems[i]);\n if (moved && [...aItems].sort().join('\\n') === [...bItems].sort().join('\\n')) return true;\n }\n return false;\n}\n\n/**\n * The home page's blocks: the dev layout when one is saved and enabled, else\n * the store's own blocks untouched. Also reports the store's blocks to the\n * editor so \"Customize\" can start from what the page showed, and withdraws\n * them when the page goes.\n *\n * Same production story as {@link useDevSettingsOverrides}: chosen once at\n * module load, so production keeps only the passthrough.\n */\nfunction useDevLayoutBlocks<T extends { path?: string }>(components: T[]): DevHomeBlock<T>[] {\n const overrides = useDevSettingsState();\n // Per block: the fields last rendered, and how often its lists were reshaped.\n const seen = useRef(new Map<string, { fields: Record<string, unknown>; mounts: number }>());\n useEffect(() => {\n devSettingsStore.setLiveBlocks(components);\n return () => devSettingsStore.setLiveBlocks(null);\n }, [components]);\n return useMemo(() => {\n if (!overrides.enabled || !overrides.layout) return components;\n return overrides.layout.map((block) => {\n const last = seen.current.get(block.id);\n const mounts =\n (last?.mounts ?? 0) + (last && listsReshaped(last.fields, block.fields) ? 1 : 0);\n seen.current.set(block.id, { fields: block.fields, mounts });\n // A new key mounts the block again, so a reshaped list reaches the page.\n const devId = mounts ? `${block.id}~${mounts}` : block.id;\n return { ...block.fields, path: block.path, __dev_id: devId } as DevHomeBlock<T>;\n });\n }, [components, overrides]);\n}\n\nexport const useDevHomeBlocks: <T extends { path?: string }>(components: T[]) => DevHomeBlock<T>[] =\n import.meta.env.DEV ? useDevLayoutBlocks : (components) => components;\n"]}
@@ -1,4 +1,4 @@
1
- import { api } from './chunk-53ZWOFFE.js';
1
+ import { api } from './chunk-UF6XPCEO.js';
2
2
  import { queryOptions } from '@tanstack/react-query';
3
3
 
4
4
  var apps = {
@@ -40,5 +40,5 @@ var apps = {
40
40
  };
41
41
 
42
42
  export { apps };
43
- //# sourceMappingURL=chunk-AVGOJEOA.js.map
44
- //# sourceMappingURL=chunk-AVGOJEOA.js.map
43
+ //# sourceMappingURL=chunk-WGUKKSPD.js.map
44
+ //# sourceMappingURL=chunk-WGUKKSPD.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/apps.ts"],"names":[],"mappings":";;;AAmCO,IAAM,IAAA,GAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlB,UAAU,YAAmC;AAC3C,IAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,GAAA,CACpB,GAAA,CAAI,eAAA,EAAiB,EAAE,OAAA,EAAS,IAAA,EAAM,CAAA,CACtC,IAAA,EAA8B;AACjC,IAAA,OAAO,QAAQ,EAAC;AAAA,EAClB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,UAAU,YAAkC;AAC1C,IAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,GAAA,CACpB,GAAA,CAAI,wBAAA,EAA0B,EAAE,OAAA,EAAS,IAAA,EAAM,CAAA,CAC/C,IAAA,EAAsC;AACzC,IAAA,OAAO,EAAE,IAAA,EAAM,IAAA,EAAM,IAAA,IAAQ,EAAC,EAAE;AAAA,EAClC,CAAA;AAAA,EAEA,OAAA,EAAS;AAAA,IACP,QAAA,EAAU,MACR,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,MAAA,EAAQ,UAAU,CAAA;AAAA,MAC7B,OAAA,EAAS,MAAM,IAAA,CAAK,QAAA,EAAS;AAAA;AAAA,MAE7B,SAAA,EAAW,QAAA;AAAA;AAAA;AAAA;AAAA,MAIX,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,IAEH,QAAA,EAAU,MACR,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,MAAA,EAAQ,UAAU,CAAA;AAAA,MAC7B,OAAA,EAAS,MAAM,IAAA,CAAK,QAAA,EAAS;AAAA;AAAA,MAE7B,SAAA,EAAW,QAAA;AAAA,MACX,KAAA,EAAO;AAAA,KACR;AAAA;AAEP","file":"chunk-AVGOJEOA.js","sourcesContent":["import { queryOptions } from '@tanstack/react-query';\nimport { api } from './client';\n\nexport interface AppSnippetRow {\n place: string;\n content: string;\n url?: string | null;\n /**\n * Raw snippet id, emitted as `data-snippet-id`. Present only on CDN rows — the\n * inline branch of the backend's snippet parser omits the key entirely.\n */\n id?: number;\n /** `{{customer.x}}` placeholders in `content` to substitute from SDK config `user.*` keys. */\n customer_parameters?: string[];\n}\n\nexport interface AppSnippet {\n service: string;\n app_id: string;\n /** Encoded app id (`getRouteKey()`): the scope id its snippets bind to via `data-scope-id`,\n * and its settings-bucket key. Absent on payloads predating the settings API. */\n id?: string;\n app_slug: string;\n status: string;\n snippets: AppSnippetRow[];\n}\n\n/**\n * Per-app public `app.*` buckets for CDN snippets, keyed by encoded app id (== `AppSnippet.id`,\n * the `Salla.appScope` scope id). One isolated bucket per app; reads within a scope are bare `app.*`.\n */\nexport interface AppSettings {\n apps: Record<string, Record<string, unknown>>;\n}\n\nexport const apps = {\n /**\n * Installed apps' snippets (scripts/HTML to inject). Timeout-bounded because it's awaited in\n * rootBeforeLoad (SSR/TTFB): a slow response degrades to no CDN tags, never stalls the page.\n */\n snippets: async (): Promise<AppSnippet[]> => {\n const { data } = await api\n .get('apps/snippets', { timeout: 2500 })\n .json<{ data?: AppSnippet[] }>();\n return data ?? [];\n },\n\n /**\n * Per-app public `app.*` buckets, keyed by encoded app id. Timeout-bounded (SSR-awaited):\n * a slow response degrades to empty buckets (fail-open), never strands injection.\n */\n settings: async (): Promise<AppSettings> => {\n const { data } = await api\n .get('apps/snippets/settings', { timeout: 2500 })\n .json<{ data?: Partial<AppSettings> }>();\n return { apps: data?.apps ?? {} };\n },\n\n queries: {\n snippets: () =>\n queryOptions({\n queryKey: ['apps', 'snippets'],\n queryFn: () => apps.snippets(),\n // Snippets are static per session; one fetch per page load is enough.\n staleTime: Infinity,\n // No retry: this is awaited in rootBeforeLoad, so the router's default `retry: 1` would\n // make the SSR wait 2 x the 2500ms timeout (plus backoff) before failing open. The\n // 2500ms timeout must be the whole budget; the client fallback query does the retrying.\n retry: 0,\n }),\n\n settings: () =>\n queryOptions({\n queryKey: ['apps', 'settings'],\n queryFn: () => apps.settings(),\n // Encoded app ids and their buckets are stable per page; one fetch is enough.\n staleTime: Infinity,\n retry: 0,\n }),\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/api/apps.ts"],"names":[],"mappings":";;;AAmCO,IAAM,IAAA,GAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAKlB,UAAU,YAAmC;AAC3C,IAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,GAAA,CACpB,GAAA,CAAI,eAAA,EAAiB,EAAE,OAAA,EAAS,IAAA,EAAM,CAAA,CACtC,IAAA,EAA8B;AACjC,IAAA,OAAO,QAAQ,EAAC;AAAA,EAClB,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,UAAU,YAAkC;AAC1C,IAAA,MAAM,EAAE,IAAA,EAAK,GAAI,MAAM,GAAA,CACpB,GAAA,CAAI,wBAAA,EAA0B,EAAE,OAAA,EAAS,IAAA,EAAM,CAAA,CAC/C,IAAA,EAAsC;AACzC,IAAA,OAAO,EAAE,IAAA,EAAM,IAAA,EAAM,IAAA,IAAQ,EAAC,EAAE;AAAA,EAClC,CAAA;AAAA,EAEA,OAAA,EAAS;AAAA,IACP,QAAA,EAAU,MACR,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,MAAA,EAAQ,UAAU,CAAA;AAAA,MAC7B,OAAA,EAAS,MAAM,IAAA,CAAK,QAAA,EAAS;AAAA;AAAA,MAE7B,SAAA,EAAW,QAAA;AAAA;AAAA;AAAA;AAAA,MAIX,KAAA,EAAO;AAAA,KACR,CAAA;AAAA,IAEH,QAAA,EAAU,MACR,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,CAAC,MAAA,EAAQ,UAAU,CAAA;AAAA,MAC7B,OAAA,EAAS,MAAM,IAAA,CAAK,QAAA,EAAS;AAAA;AAAA,MAE7B,SAAA,EAAW,QAAA;AAAA,MACX,KAAA,EAAO;AAAA,KACR;AAAA;AAEP","file":"chunk-WGUKKSPD.js","sourcesContent":["import { queryOptions } from '@tanstack/react-query';\nimport { api } from './client';\n\nexport interface AppSnippetRow {\n place: string;\n content: string;\n url?: string | null;\n /**\n * Raw snippet id, emitted as `data-snippet-id`. Present only on CDN rows — the\n * inline branch of the backend's snippet parser omits the key entirely.\n */\n id?: number;\n /** `{{customer.x}}` placeholders in `content` to substitute from SDK config `user.*` keys. */\n customer_parameters?: string[];\n}\n\nexport interface AppSnippet {\n service: string;\n app_id: string;\n /** Encoded app id (`getRouteKey()`): the scope id its snippets bind to via `data-scope-id`,\n * and its settings-bucket key. Absent on payloads predating the settings API. */\n id?: string;\n app_slug: string;\n status: string;\n snippets: AppSnippetRow[];\n}\n\n/**\n * Per-app public `app.*` buckets for CDN snippets, keyed by encoded app id (== `AppSnippet.id`,\n * the `Salla.appScope` scope id). One isolated bucket per app; reads within a scope are bare `app.*`.\n */\nexport interface AppSettings {\n apps: Record<string, Record<string, unknown>>;\n}\n\nexport const apps = {\n /**\n * Installed apps' snippets (scripts/HTML to inject). Timeout-bounded because it's awaited in\n * rootBeforeLoad (SSR/TTFB): a slow response degrades to no CDN tags, never stalls the page.\n */\n snippets: async (): Promise<AppSnippet[]> => {\n const { data } = await api\n .get('apps/snippets', { timeout: 2500 })\n .json<{ data?: AppSnippet[] }>();\n return data ?? [];\n },\n\n /**\n * Per-app public `app.*` buckets, keyed by encoded app id. Timeout-bounded (SSR-awaited):\n * a slow response degrades to empty buckets (fail-open), never strands injection.\n */\n settings: async (): Promise<AppSettings> => {\n const { data } = await api\n .get('apps/snippets/settings', { timeout: 2500 })\n .json<{ data?: Partial<AppSettings> }>();\n return { apps: data?.apps ?? {} };\n },\n\n queries: {\n snippets: () =>\n queryOptions({\n queryKey: ['apps', 'snippets'],\n queryFn: () => apps.snippets(),\n // Snippets are static per session; one fetch per page load is enough.\n staleTime: Infinity,\n // No retry: this is awaited in rootBeforeLoad, so the router's default `retry: 1` would\n // make the SSR wait 2 x the 2500ms timeout (plus backoff) before failing open. The\n // 2500ms timeout must be the whole budget; the client fallback query does the retrying.\n retry: 0,\n }),\n\n settings: () =>\n queryOptions({\n queryKey: ['apps', 'settings'],\n queryFn: () => apps.settings(),\n // Encoded app ids and their buckets are stable per page; one fetch is enough.\n staleTime: Infinity,\n retry: 0,\n }),\n },\n};\n"]}
@@ -1,4 +1,4 @@
1
- import { filesCdn, cdn } from './chunk-53ZWOFFE.js';
1
+ import { filesCdn, cdn } from './chunk-UF6XPCEO.js';
2
2
  import { storeTranslationsQueryKey, translationsQueryKey, composeMessages, isPlainObject } from './chunk-6K34BCUP.js';
3
3
  import { queryOptions } from '@tanstack/react-query';
4
4
 
@@ -126,5 +126,5 @@ var translations = {
126
126
  };
127
127
 
128
128
  export { commonTranslationsPath, storeTranslationsPath, translations };
129
- //# sourceMappingURL=chunk-T2OUBYWG.js.map
130
- //# sourceMappingURL=chunk-T2OUBYWG.js.map
129
+ //# sourceMappingURL=chunk-WZJCJCU3.js.map
130
+ //# sourceMappingURL=chunk-WZJCJCU3.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/translations.ts"],"names":[],"mappings":";;;;AAiEA,IAAM,kBAAA,GAAqB,sBAAA;AAGpB,SAAS,uBAAuB,MAAA,EAAwB;AAC7D,EAAA,OAAO,uBAAuB,MAAM,CAAA,KAAA,CAAA;AACtC;AAWO,SAAS,qBAAA,CAAsB,SAA0B,MAAA,EAAwB;AACtF,EAAA,OAAO,CAAA,aAAA,EAAgB,OAAO,CAAA,CAAA,EAAI,MAAM,CAAA,KAAA,CAAA;AAC1C;AAUA,eAAe,eACb,IAAA,EACA,EAAE,aAAa,KAAA,EAAM,GAA8B,EAAC,EAC1B;AAE1B,EAAA,MAAM,UAAA,GAAa,CAAC,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A;AAAA;AAAA;AAAA,IAgBP,QAAA,EAAU,CAAC,MAAA,KACT,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,qBAAqB,MAAM,CAAA;AAAA,MACrC,OAAA,EAAS,MAAM,YAAA,CAAa,GAAA,CAAI,MAAM;AAAA,KACvC,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAWH,OAAA,EAAS,CAAC,OAAA,EAA0B,MAAA,KAClC,YAAA,CAAa;AAAA,MACX,QAAA,EAAU,yBAAA,CAA0B,OAAA,EAAS,MAAM,CAAA;AAAA,MACnD,OAAA,EAAS,MAAM,YAAA,CAAa,QAAA,CAAS,SAAS,MAAM;AAAA,KACrD;AAAA;AAEP","file":"chunk-T2OUBYWG.js","sourcesContent":["/**\n * @fileoverview Where a storefront's words come from.\n *\n * Two files, merged: the platform's copy for this language, and the merchant's\n * own edits for this language and this store. Both are plain JSON objects on\n * the uploader's CDN, one per language.\n *\n * ```\n * https://cdn.files.salla.network/translations/common/<locale>.json the platform's\n * https://cdn.files.salla.network/translations/<storeId>/<locale>.json the merchant's\n * ```\n *\n * **What this replaces, and why.** Until now the engine read a single global\n * file, `cdn.salla.network/js/translations.json`, holding every language keyed\n * `\"<locale>.trans\"`. Nothing publishes that file: it is an object last written\n * on 2026-03-26, carrying only `ar` and `en` where the platform has 39 locales,\n * 405 keys behind `Languages-Module` and 959 English strings textually\n * different from it. So every React storefront has been serving copy from\n * March, and a key added since has never reached one. It also carried no\n * merchant overrides at all — a merchant editing their theme's wording in the\n * Dashboard changed nothing on a React theme.\n *\n * **Merchant overrides are read, and only when there are any.** Getting here\n * took two corrections worth keeping.\n *\n * The first is the address. A merchant's own wording lives at\n * `translations/<storeId>/<locale>.json`, keyed by `store()->getRouteKey()` —\n * the Optimus-encoded numeric id. An early version addressed it with\n * `resolveStoreIdentifier()`, on the claim that the two are the same string.\n * That is true of the `store-identifier` *header*, which accepts a host, a\n * username or an id, and false of the R2 key: on a custom domain the resolver\n * returns `reefperfumes.com` and on a shared host a username like\n * `mtgr-alaatr-2`. Both 404, both then read as \"this store has no overrides\",\n * and the merchant's wording silently never appears — so the feature would have\n * worked under `?storeId=` alone, which is preview and localhost. It is\n * `settings.store.id` now, which is known only after the settings query.\n *\n * The second is when to ask at all. Most stores have never customised a word,\n * and a miss is an uncached round trip (`cf-cache-status: DYNAMIC` on the 404)\n * on the critical path of every SSR render. So the request is made only when\n * `settings.languages[<ISO>].has_custom_translations` says there is something\n * to get — a flag `Languages-Module` writes when a merchant saves a\n * translation. A store without overrides pays nothing, which is what made this\n * shippable at all.\n *\n * ⚠️ The flag is written on save, so a store whose wording predates it reads as\n * `false` until someone edits a translation or the backfill runs. That is a\n * store keeping today's behaviour, not a regression — React themes have never\n * read merchant overrides — but it does mean the feature is only as complete as\n * the backfill.\n *\n * **Rollout is by fallback, not by flag.** `translations/common/` is written by\n * a sync in the theme build service that may not have run yet, and a hard switch\n * would leave every storefront with no platform strings at all. A missing common\n * file therefore falls back to the old global one, which is exactly today's\n * behaviour — so this is safe to ship before the bucket is populated, and stops\n * using the fallback on its own once it is.\n */\nimport { queryOptions } from '@tanstack/react-query';\nimport { cdn, filesCdn } from './client';\nimport { storeTranslationsQueryKey, translationsQueryKey } from './translations-key';\nimport { composeMessages, isPlainObject, type Messages } from './messages';\nimport type { TranslationMessages } from '../providers/I18nProvider';\n\n/** The global file this used to be the only reader of. See the file comment. */\nconst LEGACY_GLOBAL_FILE = 'js/translations.json';\n\n/** One language of platform copy, shared by every store. */\nexport function commonTranslationsPath(locale: string): string {\n return `translations/common/${locale}.json`;\n}\n\n/**\n * One language of a single merchant's own wording.\n *\n * `storeId` is `settings.store.id`, which is the value `Languages-Module` names\n * the object with (`store()->getRouteKey()`, the Optimus-encoded numeric id).\n * It is **not** `resolveStoreIdentifier()`: that returns a hostname on a custom\n * domain and a username on a shared host, both of which 404 here and would read\n * as \"this merchant has no overrides\" — silently, on every store but a preview.\n */\nexport function storeTranslationsPath(storeId: string | number, locale: string): string {\n return `translations/${storeId}/${locale}.json`;\n}\n\n/**\n * Reads one language file, or `null` when there is nothing to read.\n *\n * A 404 is the ordinary answer, not a failure: most stores have never had a\n * word customised, so their file does not exist. Distinguishing it from a real\n * error matters only for the log — both end in `null` — but a warning on every\n * page load of every uncustomised store is a warning nobody will read.\n */\nasync function readLocaleFile(\n path: string,\n { failLoudly = false }: { failLoudly?: boolean } = {}\n): Promise<Messages | null> {\n /** A 404 always means \"absent\"; everything else is a failure to read. */\n const unreadable = (reason: string, cause?: unknown): null => {\n if (failLoudly) throw new Error(`[translations] ${path}: ${reason}`, { cause });\n console.warn('[translations]', reason, path, cause ?? '');\n return null;\n };\n\n try {\n const response = await filesCdn.get(path, { throwHttpErrors: false, timeout: 5000 });\n if (response.status === 404) return null;\n\n if (!response.ok) {\n return unreadable(`answered ${response.status}`);\n }\n\n const data: unknown = await response.json();\n if (!isPlainObject(data)) {\n return unreadable('is not a JSON object');\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('[translations]')) throw error;\n return unreadable('could not be read', error);\n }\n}\n\n/**\n * The pre-CDN global file, sliced to one language.\n *\n * Only reached when `translations/common/<locale>.json` is missing, which is\n * the state of the bucket until the sync has run once.\n */\nasync function readLegacyGlobal(locale: string): Promise<Messages | null> {\n try {\n const data = await cdn.get(LEGACY_GLOBAL_FILE, { timeout: 5000 }).json<TranslationMessages>();\n const forLocale = data?.[`${locale}.trans`];\n return isPlainObject(forLocale) ? forLocale : null;\n } catch {\n console.warn('[translations] the legacy global file could not be read either');\n return null;\n }\n}\n\nexport const translations = {\n /**\n * The platform's copy for `locale`.\n *\n * One file, so one request. See the file comment for why the merchant's own\n * wording is not merged in here yet and what it is waiting on.\n */\n get: async (locale: string): Promise<TranslationMessages | null> => {\n const common = await readLocaleFile(commonTranslationsPath(locale));\n const base = common ?? (await readLegacyGlobal(locale));\n if (!base) return null;\n\n // Still wrapped in the `<locale>.trans` shape the rest of the engine reads.\n // `createI18nInstance` slices by that key and so does the SDK bridge in\n // `I18nProvider`; changing the envelope here would be a second change for\n // no gain, since one language is all any of them ever take out of it.\n return { [`${locale}.trans`]: base as Record<string, string> };\n },\n\n /**\n * This merchant's own wording for `locale`, or `null` if they have none.\n *\n * Only worth calling when `settings.languages[<ISO>].has_custom_translations`\n * says there is something to get. Most stores have never customised a word,\n * and a miss here is an uncached round trip — `cf-cache-status: DYNAMIC` on a\n * 404 — on the critical path of an SSR render. The flag is what makes this\n * free for everyone who does not use it.\n *\n * Returned unwrapped, unlike {@link translations.get}: this is merged into\n * that one's messages rather than handed to i18next on its own.\n */\n forStore: async (storeId: string | number, locale: string): Promise<Messages | null> =>\n // `failLoudly`, unlike the platform file: this is only ever called because\n // the settings said overrides exist, so a 500, a timeout or a body that is\n // not JSON is a failure to read them — not a store that has none. Returning\n // `null` there would cache \"no overrides\" as a success, skip the query's\n // retry, and serve Salla's wording in place of the merchant's until the\n // entry expired. A 404 still means absent, and `rootBeforeLoad` catches the\n // throw and keeps the platform copy, so the worst case is unchanged.\n readLocaleFile(storeTranslationsPath(storeId, locale), { failLoudly: true }),\n\n /**\n * The platform's copy for `locale` with this merchant's wording laid over it.\n *\n * Takes the two as values rather than fetching them, so the caller decides\n * whether the second request happens at all and both stay separately cached.\n */\n /**\n * The platform's copy for `locale` with this merchant's wording over it.\n *\n * Delegates to `composeMessages`, which every other reader of these two\n * entries also uses — see `api/messages.ts` for why there is exactly one.\n */\n merge: (\n common: TranslationMessages | null,\n overrides: Messages | null,\n locale: string\n ): TranslationMessages | null => composeMessages(common, overrides, locale) ?? null,\n\n queries: {\n /**\n * @param locale taken as an argument rather than read from the twilight\n * context, and that is load-bearing. This key is built on the server, on\n * hydration, and again lazily from the context accessor; if any of the\n * three read a locale the others had not been given yet, the hydrated page\n * would miss the dehydrated entry and refetch both files it was just\n * handed. Every caller already has the locale in hand.\n *\n * The store is deliberately **not** in the key. One document serves one\n * store — a request that names a different one is redirected with\n * `reloadDocument`, so the client never changes store under a live cache —\n * and adding a value that resolves from the request on the server and from\n * the injected env on the client is how a key stops matching across\n * hydration.\n */\n byLocale: (locale: string) =>\n queryOptions({\n queryKey: translationsQueryKey(locale),\n queryFn: () => translations.get(locale),\n }),\n\n /**\n * This merchant's overrides, cached apart from the platform's copy.\n *\n * Its own entry rather than a wider `byLocale` key, so the common file is\n * fetched and dehydrated once per language whatever the store does, and a\n * store with no overrides never has an entry at all. Both sides compute the\n * key from the settings payload, so the hydrated page finds what the server\n * dehydrated instead of refetching it.\n */\n byStore: (storeId: string | number, locale: string) =>\n queryOptions({\n queryKey: storeTranslationsQueryKey(storeId, locale),\n queryFn: () => translations.forStore(storeId, locale),\n }),\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/api/translations.ts"],"names":[],"mappings":";;;;AAiEA,IAAM,kBAAA,GAAqB,sBAAA;AAGpB,SAAS,uBAAuB,MAAA,EAAwB;AAC7D,EAAA,OAAO,uBAAuB,MAAM,CAAA,KAAA,CAAA;AACtC;AAWO,SAAS,qBAAA,CAAsB,SAA0B,MAAA,EAAwB;AACtF,EAAA,OAAO,CAAA,aAAA,EAAgB,OAAO,CAAA,CAAA,EAAI,MAAM,CAAA,KAAA,CAAA;AAC1C;AAUA,eAAe,eACb,IAAA,EACA,EAAE,aAAa,KAAA,EAAM,GAA8B,EAAC,EAC1B;AAE1B,EAAA,MAAM,UAAA,GAAa,CAAC,MAAA,EAAgB,KAAA,KAA0B;AAC5D,IAAA,IAAI,UAAA,EAAY,MAAM,IAAI,KAAA,CAAM,CAAA,eAAA,EAAkB,IAAI,CAAA,EAAA,EAAK,MAAM,CAAA,CAAA,EAAI,EAAE,KAAA,EAAO,CAAA;AAC9E,IAAA,OAAA,CAAQ,IAAA,CAAK,gBAAA,EAAkB,MAAA,EAAQ,IAAA,EAAM,SAAS,EAAE,CAAA;AACxD,IAAA,OAAO,IAAA;AAAA,EACT,CAAA;AAEA,EAAA,IAAI;AACF,IAAA,MAAM,QAAA,GAAW,MAA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MAAM,CAAA;AAAA,MACnD,OAAA,EAAS,MAAM,YAAA,CAAa,QAAA,CAAS,SAAS,MAAM;AAAA,KACrD;AAAA;AAEP","file":"chunk-WZJCJCU3.js","sourcesContent":["/**\n * @fileoverview Where a storefront's words come from.\n *\n * Two files, merged: the platform's copy for this language, and the merchant's\n * own edits for this language and this store. Both are plain JSON objects on\n * the uploader's CDN, one per language.\n *\n * ```\n * https://cdn.files.salla.network/translations/common/<locale>.json the platform's\n * https://cdn.files.salla.network/translations/<storeId>/<locale>.json the merchant's\n * ```\n *\n * **What this replaces, and why.** Until now the engine read a single global\n * file, `cdn.salla.network/js/translations.json`, holding every language keyed\n * `\"<locale>.trans\"`. Nothing publishes that file: it is an object last written\n * on 2026-03-26, carrying only `ar` and `en` where the platform has 39 locales,\n * 405 keys behind `Languages-Module` and 959 English strings textually\n * different from it. So every React storefront has been serving copy from\n * March, and a key added since has never reached one. It also carried no\n * merchant overrides at all — a merchant editing their theme's wording in the\n * Dashboard changed nothing on a React theme.\n *\n * **Merchant overrides are read, and only when there are any.** Getting here\n * took two corrections worth keeping.\n *\n * The first is the address. A merchant's own wording lives at\n * `translations/<storeId>/<locale>.json`, keyed by `store()->getRouteKey()` —\n * the Optimus-encoded numeric id. An early version addressed it with\n * `resolveStoreIdentifier()`, on the claim that the two are the same string.\n * That is true of the `store-identifier` *header*, which accepts a host, a\n * username or an id, and false of the R2 key: on a custom domain the resolver\n * returns `reefperfumes.com` and on a shared host a username like\n * `mtgr-alaatr-2`. Both 404, both then read as \"this store has no overrides\",\n * and the merchant's wording silently never appears — so the feature would have\n * worked under `?storeId=` alone, which is preview and localhost. It is\n * `settings.store.id` now, which is known only after the settings query.\n *\n * The second is when to ask at all. Most stores have never customised a word,\n * and a miss is an uncached round trip (`cf-cache-status: DYNAMIC` on the 404)\n * on the critical path of every SSR render. So the request is made only when\n * `settings.languages[<ISO>].has_custom_translations` says there is something\n * to get — a flag `Languages-Module` writes when a merchant saves a\n * translation. A store without overrides pays nothing, which is what made this\n * shippable at all.\n *\n * ⚠️ The flag is written on save, so a store whose wording predates it reads as\n * `false` until someone edits a translation or the backfill runs. That is a\n * store keeping today's behaviour, not a regression — React themes have never\n * read merchant overrides — but it does mean the feature is only as complete as\n * the backfill.\n *\n * **Rollout is by fallback, not by flag.** `translations/common/` is written by\n * a sync in the theme build service that may not have run yet, and a hard switch\n * would leave every storefront with no platform strings at all. A missing common\n * file therefore falls back to the old global one, which is exactly today's\n * behaviour — so this is safe to ship before the bucket is populated, and stops\n * using the fallback on its own once it is.\n */\nimport { queryOptions } from '@tanstack/react-query';\nimport { cdn, filesCdn } from './client';\nimport { storeTranslationsQueryKey, translationsQueryKey } from './translations-key';\nimport { composeMessages, isPlainObject, type Messages } from './messages';\nimport type { TranslationMessages } from '../providers/I18nProvider';\n\n/** The global file this used to be the only reader of. See the file comment. */\nconst LEGACY_GLOBAL_FILE = 'js/translations.json';\n\n/** One language of platform copy, shared by every store. */\nexport function commonTranslationsPath(locale: string): string {\n return `translations/common/${locale}.json`;\n}\n\n/**\n * One language of a single merchant's own wording.\n *\n * `storeId` is `settings.store.id`, which is the value `Languages-Module` names\n * the object with (`store()->getRouteKey()`, the Optimus-encoded numeric id).\n * It is **not** `resolveStoreIdentifier()`: that returns a hostname on a custom\n * domain and a username on a shared host, both of which 404 here and would read\n * as \"this merchant has no overrides\" — silently, on every store but a preview.\n */\nexport function storeTranslationsPath(storeId: string | number, locale: string): string {\n return `translations/${storeId}/${locale}.json`;\n}\n\n/**\n * Reads one language file, or `null` when there is nothing to read.\n *\n * A 404 is the ordinary answer, not a failure: most stores have never had a\n * word customised, so their file does not exist. Distinguishing it from a real\n * error matters only for the log — both end in `null` — but a warning on every\n * page load of every uncustomised store is a warning nobody will read.\n */\nasync function readLocaleFile(\n path: string,\n { failLoudly = false }: { failLoudly?: boolean } = {}\n): Promise<Messages | null> {\n /** A 404 always means \"absent\"; everything else is a failure to read. */\n const unreadable = (reason: string, cause?: unknown): null => {\n if (failLoudly) throw new Error(`[translations] ${path}: ${reason}`, { cause });\n console.warn('[translations]', reason, path, cause ?? '');\n return null;\n };\n\n try {\n const response = await filesCdn.get(path, { throwHttpErrors: false, timeout: 5000 });\n if (response.status === 404) return null;\n\n if (!response.ok) {\n return unreadable(`answered ${response.status}`);\n }\n\n const data: unknown = await response.json();\n if (!isPlainObject(data)) {\n return unreadable('is not a JSON object');\n }\n\n return data;\n } catch (error) {\n if (error instanceof Error && error.message.startsWith('[translations]')) throw error;\n return unreadable('could not be read', error);\n }\n}\n\n/**\n * The pre-CDN global file, sliced to one language.\n *\n * Only reached when `translations/common/<locale>.json` is missing, which is\n * the state of the bucket until the sync has run once.\n */\nasync function readLegacyGlobal(locale: string): Promise<Messages | null> {\n try {\n const data = await cdn.get(LEGACY_GLOBAL_FILE, { timeout: 5000 }).json<TranslationMessages>();\n const forLocale = data?.[`${locale}.trans`];\n return isPlainObject(forLocale) ? forLocale : null;\n } catch {\n console.warn('[translations] the legacy global file could not be read either');\n return null;\n }\n}\n\nexport const translations = {\n /**\n * The platform's copy for `locale`.\n *\n * One file, so one request. See the file comment for why the merchant's own\n * wording is not merged in here yet and what it is waiting on.\n */\n get: async (locale: string): Promise<TranslationMessages | null> => {\n const common = await readLocaleFile(commonTranslationsPath(locale));\n const base = common ?? (await readLegacyGlobal(locale));\n if (!base) return null;\n\n // Still wrapped in the `<locale>.trans` shape the rest of the engine reads.\n // `createI18nInstance` slices by that key and so does the SDK bridge in\n // `I18nProvider`; changing the envelope here would be a second change for\n // no gain, since one language is all any of them ever take out of it.\n return { [`${locale}.trans`]: base as Record<string, string> };\n },\n\n /**\n * This merchant's own wording for `locale`, or `null` if they have none.\n *\n * Only worth calling when `settings.languages[<ISO>].has_custom_translations`\n * says there is something to get. Most stores have never customised a word,\n * and a miss here is an uncached round trip — `cf-cache-status: DYNAMIC` on a\n * 404 — on the critical path of an SSR render. The flag is what makes this\n * free for everyone who does not use it.\n *\n * Returned unwrapped, unlike {@link translations.get}: this is merged into\n * that one's messages rather than handed to i18next on its own.\n */\n forStore: async (storeId: string | number, locale: string): Promise<Messages | null> =>\n // `failLoudly`, unlike the platform file: this is only ever called because\n // the settings said overrides exist, so a 500, a timeout or a body that is\n // not JSON is a failure to read them — not a store that has none. Returning\n // `null` there would cache \"no overrides\" as a success, skip the query's\n // retry, and serve Salla's wording in place of the merchant's until the\n // entry expired. A 404 still means absent, and `rootBeforeLoad` catches the\n // throw and keeps the platform copy, so the worst case is unchanged.\n readLocaleFile(storeTranslationsPath(storeId, locale), { failLoudly: true }),\n\n /**\n * The platform's copy for `locale` with this merchant's wording laid over it.\n *\n * Takes the two as values rather than fetching them, so the caller decides\n * whether the second request happens at all and both stay separately cached.\n */\n /**\n * The platform's copy for `locale` with this merchant's wording over it.\n *\n * Delegates to `composeMessages`, which every other reader of these two\n * entries also uses — see `api/messages.ts` for why there is exactly one.\n */\n merge: (\n common: TranslationMessages | null,\n overrides: Messages | null,\n locale: string\n ): TranslationMessages | null => composeMessages(common, overrides, locale) ?? null,\n\n queries: {\n /**\n * @param locale taken as an argument rather than read from the twilight\n * context, and that is load-bearing. This key is built on the server, on\n * hydration, and again lazily from the context accessor; if any of the\n * three read a locale the others had not been given yet, the hydrated page\n * would miss the dehydrated entry and refetch both files it was just\n * handed. Every caller already has the locale in hand.\n *\n * The store is deliberately **not** in the key. One document serves one\n * store — a request that names a different one is redirected with\n * `reloadDocument`, so the client never changes store under a live cache —\n * and adding a value that resolves from the request on the server and from\n * the injected env on the client is how a key stops matching across\n * hydration.\n */\n byLocale: (locale: string) =>\n queryOptions({\n queryKey: translationsQueryKey(locale),\n queryFn: () => translations.get(locale),\n }),\n\n /**\n * This merchant's overrides, cached apart from the platform's copy.\n *\n * Its own entry rather than a wider `byLocale` key, so the common file is\n * fetched and dehydrated once per language whatever the store does, and a\n * store with no overrides never has an entry at all. Both sides compute the\n * key from the settings payload, so the hydrated page finds what the server\n * dehydrated instead of refetching it.\n */\n byStore: (storeId: string | number, locale: string) =>\n queryOptions({\n queryKey: storeTranslationsQueryKey(storeId, locale),\n queryFn: () => translations.forStore(storeId, locale),\n }),\n },\n};\n"]}