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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
import { APP_VERSION } from '$lib/version';

// CORS Proxy Configuration
// If you're experiencing CORS issues with the HIFI API, you can set up a proxy

type RegionPreference = 'auto' | 'us' | 'eu';

export interface ApiClusterTarget {
	name: string;
	baseUrl: string;
	weight: number;
	requiresProxy: boolean;
	category: 'auto-only';
}

const V2_API_TARGETS = [
	{
		name: 'veltrix',
		baseUrl: 'https://veltrixcode-loddless.hf.space',
		weight: 100,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'squid-api',
		baseUrl: 'https://triton.squid.wtf',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'spotisaver-1',
		baseUrl: 'https://hifi-one.spotisaver.net',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'spotisaver-2',
		baseUrl: 'https://hifi-two.spotisaver.net',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'kinoplus',
		baseUrl: 'https://tidal.kinoplus.online',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'hund',
		baseUrl: 'https://hund.qqdl.site',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'katze',
		baseUrl: 'https://katze.qqdl.site',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'maus',
		baseUrl: 'https://maus.qqdl.site',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'vogel',
		baseUrl: 'https://vogel.qqdl.site',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'wolf',
		baseUrl: 'https://wolf.qqdl.site',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	},
	{
		name: 'monochrome',
		baseUrl: 'https://arran.monochrome.tf',
		weight: 15,
		requiresProxy: false,
		category: 'auto-only'
	}
] satisfies ApiClusterTarget[];

const ALL_API_TARGETS = [...V2_API_TARGETS] satisfies ApiClusterTarget[];
const US_API_TARGETS = [] satisfies ApiClusterTarget[];
const TARGET_COLLECTIONS: Record<RegionPreference, ApiClusterTarget[]> = {
	auto: [...ALL_API_TARGETS],
	eu: [],
	us: [...US_API_TARGETS]
};

const TARGETS = TARGET_COLLECTIONS.auto;

export const API_CONFIG = {
	// Cluster of target endpoints for load distribution and redundancy
	targets: TARGETS,
	baseUrl: TARGETS[0]?.baseUrl ?? 'https://tidal.401658.xyz',
	// Proxy configuration for endpoints that need it
	useProxy: true,
	proxyUrl: '/api/proxy'
};

type WeightedTarget = ApiClusterTarget & { cumulativeWeight: number };

let v1WeightedTargets: WeightedTarget[] | null = null;
let v2WeightedTargets: WeightedTarget[] | null = null;

function buildWeightedTargets(targets: ApiClusterTarget[]): WeightedTarget[] {
	const validTargets = targets.filter((target) => {
		if (!target?.baseUrl || typeof target.baseUrl !== 'string') {
			return false;
		}
		if (target.weight <= 0) {
			return false;
		}
		try {
			new URL(target.baseUrl);
			return true;
		} catch (error) {
			console.error(`Invalid API target URL for ${target.name}:`, error);
			return false;
		}
	});

	if (validTargets.length === 0) {
		throw new Error('No valid API targets configured');
	}

	let cumulative = 0;
	const collected: WeightedTarget[] = [];
	for (const target of validTargets) {
		cumulative += target.weight;
		collected.push({ ...target, cumulativeWeight: cumulative });
	}
	return collected;
}

function ensureWeightedTargets(apiVersion: 'v1' | 'v2' = 'v2'): WeightedTarget[] {
	if (apiVersion === 'v2') {
		if (!v2WeightedTargets) {
			v2WeightedTargets = buildWeightedTargets(V2_API_TARGETS);
		}
		return v2WeightedTargets;
	} else {
		if (!v1WeightedTargets) {
			// v1 includes ALL_API_TARGETS (v1) + V2_API_TARGETS (fallback with low weight)
			const v2Fallback = V2_API_TARGETS.map((t) => ({ ...t, weight: 1 }));
			v1WeightedTargets = buildWeightedTargets([...ALL_API_TARGETS, ...v2Fallback]);
		}
		return v1WeightedTargets;
	}
}

