Open-source Xbox-inspired desktop launcher for Xodus on Linux
TypeScript
[source-only] feat(store): add top paid breadth and bound featured collection reads
Nexus Maintainer4f50ccd599e8
diff --git a/assets/locales/en.json b/assets/locales/en.jsonindex 7e39a29..2ceda3d 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -826,6 +826,7 @@"ui.this_downloads_licensed_content_into_a_separate_393e175": "This downloads licensed content into a separate managed folder. Close the game first.","ui.this_log_is_too_large_for_the_clipboard_use_show_97f6e93": "This log is too large for the clipboard. Use Show log file to attach the complete file.","ui.tools_must_already_be_installed_applies_to_this_956d794": "Tools must already be installed. Applies to this game and its shortcuts, not the launcher.",+ "ui.top_paid_games_8040f77": "Top paid and trending games","ui.trending_pc_games_2025848": "Trending PC games","ui.try_a_different_title_or_a_microsoft_store_produ_326af8c": "Try a different title or a Microsoft Store Product ID.","ui.try_this_if_a_standard_dualsense_controller_is_n_114e408": "Use if a DualSense is not detected. Disables native HIDRAW for this game only. Advanced haptics and adaptive triggers may be unavailable. Does not change Xbox controller settings.",diff --git a/src/main/catalog-cache.test.ts b/src/main/catalog-cache.test.tsindex a7fc1d7..809ecd7 100644--- a/src/main/catalog-cache.test.ts+++ b/src/main/catalog-cache.test.ts@@ -16,7 +16,10 @@ it.each(['search', 'featured'] as const)('coalesces twenty concurrent %s requestconst request = () => kind === 'search' ? catalog.search('Game', 'US') : catalog.featured('US');const pending = Array.from({ length: 20 }, request);await Promise.resolve();- expect(fetcher).toHaveBeenCalledTimes(1);+ // One shared chain per key: one search request, or the two bounded Store+ // recommendation feeds for featured (trending and top paid).+ const chain = kind === 'search' ? 1 : 2;+ expect(fetcher).toHaveBeenCalledTimes(chain);gate.release();const results = await Promise.all(pending);results[0].query = 'changed';@@ -26,7 +29,7 @@ it.each(['search', 'featured'] as const)('coalesces twenty concurrent %s requestexpect(result.products).toEqual([]);}expect((await request()).products).toEqual([]);- expect(fetcher).toHaveBeenCalledTimes(1);+ expect(fetcher).toHaveBeenCalledTimes(chain);});it('shares a failure without caching it and permits a clean retry', async () => {@@ -52,7 +55,8 @@ it('separates markets, pages and featured results while retaining normalized seacatalog.search('Game', 'US'), catalog.search(' game ', 'us'), catalog.search('Game', 'CZ'),catalog.search('Game', 'US', 'page2'), catalog.featured('US'), catalog.search('featured', 'US'),]);- expect(fetcher).toHaveBeenCalledTimes(5);+ // Four search keys plus the two bounded recommendation feeds of one featured key.+ expect(fetcher).toHaveBeenCalledTimes(6);});it('evicts least-recently-used results and expires entries without extending their lifetime on hits', async () => {diff --git a/src/main/catalog.test.ts b/src/main/catalog.test.tsindex 9beb0ab..ee08447 100644--- a/src/main/catalog.test.ts+++ b/src/main/catalog.test.ts@@ -212,6 +212,148 @@ describe('CatalogService', () => {});});+describe('Public Store landing collections', () => {+ const paidSku = (price: number) => ({ Sku: { SkuType: 'full', Properties: {} }, Availabilities: [{ OrderManagementData: { Price: { MSRP: price, ListPrice: price } } }] });+ const freeSku = () => ({ Sku: { SkuType: 'full', Properties: {} }, Availabilities: [{ OrderManagementData: { Price: { MSRP: 0, ListPrice: 0 } } }] });+ const trialSku = () => ({ Sku: { SkuType: 'trial', Properties: { IsTrial: true } }, Availabilities: [{ OrderManagementData: { Price: { MSRP: 0, ListPrice: 0 } } }] });+ const row = (productId: string, title: string, price: number) => ({ productId, title, isGame: true, priceInfo: { msrp: price, price, displayPrice: price > 0 ? `$${price}` : 'Free' } });+ const game = (productId: string, skus: unknown[]) => ({ ProductId: productId, ProductType: 'Game', DisplaySkuAvailabilities: skus });+ const landingFetcher = (collections: Record<string, unknown[]>, details: Record<string, unknown>, requests: string[]) => (async (input: URL | RequestInfo) => {+ const url = new URL(String(input));+ if (url.pathname.includes('GetComputedProductsList')) {+ const name = url.searchParams.get('listName') ?? '', page = Number(url.searchParams.get('pgNo') ?? '1');+ requests.push(`${name}:${page}`);+ const payload = collections[name]?.[page - 1];+ return payload ? new Response(JSON.stringify(payload), { status: 200 }) : new Response('{}', { status: 404 });+ }+ if (url.pathname.includes('/v7.0/products')) {+ const ids = (url.searchParams.get('bigIds') ?? '').split(',').map(id => id.toUpperCase());+ requests.push(`details:${ids.length}`);+ return new Response(JSON.stringify({ Products: ids.flatMap(id => details[id] ? [details[id]] : []) }), { status: 200 });+ }+ return new Response('{}', { status: 404 });+ }) as typeof fetch;++ it('fills the landing page from trending plus top paid games inside a bounded request budget', async () => {+ const requests: string[] = [];+ const collections = {+ TopTrending: [+ { title: 'Trending games', hasMorePages: true, nextPageNumber: 2, productsList: [row('9FREETREND01', 'Free Trending', 0), row('9SHARED00001', 'Shared Paid Game', 19.99), row('9TRENDPAID01', 'Trending Paid', 9.99)] },+ { title: 'Trending games', hasMorePages: true, nextPageNumber: 3, productsList: [] },+ ],+ TopPaid: [+ { title: 'Top paid games', hasMorePages: true, nextPageNumber: 2, productsList: [row('9SHARED00001', 'Shared Paid Game', 19.99), row('9PAIDONE0001', 'Paid One', 29.99)] },+ { title: 'Top paid games', hasMorePages: true, nextPageNumber: 3, productsList: [row('9PAIDTWO0001', 'Paid Two', 39.99)] },+ { title: 'Top paid games', hasMorePages: false, productsList: [row('9PAIDTHREE01', 'Paid Three', 49.99)] },+ ],+ };+ const details = {+ '9FREETREND01': game('9FREETREND01', [freeSku()]),+ '9SHARED00001': game('9SHARED00001', [paidSku(19.99)]),+ '9TRENDPAID01': game('9TRENDPAID01', [paidSku(9.99)]),+ '9PAIDONE0001': game('9PAIDONE0001', [paidSku(29.99)]),+ '9PAIDTWO0001': game('9PAIDTWO0001', [paidSku(39.99)]),+ '9PAIDTHREE01': game('9PAIDTHREE01', [paidSku(49.99)]),+ };+ const result = await new CatalogService(landingFetcher(collections, details, requests)).featured('US');+ expect(result.products.map(product => product.title)).toEqual(['Shared Paid Game', 'Trending Paid', 'Paid One', 'Paid Two', 'Paid Three']);+ expect(result.products.filter(product => product.productId === '9SHARED00001')).toHaveLength(1);+ expect(requests.filter(request => request.startsWith('TopTrending'))).toEqual(['TopTrending:1']);+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:1', 'TopPaid:2', 'TopPaid:3']);+ expect(requests.filter(request => request.startsWith('details:')).every(request => Number(request.split(':')[1]) <= 25)).toBe(true);+ expect(result.query).toBe('Trending games');+ });++ it('keeps the surviving Store collection when the other one fails', async () => {+ const trendingOnly = (async (input: URL | RequestInfo) => {+ const url = new URL(String(input));+ if (url.pathname.includes('GetComputedProductsList')) {+ if (url.searchParams.get('listName') === 'TopPaid') return new Response('{}', { status: 503 });+ return new Response(JSON.stringify({ title: 'Trending games', productsList: [row('9TRENDING01', 'Trending Paid', 9.99)] }), { status: 200 });+ }+ return new Response(JSON.stringify({ Products: [game('9TRENDING01', [paidSku(9.99)])] }), { status: 200 });+ }) as typeof fetch;+ expect((await new CatalogService(trendingOnly).featured('US')).products.map(product => product.title)).toEqual(['Trending Paid']);++ const paidOnly = (async (input: URL | RequestInfo) => {+ const url = new URL(String(input));+ if (url.pathname.includes('GetComputedProductsList')) {+ if (url.searchParams.get('listName') === 'TopTrending') return new Response('{}', { status: 503 });+ const page = Number(url.searchParams.get('pgNo') ?? '1');+ return new Response(JSON.stringify({ title: 'Top paid games', hasMorePages: page < 2, productsList: page === 1 ? [row('9PAIDONLY01', 'Paid Only', 14.99)] : [] }), { status: 200 });+ }+ return new Response(JSON.stringify({ Products: [game('9PAIDONLY01', [paidSku(14.99)])] }), { status: 200 });+ }) as typeof fetch;+ expect((await new CatalogService(paidOnly).featured('US')).products.map(product => product.title)).toEqual(['Paid Only']);+ });++ it('fails honestly when every Store collection is unavailable', async () => {+ const offline = (async () => new Response('{}', { status: 503 })) as typeof fetch;+ await expect(new CatalogService(offline).featured('US')).rejects.toThrow('TopTrending');+ });++ it.each([+ ['string', '2'],+ ['fractional', 2.5],+ ['huge jump', 1_000_000],+ ['repeated current page', 1],+ ['backward', 0],+ ['negative sentinel', -1],+ ['boolean', true],+ ['missing', undefined],+ ])('stops pagination on a %s nextPageNumber and keeps the page one results', async (_label, nextPageNumber) => {+ const requests: string[] = [];+ const collections = {+ TopTrending: [{ title: 'Trending games', hasMorePages: false, productsList: [] }],+ TopPaid: [+ { title: 'Top paid games', hasMorePages: true, nextPageNumber, productsList: [row('9PAIDPAGE001', 'Paid Page One', 19.99)] },+ { title: 'Top paid games', hasMorePages: true, nextPageNumber: 2, productsList: [row('9PAIDPAGE002', 'Paid Page Two', 29.99)] },+ { title: 'Top paid games', hasMorePages: false, productsList: [row('9PAIDPAGE003', 'Paid Page Three', 39.99)] },+ ],+ };+ const details = {+ '9PAIDPAGE001': game('9PAIDPAGE001', [paidSku(19.99)]),+ '9PAIDPAGE002': game('9PAIDPAGE002', [paidSku(29.99)]),+ '9PAIDPAGE003': game('9PAIDPAGE003', [paidSku(39.99)]),+ };+ const result = await new CatalogService(landingFetcher(collections, details, requests)).featured('US');+ expect(result.products.map(product => product.title)).toEqual(['Paid Page One']);+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:1']);+ expect(requests.filter(request => request.startsWith('details:'))).toHaveLength(1);+ });++ it('never exceeds the paid page budget even when the feed offers further sequential pages', async () => {+ const requests: string[] = [];+ const page = (index: number) => ({+ title: 'Top paid games',+ hasMorePages: true,+ nextPageNumber: index + 1,+ productsList: [row(`9BUDGETPAGE0${index}`, `Budget Page ${index}`, 9.99 + index)],+ });+ const collections = {+ TopTrending: [{ title: 'Trending games', hasMorePages: false, productsList: [] }],+ TopPaid: [page(1), page(2), page(3), page(4), page(5)],+ };+ const details = Object.fromEntries([1, 2, 3, 4, 5].map(index => [`9BUDGETPAGE0${index}`, game(`9BUDGETPAGE0${index}`, [paidSku(9.99 + index)])]));+ const result = await new CatalogService(landingFetcher(collections, details, requests)).featured('US');+ expect(requests.filter(request => request.startsWith('TopPaid'))).toEqual(['TopPaid:1', 'TopPaid:2', 'TopPaid:3']);+ expect(result.products.map(product => product.title)).toEqual(['Budget Page 1', 'Budget Page 2', 'Budget Page 3']);+ });++ it('excludes trial and demo offers that appear in the top paid collection', async () => {+ const collections = {+ TopTrending: [{ title: 'Trending games', hasMorePages: false, productsList: [] }],+ TopPaid: [{ title: 'Top paid games', hasMorePages: false, productsList: [row('9TRIALONLY01', 'Trial Only', 29.99), row('9PAIDWITHDEMO', 'Paid With Demo', 39.99)] }],+ };+ const details = {+ '9TRIALONLY01': game('9TRIALONLY01', [trialSku()]),+ '9PAIDWITHDEMO': game('9PAIDWITHDEMO', [trialSku(), paidSku(39.99)]),+ };+ const result = await new CatalogService(landingFetcher(collections, details, [])).featured('US');+ expect(result.products.map(product => product.title)).toEqual(['Paid With Demo']);+ });+});+describe('Store-only offer policy',()=>{const sku=(price:number,props:Record<string,unknown>={},type='full')=>({Sku:{SkuType:type,Properties:props},Availabilities:[{OrderManagementData:{Price:{MSRP:price,ListPrice:price}}}]});const parse=(skus:unknown[],extra={},policy:'store'|'library'='store')=>parseCatalogProducts({productsList:[{productId:'9AAAAAAAAAAA',title:'Free Spirit',isGame:true,...extra}]},{Products:[{ProductId:'9AAAAAAAAAAA',ProductType:'Game',DisplaySkuAvailabilities:skus}]},policy);diff --git a/src/main/catalog.ts b/src/main/catalog.tsindex 2e5254b..afa26b6 100644--- a/src/main/catalog.ts+++ b/src/main/catalog.ts@@ -36,6 +36,7 @@ interface StoreSearchResponse {productsList?: unknown;cursor?: unknown;hasMorePages?: unknown;+ nextPageNumber?: unknown;}interface DisplayCatalogResponse {@@ -59,6 +60,13 @@ const STORE_HOSTS = new Set(['www.xbox.com', 'xbox.com', 'apps.microsoft.com']);const CACHE_TTL_MS = 10 * 60 * 1000;const SEARCH_CACHE_LIMIT = 100;const SEARCH_REQUEST_LIMIT = 32;+// The Store's games recommendation feeds return about ten products per page.+// Trending games are dominated by free-to-play titles that the public browsing+// policy has to hide, so the top paid collection supplies real breadth. Both+// feeds are bounded here: one page is cached for ten minutes per market.+const FEATURED_PAGE_ITEMS = 12;+const FEATURED_TRENDING_PAGES = 1;+const FEATURED_PAID_PAGES = 3;// Box art is square and carries the game's title branding, matching the// square library tiles; promotional square art is the textless fallback.const POSTER_PURPOSES = ['BoxArt', 'TitledPoster', 'Poster', 'FeaturePromotionalSquareArt'];@@ -198,6 +206,21 @@ function bundleReferences(product: Record<string, unknown> | undefined): BundleRreturn [...references].map(([productId, primary]) => ({ productId, primary }));}+/** Merge Store collections in priority order, keeping one row per product ID. */+function mergeCollections(...collections: StoreSearchResponse[]): StoreSearchResponse {+ const seen = new Set<string>();+ const productsList: StoreSearchProduct[] = [];+ for (const collection of collections) {+ for (const product of Array.isArray(collection.productsList) ? collection.productsList as StoreSearchProduct[] : []) {+ const productId = string(product?.productId)?.toUpperCase();+ if (!productId || seen.has(productId)) continue;+ seen.add(productId);+ productsList.push(product);+ }+ }+ return { productsList };+}+function packageSupport(productId: string, details: Map<string, Record<string, unknown>>, visited = new Set<string>(), budget = { remaining: 512 }): PackageSupport {if (visited.size > 6 || budget.remaining-- <= 0) return {installability: 'unknown', supportNote: 'The Store bundle metadata could not be fully resolved.',@@ -537,16 +560,57 @@ export class CatalogService {return this.cachedResult(cacheKey, () => this.featuredResult(market));}+ /** Read one public Store recommendation feed, bounded to a fixed page count. */+ private async computedCollection(listName: string, market: string, pages: number): Promise<StoreSearchResponse & { title?: unknown }> {+ const collected: StoreSearchProduct[] = [];+ let title: unknown;+ let page = 1;+ for (let index = 0; index < pages; index += 1) {+ const url = new URL('https://apps.microsoft.com/api/Reco/GetComputedProductsList');+ for (const [key, value] of Object.entries({+ listName, pgNo: String(page), noItems: String(FEATURED_PAGE_ITEMS), filteredCategories: 'AllProducts',+ mediaType: 'Games', gl: market, hl: 'en-us', exp: '0',+ })) url.searchParams.set(key, value);+ const response = await this.fetcher(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });+ if (!response.ok) throw new Error(`Microsoft Store ${listName} collection returned HTTP ${response.status}.`);+ const payload = await response.json() as StoreSearchResponse & { title?: unknown };+ title = title ?? payload.title;+ const products = Array.isArray(payload.productsList) ? payload.productsList as StoreSearchProduct[] : [];+ collected.push(...products);+ if (payload.hasMorePages !== true || products.length === 0) break;+ // Captured contract (US pages 1..10, CZ pages 1..3, TopPaid pages 1..3):+ // a continuation names exactly the next page while hasMorePages is true,+ // and the end of a feed reports nextPageNumber -1 with hasMorePages+ // false. Any other value (string, fraction, repeat, jump, sentinel) stops+ // pagination and keeps the products already collected instead of+ // following it, so the request budget cannot be redirected.+ if (payload.nextPageNumber !== page + 1) break;+ page += 1;+ }+ return { productsList: collected, title };+ }+private async featuredResult(market: string): Promise<CatalogSearchResult> {- const url = new URL('https://apps.microsoft.com/api/Reco/GetComputedProductsList');- for (const [key, value] of Object.entries({- listName: 'TopTrending', pgNo: '1', noItems: '12', filteredCategories: 'AllProducts',- mediaType: 'Games', gl: market, hl: 'en-us', exp: '0',- })) url.searchParams.set(key, value);- const response = await this.fetcher(url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });- if (!response.ok) throw new Error(`Microsoft Store featured collection returned HTTP ${response.status}.`);- const search = await response.json() as StoreSearchResponse & { title?: unknown };- return this.result(search, string(search.title) ?? 'Trending games', market, false);+ // Two honest public collections. Trending games are dominated by+ // free-to-play offers that the public browsing policy must hide, so the top+ // paid games collection supplies the real breadth of the landing page.+ // Each feed is bounded by FEATURED_*_PAGES and served from the ten minute+ // cache, so a page load never becomes an unbounded request fan-out.+ const [trending, paid] = await Promise.allSettled([+ this.computedCollection('TopTrending', market, FEATURED_TRENDING_PAGES),+ this.computedCollection('TopPaid', market, FEATURED_PAID_PAGES),+ ]);+ if (trending.status === 'rejected' && paid.status === 'rejected') {+ throw trending.reason instanceof Error ? trending.reason : new Error('Microsoft Store featured collections could not be loaded.');+ }+ const merged = mergeCollections(+ ...(trending.status === 'fulfilled' ? [trending.value] : []),+ ...(paid.status === 'fulfilled' ? [paid.value] : []),+ );+ const title = string(trending.status === 'fulfilled' ? trending.value.title : undefined)+ ?? string(paid.status === 'fulfilled' ? paid.value.title : undefined)+ ?? 'Featured games';+ return this.result(merged, title, market, false);}async posters(ids: string[], rawMarket: string): Promise<Map<string, string>> {diff --git a/src/renderer/App.tsx b/src/renderer/App.tsxindex e32ac21..0474598 100644--- a/src/renderer/App.tsx+++ b/src/renderer/App.tsx@@ -371,7 +371,7 @@ export function StorePage({ data, toast, go, initialQuery }: { data: AppSnapshotif(detailOpen&&selected)return <main ref={pageRef} className="page store-page library-detail-open"><CatalogGameDetails key={`${selected.productId}:${data.auth.username}:${data.auth.player}:${data.auth.stored}:${data.auth.running}:${data.backend.binaryPath}:${data.settings.market}`} product={selected} data={data} storeMode storeAccess={access} back={()=>setDetailOpen(false)} backLabel={ui('game.back_to_store')} toast={toast}/></main>;return <main ref={pageRef} className="page store-page"><header className="page-header"><div><h1>{ui("ui.store_ee7da93")}</h1></div><span className="catalog-source"><StatusDot />Microsoft Store</span></header>- {!catalog ? <section className="featured-catalog"><SectionTitle title={ui("ui.featured_c533caf")} />{featuredLoading ? <div className="catalog-loading"><LoaderCircle className="spin" /><span>{ui("ui.loading_live_store_collection_20763b0")}</span></div> : featured?.products.length ? <><div className="featured-rail">{featured.products.slice(0, 3).map((product) => <button className="featured-tile" key={product.productId} data-gamepad-detail-target={product.productId} onClick={() => selectProduct(product)}>{product.heroUrl || product.posterUrl ? <img src={product.heroUrl ?? product.posterUrl} alt="" /> : <div className="featured-tile-placeholder"><Gamepad2 /></div>}<span className="featured-tile-copy"><GameTitle title={product.title} /><small>{product.publisher ?? 'Microsoft Store'} · {product.installability === 'supported' ? ui('store.verified_pc') : ui("ui.check_package_support_79592da")}</small></span></button>)}</div><SectionTitle title={ui("ui.trending_pc_games_2025848")} />{productGrid(featured.products.slice(3))}</> : <div className="catalog-empty"><Store /><h2>{ui("ui.featured_games_are_temporarily_unavailable_3901a69")}</h2><p>{featuredError ?? ui("ui.search_still_works_with_live_microsoft_store_dat_b3eeb72")}</p></div>}</section> : null}+ {!catalog ? <section className="featured-catalog"><SectionTitle title={ui("ui.featured_c533caf")} />{featuredLoading ? <div className="catalog-loading"><LoaderCircle className="spin" /><span>{ui("ui.loading_live_store_collection_20763b0")}</span></div> : featured?.products.length ? <><div className="featured-rail">{featured.products.slice(0, 3).map((product) => <button className="featured-tile" key={product.productId} data-gamepad-detail-target={product.productId} onClick={() => selectProduct(product)}>{product.heroUrl || product.posterUrl ? <img src={product.heroUrl ?? product.posterUrl} alt="" /> : <div className="featured-tile-placeholder"><Gamepad2 /></div>}<span className="featured-tile-copy"><GameTitle title={product.title} /><small>{product.publisher ?? 'Microsoft Store'} · {product.installability === 'supported' ? ui('store.verified_pc') : ui("ui.check_package_support_79592da")}</small></span></button>)}</div><SectionTitle title={ui("ui.top_paid_games_8040f77")} />{productGrid(featured.products.slice(3))}</> : <div className="catalog-empty"><Store /><h2>{ui("ui.featured_games_are_temporarily_unavailable_3901a69")}</h2><p>{featuredError ?? ui("ui.search_still_works_with_live_microsoft_store_dat_b3eeb72")}</p></div>}</section> : null}{catalog ? <><SectionTitle title={ui("ui.results_for_343a212", { query: catalog.query })} />{productGrid(catalog.products)}{catalog.products.length === 0 ? <div className="empty-state compact"><div><Search /></div><h2>{ui("ui.no_games_found_6da4c04")}</h2><p>{ui("ui.try_a_different_title_or_a_microsoft_store_produ_326af8c")}</p></div> : null}{catalog.hasMore ? <div className="load-more" data-gamepad-library-footer><button className="secondary" aria-disabled={loadingMore} aria-busy={loadingMore} onClick={() => { if (!loadingMore) void loadMore(); }}>{loadingMore ? <LoaderCircle className="spin" /> : <Plus />}{ui("ui.load_more_results_e03f1e4")}</button></div> : null}</> : null}