@salla.sa/twilight-theme-engine 1.0.67 → 1.0.68
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AddToCartForm-UVQG3BI5.js → AddToCartForm-TX36PDIE.js} +3 -3
- package/dist/{AddToCartForm-UVQG3BI5.js.map → AddToCartForm-TX36PDIE.js.map} +1 -1
- package/dist/{BlogAuthorPage-7HVGT3CS.js → BlogAuthorPage-AT6YYDG4.js} +17 -17
- package/dist/{BlogAuthorPage-7HVGT3CS.js.map → BlogAuthorPage-AT6YYDG4.js.map} +1 -1
- package/dist/{BlogCategoryPage-MSITS6B3.js → BlogCategoryPage-ELPLV67S.js} +17 -17
- package/dist/{BlogCategoryPage-MSITS6B3.js.map → BlogCategoryPage-ELPLV67S.js.map} +1 -1
- package/dist/{BlogPage-6FLWZBK3.js → BlogPage-RO3U4OTI.js} +15 -15
- package/dist/{BlogPage-6FLWZBK3.js.map → BlogPage-RO3U4OTI.js.map} +1 -1
- package/dist/{BlogSinglePage-LSF5P4GA.js → BlogSinglePage-HSRVLJYE.js} +15 -15
- package/dist/{BlogSinglePage-LSF5P4GA.js.map → BlogSinglePage-HSRVLJYE.js.map} +1 -1
- package/dist/{BlogTagPage-JPOF3OC4.js → BlogTagPage-KLCLNP2Q.js} +17 -17
- package/dist/{BlogTagPage-JPOF3OC4.js.map → BlogTagPage-KLCLNP2Q.js.map} +1 -1
- package/dist/{BrandsPage-7G5VWJ2S.js → BrandsPage-C2TTKTMV.js} +16 -16
- package/dist/{BrandsPage-7G5VWJ2S.js.map → BrandsPage-C2TTKTMV.js.map} +1 -1
- package/dist/{Breadcrumb-MNYKDV27.js → Breadcrumb-MLWGLXJZ.js} +15 -15
- package/dist/{Breadcrumb-MNYKDV27.js.map → Breadcrumb-MLWGLXJZ.js.map} +1 -1
- package/dist/{CartItem-DNA2TJ6B.js → CartItem-5JKJ3AD6.js} +15 -15
- package/dist/{CartItem-DNA2TJ6B.js.map → CartItem-5JKJ3AD6.js.map} +1 -1
- package/dist/{CartSummary-RTDKJUV7.js → CartSummary-ZNBVWC2P.js} +15 -15
- package/dist/{CartSummary-RTDKJUV7.js.map → CartSummary-ZNBVWC2P.js.map} +1 -1
- package/dist/{Copyright-IR4VD3I6.js → Copyright-LBUY2AJJ.js} +3 -3
- package/dist/{Copyright-IR4VD3I6.js.map → Copyright-LBUY2AJJ.js.map} +1 -1
- package/dist/{CustomerLayout-6YWOUFEN.js → CustomerLayout-YDJQYMQI.js} +15 -15
- package/dist/{CustomerLayout-6YWOUFEN.js.map → CustomerLayout-YDJQYMQI.js.map} +1 -1
- package/dist/{Footer-YQHS47HV.js → Footer-X46MKKA5.js} +15 -15
- package/dist/{Footer-YQHS47HV.js.map → Footer-X46MKKA5.js.map} +1 -1
- package/dist/{Header-VEI2M3XJ.js → Header-YK5QFAO7.js} +4 -4
- package/dist/{Header-VEI2M3XJ.js.map → Header-YK5QFAO7.js.map} +1 -1
- package/dist/{LoyaltyPage-L7LABJWG.js → LoyaltyPage-RM3WQLVC.js} +15 -15
- package/dist/{LoyaltyPage-L7LABJWG.js.map → LoyaltyPage-RM3WQLVC.js.map} +1 -1
- package/dist/{LoyaltyPointsPage-Z2GAMWCG.js → LoyaltyPointsPage-AN7VC3AF.js} +3 -3
- package/dist/{LoyaltyPointsPage-Z2GAMWCG.js.map → LoyaltyPointsPage-AN7VC3AF.js.map} +1 -1
- package/dist/{MainMenu-76GBUVNZ.js → MainMenu-ETIJZLKV.js} +6 -6
- package/dist/{MainMenu-76GBUVNZ.js.map → MainMenu-ETIJZLKV.js.map} +1 -1
- package/dist/{MasterLayout-GEQBU2MH.js → MasterLayout-QSYGLVJD.js} +15 -15
- package/dist/{MasterLayout-GEQBU2MH.js.map → MasterLayout-QSYGLVJD.js.map} +1 -1
- package/dist/{MobileMenu-DS5OJRCO.js → MobileMenu-V624P4XH.js} +16 -16
- package/dist/{MobileMenu-DS5OJRCO.js.map → MobileMenu-V624P4XH.js.map} +1 -1
- package/dist/{NotificationsPage-OT2WY2EF.js → NotificationsPage-MAN7PINP.js} +15 -15
- package/dist/{NotificationsPage-OT2WY2EF.js.map → NotificationsPage-MAN7PINP.js.map} +1 -1
- package/dist/{OrderSinglePage-XGPSBIA3.js → OrderSinglePage-43FJCEPN.js} +16 -16
- package/dist/{OrderSinglePage-XGPSBIA3.js.map → OrderSinglePage-43FJCEPN.js.map} +1 -1
- package/dist/{OrdersPage-A5TARKJ7.js → OrdersPage-TW3VH6EN.js} +15 -15
- package/dist/{OrdersPage-A5TARKJ7.js.map → OrdersPage-TW3VH6EN.js.map} +1 -1
- package/dist/{PageSingle-VUNU2BG4.js → PageSingle-AX7M6XH3.js} +9 -4
- package/dist/PageSingle-AX7M6XH3.js.map +1 -0
- package/dist/{ProductDetails-2JWKUXLI.js → ProductDetails-4ABLVN5Z.js} +3 -3
- package/dist/{ProductDetails-2JWKUXLI.js.map → ProductDetails-4ABLVN5Z.js.map} +1 -1
- package/dist/{ProfilePage-AVUCRBHQ.js → ProfilePage-ACF2CGYH.js} +15 -15
- package/dist/{ProfilePage-AVUCRBHQ.js.map → ProfilePage-ACF2CGYH.js.map} +1 -1
- package/dist/{SeoCartWidget-X5HTL62D.js → SeoCartWidget-AFJRAXWF.js} +19 -21
- package/dist/SeoCartWidget-AFJRAXWF.js.map +1 -0
- package/dist/{SettingsPage-WGGKT3I4.js → SettingsPage-FYFH4QLC.js} +15 -15
- package/dist/{SettingsPage-WGGKT3I4.js.map → SettingsPage-FYFH4QLC.js.map} +1 -1
- package/dist/{StoreClosedNotification-XDYQO7JF.js → StoreClosedNotification-PPQFOIW3.js} +16 -16
- package/dist/{StoreClosedNotification-XDYQO7JF.js.map → StoreClosedNotification-PPQFOIW3.js.map} +1 -1
- package/dist/{TestimonialsPage-CKAYXFER.js → TestimonialsPage-Q5UIOYG6.js} +8 -4
- package/dist/TestimonialsPage-Q5UIOYG6.js.map +1 -0
- package/dist/{ThankYouPage-ZTCFTEI7.js → ThankYouPage-FKM3DCWO.js} +16 -21
- package/dist/ThankYouPage-FKM3DCWO.js.map +1 -0
- package/dist/{WalletPage-XKAOZIO2.js → WalletPage-WI7DXCGJ.js} +16 -16
- package/dist/{WalletPage-XKAOZIO2.js.map → WalletPage-WI7DXCGJ.js.map} +1 -1
- package/dist/{WishlistPage-LHIUUR4U.js → WishlistPage-G5Z2W5QD.js} +18 -23
- package/dist/WishlistPage-G5Z2W5QD.js.map +1 -0
- package/dist/api/apps.js +3 -3
- package/dist/api/brands.js +3 -3
- package/dist/api/cart.js +3 -3
- package/dist/api/category.js +3 -3
- package/dist/api/client.js +2 -2
- package/dist/api/home.js +3 -3
- package/dist/api/loyalty.js +3 -3
- package/dist/api/menu.js +3 -3
- package/dist/api/notification.js +3 -3
- package/dist/api/order.js +3 -3
- package/dist/api/page.js +3 -3
- package/dist/api/product.js +3 -3
- package/dist/api/profile.js +2 -2
- package/dist/api/store.js +3 -3
- package/dist/api/translations.js +3 -3
- package/dist/api/user.js +3 -3
- package/dist/api/wishlist.js +4 -4
- package/dist/{chunk-RH5VLLTG.js → chunk-2IYOHSQN.js} +4 -4
- package/dist/{chunk-RH5VLLTG.js.map → chunk-2IYOHSQN.js.map} +1 -1
- package/dist/{chunk-3L5VG2X4.js → chunk-4YQQVUXS.js} +4 -4
- package/dist/{chunk-3L5VG2X4.js.map → chunk-4YQQVUXS.js.map} +1 -1
- package/dist/chunk-5Y64476S.js +80 -0
- package/dist/chunk-5Y64476S.js.map +1 -0
- package/dist/{chunk-W5K6YUA2.js → chunk-AH6KEBKX.js} +6 -6
- package/dist/{chunk-W5K6YUA2.js.map → chunk-AH6KEBKX.js.map} +1 -1
- package/dist/{chunk-TOPFB6FL.js → chunk-B2OHRXRD.js} +3 -3
- package/dist/{chunk-TOPFB6FL.js.map → chunk-B2OHRXRD.js.map} +1 -1
- package/dist/{chunk-3Q22KK7C.js → chunk-CTLTXDHH.js} +5 -5
- package/dist/{chunk-3Q22KK7C.js.map → chunk-CTLTXDHH.js.map} +1 -1
- package/dist/{chunk-UEQFXSTX.js → chunk-DISOIXUL.js} +124 -119
- package/dist/chunk-DISOIXUL.js.map +1 -0
- package/dist/{chunk-5X2UFNKY.js → chunk-DZT26OCM.js} +3 -3
- package/dist/{chunk-5X2UFNKY.js.map → chunk-DZT26OCM.js.map} +1 -1
- package/dist/{chunk-TTMYT3RB.js → chunk-E2XHLK5O.js} +3 -3
- package/dist/{chunk-TTMYT3RB.js.map → chunk-E2XHLK5O.js.map} +1 -1
- package/dist/{chunk-GOPUP26T.js → chunk-E43ALK3R.js} +4 -9
- package/dist/chunk-E43ALK3R.js.map +1 -0
- package/dist/{chunk-VI5R46KX.js → chunk-EBFYRFMI.js} +7 -7
- package/dist/{chunk-VI5R46KX.js.map → chunk-EBFYRFMI.js.map} +1 -1
- package/dist/chunk-EI52BZFN.js +14 -0
- package/dist/{chunk-TFROBJP5.js.map → chunk-EI52BZFN.js.map} +1 -1
- package/dist/{chunk-A4UQKSOU.js → chunk-ELS6I3O2.js} +4 -4
- package/dist/{chunk-A4UQKSOU.js.map → chunk-ELS6I3O2.js.map} +1 -1
- package/dist/{chunk-UIOLSYKV.js → chunk-ETPOZJHG.js} +3 -3
- package/dist/{chunk-UIOLSYKV.js.map → chunk-ETPOZJHG.js.map} +1 -1
- package/dist/{chunk-FTM3RIVB.js → chunk-FBOSUTNC.js} +3 -3
- package/dist/{chunk-FTM3RIVB.js.map → chunk-FBOSUTNC.js.map} +1 -1
- package/dist/{chunk-EFMAB636.js → chunk-G2VNDZID.js} +3 -3
- package/dist/{chunk-EFMAB636.js.map → chunk-G2VNDZID.js.map} +1 -1
- package/dist/{chunk-PWBMSGMU.js → chunk-H7BCB2HO.js} +6 -23
- package/dist/chunk-H7BCB2HO.js.map +1 -0
- package/dist/{chunk-EYFMLMMF.js → chunk-I4XPOEQY.js} +3 -3
- package/dist/{chunk-EYFMLMMF.js.map → chunk-I4XPOEQY.js.map} +1 -1
- package/dist/{chunk-P3OPJL6I.js → chunk-IKUDCH7Q.js} +3 -3
- package/dist/{chunk-P3OPJL6I.js.map → chunk-IKUDCH7Q.js.map} +1 -1
- package/dist/{chunk-FAVZMJRY.js → chunk-ITHU2R5C.js} +6 -6
- package/dist/{chunk-FAVZMJRY.js.map → chunk-ITHU2R5C.js.map} +1 -1
- package/dist/{chunk-SOPZ72BU.js → chunk-J2YKHDMH.js} +3 -3
- package/dist/{chunk-SOPZ72BU.js.map → chunk-J2YKHDMH.js.map} +1 -1
- package/dist/{chunk-FRFTO2HP.js → chunk-J5DXKBVJ.js} +6 -6
- package/dist/{chunk-FRFTO2HP.js.map → chunk-J5DXKBVJ.js.map} +1 -1
- package/dist/{chunk-HDO37URJ.js → chunk-K6SNUM3L.js} +3 -3
- package/dist/{chunk-HDO37URJ.js.map → chunk-K6SNUM3L.js.map} +1 -1
- package/dist/{chunk-VAW73MFZ.js → chunk-KCCU3S5F.js} +9 -9
- package/dist/chunk-KCCU3S5F.js.map +1 -0
- package/dist/{chunk-Q3COPV5Z.js → chunk-L2DRHH4E.js} +3 -3
- package/dist/{chunk-Q3COPV5Z.js.map → chunk-L2DRHH4E.js.map} +1 -1
- package/dist/{chunk-UZKTK6YV.js → chunk-NCTG4ZTU.js} +3 -3
- package/dist/{chunk-UZKTK6YV.js.map → chunk-NCTG4ZTU.js.map} +1 -1
- package/dist/{chunk-EQ32CL4D.js → chunk-NTIGQYSN.js} +3 -3
- package/dist/{chunk-EQ32CL4D.js.map → chunk-NTIGQYSN.js.map} +1 -1
- package/dist/{chunk-VGIK4BW6.js → chunk-OFRV3WKR.js} +4 -4
- package/dist/{chunk-VGIK4BW6.js.map → chunk-OFRV3WKR.js.map} +1 -1
- package/dist/{chunk-6IRWFBGU.js → chunk-TRZAQSHU.js} +3 -3
- package/dist/{chunk-6IRWFBGU.js.map → chunk-TRZAQSHU.js.map} +1 -1
- package/dist/{chunk-Y43T7PJV.js → chunk-TY3XJOIQ.js} +3 -3
- package/dist/{chunk-Y43T7PJV.js.map → chunk-TY3XJOIQ.js.map} +1 -1
- package/dist/{chunk-EAZGFREP.js → chunk-VAMIJGCU.js} +3 -3
- package/dist/{chunk-EAZGFREP.js.map → chunk-VAMIJGCU.js.map} +1 -1
- package/dist/{chunk-RJAVZBUK.js → chunk-XBW7EHBA.js} +3 -3
- package/dist/{chunk-RJAVZBUK.js.map → chunk-XBW7EHBA.js.map} +1 -1
- package/dist/{chunk-GYXT7T2Z.js → chunk-XCYIGCUN.js} +3 -3
- package/dist/{chunk-GYXT7T2Z.js.map → chunk-XCYIGCUN.js.map} +1 -1
- package/dist/{chunk-VKB5AQUS.js → chunk-Y7NC2NDA.js} +3 -3
- package/dist/{chunk-VKB5AQUS.js.map → chunk-Y7NC2NDA.js.map} +1 -1
- package/dist/components/cart/SeoCartWidget.d.ts.map +1 -1
- package/dist/components/cart/index.js +1 -1
- package/dist/components/common/index.js +1 -1
- package/dist/components/drawer/index.js +13 -13
- package/dist/components/home/index.js +17 -17
- package/dist/components/layout/index.js +1 -1
- package/dist/components/product/index.js +14 -14
- package/dist/components/store/index.js +15 -15
- package/dist/{document-class-SPTMBRWL.js → document-class-P33S4CA7.js} +9 -9
- package/dist/{document-class-SPTMBRWL.js.map → document-class-P33S4CA7.js.map} +1 -1
- package/dist/hooks/index.js +13 -13
- package/dist/hooks/useComments.d.ts.map +1 -1
- package/dist/hooks/useComments.js +6 -1
- package/dist/hooks/useGtm.js +13 -13
- package/dist/hooks/useMoney.js +13 -13
- package/dist/hooks/usePageConfig.d.ts.map +1 -1
- package/dist/hooks/useProduct.d.ts.map +1 -1
- package/dist/hooks/useProduct.js +6 -1
- package/dist/hooks/useStore.js +13 -13
- package/dist/hooks/useUser.js +4 -4
- package/dist/index.js +13 -13
- package/dist/{not-found-T2WYF64G.js → not-found-4R764WCJ.js} +16 -16
- package/dist/{not-found-T2WYF64G.js.map → not-found-4R764WCJ.js.map} +1 -1
- package/dist/providers/TwilightProvider.d.ts.map +1 -1
- package/dist/providers/index.js +13 -13
- package/dist/providers/twilight-init.d.ts.map +1 -1
- package/dist/routes/account/orders.js +4 -4
- package/dist/routes/account/wishlist/WishlistPage.d.ts.map +1 -1
- package/dist/routes/account.js +13 -13
- package/dist/routes/blog.js +8 -8
- package/dist/routes/brands.js +4 -4
- package/dist/routes/cart.js +21 -21
- package/dist/routes/home.js +18 -18
- package/dist/routes/loyalty.js +5 -5
- package/dist/routes/page.js +4 -4
- package/dist/routes/product-listing/ProductListPage.d.ts.map +1 -1
- package/dist/routes/product-listing/useAppliedFilters.d.ts.map +1 -1
- package/dist/routes/product-listing.js +21 -29
- package/dist/routes/product-listing.js.map +1 -1
- package/dist/routes/product.js +17 -17
- package/dist/routes/testimonials.js +1 -1
- package/dist/routes/thank-you/ThankYouPage.d.ts.map +1 -1
- package/dist/routes/thank-you.js +4 -4
- package/dist/skeleton.js +18 -18
- package/dist/tanstack.js +8 -8
- package/dist/utils/index.d.ts +1 -1
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +2 -2
- package/dist/utils/sdk-helpers.d.ts +36 -0
- package/dist/utils/sdk-helpers.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/PageSingle-VUNU2BG4.js.map +0 -1
- package/dist/SeoCartWidget-X5HTL62D.js.map +0 -1
- package/dist/TestimonialsPage-CKAYXFER.js.map +0 -1
- package/dist/ThankYouPage-ZTCFTEI7.js.map +0 -1
- package/dist/WishlistPage-LHIUUR4U.js.map +0 -1
- package/dist/chunk-GOPUP26T.js.map +0 -1
- package/dist/chunk-PWBMSGMU.js.map +0 -1
- package/dist/chunk-TFROBJP5.js +0 -14
- package/dist/chunk-UEQFXSTX.js.map +0 -1
- package/dist/chunk-VAW73MFZ.js.map +0 -1
- package/dist/chunk-WY4IYO3G.js +0 -25
- package/dist/chunk-WY4IYO3G.js.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { order } from './chunk-
|
|
1
|
+
import { order } from './chunk-TRZAQSHU.js';
|
|
2
2
|
import { buildHreflangAlternates } from './chunk-TZ3E5BN4.js';
|
|
3
3
|
import { unauthorized, orUnauthorized } from './chunk-SSPAMQRV.js';
|
|
4
4
|
import { RouteId } from './chunk-ZGHRSRDO.js';
|
|
5
|
-
import { getAuthToken } from './chunk-
|
|
5
|
+
import { getAuthToken } from './chunk-IKUDCH7Q.js';
|
|
6
6
|
import { getTwilightContext } from './chunk-N2S25NXP.js';
|
|
7
7
|
import { lazy } from 'react';
|
|
8
8
|
|
|
@@ -55,9 +55,9 @@ async function orderSingleLoader({
|
|
|
55
55
|
}
|
|
56
56
|
|
|
57
57
|
// src/routes/account/orders/index.tsx
|
|
58
|
-
var LazyOrdersPage = lazy(() => import('./OrdersPage-
|
|
58
|
+
var LazyOrdersPage = lazy(() => import('./OrdersPage-TW3VH6EN.js').then((m) => ({ default: m.OrdersPage })));
|
|
59
59
|
var LazyOrderSinglePage = lazy(
|
|
60
|
-
() => import('./OrderSinglePage-
|
|
60
|
+
() => import('./OrderSinglePage-43FJCEPN.js').then((m) => ({ default: m.OrderSinglePage }))
|
|
61
61
|
);
|
|
62
62
|
var OrdersPage = LazyOrdersPage;
|
|
63
63
|
var OrderSinglePage = LazyOrderSinglePage;
|
|
@@ -109,5 +109,5 @@ var OrderSingle = {
|
|
|
109
109
|
};
|
|
110
110
|
|
|
111
111
|
export { OrderSingle, OrderSinglePage, Orders, OrdersPage, orderSingleLoader, ordersLoader };
|
|
112
|
-
//# sourceMappingURL=chunk-
|
|
113
|
-
//# sourceMappingURL=chunk-
|
|
112
|
+
//# sourceMappingURL=chunk-J5DXKBVJ.js.map
|
|
113
|
+
//# sourceMappingURL=chunk-J5DXKBVJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/routes/account/orders/loader.ts","../src/routes/account/orders/index.tsx"],"names":[],"mappings":";;;;;;;;;AAQA,eAAsB,YAAA,CACpB,KACA,MAAA,EAI0B;AAC1B,EAAA,IAAI,CAAC,YAAA,EAAa,EAAG,MAAM,YA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AAA,IACjB,WAAA,EAAa,KAAK,IAAA,CAAK,WAAA;AAAA,IACvB,oBAAoB,uBAAA,CAAwB,GAAA,CAAI,QAAA,EAAU,GAAA,CAAI,SAAS,QAAQ;AAAA,GACjF;AAEA,EAAA,OAAO,IAAA;AACT;AAEO,IAAM,MAAA,GAAS;AAAA,EACpB,IAAI,OAAA,CAAQ,qBAAA;AAAA,EACZ,MAAA,EAAQ,sBAAA;AAAA,EACR,IAAA,EAAM,UAAA;AAAA,EACN,SAAA,EAAW;AACb;AACO,IAAM,WAAA,GAAc;AAAA,EACzB,IAAI,OAAA,CAAQ,sBAAA;AAAA,EACZ,MAAA,EAAQ,2BAAA;AAAA,EACR,IAAA,EAAM,eAAA;AAAA,EACN,SAAA,EAAW;AACb","file":"chunk-J5DXKBVJ.js","sourcesContent":["import { order } from '../../../api/order';\nimport { getTwilightContext } from '../../../twilight/context';\nimport { RouteId } from '../../../router/route-ids';\nimport { orUnauthorized, unauthorized } from '../../../providers/NavigationProvider';\nimport { getAuthToken } from '../../../api/client';\nimport type { OrdersPageProps, OrderSinglePageProps, OrdersQuery } from './types';\nimport type { IdParams } from '../../types';\n\nexport async function ordersLoader(\n ctx: { query?: OrdersQuery; with_items?: boolean | number },\n extend?: (\n data: OrdersPageProps,\n ctx: { params: Record<string, never> }\n ) => Promise<Record<string, unknown>> | Record<string, unknown>\n): Promise<OrdersPageProps> {\n if (!getAuthToken()) throw unauthorized();\n const query = ctx.query;\n const isPending = query?.status === 'pending';\n const response = await orUnauthorized(\n order.list({\n // Only decides the empty state; <salla-orders> applies its own review filter (`?tab=waiting`).\n status: query?.status,\n ...(ctx.with_items ? { with_items: ctx.with_items } : {}),\n })\n );\n const i18n = getTwilightContext().i18n;\n const pageData: OrdersPageProps = {\n page: {\n title: isPending ? i18n.t('common.titles.pending_orders') : i18n.t('common.titles.orders'),\n slug: RouteId.CUSTOMER_ORDERS_INDEX,\n },\n orders: response.data,\n cursor: response.cursor,\n query,\n };\n\n if (extend) {\n const extra = await extend(pageData, { params: {} });\n return { ...pageData, ...extra } as OrdersPageProps;\n }\n return pageData;\n}\n\nexport async function orderSingleLoader({\n params,\n}: {\n params: IdParams;\n}): Promise<OrderSinglePageProps> {\n if (!getAuthToken()) throw unauthorized();\n const [data, componentsOrder] = await Promise.all([\n order.findOrThrow(params.id),\n orUnauthorized(order.findForComponents(params.id)),\n ]);\n const i18n = getTwilightContext().i18n;\n return {\n page: {\n slug: RouteId.CUSTOMER_ORDERS_SINGLE,\n id: String(params.id),\n title: i18n\n .t('pages.orders.order_details')\n .replace(':id', String(data.order.reference_id ?? params.id)),\n },\n order: data.order,\n componentsOrder,\n };\n}\n","import type { HeadDescriptor } from '../../../utils/head';\nimport { buildHreflangAlternates } from '../../../utils/baseHead';\nimport { lazy } from 'react';\nimport { ordersLoader, orderSingleLoader } from './loader';\nimport type { OrdersPageProps, OrderSinglePageProps, OrdersSearchParams } from './types';\nimport type { IdParams } from '../../types';\nimport type { TwilightContext } from '../../../twilight/context';\nimport { RouteId } from '../../../router/route-ids';\n\n// Lazy-load components for code-splitting\nconst LazyOrdersPage = lazy(() => import('./OrdersPage').then((m) => ({ default: m.OrdersPage })));\nconst LazyOrderSinglePage = lazy(() =>\n import('./OrderSinglePage').then((m) => ({ default: m.OrderSinglePage }))\n);\n\nexport const OrdersPage = LazyOrdersPage;\nexport const OrderSinglePage = LazyOrderSinglePage;\nexport { ordersLoader, orderSingleLoader } from './loader';\nexport type {\n OrdersPageProps,\n OrderSinglePageProps,\n OrdersSearchParams,\n OrdersQuery,\n} from './types';\n\nasync function ordersLoaderWithExtend(\n ctx: { search?: OrdersSearchParams; locale?: string; with_items?: boolean | number },\n extend?: (\n data: OrdersPageProps,\n ctx: { params: Record<string, never> }\n ) => Promise<Record<string, unknown>> | Record<string, unknown>\n): Promise<OrdersPageProps> {\n const query = ctx.search;\n const data = await ordersLoader({ query, with_items: ctx.with_items }, extend);\n\n if (extend) {\n const extra = await extend(data, { params: {} });\n return { ...data, ...extra } as OrdersPageProps;\n }\n return data;\n}\n\nfunction ordersHead(ctx: TwilightContext, data: OrdersPageProps): HeadDescriptor {\n const isPending = ctx.location.search?.status === 'pending';\n const base: HeadDescriptor = {\n title: ctx.i18n.t(isPending ? 'common.titles.pending_orders' : 'common.titles.orders'),\n description: data.page.description,\n alternateLanguages: buildHreflangAlternates(ctx.settings, ctx.location.pathname),\n };\n\n return base;\n}\n\nasync function orderSingleLoaderWithExtend(\n ctx: { params: IdParams; locale?: string },\n extend?: (\n data: OrderSinglePageProps,\n ctx: { params: IdParams }\n ) => Promise<Record<string, unknown>> | Record<string, unknown>\n): Promise<OrderSinglePageProps> {\n const data = await orderSingleLoader({ params: ctx.params });\n\n if (extend) {\n const extra = await extend(data, ctx);\n return { ...data, ...extra } as OrderSinglePageProps;\n }\n return data;\n}\n\nfunction orderSingleHead(ctx: TwilightContext, data: OrderSinglePageProps): HeadDescriptor {\n const base: HeadDescriptor = {\n title: data.page.title,\n description: data.page.description,\n alternateLanguages: buildHreflangAlternates(ctx.settings, ctx.location.pathname),\n };\n\n return base;\n}\n\nexport const Orders = {\n id: RouteId.CUSTOMER_ORDERS_INDEX,\n loader: ordersLoaderWithExtend,\n head: ordersHead,\n Component: LazyOrdersPage,\n} as const;\nexport const OrderSingle = {\n id: RouteId.CUSTOMER_ORDERS_SINGLE,\n loader: orderSingleLoaderWithExtend,\n head: orderSingleHead,\n Component: LazyOrderSinglePage,\n} as const;\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { orThrow } from './chunk-SSPAMQRV.js';
|
|
2
|
-
import { getActiveScope, api } from './chunk-
|
|
2
|
+
import { getActiveScope, api } from './chunk-IKUDCH7Q.js';
|
|
3
3
|
import { getTwilightContext } from './chunk-N2S25NXP.js';
|
|
4
4
|
import { defaultShouldDehydrateQuery, queryOptions } from '@tanstack/react-query';
|
|
5
5
|
|
|
@@ -174,5 +174,5 @@ var product = {
|
|
|
174
174
|
};
|
|
175
175
|
|
|
176
176
|
export { getProductPreview, isProductPreviewQuery, product, productDetailQueryKey, productPreviewQueryKey, rememberProductPreview, shouldDehydrateQuery };
|
|
177
|
-
//# sourceMappingURL=chunk-
|
|
178
|
-
//# sourceMappingURL=chunk-
|
|
177
|
+
//# sourceMappingURL=chunk-K6SNUM3L.js.map
|
|
178
|
+
//# sourceMappingURL=chunk-K6SNUM3L.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/api/product.ts"],"names":["product"],"mappings":";;;;;AA+FA,SAAS,iBAAA,GAAoB;AAC3B,EAAA,IAAI;AACF,IAAA,MAAM,WAAA,GAAc,oBAAmB,CAAE,WAAA;AACzC,IAAA,OAAO,WAAA,IAAe,OAAO,WAAA,CAAY,YAAA,KAAiB,aAAa,WAAA,GAAc,IAAA;AAAA,EACvF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEO,SAAS,uBAAuB,EAAA,EAAY;AACjD,EAAA,OAAO,CAAC,UAAA,EAAY,SAAA,EAAW,MAAA,CAAO,EAAE,GAAG,EAAE,KAAA,EAAO,cAAA,EAAe,EAAG,CAAA;AACxE;AAEO,SAAS,sBAAsB,EAAA,EAAY;AAChD,EAAA,OAAO,CAAC,YAAY,QAAA,EAAU,EAAA,EAAI,EAAE,KAAA,EAAO,cAAA,IAAkB,CAAA;AAC/D;AAGO,SAAS,sBAAsB,KAAA,EAAkD;AACtF,EAAA,OAAO,KAAA,CAAM,SAAS,CAAC,CAAA,KAAM,cAAc,KAAA,CAAM,QAAA,CAAS,CAAC,CAAA,KAAM,SAAA;AACnE;AAMO,SAAS,qBACd,KAAA,EACS;AACT,EAAA,OACE,CAAC,sBAAsB,KAAK,CAAA,KAC3B,4BAA4B,KAAK,CAAA,IAAK,KAAA,CAAM,KAAA,CAAM,MAAA,KAAW,SAAA,CAAA;AAElE;AAOO,SAAS,uBAAuBA,QAAAA,EAAwB;AAC7D,EAAA,MAAM,cAAc,iBAAA,EAAkB;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AA,CAAK,EAAE,CAAA;AAAA;AAAA;AAAA,MAG9B,eAAA,EAAiB,MAAM,iBAAA,CAAkB,EAAE;AAAA,KAC5C,CAAA;AAAA,IACH,IAAA,EAAM,CAAC,MAAA,KACL,YAAA,CAAa;AAAA;AAAA,MAEX,QAAA,EAAU,CAAC,UAAA,EAAY,MAAA,EAAQ,QAAQ,EAAE,KAAA,EAAO,cAAA,EAAe,EAAG,CAAA;AAAA,MAClE,OAAA,EAAS,CAAC,EAAE,MAAA,EAAO,KAAM,OAAA,CAAQ,IAAA,CAAK,EAAE,GAAG,MAAA,EAAQ,MAAA,EAAQ;AAAA,KAC5D;AAAA;AAEP","file":"chunk-HDO37URJ.js","sourcesContent":["import { queryOptions, defaultShouldDehydrateQuery } from '@tanstack/react-query';\nimport { api, getActiveScope } from './client';\nimport type { Product } from '../types';\nimport type { Pagination, PaginatedResult } from './types';\nimport { orThrow } from '../providers/NavigationProvider';\nimport { getTwilightContext } from '../twilight/context';\nimport type { ActiveScope } from '../utils/cookies';\n\n// ===== Filter Types =====\n\nexport interface FilterValue {\n key?: string;\n count?: number;\n value?: string;\n from?: number | '*';\n to?: number | '*';\n}\n\nexport interface Filter {\n key?: string;\n label?: string;\n type?: string;\n values?: FilterValue[];\n max?: number;\n min?: number;\n}\n\n// ===== Product List Types =====\n\nexport type ProductsListSource =\n | 'brands'\n | 'categories'\n | 'json'\n | 'landing-page'\n | 'latest'\n | 'offers'\n | 'recently'\n | 'related'\n | 'selected'\n | 'tags'\n | 'top-rated'\n | 'wishlist'\n | 'search'\n | 'sales'\n | 'reorder'\n | 'best_selling';\n\nexport interface ProductsListParams {\n /** Source type (wishlist, latest, brands, etc.) */\n source: ProductsListSource;\n /**\n * The ids the source reads, as an array: category, brand, tag or product ids\n * (`sourceValue: [708738657]`). Sent as `source_value[]`.\n */\n sourceValue?: string | number | number[] | null;\n /** The search words when `source` is `'search'`. Sent as `keyword`; other sources ignore it. */\n keyword?: string;\n /** Page number for offset-based pagination */\n page?: number;\n /** Cursor for cursor-based pagination (from previous response) */\n cursor?: string | null;\n /** Items per page (default: 15) */\n perPage?: number;\n /** Sort option */\n sort?: string;\n /** Enable filters on the response */\n filterable?: boolean;\n /** Applied `<salla-filters>` selection (the `salla-filters::changed` payload). */\n filters?: ProductListFilters;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n}\n\n/** One `<salla-filters>` value: a scalar, a list, or a nested `{ sub-key: value }` (variants). */\nexport type ProductListFilterValue =\n string | number | Array<string | number> | { [key: string]: ProductListFilterValue };\n\n/** A `<salla-filters>` selection, i.e. the `salla-filters::changed` payload. */\nexport type ProductListFilters = Record<string, ProductListFilterValue>;\n\nexport type ProductsListResult = PaginatedResult<Product> & {\n filters?: Filter[];\n};\n\nexport interface ProductsListResponse {\n data: Product[];\n cursor?: Pagination;\n filters?: Filter[];\n}\n\n// ===== List-card preview cache =====\n// List payloads are a subset of details (one `image`, no `options` / `images[]`).\n// They live on a separate query key so they can paint a sheet/quick-view without\n// being treated as a successful `products/{id}/details` fetch.\n\nfunction queryClientOrNull() {\n try {\n const queryClient = getTwilightContext().queryClient;\n return queryClient && typeof queryClient.setQueryData === 'function' ? queryClient : null;\n } catch {\n return null;\n }\n}\n\nexport function productPreviewQueryKey(id: string) {\n return ['products', 'preview', String(id), { scope: getActiveScope() }] as const;\n}\n\nexport function productDetailQueryKey(id: string) {\n return ['products', 'detail', id, { scope: getActiveScope() }] as const;\n}\n\n/** True when this query is a list-card stand-in — skip it when dehydrating SSR. */\nexport function isProductPreviewQuery(query: { queryKey: readonly unknown[] }): boolean {\n return query.queryKey[0] === 'products' && query.queryKey[1] === 'preview';\n}\n\n/**\n * Default dehydrate policy (success) plus pending SSR-stream queries, minus\n * list-card stand-ins. Replacing the default wholesale would ship error states.\n */\nexport function shouldDehydrateQuery(\n query: Parameters<typeof defaultShouldDehydrateQuery>[0]\n): boolean {\n return (\n !isProductPreviewQuery(query) &&\n (defaultShouldDehydrateQuery(query) || query.state.status === 'pending')\n );\n}\n\n/**\n * Remember a list/card product so `product.queries.detail(id)` can use it as\n * `placeholderData` while details load. No-op if details for this id are already\n * cached. Themes that fetch products outside `product.list` should call this.\n */\nexport function rememberProductPreview(product: Product): void {\n const queryClient = queryClientOrNull();\n if (!queryClient || product?.id == null) return;\n const id = String(product.id);\n if (queryClient.getQueryState(productDetailQueryKey(id))?.status === 'success') return;\n queryClient.setQueryData(productPreviewQueryKey(id), product);\n}\n\nfunction scopeFromQueryKey(queryKey: readonly unknown[]): ActiveScope | null | undefined {\n const last = queryKey[queryKey.length - 1];\n if (last == null || typeof last !== 'object' || !('scope' in last)) return undefined;\n return (last as { scope: ActiveScope | null }).scope;\n}\n\nfunction isSameScope(a: ActiveScope | null | undefined, b: ActiveScope | null): boolean {\n if (a === undefined) return false;\n if (a === b) return true;\n if (a == null || b == null) return a == null && b == null;\n return (\n a.id === b.id &&\n a.type === b.type &&\n a.allocation_id === b.allocation_id &&\n a.allocation_type === b.allocation_type\n );\n}\n\nconst LIST_QUERY_PREFIXES = [\n ['products', 'list'],\n ['wishlist', 'list'],\n] as const;\n\n/**\n * Rebuild the scoped preview index from hydrated list/wishlist queries (SSR\n * dehydrate drops preview keys). Subsequent lookups hit `productPreviewQueryKey`.\n */\nfunction findProductInScopedLists(\n queryClient: NonNullable<ReturnType<typeof queryClientOrNull>>,\n id: string\n): Product | undefined {\n const scope = getActiveScope();\n let found: Product | undefined;\n for (const prefix of LIST_QUERY_PREFIXES) {\n for (const [queryKey, data] of queryClient.getQueriesData<ProductsListResult>({\n queryKey: prefix,\n })) {\n if (!isSameScope(scopeFromQueryKey(queryKey), scope)) continue;\n for (const item of data?.items ?? []) {\n if (item?.id == null) continue;\n rememberProductPreview(item);\n if (!found && String(item.id) === id) found = item;\n }\n }\n }\n return found;\n}\n\n/**\n * List-card product for `placeholderData`. Prefers the preview key; if that was\n * dropped on SSR dehydrate, rebuilds it from the current-scope list/wishlist.\n */\nexport function getProductPreview(id: string): Product | undefined {\n const queryClient = queryClientOrNull();\n if (!queryClient) return undefined;\n const key = String(id);\n return (\n queryClient.getQueryData(productPreviewQueryKey(key)) ??\n findProductInScopedLists(queryClient, key)\n );\n}\n\nfunction rememberProductPreviews(items: Product[]): void {\n for (const item of items) rememberProductPreview(item);\n}\n\n/**\n * Search sends its words as `keyword` (a `sourceValue` string is still read there, as before);\n * every other source sends its ids as `source_value[]`, which the API requires as an array.\n */\nfunction appendSourceParams(\n searchParams: URLSearchParams,\n { source, sourceValue, keyword }: Pick<ProductsListParams, 'source' | 'sourceValue' | 'keyword'>\n): void {\n if (source === 'search') {\n const words = keyword ?? sourceValue;\n if (words !== undefined) searchParams.set('keyword', String(words));\n } else if (Array.isArray(sourceValue)) {\n sourceValue.forEach((val) => searchParams.append('source_value[]', String(val)));\n } else if (sourceValue !== undefined) {\n searchParams.append('source_value[]', String(sourceValue));\n }\n}\n\n/**\n * Sends an applied filter selection the way the SDK's `<salla-products-list>` does:\n * `filters[key]=v`, `filters[key][]=v` or `filters[key][sub]=v`.\n */\nfunction appendFilterParams(\n searchParams: URLSearchParams,\n filters?: Record<string, ProductListFilterValue>,\n parentKey = 'filters'\n): void {\n if (!filters) return;\n for (const [key, value] of Object.entries(filters)) {\n const fullKey = `${parentKey}[${key}]`;\n if (Array.isArray(value)) {\n value.forEach((item) => searchParams.append(`${fullKey}[]`, String(item)));\n } else if (value !== null && typeof value === 'object') {\n appendFilterParams(searchParams, value, fullKey);\n } else if (value !== undefined && value !== null) {\n searchParams.append(fullKey, String(value));\n }\n }\n}\n\n/** A `category_id` filter replaces the page's category as the list source (as in the SDK). */\nfunction categoryFilterIds(filters?: ProductListFilters): number[] | null {\n const raw = filters?.category_id;\n if (raw === undefined || raw === null) return null;\n const ids = Array.isArray(raw) ? raw : typeof raw === 'object' ? Object.values(raw) : [raw];\n return ids.map(Number);\n}\n\n// ===== API Functions =====\n\nexport const product = {\n find: async (id: string): Promise<Product> => {\n const endpoint = `products/${id}/details?with[]=images&with[]=category&with[]=rating&with[]=notify_availability&with[]=tags&with[]=brand&with[]=options&with[]=skus&with[]=skus_availability&with[]=included_products&with[]=bundle&with[]=sold_quantity`;\n const { data } = await api.get(endpoint).json<{ data: Product }>();\n return data;\n },\n\n findOrThrow: (id: string): Promise<Product> => orThrow(product.find(id)),\n\n /**\n * Fetch products list with pagination support\n * Used by native ProductsList component for SSR loaders\n *\n * API pattern: GET /products?source=wishlist&page=1\n */\n list: async (params: ProductsListParams): Promise<ProductsListResult> => {\n const {\n source,\n sourceValue,\n keyword,\n page,\n cursor,\n perPage = 16,\n sort,\n filterable,\n filters,\n signal,\n } = params;\n\n // Build URL with query parameters\n const searchParams = new URLSearchParams();\n searchParams.set('source', source);\n // Only send page when explicitly provided — cursor-based callers omit it entirely\n if (page !== undefined) searchParams.set('page', String(page));\n searchParams.set('per_page', String(perPage));\n\n appendSourceParams(searchParams, {\n source,\n sourceValue: (source === 'categories' && categoryFilterIds(filters)) || sourceValue,\n keyword,\n });\n appendFilterParams(searchParams, filters);\n\n // Add filterable parameter\n if (filterable !== undefined) {\n searchParams.set('filterable', filterable ? '1' : '0');\n }\n\n // Add sort parameter\n if (sort) {\n searchParams.set('sort', sort);\n }\n\n // Add cursor for cursor-based pagination\n if (cursor) {\n searchParams.set('cursor', cursor);\n }\n\n // Make the request\n const options: Record<string, unknown> = {};\n if (signal) options.signal = signal;\n\n const response = await api\n .get(`products?${searchParams.toString()}`, options as any)\n .json<ProductsListResponse>();\n\n const items = response.data ?? [];\n rememberProductPreviews(items);\n\n return {\n items,\n next: response.cursor?.next ?? null,\n filters: response.filters,\n };\n },\n\n queries: {\n detail: (id: string) =>\n queryOptions({\n // Stock and availability are resolved per branch allocation — same as the list.\n queryKey: productDetailQueryKey(id),\n queryFn: () => product.find(id),\n // List-card product, if one was remembered. Not written as the detail\n // cache entry — `queryFn` still hits products/{id}/details.\n placeholderData: () => getProductPreview(id),\n }),\n list: (params: Omit<ProductsListParams, 'signal'>) =>\n queryOptions({\n // Scope (branch) varies product availability — key must include it.\n queryKey: ['products', 'list', params, { scope: getActiveScope() }],\n queryFn: ({ signal }) => product.list({ ...params, signal }),\n }),\n },\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/api/product.ts"],"names":["product"],"mappings":";;;;;AA+FA,SAAS,iBAAA,GAAoB;AAC3B,EAAA,IAAI;AACF,IAAA,MAAM,WAAA,GAAc,oBAAmB,CAAE,WAAA;AACzC,IAAA,OAAO,WAAA,IAAe,OAAO,WAAA,CAAY,YAAA,KAAiB,aAAa,WAAA,GAAc,IAAA;AAAA,EACvF,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF;AAEO,SAAS,uBAAuB,EAAA,EAAY;AACjD,EAAA,OAAO,CAAC,UAAA,EAAY,SAAA,EAAW,MAAA,CAAO,EAAE,GAAG,EAAE,KAAA,EAAO,cAAA,EAAe,EAAG,CAAA;AACxE;AAEO,SAAS,sBAAsB,EAAA,EAAY;AAChD,EAAA,OAAO,CAAC,YAAY,QAAA,EAAU,EAAA,EAAI,EAAE,KAAA,EAAO,cAAA,IAAkB,CAAA;AAC/D;AAGO,SAAS,sBAAsB,KAAA,EAAkD;AACtF,EAAA,OAAO,KAAA,CAAM,SAAS,CAAC,CAAA,KAAM,cAAc,KAAA,CAAM,QAAA,CAAS,CAAC,CAAA,KAAM,SAAA;AACnE;AAMO,SAAS,qBACd,KAAA,EACS;AACT,EAAA,OACE,CAAC,sBAAsB,KAAK,CAAA,KAC3B,4BAA4B,KAAK,CAAA,IAAK,KAAA,CAAM,KAAA,CAAM,MAAA,KAAW,SAAA,CAAA;AAElE;AAOO,SAAS,uBAAuBA,QAAAA,EAAwB;AAC7D,EAAA,MAAM,cAAc,iBAAA,EAAkB;AACtC,EAAA,IAAI,CAAC,WAAA,IAAeA,QAAAA,EAAS,EAAA,IAAM,IAAA,EAAM;AACzC,EAAA,MAAM,EAAA,GAAK,MAAA,CAAOA,QAAAA,CAAQ,EAAE,CAAA;AAC5B,EAAA,IAAI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;AAAA,MAEX,QAAA,EAAU,CAAC,UAAA,EAAY,MAAA,EAAQ,QAAQ,EAAE,KAAA,EAAO,cAAA,EAAe,EAAG,CAAA;AAAA,MAClE,OAAA,EAAS,CAAC,EAAE,MAAA,EAAO,KAAM,OAAA,CAAQ,IAAA,CAAK,EAAE,GAAG,MAAA,EAAQ,MAAA,EAAQ;AAAA,KAC5D;AAAA;AAEP","file":"chunk-K6SNUM3L.js","sourcesContent":["import { queryOptions, defaultShouldDehydrateQuery } from '@tanstack/react-query';\nimport { api, getActiveScope } from './client';\nimport type { Product } from '../types';\nimport type { Pagination, PaginatedResult } from './types';\nimport { orThrow } from '../providers/NavigationProvider';\nimport { getTwilightContext } from '../twilight/context';\nimport type { ActiveScope } from '../utils/cookies';\n\n// ===== Filter Types =====\n\nexport interface FilterValue {\n key?: string;\n count?: number;\n value?: string;\n from?: number | '*';\n to?: number | '*';\n}\n\nexport interface Filter {\n key?: string;\n label?: string;\n type?: string;\n values?: FilterValue[];\n max?: number;\n min?: number;\n}\n\n// ===== Product List Types =====\n\nexport type ProductsListSource =\n | 'brands'\n | 'categories'\n | 'json'\n | 'landing-page'\n | 'latest'\n | 'offers'\n | 'recently'\n | 'related'\n | 'selected'\n | 'tags'\n | 'top-rated'\n | 'wishlist'\n | 'search'\n | 'sales'\n | 'reorder'\n | 'best_selling';\n\nexport interface ProductsListParams {\n /** Source type (wishlist, latest, brands, etc.) */\n source: ProductsListSource;\n /**\n * The ids the source reads, as an array: category, brand, tag or product ids\n * (`sourceValue: [708738657]`). Sent as `source_value[]`.\n */\n sourceValue?: string | number | number[] | null;\n /** The search words when `source` is `'search'`. Sent as `keyword`; other sources ignore it. */\n keyword?: string;\n /** Page number for offset-based pagination */\n page?: number;\n /** Cursor for cursor-based pagination (from previous response) */\n cursor?: string | null;\n /** Items per page (default: 15) */\n perPage?: number;\n /** Sort option */\n sort?: string;\n /** Enable filters on the response */\n filterable?: boolean;\n /** Applied `<salla-filters>` selection (the `salla-filters::changed` payload). */\n filters?: ProductListFilters;\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n}\n\n/** One `<salla-filters>` value: a scalar, a list, or a nested `{ sub-key: value }` (variants). */\nexport type ProductListFilterValue =\n string | number | Array<string | number> | { [key: string]: ProductListFilterValue };\n\n/** A `<salla-filters>` selection, i.e. the `salla-filters::changed` payload. */\nexport type ProductListFilters = Record<string, ProductListFilterValue>;\n\nexport type ProductsListResult = PaginatedResult<Product> & {\n filters?: Filter[];\n};\n\nexport interface ProductsListResponse {\n data: Product[];\n cursor?: Pagination;\n filters?: Filter[];\n}\n\n// ===== List-card preview cache =====\n// List payloads are a subset of details (one `image`, no `options` / `images[]`).\n// They live on a separate query key so they can paint a sheet/quick-view without\n// being treated as a successful `products/{id}/details` fetch.\n\nfunction queryClientOrNull() {\n try {\n const queryClient = getTwilightContext().queryClient;\n return queryClient && typeof queryClient.setQueryData === 'function' ? queryClient : null;\n } catch {\n return null;\n }\n}\n\nexport function productPreviewQueryKey(id: string) {\n return ['products', 'preview', String(id), { scope: getActiveScope() }] as const;\n}\n\nexport function productDetailQueryKey(id: string) {\n return ['products', 'detail', id, { scope: getActiveScope() }] as const;\n}\n\n/** True when this query is a list-card stand-in — skip it when dehydrating SSR. */\nexport function isProductPreviewQuery(query: { queryKey: readonly unknown[] }): boolean {\n return query.queryKey[0] === 'products' && query.queryKey[1] === 'preview';\n}\n\n/**\n * Default dehydrate policy (success) plus pending SSR-stream queries, minus\n * list-card stand-ins. Replacing the default wholesale would ship error states.\n */\nexport function shouldDehydrateQuery(\n query: Parameters<typeof defaultShouldDehydrateQuery>[0]\n): boolean {\n return (\n !isProductPreviewQuery(query) &&\n (defaultShouldDehydrateQuery(query) || query.state.status === 'pending')\n );\n}\n\n/**\n * Remember a list/card product so `product.queries.detail(id)` can use it as\n * `placeholderData` while details load. No-op if details for this id are already\n * cached. Themes that fetch products outside `product.list` should call this.\n */\nexport function rememberProductPreview(product: Product): void {\n const queryClient = queryClientOrNull();\n if (!queryClient || product?.id == null) return;\n const id = String(product.id);\n if (queryClient.getQueryState(productDetailQueryKey(id))?.status === 'success') return;\n queryClient.setQueryData(productPreviewQueryKey(id), product);\n}\n\nfunction scopeFromQueryKey(queryKey: readonly unknown[]): ActiveScope | null | undefined {\n const last = queryKey[queryKey.length - 1];\n if (last == null || typeof last !== 'object' || !('scope' in last)) return undefined;\n return (last as { scope: ActiveScope | null }).scope;\n}\n\nfunction isSameScope(a: ActiveScope | null | undefined, b: ActiveScope | null): boolean {\n if (a === undefined) return false;\n if (a === b) return true;\n if (a == null || b == null) return a == null && b == null;\n return (\n a.id === b.id &&\n a.type === b.type &&\n a.allocation_id === b.allocation_id &&\n a.allocation_type === b.allocation_type\n );\n}\n\nconst LIST_QUERY_PREFIXES = [\n ['products', 'list'],\n ['wishlist', 'list'],\n] as const;\n\n/**\n * Rebuild the scoped preview index from hydrated list/wishlist queries (SSR\n * dehydrate drops preview keys). Subsequent lookups hit `productPreviewQueryKey`.\n */\nfunction findProductInScopedLists(\n queryClient: NonNullable<ReturnType<typeof queryClientOrNull>>,\n id: string\n): Product | undefined {\n const scope = getActiveScope();\n let found: Product | undefined;\n for (const prefix of LIST_QUERY_PREFIXES) {\n for (const [queryKey, data] of queryClient.getQueriesData<ProductsListResult>({\n queryKey: prefix,\n })) {\n if (!isSameScope(scopeFromQueryKey(queryKey), scope)) continue;\n for (const item of data?.items ?? []) {\n if (item?.id == null) continue;\n rememberProductPreview(item);\n if (!found && String(item.id) === id) found = item;\n }\n }\n }\n return found;\n}\n\n/**\n * List-card product for `placeholderData`. Prefers the preview key; if that was\n * dropped on SSR dehydrate, rebuilds it from the current-scope list/wishlist.\n */\nexport function getProductPreview(id: string): Product | undefined {\n const queryClient = queryClientOrNull();\n if (!queryClient) return undefined;\n const key = String(id);\n return (\n queryClient.getQueryData(productPreviewQueryKey(key)) ??\n findProductInScopedLists(queryClient, key)\n );\n}\n\nfunction rememberProductPreviews(items: Product[]): void {\n for (const item of items) rememberProductPreview(item);\n}\n\n/**\n * Search sends its words as `keyword` (a `sourceValue` string is still read there, as before);\n * every other source sends its ids as `source_value[]`, which the API requires as an array.\n */\nfunction appendSourceParams(\n searchParams: URLSearchParams,\n { source, sourceValue, keyword }: Pick<ProductsListParams, 'source' | 'sourceValue' | 'keyword'>\n): void {\n if (source === 'search') {\n const words = keyword ?? sourceValue;\n if (words !== undefined) searchParams.set('keyword', String(words));\n } else if (Array.isArray(sourceValue)) {\n sourceValue.forEach((val) => searchParams.append('source_value[]', String(val)));\n } else if (sourceValue !== undefined) {\n searchParams.append('source_value[]', String(sourceValue));\n }\n}\n\n/**\n * Sends an applied filter selection the way the SDK's `<salla-products-list>` does:\n * `filters[key]=v`, `filters[key][]=v` or `filters[key][sub]=v`.\n */\nfunction appendFilterParams(\n searchParams: URLSearchParams,\n filters?: Record<string, ProductListFilterValue>,\n parentKey = 'filters'\n): void {\n if (!filters) return;\n for (const [key, value] of Object.entries(filters)) {\n const fullKey = `${parentKey}[${key}]`;\n if (Array.isArray(value)) {\n value.forEach((item) => searchParams.append(`${fullKey}[]`, String(item)));\n } else if (value !== null && typeof value === 'object') {\n appendFilterParams(searchParams, value, fullKey);\n } else if (value !== undefined && value !== null) {\n searchParams.append(fullKey, String(value));\n }\n }\n}\n\n/** A `category_id` filter replaces the page's category as the list source (as in the SDK). */\nfunction categoryFilterIds(filters?: ProductListFilters): number[] | null {\n const raw = filters?.category_id;\n if (raw === undefined || raw === null) return null;\n const ids = Array.isArray(raw) ? raw : typeof raw === 'object' ? Object.values(raw) : [raw];\n return ids.map(Number);\n}\n\n// ===== API Functions =====\n\nexport const product = {\n find: async (id: string): Promise<Product> => {\n const endpoint = `products/${id}/details?with[]=images&with[]=category&with[]=rating&with[]=notify_availability&with[]=tags&with[]=brand&with[]=options&with[]=skus&with[]=skus_availability&with[]=included_products&with[]=bundle&with[]=sold_quantity`;\n const { data } = await api.get(endpoint).json<{ data: Product }>();\n return data;\n },\n\n findOrThrow: (id: string): Promise<Product> => orThrow(product.find(id)),\n\n /**\n * Fetch products list with pagination support\n * Used by native ProductsList component for SSR loaders\n *\n * API pattern: GET /products?source=wishlist&page=1\n */\n list: async (params: ProductsListParams): Promise<ProductsListResult> => {\n const {\n source,\n sourceValue,\n keyword,\n page,\n cursor,\n perPage = 16,\n sort,\n filterable,\n filters,\n signal,\n } = params;\n\n // Build URL with query parameters\n const searchParams = new URLSearchParams();\n searchParams.set('source', source);\n // Only send page when explicitly provided — cursor-based callers omit it entirely\n if (page !== undefined) searchParams.set('page', String(page));\n searchParams.set('per_page', String(perPage));\n\n appendSourceParams(searchParams, {\n source,\n sourceValue: (source === 'categories' && categoryFilterIds(filters)) || sourceValue,\n keyword,\n });\n appendFilterParams(searchParams, filters);\n\n // Add filterable parameter\n if (filterable !== undefined) {\n searchParams.set('filterable', filterable ? '1' : '0');\n }\n\n // Add sort parameter\n if (sort) {\n searchParams.set('sort', sort);\n }\n\n // Add cursor for cursor-based pagination\n if (cursor) {\n searchParams.set('cursor', cursor);\n }\n\n // Make the request\n const options: Record<string, unknown> = {};\n if (signal) options.signal = signal;\n\n const response = await api\n .get(`products?${searchParams.toString()}`, options as any)\n .json<ProductsListResponse>();\n\n const items = response.data ?? [];\n rememberProductPreviews(items);\n\n return {\n items,\n next: response.cursor?.next ?? null,\n filters: response.filters,\n };\n },\n\n queries: {\n detail: (id: string) =>\n queryOptions({\n // Stock and availability are resolved per branch allocation — same as the list.\n queryKey: productDetailQueryKey(id),\n queryFn: () => product.find(id),\n // List-card product, if one was remembered. Not written as the detail\n // cache entry — `queryFn` still hits products/{id}/details.\n placeholderData: () => getProductPreview(id),\n }),\n list: (params: Omit<ProductsListParams, 'signal'>) =>\n queryOptions({\n // Scope (branch) varies product availability — key must include it.\n queryKey: ['products', 'list', params, { scope: getActiveScope() }],\n queryFn: ({ signal }) => product.list({ ...params, signal }),\n }),\n },\n};\n"]}
|
|
@@ -2,15 +2,15 @@ import { ErrorPage } from './chunk-Z4Y55HWX.js';
|
|
|
2
2
|
import { ensureTwilightContextFromMatches, tanstackHeadAdapter } from './chunk-BE3JDKE2.js';
|
|
3
3
|
import { dispatchRouteChanged } from './chunk-5ZR2HKZ7.js';
|
|
4
4
|
import { resolveHead, mergeHead, setHeadAdapter } from './chunk-GD26FI4J.js';
|
|
5
|
-
import { store } from './chunk-
|
|
6
|
-
import { translations } from './chunk-
|
|
5
|
+
import { store } from './chunk-NTIGQYSN.js';
|
|
6
|
+
import { translations } from './chunk-L2DRHH4E.js';
|
|
7
7
|
import { buildBaseHead } from './chunk-TZ3E5BN4.js';
|
|
8
|
-
import { shouldDehydrateQuery } from './chunk-
|
|
9
|
-
import { apps } from './chunk-
|
|
8
|
+
import { shouldDehydrateQuery } from './chunk-K6SNUM3L.js';
|
|
9
|
+
import { apps } from './chunk-ETPOZJHG.js';
|
|
10
10
|
import { renderThemeHookSlotsScript, renderAppScopeInstallScript } from './chunk-2XGQSJKH.js';
|
|
11
11
|
import { RedirectError, NotFoundError, UnauthorizedError } from './chunk-SSPAMQRV.js';
|
|
12
12
|
import { RouteId } from './chunk-ZGHRSRDO.js';
|
|
13
|
-
import { syncSdkLocale } from './chunk-
|
|
13
|
+
import { syncSdkLocale } from './chunk-5Y64476S.js';
|
|
14
14
|
import { renderRuntimeEnvScript, escapeForInlineScript, resolveStoreBase, readEnv, resolveStoreBaseRedirect } from './chunk-TYLKNVQA.js';
|
|
15
15
|
import { AUTH_TOKEN_COOKIE_NAME, syncScopeCookie, extractTokenFromCookies, prefixStoreBase, stripStoreBase } from './chunk-SR4OTLTJ.js';
|
|
16
16
|
import { getTwilightContext, SettingsError, updateTwilightContext, createI18nInstance, messagesForLocale } from './chunk-N2S25NXP.js';
|
|
@@ -118,7 +118,7 @@ async function rootBeforeLoad(ctx) {
|
|
|
118
118
|
existingToken = null;
|
|
119
119
|
}
|
|
120
120
|
const cookieToken = typeof document !== "undefined" ? extractTokenFromCookies(document.cookie, AUTH_TOKEN_COOKIE_NAME) : null;
|
|
121
|
-
const sallaToken = typeof window !== "undefined" &&
|
|
121
|
+
const sallaToken = typeof window !== "undefined" && typeof window.salla?.storage?.get === "function" ? window.salla.storage.get(AUTH_TOKEN_COOKIE_NAME) : null;
|
|
122
122
|
const serverCookieToken = readServerCookieToken();
|
|
123
123
|
const authToken = ctx.serverContext?.authToken ?? serverCookieToken ?? existingToken ?? cookieToken ?? sallaToken ?? null;
|
|
124
124
|
updateTwilightContext({
|
|
@@ -466,7 +466,7 @@ function resolveRouteId(tanstackId) {
|
|
|
466
466
|
return TANSTACK_ROUTE_ID_MAP[tanstackId] ?? tanstackId;
|
|
467
467
|
}
|
|
468
468
|
var LazyNotFoundPage = lazy(
|
|
469
|
-
() => import('./not-found-
|
|
469
|
+
() => import('./not-found-4R764WCJ.js').then((m) => ({ default: m.NotFoundPage }))
|
|
470
470
|
);
|
|
471
471
|
function StoreUnavailablePage() {
|
|
472
472
|
return /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsx(
|
|
@@ -801,5 +801,5 @@ function tanstackDocumentAdapter(descriptor) {
|
|
|
801
801
|
}
|
|
802
802
|
|
|
803
803
|
export { RouteDocumentSync, TanStackDocumentSync, createRouter, createTwilightRootRoute, rootHead, tanstackDocumentAdapter, useTanstackDocumentAttrs };
|
|
804
|
-
//# sourceMappingURL=chunk-
|
|
805
|
-
//# sourceMappingURL=chunk-
|
|
804
|
+
//# sourceMappingURL=chunk-KCCU3S5F.js.map
|
|
805
|
+
//# sourceMappingURL=chunk-KCCU3S5F.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tanstack/search.ts","../src/routes/root/beforeLoad.ts","../src/routes/root/head.ts","../src/tanstack/store-base.ts","../src/tanstack/router.tsx","../src/tanstack/document-class.ts"],"names":["store","createTanStackRouter"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAM,MAAA,GAAS,CAAC,CAAC,GAAA,EAAK,KAAK,CAAA,KAAyB,GAAA,CAAI,QAAA,CA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,EAAW,YAAA,CAAa,iBAAA,CAAkB,eAAe,CAAC;AAAA,GAC5D;AACF;AAKO,SAAS,wBAAwB,UAAA,EAGtC;AACA,EAAA,OAAO;AAAA,IACL,SAAA,EAAW,aAAa,iBAAA,CAAkB,CAAC,WAAW,IAAA,IAAQ,EAAE,CAAC,CAAC,CAAA;AAAA,IAClE,SAAA,EAAW,aAAa,iBAAA,CAAkB,CAAC,WAAW,IAAA,IAAQ,EAAE,CAAC,CAAC;AAAA,GACpE;AACF","file":"chunk-KCCU3S5F.js","sourcesContent":["import { defaultStringifySearch } from '@tanstack/react-router';\n\nconst isList = ([key, value]: [string, unknown]) => key.endsWith('[]') && Array.isArray(value);\n\n/** The router's query serialiser, writing `[]` keys back as repeated keys, as `<salla-filters>` does. */\nexport function stringifySearch(search: Record<string, unknown>): string {\n const entries = Object.entries(search);\n const lists = entries.filter(isList) as [string, unknown[]][];\n if (!lists.length) return defaultStringifySearch(search);\n\n const rest = defaultStringifySearch(\n Object.fromEntries(entries.filter((entry) => !isList(entry)))\n );\n const repeated = lists.flatMap(([key, values]) =>\n values.map(\n (value) =>\n `${encodeURIComponent(key)}=${encodeURIComponent(typeof value === 'string' ? value : JSON.stringify(value))}`\n )\n );\n return `${rest || '?'}${rest ? '&' : ''}${repeated.join('&')}`;\n}\n","import type { QueryClient } from '@tanstack/react-query';\nimport { redirect } from '@tanstack/react-router';\nimport { createIsomorphicFn } from '@tanstack/react-start';\nimport { getCookie } from '@tanstack/react-start/server';\nimport type { StoreContext } from '../../api/store';\nimport { store as storeApi } from '../../api/store';\nimport { apps, type AppSnippet, type AppSettings } from '../../api/apps';\nimport { translations } from '../../api/translations';\nimport { FALLBACK_LOCALE, getLanguageInfo } from '../../providers/locale-constants';\nimport { createI18nInstance } from '../../providers/i18n-factory';\nimport type { TwilightLocation } from '../../twilight/context';\nimport { getTwilightContext, updateTwilightContext } from '../../twilight/context';\nimport {\n AUTH_TOKEN_COOKIE_NAME,\n extractTokenFromCookies,\n syncScopeCookie,\n} from '../../utils/cookies';\nimport { syncSdkLocale } from '../../utils/sdk-helpers';\nimport { SettingsError } from '../../utils/errors';\nimport { resolveStoreBaseRedirect } from '../../utils/store-identity';\n\n// Reads the `token` cookie from the incoming request on the SERVER. twilightMiddleware\n// extracts the same cookie into a custom ALS, but that ALS does NOT propagate to the\n// route's beforeLoad / React SSR render (they run in a different async scope), so the\n// token must be read again here from the framework's own request context. On the client\n// this is a no-op (the cookie is read from document.cookie below instead). The server\n// import is stripped from the client bundle by createIsomorphicFn.\nconst readServerCookieToken = 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 => null);\n\nexport interface BeforeLoadResult {\n settings: StoreContext;\n locale: string;\n dir: 'ltr' | 'rtl';\n authToken: string | null;\n /** Installed apps' snippets, threaded through the beforeLoad context (and recovered on the\n * client via ensureTwilightContextFromMatches) so AppsSnippets can render CDN tags in SSR. */\n appsSnippets?: AppSnippet[];\n /** Per-app public `app.*` buckets, threaded the same way so rootHead can install the\n * `Salla.appScope` factory inline in the SSR head. */\n appsSettings?: AppSettings;\n}\n\n/**\n * The platform's copy for `locale`, with this merchant's own wording over it.\n *\n * Returns the platform's copy untouched — and makes no request — unless the\n * settings say this language has overrides. That gate is the whole reason this\n * is affordable: the object 404s for most stores, uncached, on the critical\n * path of an SSR render.\n *\n * The entry is found by ISO code rather than by index or key. The API sends\n * `languages` as an object keyed by **upper-case** ISO, and `storeApi` converts\n * it to an array on the way through (`languagesToArray`), so neither the\n * upper-case key nor a position is available here — and matching case-sensitively\n * on `code` would be a lookup that misses silently, leaving the flag absent and\n * the feature simply never running.\n *\n * Nothing about this is fatal. A failed override read leaves the platform's\n * copy in place, which is a storefront in the words Salla ships rather than a\n * storefront that did not render.\n */\nasync function withMerchantTranslations(\n queryClient: QueryClient,\n settings: StoreContext,\n locale: string,\n common: Awaited<ReturnType<typeof translations.get>>\n): Promise<Awaited<ReturnType<typeof translations.get>>> {\n const wanted = locale.toLowerCase();\n const language = settings.languages?.find(\n (entry) => (entry.iso_code ?? entry.code)?.toLowerCase() === wanted\n );\n const storeId = settings.store?.id;\n\n if (!language?.has_custom_translations || !storeId) return common;\n\n try {\n const overrides = await queryClient.ensureQueryData(\n translations.queries.byStore(storeId, locale)\n );\n\n return translations.merge(common, overrides, locale);\n } catch (error) {\n console.warn('[salla] merchant translations could not be read; using the platform copy', error);\n return common;\n }\n}\n\nexport async function rootBeforeLoad(ctx: {\n params: Record<string, string>;\n location: TwilightLocation;\n context: {\n queryClient: QueryClient;\n setLocation?: (location: Partial<TwilightLocation>) => void;\n };\n serverContext?: {\n authToken?: string | null;\n };\n}): Promise<BeforeLoadResult> {\n const locale = ctx.params.locale || FALLBACK_LOCALE;\n const { dir } = getLanguageInfo(locale);\n\n if (ctx.context.setLocation) {\n ctx.context.setLocation(ctx.location);\n }\n\n // Set locale in context before any API calls so interceptor uses correct locale\n updateTwilightContext({ locale });\n\n // Re-assert the locale on the Salla SDK on every navigation. The SDK's axios\n // accept-language header drifts off the route locale (navigator.language default,\n // account-language override on profile fetch — see syncSdkLocale), which makes\n // SDK API calls (e.g. the cart's salla.api.cart.details) return wrong-locale data.\n syncSdkLocale(locale);\n\n // Mirror the SDK's selected branch into the `scope` cookie. The SDK persists the\n // selection in localStorage ONLY, so the server — which can only see cookies —\n // would otherwise compute scope=null for every visitor who picked a branch, and\n // the dehydrated settings query (keyed on the scope) would never match on the\n // client. No-op on the server and while the SDK storage API is still hydrating.\n syncScopeCookie();\n\n const [settingsResult, translationsResult, snippetsResult, appSettingsResult] = await Promise.all(\n [\n ctx.context.queryClient.ensureQueryData(storeApi.queries.settings()),\n ctx.context.queryClient.ensureQueryData(translations.queries.byLocale(locale)),\n // Snippets → SSR CDN <script> tags (AppsSnippets.ssrCdnScripts). Non-fatal + logged:\n // on failure AppsSnippets falls back to its own client-side query for the same data,\n // so the tags render a paint later instead of being lost for the page load.\n ctx.context.queryClient.ensureQueryData(apps.queries.snippets()).catch((error): undefined => {\n console.warn('[salla] apps/snippets prefetch failed; rendering no CDN snippet tags', error);\n return undefined;\n }),\n // Buckets → rootHead installs `Salla.appScope` inline in the SSR head (before any snippet\n // onReady runs). Non-fatal + logged: the head installs the factory either way, and the\n // client query seeds the buckets into that install once it resolves.\n ctx.context.queryClient.ensureQueryData(apps.queries.settings()).catch((error): undefined => {\n console.warn(\n '[salla] apps/snippets/settings prefetch failed; appScope buckets unseeded',\n error\n );\n return undefined;\n }),\n ]\n );\n\n if (!settingsResult) {\n throw new SettingsError('Failed to load store settings. Make sure VITE_STORE_DOMAIN is set.');\n }\n\n // On a host where the store is the root of every URL, a page has one address:\n // `/<username>/…`. A request that found its store some other way (`?storeId=`,\n // the preview cookie, `VITE_STORE_DOMAIN`) is sent there now that the settings\n // say what the username is. A full load rather than a client navigation, because\n // the router handling this request was built without that root.\n const storeBaseHref = resolveStoreBaseRedirect(settingsResult.store?.username, ctx.location.href);\n if (storeBaseHref) {\n throw redirect({ href: storeBaseHref, reloadDocument: true, replace: true });\n }\n\n // The merchant's own wording, laid over the platform's — but only when the\n // settings say this language has any.\n //\n // Sequenced after the `Promise.all` on purpose: the object is keyed by\n // `settings.store.id`, which the settings query is what produces, so this\n // cannot join the batch above. The cost of a second round trip is why it is\n // gated rather than always fetched — see `api/translations.ts` for the two\n // corrections that shape led to.\n const messages = await withMerchantTranslations(\n ctx.context.queryClient,\n settingsResult,\n locale,\n translationsResult\n );\n\n // Create i18n instance with loaded translations\n const i18n = createI18nInstance(locale, messages ?? undefined);\n\n // Resolve authToken with fallback chain:\n // 1. SSR context (from middleware extracting cookies on server)\n // 2. The twilight context token. On the SERVER this is the token twilightMiddleware\n // extracted from the `token` cookie into the request ALS — reading it here is\n // essential, otherwise this loader's updateTwilightContext() below would\n // overwrite the middleware's token with null and every SSR render (e.g. the\n // account hub) would be unauthenticated. On the CLIENT it's the clientStore\n // token from hydration or a previous navigation.\n // 3. The `token` cookie read directly — client fallback when clientStore is empty\n // and salla.storage hasn't hydrated yet.\n // 4. Salla SDK storage (salla.storage.get('token'))\n let existingToken: string | null = null;\n try {\n existingToken = getTwilightContext().authToken;\n } catch {\n // No request context (e.g. server call outside the middleware ALS) — fall through.\n existingToken = null;\n }\n const cookieToken =\n typeof document !== 'undefined'\n ? extractTokenFromCookies(document.cookie, AUTH_TOKEN_COOKIE_NAME)\n : null;\n const sallaToken =\n typeof window !== 'undefined' && typeof window.salla?.storage?.get === 'function'\n ? (window.salla.storage.get(AUTH_TOKEN_COOKIE_NAME) as string | null)\n : null;\n const serverCookieToken = readServerCookieToken();\n const authToken =\n ctx.serverContext?.authToken ??\n serverCookieToken ??\n existingToken ??\n cookieToken ??\n sallaToken ??\n null;\n\n updateTwilightContext({\n queryClient: ctx.context.queryClient,\n settings: settingsResult,\n locale,\n location: ctx.location,\n i18n,\n authToken,\n appsSnippets: snippetsResult,\n appsSettings: appSettingsResult,\n });\n\n return {\n settings: settingsResult,\n locale,\n dir,\n authToken,\n appsSnippets: snippetsResult,\n appsSettings: appSettingsResult,\n };\n}\n","import type { HeadDescriptor, HeadResult } from '../../utils/head';\nimport { mergeHead, resolveHead } from '../../utils/head';\nimport { buildBaseHead } from '../../utils/baseHead';\nimport { FALLBACK_LOCALE } from '../../providers/locale-constants';\nimport { getTwilightContext } from '../../twilight/context';\nimport type { TwilightContextMatch } from '../../twilight/ensure-context';\nimport { ensureTwilightContextFromMatches } from '../../twilight/ensure-context';\nimport type { StoreContext } from '../../api/store';\nimport type { AppSnippet } from '../../api/apps';\nimport { SettingsError } from '../../utils/errors';\nimport { renderAppScopeInstallScript } from '../../utils/app-scope';\nimport { renderThemeHookSlotsScript } from '../../utils/theme-hook-slots';\nimport { escapeForInlineScript } from '../../utils/inline-script';\nimport { readEnv, renderRuntimeEnvScript } from '../../utils/runtime-env';\n\nconst SALLA_ICONS_CSS_URL = 'https://cdn.assets.salla.network/static/fonts/sallaicons.css?v=2.0.5';\nconst LIT_VERSION = '3.3.3';\nconst LIT_CDN_BASE = `https://cdn.assets.salla.network/static/lit/${LIT_VERSION}`;\n\n/** Bare-specifier map for the lit build the engine's `<salla-*>` web components resolve against. */\nconst LIT_IMPORTS: Record<string, string> = {\n lit: `${LIT_CDN_BASE}/lit.js`,\n 'lit/': `${LIT_CDN_BASE}/`,\n 'lit-html': `${LIT_CDN_BASE}/lit-html/lit-html.js`,\n 'lit-html/': `${LIT_CDN_BASE}/lit-html/`,\n 'lit-element': `${LIT_CDN_BASE}/lit-element/lit-element.js`,\n 'lit-element/': `${LIT_CDN_BASE}/lit-element/`,\n '@lit/reactive-element': `${LIT_CDN_BASE}/reactive-element/reactive-element.js`,\n '@lit/reactive-element/': `${LIT_CDN_BASE}/reactive-element/`,\n};\n\nconst TWILIGHT_RELEASE_CDN = 'https://cdn.salla.network/js/twilight';\nconst TWILIGHT_DEV_CDN = 'https://cdn.assets.salla.network/dev/@salla.sa/twilight';\n// The oldest Twilight release this engine works with. Raise it whenever the engine\n// starts relying on something newer; the reason lives in that commit. Today's floor:\n// components ship their own CSS, which themes no longer compile (SallaApp/twilight#2107).\nconst MIN_TWILIGHT_VERSION = '2.14.538';\n// Last resort when no override and no platform pin, and the substitute for a pin below the floor.\nconst DEFAULT_TWILIGHT_VERSION = '2.14.584';\nconst releaseUrl = (version: string): string =>\n `${TWILIGHT_RELEASE_CDN}/${version}/twilight.esm.js`;\n// The head is built more than once per request (early hints, then the page); say it once.\nconst warnedPins = new Set<string>();\n\n/** `x.y.z` release pins only; dev shas and other strings are loaded as given. */\nfunction belowMinimum(version: string): boolean {\n return (\n /^\\d+\\.\\d+\\.\\d+$/.test(version) &&\n version.localeCompare(MIN_TWILIGHT_VERSION, undefined, { numeric: true }) < 0\n );\n}\n\n/**\n * Which twilight.esm.js the storefront loads, in priority order:\n * 1. `VITE_TWILIGHT_URL` — full local/deployment override.\n * 2. `VITE_TWILIGHT_VERSION` — dev-CDN build override.\n * 3. `theme.twilight.version` from the settings endpoint — the platform-pinned\n * release used when no environment override is configured.\n * 4. The engine's default release, also used when the pin is below the engine minimum.\n */\nexport function resolveTwilightSdkUrl(settings?: StoreContext): string {\n const urlOverride = readEnv('VITE_TWILIGHT_URL');\n if (urlOverride) return urlOverride;\n\n const versionOverride = readEnv('VITE_TWILIGHT_VERSION');\n if (versionOverride) return `${TWILIGHT_DEV_CDN}/${versionOverride}/twilight.esm.js`;\n\n const pinnedVersion = settings?.theme?.twilight?.version;\n if (pinnedVersion && belowMinimum(pinnedVersion)) {\n if (!warnedPins.has(pinnedVersion)) {\n warnedPins.add(pinnedVersion);\n console.warn(\n `[twilight] theme.twilight.version ${pinnedVersion} is below the engine minimum ${MIN_TWILIGHT_VERSION}; loading ${DEFAULT_TWILIGHT_VERSION} instead`\n );\n }\n return releaseUrl(DEFAULT_TWILIGHT_VERSION);\n }\n if (pinnedVersion) return releaseUrl(pinnedVersion);\n\n return releaseUrl(DEFAULT_TWILIGHT_VERSION);\n}\n\nconst MEDIA_SWAP_SCRIPT = `\n(function(){var e=function(t){var l=document.getElementById(t);if(l){if(l.sheet||\"all\"===l.media)l.media=\"all\";else l.onload=function(){this.media=\"all\"}}};e(\"salla-theme-font\");e(\"salla-icons-css\")})();\n`.trim();\n\nconst LOADING_CSS = `\n.loading-overlay{position:fixed;inset:0;display:flex;align-items:center;justify-content:center;background:#fff;z-index:9999}\n.loading-spinner{animation:spin 1s linear infinite;border-radius:9999px;height:3rem;width:3rem;border-bottom:2px solid var(--color-primary,#000)}\n@keyframes spin{from{transform:rotate(0deg)}to{transform:rotate(360deg)}}\nhtml,body{margin:0;padding:0;height:100%}\n`.trim();\n\nconst SALLA_INIT_SCRIPT = `\nwindow.salla = window.Salla = window.Salla || window.salla || {};\nwindow.Salla.onReady = window.Salla.onReady || function(callback) {\n return new Promise(function(resolve) {\n if (window.Salla.status === 'ready') {\n var config = window.salla && window.salla.config && window.salla.config.all();\n resolve(callback ? callback(config) : config);\n } else {\n window.addEventListener('twilight::initiated', function(event) {\n resolve(callback ? callback(event.detail) : event.detail);\n }, { once: true });\n }\n });\n};\n`.trim();\n\n/**\n * Distinct snippet-host origins to `preconnect` (warm DNS/TCP/TLS during parse). From the real\n * URLs (dev/prod-correct), deduped and capped at 4. No `crossOrigin`: snippets are no-cors fetches.\n */\nexport function snippetPreconnectOrigins(snippets: readonly AppSnippet[] | undefined): string[] {\n if (!snippets?.length) return [];\n const origins = new Set<string>();\n for (const app of snippets) {\n if (app.status !== 'enabled') continue;\n for (const s of app.snippets) {\n if (!s.url) continue;\n try {\n origins.add(new URL(s.url).origin);\n } catch {\n /* skip a malformed snippet url rather than breaking the head */\n }\n if (origins.size >= 4) return [...origins];\n }\n }\n return [...origins];\n}\n\nexport function rootHead(ctx: {\n params: Record<string, string>;\n matches?: readonly TwilightContextMatch[];\n}): HeadResult {\n // Re-run on the client during hydration, where the twilight module store may\n // still be empty. Recover it from the resolved match context so the head is\n // built from real settings instead of falling through to 'Store Unavailable'.\n ensureTwilightContextFromMatches(ctx.matches);\n\n let settings: StoreContext | undefined;\n try {\n settings = getTwilightContext().settings;\n } catch (e) {\n if (e instanceof SettingsError) {\n return resolveHead({\n title: 'Store Unavailable',\n });\n }\n throw e;\n }\n const locale = ctx.params.locale || FALLBACK_LOCALE;\n const parts = deriveHeadParts(settings);\n\n return resolveHead(\n mergeHead(buildBaseHead(settings, locale), {\n meta: buildRootMeta(parts),\n links: buildRootLinks(parts),\n styles: buildRootStyles(parts),\n importMap: [{ imports: LIT_IMPORTS }],\n scripts: buildRootScripts(parts),\n })\n );\n}\n\n/** Everything the root head's tag builders read, derived once from the store settings. */\ninterface RootHeadParts {\n store: StoreContext['store'] | undefined;\n favicon?: string;\n primaryColor?: string;\n fontUrl?: string;\n fontUrlWithDisplay?: string;\n isGoogleFont?: boolean;\n fontFamilyName?: string;\n customJs?: string;\n customCss?: string;\n isCustomCssUrl?: boolean;\n isCustomJsUrl?: boolean;\n twilightSdkUrl: string;\n snippetPreconnects: Array<{ rel: 'preconnect'; href: string }>;\n appScopeInstallScript: string;\n themeHookSlotsScript: string | null;\n runtimeEnvScript: string | null;\n}\n\n/** Google Fonts only honours `display=swap` as a query param; other hosts get the @font-face\n * override instead (see buildRootStyles). */\nfunction deriveFontParts(theme?: StoreContext['theme']) {\n const font = theme?.font;\n const fontUrl = font?.url || font?.path;\n const isGoogleFont = fontUrl?.includes('fonts.googleapis.com');\n const needsDisplay = Boolean(isGoogleFont && fontUrl && !fontUrl.includes('display='));\n const separator = fontUrl?.includes('?') ? '&' : '?';\n\n return {\n fontUrl,\n isGoogleFont,\n fontFamilyName: font?.family_name,\n fontUrlWithDisplay: needsDisplay ? `${fontUrl}${separator}display=swap` : fontUrl,\n };\n}\n\n/** Theme customization JS/CSS, each either a URL to load or an inline blob to embed. */\nfunction deriveCustomizationParts(theme?: StoreContext['theme']) {\n const customization = theme?.customization;\n const customJs = customization?.js?.trim();\n const customCss = customization?.css?.trim();\n const isUrl = (value?: string): boolean =>\n Boolean(value?.startsWith('http') || value?.startsWith('//'));\n\n return {\n customJs,\n customCss,\n isCustomCssUrl: isUrl(customCss),\n isCustomJsUrl: isUrl(customJs),\n };\n}\n\nfunction deriveHeadParts(settings?: StoreContext): RootHeadParts {\n const store = settings?.store;\n\n return {\n store,\n favicon: store?.icon,\n primaryColor: settings?.theme?.color?.primary,\n ...deriveFontParts(settings?.theme),\n ...deriveCustomizationParts(settings?.theme),\n twilightSdkUrl: resolveTwilightSdkUrl(settings),\n // Warm the connection to the snippet host(s) during head parse, so the body's deferred\n // `<script src>` snippet tags fetch off an already-open socket instead of DNS+TCP+TLS.\n snippetPreconnects: snippetPreconnectOrigins(getTwilightContext().appsSnippets).map((href) => ({\n rel: 'preconnect' as const,\n href,\n })),\n // Install `Salla.appScope` inline at parse time, before the SDK is ready — else a snippet's\n // onReady callback calls it too early and throws. Always emitted, even when the settings\n // prefetch failed: the CDN snippet tags ship regardless (they come from the *snippets*\n // endpoint), so the factory has to exist for them. `installAppScope` then seeds the real\n // buckets into this install once the client query resolves.\n appScopeInstallScript: renderAppScopeInstallScript(\n getTwilightContext().appsSettings ?? { apps: {} }\n ),\n // Whitelist the theme's own hook slots at parse time too, for the same reason: apps register\n // their `onReady` callbacks from parser-inserted snippet tags, long before React hydrates.\n themeHookSlotsScript: renderThemeHookSlotsScript(),\n // Env this render resolved (worker `vars` live in server-only `process.env`), handed to the\n // client so it doesn't silently fall back to the production defaults. Re-rendered on the\n // client during hydration, where it resolves to the same values or to nothing.\n runtimeEnvScript: renderRuntimeEnvScript(),\n };\n}\n\nfunction buildRootMeta(p: RootHeadParts): NonNullable<HeadDescriptor['meta']> {\n return [\n { name: 'robots', content: 'index, follow' },\n { name: 'msapplication-TileColor', content: '#ffffff' },\n ...(p.favicon ? [{ name: 'msapplication-TileImage', content: p.favicon }] : []),\n ...(p.primaryColor\n ? [\n { name: 'theme-color', content: p.primaryColor },\n { name: 'msapplication-navbutton-color', content: p.primaryColor },\n { name: 'apple-mobile-web-app-status-bar-style', content: p.primaryColor },\n ]\n : []),\n ];\n}\n\nfunction buildRootLinks(p: RootHeadParts): NonNullable<HeadDescriptor['links']> {\n return [\n { rel: 'preconnect', href: 'https://api.salla.dev' },\n { rel: 'preconnect', href: 'https://cdn.salla.sa' },\n { rel: 'preconnect', href: 'https://cdn.assets.salla.network', crossOrigin: 'anonymous' },\n // Warm the installed apps' CDN snippet host(s) — see snippetPreconnectOrigins.\n ...p.snippetPreconnects,\n ...(p.fontUrl\n ? [\n {\n rel: 'preconnect' as const,\n href: 'https://fonts.gstatic.com',\n crossOrigin: 'anonymous' as const,\n },\n ]\n : []),\n { rel: 'modulepreload', href: p.twilightSdkUrl },\n ...(p.fontUrlWithDisplay\n ? [\n {\n id: 'salla-theme-font',\n rel: 'stylesheet',\n href: p.fontUrlWithDisplay,\n media: 'print',\n },\n ]\n : []),\n ...(p.fontUrlWithDisplay && !p.isGoogleFont && p.fontFamilyName\n ? [\n {\n id: 'salla-font-display-override',\n rel: 'preload',\n as: 'style',\n href: p.fontUrlWithDisplay,\n },\n ]\n : []),\n ...(p.favicon ? [{ rel: 'icon', href: p.favicon }] : []),\n ...(p.favicon\n ? [{ id: 'salla-apple-icon', rel: 'apple-touch-icon-precomposed', href: p.favicon }]\n : []),\n ...(p.isCustomCssUrl && p.customCss\n ? [{ id: 'salla-custom-css', rel: 'stylesheet', href: p.customCss }]\n : []),\n {\n id: 'salla-icons-css',\n rel: 'stylesheet',\n href: SALLA_ICONS_CSS_URL,\n media: 'print',\n },\n // {\n // id: 'intl-tel-input-css',\n // rel: 'stylesheet',\n // href: 'https://cdn.jsdelivr.net/npm/intl-tel-input@26.8.0/build/css/intlTelInput.css',\n // },\n ...(p.isCustomJsUrl && p.customJs\n ? [{ id: 'salla-custom-js-preload', rel: 'preload', as: 'script', href: p.customJs }]\n : []),\n ];\n}\n\n// Hoistable (href + precedence): the web components insert their own <style> near the top of\n// <head> before hydration, which a positionally hydrated <style> would be matched against.\nconst hoisted = (id: string, children: string) => ({\n id,\n href: id,\n precedence: 'default',\n children,\n});\n\nfunction buildRootStyles(p: RootHeadParts): NonNullable<HeadDescriptor['styles']> {\n return [\n hoisted('twilight-loading', LOADING_CSS),\n ...(!p.isGoogleFont && p.fontFamilyName\n ? [\n hoisted(\n 'salla-font-display-swap',\n `@font-face{font-family:\"${p.fontFamilyName}\";font-display:swap;src:local(\"${p.fontFamilyName}\")}`\n ),\n ]\n : []),\n ...(!p.isCustomCssUrl && p.customCss ? [hoisted('salla-custom-css', p.customCss)] : []),\n ];\n}\n\nfunction buildRootScripts(p: RootHeadParts): NonNullable<HeadDescriptor['scripts']> {\n return [\n // First: the API base / store identifier this render used, so the hydrated client\n // resolves the same ones (worker `vars` never reach the browser bundle on their own).\n ...(p.runtimeEnvScript ? [{ id: 'salla-runtime-env', children: p.runtimeEnvScript }] : []),\n { id: 'twilight-init', children: SALLA_INIT_SCRIPT },\n // After twilight-init (which defines window.Salla) and before the SDK module, so the\n // appScope factory exists ahead of any snippet's onReady callback firing.\n { id: 'salla-app-scope', children: p.appScopeInstallScript },\n // Arms the hook-slot whitelist push here, so its `twilight::initiated` listener is\n // registered before any app snippet's — listeners fire in registration order.\n ...(p.themeHookSlotsScript\n ? [{ id: 'salla-theme-hook-slots', children: p.themeHookSlotsScript }]\n : []),\n { id: 'salla-async-css', children: MEDIA_SWAP_SCRIPT },\n { id: 'salla-sdk', type: 'module', src: p.twilightSdkUrl },\n ...(p.store?.settings?.ticketing_system_enabled\n ? [\n {\n id: 'salla-ticketing-script',\n src: 'https://cdn.assets.salla.network/latest/@salla.sa/ui-store-ticketing-system/ticketing-system.es.js',\n type: 'module',\n },\n ]\n : []),\n ...(p.customJs ? [buildCustomJsScript(p.customJs, Boolean(p.isCustomJsUrl))] : []),\n ];\n}\n\n/** A URL customization is loaded after SDK init; an inline one is wrapped so a syntax/runtime\n * error in partner JS warns instead of taking the page down. */\nfunction buildCustomJsScript(customJs: string, isUrl: boolean) {\n return {\n id: 'salla-custom-js',\n children: isUrl\n ? `window.addEventListener('twilight::initiated',function(){var s=document.createElement('script');s.src=${escapeForInlineScript(JSON.stringify(customJs))};s.async=true;document.head.appendChild(s)},{once:true});`\n : `try { ${customJs} } catch(e) { console.warn(\"[ThemeCustomization] Custom JS error:\", e); }`,\n };\n}\n","/**\n * @fileoverview The store segment, carried by the router instead of the route tree.\n *\n * TanStack Router rewrites every location it reads and every one it writes:\n * `input` runs before a URL is matched, and `output` before an href is rendered,\n * pushed to history or sent as a redirect's `Location`. So on a host where the\n * store is the root, the route tree stays `/{-$locale}/cart` and\n * `<Link to=\"/cart\">` renders `/mtgr-alaatr-2/cart` by itself.\n *\n * Why not the router's `basepath`: TanStack Start overwrites it from the build on\n * both sides (`router.update({ basepath })` per request on the server, and in\n * `hydrateStart` on the client). `rewrite` is a separate option that the router\n * composes with that basepath, so it survives. Server functions are dispatched on\n * the raw URL before the router runs, and assets are root-absolute, so neither\n * moves. See `docs/store-base-path.md`.\n */\nimport type { LocationRewrite } from '@tanstack/react-router';\nimport { prefixStoreBase, stripStoreBase } from '../utils/store-base';\n\n/** A rewrite that serves the application from `/<base>`. */\nexport function storeBaseRewrite(base: string): LocationRewrite {\n return {\n input: ({ url }) => {\n url.pathname = stripStoreBase(url.pathname, base);\n return url;\n },\n output: ({ url }) => {\n url.pathname = prefixStoreBase(url.pathname, base);\n return url;\n },\n };\n}\n","import type { ReactNode } from 'react';\nimport { lazy, Suspense } from 'react';\nimport {\n createRouter as createTanStackRouter,\n createRootRouteWithContext,\n} from '@tanstack/react-router';\nimport type { RouterHistory } from '@tanstack/react-router';\nimport { QueryClient } from '@tanstack/react-query';\nimport { shouldDehydrateQuery } from '../api/product';\nimport { PageSkeleton } from '@salla.sa/twilight-components-react/skeletons';\nimport { setHeadAdapter } from '../utils/head';\nimport { tanstackHeadAdapter } from './head';\nimport { stringifySearch } from './search';\nimport { updateTwilightContext, type TwilightLocation } from '../twilight/context';\nimport { dispatchRouteChanged } from '../utils/sdk-events';\nimport { rootBeforeLoad, type BeforeLoadResult } from '../routes/root/beforeLoad';\nimport { rootHead } from '../routes/root/head';\nimport { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query';\nimport type { AnyRouter } from '@tanstack/react-router';\nimport { RouteId, type RouteIdType } from '../router/route-ids';\nimport { UnauthorizedError, NotFoundError, RedirectError } from '../providers/NavigationProvider';\nimport { ErrorPage } from '../components/common/ErrorPage';\nimport type { StoreContext } from '../api/store';\nimport type { AppSnippet, AppSettings } from '../api/apps';\nimport { createI18nInstance } from '../providers/i18n-factory';\nimport { messagesForLocale } from '../api/messages';\nimport { resolveStoreBase } from '../utils/store-identity';\nimport { storeBaseRewrite } from './store-base';\n\n/**\n * Initial router context passed from createRouter to beforeLoad.\n */\nexport interface RouterInitialContext {\n queryClient: QueryClient;\n setLocation: (_location: Partial<TwilightLocation>) => void;\n}\n\n/**\n * TanStack Router ID Mapping\n *\n * Maps TanStack's auto-generated path-based route IDs to semantic RouteId constants.\n * This mapping is TanStack-specific because different frameworks generate route IDs differently:\n *\n * - TanStack: Uses file path as ID (e.g., '/{-$locale}/cart')\n * - Next.js: Uses file path without locale (e.g., '/cart')\n *\n * The mapping enables hooks like useIsHome(), useIsProduct() to work consistently\n * across frameworks while each framework has its own ID generation strategy.\n */\nexport const TANSTACK_ROUTE_ID_MAP: Record<string, RouteIdType> = {\n '/{-$locale}/': RouteId.INDEX,\n '/{-$locale}/cart': RouteId.CART,\n '/{-$locale}/search': RouteId.SEARCH,\n\n '/{-$locale}/latest-products': RouteId.PRODUCT_INDEX_LATEST,\n '/{-$locale}/most-sales-products': RouteId.PRODUCT_INDEX_SALES,\n '/{-$locale}/offers': RouteId.PRODUCT_INDEX_OFFERS,\n\n '/{-$locale}/$slug/c{$id}': RouteId.PRODUCT_INDEX,\n '/{-$locale}/$slug/p{$id}': RouteId.PRODUCT_SINGLE,\n '/{-$locale}/$slug/brand-{$id}': RouteId.BRANDS_SINGLE,\n '/{-$locale}/$slug/tag-{$id}': RouteId.PRODUCT_INDEX_TAG,\n '/{-$locale}/$slug/page-{$id}': RouteId.PAGE_SINGLE,\n\n '/{-$locale}/blog': RouteId.BLOG_INDEX,\n '/{-$locale}/blog/$slug/a-{$id}': RouteId.BLOG_SINGLE,\n '/{-$locale}/blog/$slug/c-{$id}': RouteId.BLOG_INDEX_CATEGORY,\n '/{-$locale}/blog/$slug/tag-{$id}': RouteId.BLOG_INDEX_TAG,\n '/{-$locale}/blog/author/$id': RouteId.BLOG_INDEX_AUTHOR,\n\n '/{-$locale}/brands': RouteId.BRANDS_INDEX,\n '/{-$locale}/brands/$id': RouteId.BRANDS_SINGLE,\n '/{-$locale}/tags/$id': RouteId.PRODUCT_INDEX_TAG,\n\n '/{-$locale}/profile': RouteId.CUSTOMER_PROFILE,\n '/{-$locale}/wishlist': RouteId.CUSTOMER_WISHLIST,\n '/{-$locale}/wallet': RouteId.CUSTOMER_WALLET,\n '/{-$locale}/notifications': RouteId.CUSTOMER_NOTIFICATIONS,\n '/{-$locale}/settings': RouteId.CUSTOMER_SETTINGS,\n '/{-$locale}/orders': RouteId.CUSTOMER_ORDERS_INDEX,\n '/{-$locale}/order/$id': RouteId.CUSTOMER_ORDERS_SINGLE,\n '/{-$locale}/pending-orders': RouteId.CUSTOMER_ORDERS_INDEX_PENDING,\n '/{-$locale}/account/pending_orders': RouteId.CUSTOMER_ORDERS_INDEX_PENDING,\n '/{-$locale}/account/rating': RouteId.CUSTOMER_ORDERS_INDEX,\n\n '/{-$locale}/logout': RouteId.LOGOUT,\n '/{-$locale}/loyalty': RouteId.LOYALTY,\n '/{-$locale}/loyalty_points': RouteId.CUSTOMER_LOYALTY_POINTS,\n '/{-$locale}/testimonials': RouteId.TESTIMONIALS,\n '/{-$locale}/thankyou/$orderId': RouteId.THANK_YOU,\n};\n\n/**\n * Resolves a TanStack route ID to a semantic RouteId constant.\n * Falls back to the original ID if no mapping exists.\n * @internal Exported for testing\n */\nexport function resolveRouteId(tanstackId: string): string {\n return TANSTACK_ROUTE_ID_MAP[tanstackId] ?? tanstackId;\n}\n\n// Lazy load NotFoundPage for code splitting\nconst LazyNotFoundPage = lazy(() =>\n import('../routes/not-found').then((m) => ({ default: m.NotFoundPage }))\n);\n\n/**\n * Error component shown when the root route fails to load.\n * This renders a minimal HTML page with error details.\n */\nfunction StoreUnavailablePage() {\n return (\n <>\n <div\n style={{\n position: 'fixed',\n inset: 0,\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n background: '#f9fafb',\n }}\n >\n <div style={{ textAlign: 'center', padding: '2rem' }}>\n <h1 style={{ fontSize: '1.5rem', marginBottom: '0.5rem' }}>\n Store is temporarily unavailable\n </h1>\n <p style={{ color: '#6b7280' }}>\n We're having trouble loading the store. Please try again in a moment.\n </p>\n <button\n type=\"button\"\n onClick={() => window.location.reload()}\n style={{\n marginTop: '1rem',\n padding: '0.75rem 1.5rem',\n fontSize: '1rem',\n border: 'none',\n borderRadius: '0.5rem',\n background: '#111827',\n color: '#fff',\n cursor: 'pointer',\n }}\n >\n Retry\n </button>\n </div>\n </div>\n </>\n );\n}\n\nfunction RootErrorComponent({ error: _error }: { error: Error }) {\n return (\n <html lang=\"ar\" dir=\"rtl\">\n <head>\n <meta charSet=\"UTF-8\" />\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n <title>Store Unavailable</title>\n </head>\n <body style={{ margin: 0, fontFamily: 'sans-serif' }}>\n <StoreUnavailablePage />\n </body>\n </html>\n );\n}\n\n/**\n * Creates the root route pre-configured with RouterInitialContext.\n * beforeLoad will fetch settings/translations, loader returns serializable data.\n *\n * @example\n * ```ts\n * export const Route = createTwilightRootRoute()({ shellComponent });\n * ```\n */\nexport function createTwilightRootRoute() {\n const factory = createRootRouteWithContext<RouterInitialContext>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- TanStack Router factory expects `any` for spread options\n return (options: any) =>\n factory({\n beforeLoad: rootBeforeLoad,\n head: rootHead,\n errorComponent: RootErrorComponent,\n ...options,\n });\n}\n\n/**\n * Default error component for route-level errors.\n */\nexport function DefaultErrorComponent({ error }: { error: unknown }) {\n if (error instanceof RedirectError) {\n return null;\n }\n\n if (error instanceof NotFoundError) {\n return <ErrorPage code={404} message={error.message} />;\n }\n\n if (error instanceof UnauthorizedError) {\n return <ErrorPage code={401} message={error.message} showAction={false} />;\n }\n\n const message =\n error instanceof Error\n ? error.message\n : error &&\n typeof error === 'object' &&\n 'message' in error &&\n typeof error.message === 'string'\n ? error.message\n : undefined;\n\n if (error && typeof error === 'object' && 'response' in error) {\n return <ErrorPage code={400} message={message} />;\n }\n\n return <ErrorPage code={500} message={message} />;\n}\n\n/**\n * SSR integration for Twilight context — mirrors TanStack Query's\n * `setupRouterSsrQueryIntegration` pattern.\n *\n * On the **server**: wraps `router.options.dehydrate` to include twilight\n * context data (settings, locale, location, authToken) alongside the router state.\n *\n * On the **client**: wraps `router.options.hydrate` to populate the module-level\n * store from the root match's `__beforeLoadContext` BEFORE head functions re-run.\n * TanStack's `hydrate()` calls `router.options.hydrate()` at line 114 of\n * `ssr-client.ts`, right before it re-evaluates head functions (line 120+).\n * By populating the store here, `getTwilightContext().settings` is available\n * to `rootHead()` and all child head functions during client hydration.\n */\nfunction setupTwilightSsrIntegration(router: AnyRouter, queryClient: QueryClient): void {\n if (typeof window === 'undefined') {\n // Server: also populate twilightCtx from root match context on dehydrate\n return;\n }\n\n // Client: hook into router.options.hydrate to populate the module store\n // from the root match's __beforeLoadContext (set by rootBeforeLoad on the server)\n const ogHydrate = router.options.hydrate;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n router.options.hydrate = async (dehydratedData: any) => {\n await ogHydrate?.(dehydratedData);\n hydrateTwilightContext(router, queryClient);\n };\n}\n\nfunction warnHydrationBail(reason: string): void {\n // Silent failure here is what blanks the storefront: every head function that\n // runs next reads `getTwilightContext().settings`, which throws when the store\n // is empty. `ensureTwilightContextFromMatches` recovers at the point of use,\n // but the bail still signals a regression worth seeing in dev.\n if (import.meta.env?.DEV) {\n console.warn(`[Twilight] Could not hydrate twilight context: ${reason}`);\n }\n}\n\nfunction hydrateTwilightContext(router: AnyRouter, queryClient: QueryClient): void {\n const rootMatch = router.state?.matches?.[0];\n if (!rootMatch) {\n warnHydrationBail('no root match in router state');\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const beforeLoadCtx = (rootMatch as any).__beforeLoadContext as BeforeLoadResult | undefined;\n const matchCtx = rootMatch.context as Record<string, unknown> | undefined;\n\n const settings = (beforeLoadCtx?.settings ?? matchCtx?.settings) as StoreContext | undefined;\n const locale = (beforeLoadCtx?.locale ?? matchCtx?.locale) as string | undefined;\n const authToken = (beforeLoadCtx?.authToken ?? matchCtx?.authToken) as string | null;\n // Recover snippets here too: this is the primary hydration pass and populates settings, so the\n // best-effort ensureTwilightContextFromMatches fallback then short-circuits — if we skipped\n // appsSnippets here it would never reach the client store, and AppsSnippets' SSR-rendered CDN\n // tags would mismatch on hydration.\n const appsSnippets =\n beforeLoadCtx?.appsSnippets ?? (matchCtx?.appsSnippets as AppSnippet[] | undefined);\n // Recover appScope buckets too (like appsSnippets): this primary pass populates settings, so the\n // ensure-context fallback short-circuits — keep the client store in parity for head/install.\n const appsSettings =\n beforeLoadCtx?.appsSettings ?? (matchCtx?.appsSettings as AppSettings | undefined);\n\n if (!settings || !locale) {\n warnHydrationBail(\n `root match carried no ${!settings ? 'settings' : 'locale'} (beforeLoadContext and context both empty)`\n );\n return;\n }\n\n // Composed by the shared helper rather than read straight off one key.\n // There are two entries now — the platform's copy and this merchant's — and\n // reading only the first is how the server rendered the merchant's wording\n // and hydration replaced it with Salla's (Greptile's P1 on #366).\n const i18n = createI18nInstance(locale, messagesForLocale(queryClient, locale));\n\n const location = router.state?.location\n ? {\n href: router.state.location.href,\n pathname: router.state.location.pathname,\n search: router.state.location.search as Record<string, unknown>,\n searchStr: router.state.location.searchStr,\n state: router.state.location.state as unknown as Record<string, unknown>,\n hash: router.state.location.hash,\n }\n : undefined;\n\n const matches = router.state?.matches;\n const page = matches?.reduceRight(\n (found, m) => found ?? ((m as any).loaderData?.page ? (m as any).loaderData.page : null),\n null as any\n );\n\n // Resolve routeId on the initial load too — `onResolved` only fires on later\n // navigations, so without this the store keeps the empty default until the\n // first SPA navigation (breaks useRouteId/useIsHome on first paint/refresh).\n const leafMatch = matches?.[matches.length - 1];\n const routeId = leafMatch?.routeId ? resolveRouteId(leafMatch.routeId as string) : undefined;\n\n updateTwilightContext({\n queryClient,\n settings,\n locale,\n i18n,\n authToken,\n location,\n page,\n routeId,\n appsSnippets,\n appsSettings,\n });\n}\n\n/** Publishes the deepest match's loader `page` to the twilight context and `salla.config`. */\nfunction syncPageFromMatches(router: AnyRouter): void {\n const matches = router.state?.matches;\n if (!matches) return;\n const page = matches.reduceRight(\n (found, m) => found ?? ((m as any).loaderData?.page ? (m as any).loaderData.page : null),\n null as any\n );\n if (!page) return;\n updateTwilightContext({ page });\n const sdkPage = {\n ...page,\n url: page.url ?? router.state.location.pathname + router.state.location.searchStr,\n };\n const push = () => window.salla?.config?.set?.('page', sdkPage);\n // The SDK script can run after hydration; it must have the page before it is ready.\n if (window.salla?.config?.set) push();\n else window.addEventListener('salla::created', push, { once: true });\n}\n\n/**\n * Options for creating the TanStack Router instance.\n */\nexport interface CreateRouterOptions {\n defaultPendingComponent?: (() => ReactNode) | false;\n defaultPendingMs?: number;\n defaultPendingMinMs?: number;\n defaultStaleTime?: number;\n history?: RouterHistory;\n}\n\n/**\n * Creates and configures the TanStack Router instance for the Twilight theme.\n *\n * This router is pre-configured with:\n * - Route tree generated by the TanStack Router plugin\n * - Intent-based preload for better performance\n * - Scroll restoration for better UX\n * - Locale-aware default NotFoundPage (redirects `/cart` → `/ar/cart`)\n * - Trailing slash normalization for consistent URL handling\n * - Page skeleton shown during route transitions (via `defaultPendingComponent`)\n * - SSR query integration for Cloudflare compatibility\n *\n * @param routeTree - The generated route tree from the consuming project\n * @param options - Optional overrides for pending component behavior\n * @returns Configured TanStack Router instance\n */\nexport function createRouter(routeTree: any, options?: CreateRouterOptions) {\n setHeadAdapter(tanstackHeadAdapter);\n\n const {\n defaultPendingComponent: pendingOpt,\n defaultPendingMs = 100,\n defaultPendingMinMs = 200,\n defaultStaleTime = Infinity,\n history,\n } = options ?? {};\n\n const pendingComponent =\n pendingOpt === false ? undefined : (pendingOpt ?? (() => <PageSkeleton />));\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60_000,\n gcTime: 5 * 60_000,\n retry: 1,\n refetchOnWindowFocus: false,\n },\n mutations: {\n retry: 0,\n },\n dehydrate: {\n shouldDehydrateQuery,\n },\n },\n });\n\n // Store queryClient in the holder for access by loaders via getTwilightContext()\n updateTwilightContext({ queryClient });\n\n // On a host that serves many stores, the store is the first segment of every\n // URL. The router carries it instead of the route tree: it is stripped before\n // matching and added to every href the router builds. Decided per request on\n // the server, and taken from what SSR published in the browser.\n const storeBase = resolveStoreBase();\n\n const router = createTanStackRouter({\n routeTree,\n ...(history ? { history } : {}),\n ...(storeBase ? { rewrite: storeBaseRewrite(storeBase) } : {}),\n context: {\n queryClient,\n setLocation: (location: Partial<TwilightLocation>) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n updateTwilightContext({ location } as any);\n },\n },\n defaultPreload: 'intent',\n scrollRestoration: true,\n scrollRestorationBehavior: 'instant',\n trailingSlash: 'never',\n stringifySearch,\n defaultStaleTime,\n defaultNotFoundComponent: () => (\n <Suspense fallback={<PageSkeleton />}>\n <LazyNotFoundPage />\n </Suspense>\n ),\n defaultPendingComponent: pendingComponent,\n defaultPendingMs,\n defaultPendingMinMs,\n defaultErrorComponent: DefaultErrorComponent,\n });\n\n // Setup SSR query integration (native, with incremental streaming)\n setupRouterSsrQueryIntegration({ router, queryClient });\n\n // Setup Twilight SSR integration — populates the module store from\n // dehydrated match context BEFORE head functions re-run on the client.\n // This mirrors how setupRouterSsrQueryIntegration hydrates QueryClient.\n setupTwilightSsrIntegration(router, queryClient);\n\n // Subscribe to navigation events to sync location and routeId\n function syncNavigationState() {\n const state = router?.state;\n if (!state?.location) return;\n\n const loc = state.location;\n updateTwilightContext({\n location: {\n href: loc.href,\n pathname: loc.pathname,\n search: loc.search as Record<string, unknown>,\n searchStr: loc.searchStr,\n state: loc.state as unknown as Record<string, unknown>,\n hash: loc.hash,\n },\n });\n\n const matches = state.matches;\n const leafMatch = matches[matches.length - 1];\n if (leafMatch?.routeId) {\n const semanticId = resolveRouteId(leafMatch.routeId as string);\n updateTwilightContext({ routeId: semanticId });\n }\n\n const rootMatch = state.matches[0];\n if (rootMatch?.context) {\n const ctx = rootMatch.context as BeforeLoadResult;\n if (ctx?.settings) {\n updateTwilightContext({ settings: ctx.settings, locale: ctx.locale });\n }\n }\n }\n\n // Extract page from matches as soon as loaders complete (before components mount),\n // so useTwilightInit's useEffect sees page data when it calls sdk.init().\n router.subscribe('onLoad', () => syncPageFromMatches(router));\n // A direct load resolves through hydration, which emits no onLoad; its first render does emit onRendered.\n router.subscribe('onRendered', () => syncPageFromMatches(router));\n\n // Sync location, routeId, and settings after navigation fully resolves\n router.subscribe('onResolved', () => {\n syncNavigationState();\n dispatchRouteChanged();\n });\n\n return router;\n}\n\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: ReturnType<typeof createRouter>;\n }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- Required by TanStack Router module augmentation pattern\n interface RouterContext extends RouterInitialContext {}\n}\n","import { useRouterState } from '@tanstack/react-router';\nimport {\n mergeElementAttrs,\n toReactProps,\n type DocumentElementDescriptor,\n} from '../utils/document-class';\nimport { useDocumentClass } from '../hooks/useDocumentClass';\nimport { updateTwilightContext } from '../twilight/context';\nimport { resolveRouteId } from './router';\n\n// ============================================================================\n// Route → body class map (mirrors PHP Route2Class::generateClassString)\n// Keyed by TanStack Router route ID (the path passed to createFileRoute).\n// null = intentionally classless (e.g. root layout routes).\n// ============================================================================\n\nconst ROUTE_CLASS_MAP: Record<string, string | null> = {\n '/{-$locale}/': 'index',\n '/{-$locale}/cart': 'cart',\n '/{-$locale}/$slug/c{$id}': 'product-index',\n '/{-$locale}/offers': 'product-index-offers',\n '/{-$locale}/latest-products': 'product-index-latest',\n '/{-$locale}/most-sales-products': 'product-index-sales',\n '/{-$locale}/search': 'product-index-search',\n '/{-$locale}/$slug/tag-{$id}': 'product-index-tag',\n '/{-$locale}/tags/$id': 'product-index-tag',\n '/{-$locale}/$slug/p{$id}': 'product-single',\n '/{-$locale}/$slug/page-{$id}': 'page-single',\n '/{-$locale}/page/$slug': 'page-single',\n '/{-$locale}/p/$slug': 'page-single',\n '/{-$locale}/thankyou/$orderId': 'thank-you',\n '/{-$locale}/orders': 'customer-orders-index',\n '/{-$locale}/pending-orders': 'customer-orders-index-pending', // redirect to /account/orders?status=pending\n '/{-$locale}/account/pending_orders': 'customer-orders-index-pending',\n '/{-$locale}/account/rating': 'customer-orders-index', // redirect to /account/orders\n '/{-$locale}/order/$id': 'customer-orders-single',\n '/{-$locale}/profile': 'customer-profile',\n '/{-$locale}/wallet': 'customer-wallet',\n '/{-$locale}/wishlist': 'customer-wishlist',\n '/{-$locale}/notifications': 'customer-notifications',\n '/{-$locale}/testimonials': 'testimonials',\n '/{-$locale}/brands': 'brands-index',\n '/{-$locale}/brands/$id': 'brands-single',\n '/{-$locale}/$slug/brand-{$id}': 'brands-single',\n '/{-$locale}/blog': 'blog-index',\n '/{-$locale}/blog/$slug/a-{$id}': 'blog-single',\n '/{-$locale}/blog/$slug/c-{$id}': 'blog-index-category',\n '/{-$locale}/blog/$slug/tag-{$id}': 'blog-index-tag',\n '/{-$locale}/blog/author/$id': 'blog-index-author',\n '/{-$locale}/loyalty': 'loyalty',\n '/{-$locale}/loyalty_points': 'customer-loyalty-points',\n};\n\n// ============================================================================\n// RouteDocumentSync — resolves body class from active route ID at runtime.\n// ============================================================================\n\n/**\n * Applies the per-route body class by looking up the deepest active route ID\n * in the built-in route→class map.\n *\n * For custom routes not in the built-in map, use `useDocumentClass` directly\n * inside your route component.\n *\n * Note: This will throw if rendered outside a TanStack Router context.\n * Use TanStackDocumentSync for safe usage inside TwilightProvider.\n */\nexport function RouteDocumentSync(): null {\n const matches = useRouterState({ select: (s) => s.matches });\n\n let routeClass: string | null = null;\n for (let i = matches.length - 1; i >= 0; i--) {\n const id = matches[i].routeId;\n if (id in ROUTE_CLASS_MAP) {\n routeClass = ROUTE_CLASS_MAP[id];\n break;\n }\n }\n\n useDocumentClass(routeClass ? { body: { class: routeClass } } : {});\n return null;\n}\n\n/**\n * Safe version of RouteDocumentSync for use in TwilightProvider.\n * Handles being rendered outside a TanStack Router context gracefully.\n * Uses a wrapper component pattern to conditionally render hooks.\n */\nexport function TanStackDocumentSync(): null {\n const matches = useRouterState({ select: (s) => s.matches }) || [];\n\n // On the server routeId is never synced (onResolved is client-only), so useIsHome()\n // etc. disagree with the client and cause hydration mismatches. Sync it here — this\n // renders before the layout. Client already has it from onResolved.\n if (typeof window === 'undefined') {\n const leaf = matches[matches.length - 1];\n if (leaf?.routeId) {\n updateTwilightContext({ routeId: resolveRouteId(leaf.routeId as string) });\n }\n }\n\n let routeClass: string | null = null;\n for (let i = matches.length - 1; i >= 0; i--) {\n const id = matches[i].routeId;\n if (id in ROUTE_CLASS_MAP) {\n routeClass = ROUTE_CLASS_MAP[id];\n break;\n }\n }\n\n useDocumentClass(routeClass ? { body: { class: routeClass } } : {});\n return null;\n}\n\n// ============================================================================\n// Type augmentation — extend TanStack Router's staticData type\n// ============================================================================\n\ndeclare module '@tanstack/react-router' {\n interface StaticDataRouteOption {\n documentAttrs?: DocumentElementDescriptor;\n }\n}\n\nexport interface TanstackRouteStaticData {\n documentAttrs?: DocumentElementDescriptor;\n}\n\n// ============================================================================\n// useTanstackDocumentAttrs — for TanStack Start SSR root layouts\n// ============================================================================\n\n/**\n * Read and merge `<body>` / `<html>` attributes from all currently active\n * route matches (via `staticData.documentAttrs`).\n *\n * Returns React-ready prop objects ready to spread onto `<html>` and `<body>`.\n */\nexport function useTanstackDocumentAttrs(): {\n bodyAttrs: Record<string, string>;\n htmlAttrs: Record<string, string>;\n} {\n const matches = useRouterState({ select: (s) => s.matches });\n\n const bodyDescriptors = matches.map(\n (m) => (m.staticData as TanstackRouteStaticData | undefined)?.documentAttrs?.body ?? {}\n );\n const htmlDescriptors = matches.map(\n (m) => (m.staticData as TanstackRouteStaticData | undefined)?.documentAttrs?.html ?? {}\n );\n\n return {\n bodyAttrs: toReactProps(mergeElementAttrs(bodyDescriptors)),\n htmlAttrs: toReactProps(mergeElementAttrs(htmlDescriptors)),\n };\n}\n\n/**\n * Pure adapter: converts a `DocumentElementDescriptor` to React-ready props.\n */\nexport function tanstackDocumentAdapter(descriptor: DocumentElementDescriptor): {\n bodyAttrs: Record<string, string>;\n htmlAttrs: Record<string, string>;\n} {\n return {\n bodyAttrs: toReactProps(mergeElementAttrs([descriptor.body ?? {}])),\n htmlAttrs: toReactProps(mergeElementAttrs([descriptor.html ?? {}])),\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { filesCdn, cdn } from './chunk-
|
|
1
|
+
import { filesCdn, cdn } from './chunk-IKUDCH7Q.js';
|
|
2
2
|
import { storeTranslationsQueryKey, translationsQueryKey, composeMessages, isPlainObject } from './chunk-N2S25NXP.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-
|
|
130
|
-
//# sourceMappingURL=chunk-
|
|
129
|
+
//# sourceMappingURL=chunk-L2DRHH4E.js.map
|
|
130
|
+
//# sourceMappingURL=chunk-L2DRHH4E.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,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;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;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-Q3COPV5Z.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,MAAM,QAAA,CAAS,GAAA,CAAI,IAAA,EAAM,EAAE,eAAA,EAAiB,KAAA,EAAO,OAAA,EAAS,GAAA,EAAM,CAAA;AACnF,IAAA,IAAI,QAAA,CAAS,MAAA,KAAW,GAAA,EAAK,OAAO,IAAA;AAEpC,IAAA,IAAI,CAAC,SAAS,EAAA,EAAI;AAChB,MAAA,OAAO,UAAA,CAAW,CAAA,SAAA,EAAY,QAAA,CAAS,MAAM,CAAA,CAAE,CAAA;AAAA,IAC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AA,EAC/D,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,QAAA,EAAU,OAAO,OAAA,EAA0B,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAQzC,cAAA,CAAe,sBAAsB,OAAA,EAAS,MAAM,GAAG,EAAE,UAAA,EAAY,MAAM;AAAA,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAc7E,KAAA,EAAO,CACL,MAAA,EACA,SAAA,EACA,WAC+B,eAAA,CAAgB,MAAA,EAAQ,SAAA,EAAW,MAAM,CAAA,IAAK,IAAA;AAAA,EAE/E,OAAA,EAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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-L2DRHH4E.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,4 +1,4 @@
|
|
|
1
|
-
import { user } from './chunk-
|
|
1
|
+
import { user } from './chunk-DZT26OCM.js';
|
|
2
2
|
import { getTwilightContext } from './chunk-N2S25NXP.js';
|
|
3
3
|
import { useQuery } from '@tanstack/react-query';
|
|
4
4
|
|
|
@@ -13,5 +13,5 @@ function useUser() {
|
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
export { useUser };
|
|
16
|
-
//# sourceMappingURL=chunk-
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
16
|
+
//# sourceMappingURL=chunk-NCTG4ZTU.js.map
|
|
17
|
+
//# sourceMappingURL=chunk-NCTG4ZTU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/useUser.ts"],"names":[],"mappings":";;;;AAUO,SAAS,OAAA,GAAyB;AACvC,EAAA,MAAM,KAAA,GAAQ,oBAAmB,CAAE,SAAA;AAEnC,EAAA,MAAM,QAAQ,QAAA,CAAS;AAAA,IACrB,GAAG,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAQ;AAAA,IACxB,OAAA,EAAS,CAAC,CAAC,KAAA;AAAA,IACX,eAAA,EAAiB;AAAA,GAClB,CAAA;AAED,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,UAAA,EAAY,CAAC,CAAC,KAAA,EAAM;AACzC","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/hooks/useUser.ts"],"names":[],"mappings":";;;;AAUO,SAAS,OAAA,GAAyB;AACvC,EAAA,MAAM,KAAA,GAAQ,oBAAmB,CAAE,SAAA;AAEnC,EAAA,MAAM,QAAQ,QAAA,CAAS;AAAA,IACrB,GAAG,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAQ;AAAA,IACxB,OAAA,EAAS,CAAC,CAAC,KAAA;AAAA,IACX,eAAA,EAAiB;AAAA,GAClB,CAAA;AAED,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,UAAA,EAAY,CAAC,CAAC,KAAA,EAAM;AACzC","file":"chunk-NCTG4ZTU.js","sourcesContent":["import { useQuery, type UseQueryResult } from '@tanstack/react-query';\nimport { getTwilightContext } from '../twilight/context';\nimport { user } from '../api/user';\nimport type { User } from '../types';\n\nexport type UseUserReturn = UseQueryResult<User | null> & {\n /** True when an auth token exists (regardless of query state). */\n isLoggedIn: boolean;\n};\n\nexport function useUser(): UseUserReturn {\n const token = getTwilightContext().authToken;\n\n const query = useQuery({\n ...user.queries.current(),\n enabled: !!token,\n placeholderData: null,\n });\n\n return { ...query, isLoggedIn: !!token };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getActiveScope, requestedThemeVersionId, getActiveScopeId, api, STORE_IDENTIFIER_HEADER } from './chunk-
|
|
1
|
+
import { getActiveScope, requestedThemeVersionId, getActiveScopeId, api, STORE_IDENTIFIER_HEADER } from './chunk-IKUDCH7Q.js';
|
|
2
2
|
import { resolveStoreIdentifier } from './chunk-TYLKNVQA.js';
|
|
3
3
|
import { getTwilightContext } from './chunk-N2S25NXP.js';
|
|
4
4
|
import { queryOptions } from '@tanstack/react-query';
|
|
@@ -80,5 +80,5 @@ var store = {
|
|
|
80
80
|
};
|
|
81
81
|
|
|
82
82
|
export { store };
|
|
83
|
-
//# sourceMappingURL=chunk-
|
|
84
|
-
//# sourceMappingURL=chunk-
|
|
83
|
+
//# sourceMappingURL=chunk-NTIGQYSN.js.map
|
|
84
|
+
//# sourceMappingURL=chunk-NTIGQYSN.js.map
|