export function selectApiTarget(apiVersion: 'v1' | 'v2' = 'v2'): ApiClusterTarget {
	const targets = ensureWeightedTargets(apiVersion);
	return selectFromWeightedTargets(targets);
}

export function getPrimaryTarget(apiVersion: 'v1' | 'v2' = 'v2'): ApiClusterTarget {
	return ensureWeightedTargets(apiVersion)[0];
}

function selectFromWeightedTargets(weighted: WeightedTarget[]): ApiClusterTarget {
	if (weighted.length === 0) {
		throw new Error('No weighted targets available for selection');
	}

	const totalWeight = weighted[weighted.length - 1]?.cumulativeWeight ?? 0;
	if (totalWeight <= 0) {
		return weighted[0];
	}

	const random = Math.random() * totalWeight;
	for (const target of weighted) {
		if (random < target.cumulativeWeight) {
			return target;
		}
	}

	return weighted[0];
}

export function getTargetsForRegion(region: RegionPreference = 'auto'): ApiClusterTarget[] {
	const targets = TARGET_COLLECTIONS[region];
	return Array.isArray(targets) ? targets : [];
}

export function selectApiTargetForRegion(region: RegionPreference): ApiClusterTarget {
	if (region === 'auto') {
		return selectApiTarget();
	}

	const targets = getTargetsForRegion(region);
	if (targets.length === 0) {
		return selectApiTarget();
	}

	const weighted = buildWeightedTargets(targets);
	return selectFromWeightedTargets(weighted);
}

export function hasRegionTargets(region: RegionPreference): boolean {
	if (region === 'auto') {
		return TARGET_COLLECTIONS.auto.length > 0;
	}

	return getTargetsForRegion(region).length > 0;
}

function parseTargetBase(target: ApiClusterTarget): URL | null {
	try {
		return new URL(target.baseUrl);
	} catch (error) {
		console.error(`Invalid API target base URL for ${target.name}:`, error);
		return null;
	}
}

function getBaseApiUrl(target?: ApiClusterTarget): URL | null {
	const chosen = target ?? getPrimaryTarget();
	return parseTargetBase(chosen);
}

function stripTrailingSlash(path: string): string {
	if (path === '/') return path;
	return path.replace(/\/+$/, '') || '/';
}

function combinePaths(basePath: string, relativePath: string): string {
	const trimmedBase = stripTrailingSlash(basePath || '/');
	const normalizedRelative = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
	if (trimmedBase === '/' || trimmedBase === '') {
		return normalizedRelative;
	}
	if (normalizedRelative === '/') {
		return `${trimmedBase}/`;
	}
	return `${trimmedBase}${normalizedRelative}`;
}

function getRelativePath(url: URL, targetBase: URL): string {
	const basePath = stripTrailingSlash(targetBase.pathname || '/');
	const currentPath = url.pathname || '/';
	if (basePath === '/' || basePath === '') {
		return currentPath.startsWith('/') ? currentPath : `/${currentPath}`;
	}
	if (!currentPath.startsWith(basePath)) {
		return currentPath;
	}
	const relative = currentPath.slice(basePath.length);
	if (!relative) {
		return '/';
	}
	return relative.startsWith('/') ? relative : `/${relative}`;
}

function matchesTarget(url: URL, target: ApiClusterTarget): boolean {
	const base = parseTargetBase(target);
	if (!base) {
		return false;
	}

	if (url.origin !== base.origin) {
		return false;
	}

	const basePath = stripTrailingSlash(base.pathname || '/');
	if (basePath === '/' || basePath === '') {
		return true;
	}

	const targetPath = stripTrailingSlash(url.pathname || '/');
	return targetPath === basePath || targetPath.startsWith(`${basePath}/`);
}

function findTargetForUrl(url: URL): ApiClusterTarget | null {
	for (const target of API_CONFIG.targets) {
		if (matchesTarget(url, target)) {
			return target;
		}
	}
	return null;
}

export function isProxyTarget(url: URL): boolean {
	const target = findTargetForUrl(url);
	return target?.requiresProxy === true;
}

function shouldPreferPrimaryTarget(url: URL): boolean {
	const path = url.pathname.toLowerCase();

	// Prefer the proxied primary target for endpoints that routinely require the legacy domain
	if (path.includes('/album/') || path.includes('/artist/') || path.includes('/playlist/')) {
		return true;
	}

	if (path.includes('/search/')) {
		const params = url.searchParams;
		if (params.has('a') || params.has('al') || params.has('p')) {
			return true;
		}
	}

	return false;
}

function resolveUrl(url: string): URL | null {
	try {
		return new URL(url);
	} catch {
		const baseApiUrl = getBaseApiUrl();
		if (!baseApiUrl) {
			return null;
		}

		try {
			return new URL(url, baseApiUrl);
		} catch {
			return null;
		}
	}
}

/**
 * Create a proxied URL if needed
 */
export function getProxiedUrl(url: string): string {
	if (!API_CONFIG.useProxy || !API_CONFIG.proxyUrl) {
		return url;
	}

	const targetUrl = resolveUrl(url);
	if (!targetUrl) {
		return url;
	}

	if (!isProxyTarget(targetUrl)) {
		return url;
	}

	return `${API_CONFIG.proxyUrl}?url=${encodeURIComponent(targetUrl.toString())}`;
}

function isLikelyProxyErrorEntry(entry: unknown): boolean {
	if (!entry || typeof entry !== 'object') {
		return false;
	}

	const record = entry as Record<string, unknown>;
	const status = typeof record.status === 'number' ? record.status : undefined;
	const subStatus = typeof record.subStatus === 'number' ? record.subStatus : undefined;
	const userMessage = typeof record.userMessage === 'string' ? record.userMessage : undefined;
	const detail = typeof record.detail === 'string' ? record.detail : undefined;

	if (typeof status === 'number' && status >= 400) {
		return true;
	}

	if (typeof subStatus === 'number' && subStatus >= 400) {
		return true;
	}

	const tokenPattern = /(token|invalid|unauthorized)/i;
	if (userMessage && tokenPattern.test(userMessage)) {
		return true;
	}

	if (detail && tokenPattern.test(detail)) {
		return true;
	}

	return false;
}

function isLikelyProxyErrorPayload(payload: unknown): boolean {
	if (Array.isArray(payload)) {
		return payload.some((entry) => isLikelyProxyErrorEntry(entry));
	}

	if (payload && typeof payload === 'object') {
		return isLikelyProxyErrorEntry(payload);
	}

	return false;
}

async function isUnexpectedProxyResponse(response: Response): Promise<boolean> {
	if (!response.ok) {
		return false;
	}

	const contentType = response.headers.get('content-type');
	if (!contentType || !contentType.toLowerCase().includes('application/json')) {
		return false;
	}

	try {
		const payload = await response.clone().json();
		return isLikelyProxyErrorPayload(payload);
	} catch {
		return false;
	}
}

function isV2Target(target: ApiClusterTarget): boolean {
	return V2_API_TARGETS.some((t) => t.name === target.name);
}

/**
 * Fetch with CORS handling
 */
export async function fetchWithCORS(
	url: string,
	options?: RequestInit & {
		apiVersion?: 'v1' | 'v2';
		preferredQuality?: string;
		validateResponse?: (res: Response) => Promise<boolean>;
	}
): Promise<Response> {
	const resolvedUrl = resolveUrl(url);
	if (!resolvedUrl) {
		throw new Error(`Unable to resolve URL: ${url}`);
	}

	const originTarget = findTargetForUrl(resolvedUrl);
	if (!originTarget) {
		return fetch(getProxiedUrl(resolvedUrl.toString()), {
			...options
		});
	}

	const apiVersion = options?.apiVersion ?? 'v2';
	const weightedTargets = ensureWeightedTargets(apiVersion);
	const attemptOrder: ApiClusterTarget[] = [];
	if (shouldPreferPrimaryTarget(resolvedUrl)) {
		const primary = getPrimaryTarget(apiVersion);
		if (!attemptOrder.some((candidate) => candidate.name === primary.name)) {
			attemptOrder.push(primary);
		}
	}

	const selected = selectApiTarget(apiVersion);
	if (!attemptOrder.some((candidate) => candidate.name === selected.name)) {
		attemptOrder.push(selected);
	}

	for (const target of weightedTargets) {
		if (!attemptOrder.some((candidate) => candidate.name === target.name)) {
			attemptOrder.push(target);
		}
	}

	let uniqueTargets = attemptOrder.filter(
		(target, index, array) => array.findIndex((entry) => entry.name === target.name) === index
	);

	if (uniqueTargets.length === 0) {
		uniqueTargets = [getPrimaryTarget(apiVersion)];
	}

	const originBase = parseTargetBase(originTarget);
	if (!originBase) {
		throw new Error('Invalid origin target configuration.');
	}

	const totalAttempts = Math.max(3, uniqueTargets.length);
	let lastError: unknown = null;
	let lastResponse: Response | null = null;
	let lastUnexpectedResponse: Response | null = null;
	let lastValidButRejectedResponse: Response | null = null;

	for (let attempt = 0; attempt < totalAttempts; attempt += 1) {
		const target = uniqueTargets[attempt % uniqueTargets.length];
		const targetBase = parseTargetBase(target);
		if (!targetBase) {
			continue;
		}

		const relativePath = getRelativePath(resolvedUrl, originBase);
		const rewrittenPath = combinePaths(targetBase.pathname || '/', relativePath);
		const rewrittenUrl = new URL(
			rewrittenPath + resolvedUrl.search + resolvedUrl.hash,
			targetBase.origin
		);

		// If we are falling back to a v2 target and have a preferred quality (e.g. HI_RES_LOSSLESS),
		// upgrade the quality parameter in the URL.
		if (
			isV2Target(target) &&
			options?.preferredQuality &&
			rewrittenUrl.searchParams.has('quality')
		) {
			rewrittenUrl.searchParams.set('quality', options.preferredQuality);
		}

		const finalUrl = getProxiedUrl(rewrittenUrl.toString());

		const headers = new Headers(options?.headers);
		const isCustom =
			[...V2_API_TARGETS].some((t) => t.name === target.name) &&
			!target.baseUrl.includes('tidal.com') &&
			!target.baseUrl.includes('api.tidal.com') &&
			!target.baseUrl.includes('monochrome.tf');

		if (isCustom) {
			headers.set('X-Client', `BiniLossless/${APP_VERSION}`);
		}

		try {
			const response = await fetch(finalUrl, {
				...options,
				headers
			});
			if (response.ok) {
				const unexpected = await isUnexpectedProxyResponse(response);
				if (!unexpected) {
					if (options?.validateResponse) {
						const isValid = await options.validateResponse(response.clone());
						if (!isValid) {
							lastValidButRejectedResponse = response;
							continue;
						}
					}
					return response;
				}
				lastUnexpectedResponse = response;
				continue;
			}

			lastResponse = response;
		} catch (error) {
			lastError = error;
			if (error instanceof TypeError && error.message.includes('CORS')) {
				continue;
			}
		}
	}

	if (lastValidButRejectedResponse) {
		return lastValidButRejectedResponse;
	}

	if (lastUnexpectedResponse) {
		return lastUnexpectedResponse;
	}

	if (lastResponse) {
		return lastResponse;
	}

	if (lastError) {
		if (
			lastError instanceof TypeError &&
			typeof lastError.message === 'string' &&
			lastError.message.includes('CORS')
		) {
			throw new Error(
				'CORS error detected. Please configure a proxy in src/lib/config.ts or enable CORS on your backend.'
			);
		}
		throw lastError;
	}

	throw new Error('All API targets failed without response.');
}